Skip to content

fastai/fastsql1

Repository files navigation

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.

from fastsql import conn_db
from fastcore.utils import *
url = 'https://github.com/lerocha/chinook-database/raw/master/ChinookDatabase/DataSources/Chinook_Sqlite.sqlite'
path = Path('chinook.sqlite')
if not path.exists(): urlsave(url, path)
connstr = f"sqlite:///{path}"
db = conn_db(connstr)
' '.join(db.tables)
'Album Artist Customer Employee Genre Invoice InvoiceLine Track MediaType Playlist PlaylistTrack'
a = db.Album
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.

rs = db.sql('select AlbumId,Title from Album')
rs[0]
Row(AlbumId=1, Title='For Those About To Rock We Salute You')
a.get(a.c.Title.startswith('F'), limit=5)
[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)]
db.close()