diff --git a/Chinook_Sqlite.sqlite b/Chinook_Sqlite.sqlite new file mode 100644 index 0000000..00a750d Binary files /dev/null and b/Chinook_Sqlite.sqlite differ diff --git a/Essential-SQLAlchemy-2nd.org b/Essential-SQLAlchemy-2nd.org index d1b6e84..94c9d3e 100644 --- a/Essential-SQLAlchemy-2nd.org +++ b/Essential-SQLAlchemy-2nd.org @@ -3173,3 +3173,73 @@ sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) CHECK constraint failed: assert results == cookie_orders #+END_SRC + +* Chapter 5: Reflection + +** SQLAlchemy v2 +:PROPERTIES: +:header-args: :tangle ch5-v2.py +:header-args:python: :session *ch5* +:END: + +#+BEGIN_SRC python :results none + from sqlalchemy import MetaData, create_engine + metadata = MetaData() + engine = create_engine("sqlite:///Chinook_Sqlite.sqlite") +#+END_SRC + +#+BEGIN_SRC python :results table + from sqlalchemy import Table + + artist = Table("Artist", metadata, autoload_with=engine) + artist.columns.keys() +#+END_SRC + +#+RESULTS: +| ArtistId | Name | + +#+BEGIN_SRC python :results table + from sqlalchemy import select + + with engine.begin() as connection: + s = select(artist).limit(10) + result = connection.execute(s).fetchall() + result +#+END_SRC + +#+RESULTS: +| 1 | AC/DC | +| 2 | Accept | +| 3 | Aerosmith | +| 4 | Alanis Morissette | +| 5 | Alice In Chains | +| 6 | Antônio Carlos Jobim | +| 7 | Apocalyptica | +| 8 | Audioslave | +| 9 | BackBeat | +| 10 | Billy Cobham | + +#+BEGIN_SRC python :results value + album = Table('Album', metadata, autoload_with=engine) + res = metadata.tables['Album'] + repr(res) +#+END_SRC + +#+RESULTS: +: Table('Album', MetaData(), Column('AlbumId', INTEGER(), table=, primary_key=True, nullable=False), Column('Title', NVARCHAR(length=160), table=, nullable=False), Column('ArtistId', INTEGER(), ForeignKey('Artist.ArtistId'), table=, nullable=False), schema=None) + +#+BEGIN_SRC python :results value + album.foreign_keys +#+END_SRC + +#+RESULTS: +: {ForeignKey('Artist.ArtistId')} + +*** Reflecting a Whole Database +#+BEGIN_SRC python :results table + metadata.reflect(bind=engine) + list(metadata.tables.keys()) +#+END_SRC + +#+RESULTS: +| Artist | Album | Customer | Employee | Genre | Invoice | InvoiceLine | Track | MediaType | Playlist | PlaylistTrack |