from fastsql import conn_db
from fastcore.utils import *
fastsql
A bit of extra usability for sqlalchemy v2.
Install
pip install fastsql
Example
This little library provides a single function, conn_db
, which returns an extended sqlalchemy MetaData
object which you can use for accessing your database with full dynamic autocomplete support in Jupyter and IPython. So it’s particularly useful for interactive development.
We demonstrate it here using the ‘chinook’ sample database.
= 'https://github.com/lerocha/chinook-database/raw/master/ChinookDatabase/DataSources/Chinook_Sqlite.sqlite'
url = Path('chinook.sqlite')
path if not path.exists(): urlsave(url, path)
= f"sqlite:///{path}"
connstr = conn_db(connstr) db
' '.join(db.tables)
'Album Artist Customer Employee Genre Invoice InvoiceLine Track MediaType Playlist PlaylistTrack'
= db.Album a
list(a.c)
[Column('AlbumId', INTEGER(), table=<Album>, primary_key=True, nullable=False),
Column('Title', NVARCHAR(length=160), table=<Album>, nullable=False),
Column('ArtistId', INTEGER(), ForeignKey('Artist.ArtistId'), table=<Album>, nullable=False)]
Rows are returned as named tuples.
= db.sql('select AlbumId,Title from Album')
rs 0] rs[
Row(AlbumId=1, Title='For Those About To Rock We Salute You')
'F'), limit=5) a.get(a.c.Title.startswith(
[Row(AlbumId=1, Title='For Those About To Rock We Salute You', ArtistId=1),
Row(AlbumId=7, Title='Facelift', ArtistId=5),
Row(AlbumId=60, Title='Fireball', ArtistId=58),
Row(AlbumId=88, Title='Faceless', ArtistId=87),
Row(AlbumId=99, Title='Fear Of The Dark', ArtistId=90)]
This is the query that ran behind the scenes:
print(a.select().where(a.c.Title.startswith('F')).limit(5))
SELECT "Album"."AlbumId", "Album"."Title", "Album"."ArtistId"
FROM "Album"
WHERE ("Album"."Title" LIKE :Title_1 || '%')
LIMIT :param_1
db.close()