So as part of learning sql alchemy I am querying the chinook database, following documentation and my lesson structure I believe I have setup the correct format for querying my tables.
### --- USING SQL ALCHEMY TO QUERY DATABASES --- ###
### --- IMPORT --- ###
from sqlalchemy import (
create_engine, Table, Column, Float, ForeignKey, Integer, String, MetaData
)
### --- SETUP DB --- ###
# executing the instructions from our localhost "chinook" db
#(3/// means hosted locally)
db = create_engine("postgresql:///chinook")
# save a collection about our table objects and the data inside them
meta = MetaData(db)
### --- QUERY --- ###
#1. create variable for table we want to utilize
#(we feed in the subheadings we want, artist, id, name)
artist_table = Table(
"Artist", meta,
Column("ArtistId", Integer, primary_key=True),
Column("Name", String)
)
#variable for album other tables would be made in the same way
album_table = Table(
"Album", meta,
Column("AlbumId", Integer, primary_key=True),
Column("Title", String),
Column("ArtistId", Integer, ForeignKey("artist_table.ArtistId"))
)
#seeing as artist id is a key that's linked from artist this is a foreign key for this table
#pretty much we want to set the table and column to point to
track_table = Table(
"Track", meta,
Column("TrackId", Integer, primary_key=True),
Column("Name", String),
Column("AlbumId", Integer, ForeignKey("album_table.AlbumId")),
Column("MediaTypeId", Integer, primary_key=False),
Column("GenreId", Integer, primary_key=False),
Column("Composer", String),
Column("Milliseconds", Integer),
Column("Bytes", Integer),
Column("UnitPrice", Float)
)
However when i run the actual queries i get this error
Traceback (most recent call last):
File "/workspace/PostGres_Chinook_Example/sql-expressions.py", line 15, in <module>
meta = MetaData(db)
^^^^^^^^^^^^
File "/workspace/.pip-modules/lib/python3.12/site-packages/sqlalchemy/sql/schema.py", line 5481, in __init__
raise exc.ArgumentError(
sqlalchemy.exc.ArgumentError: expected schema argument to be a string, got <class 'sqlalchemy.engine.base.Engine'>.
Im not sure where i'm going wrong outside of it possibly being the version of sqlalchemy (which i tried changing and it threw a different error entirely)
Any direction on where i'm going wrong here would be appreciated.
The metadata exists independently from the engine so you don't explicitly tie them together. Ie. Don't pass db to MetaData().
Once you fully define the metadata (and the tables) you can then use the engine to create the metadata like
metadata.create_all(engine)
https://docs.sqlalchemy.org/en/20/core/metadata.html#creating-and-dropping-database-tables