### Manually Build and Install Cython Extensions Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/intro.rst Installs Cython, pre-builds the C extensions for performance optimization, and completes the setup.py installation. ```shell # cd into SQLAlchemy source distribution cd path/to/sqlalchemy # install cython pip install cython # optionally build Cython extensions ahead of install python setup.py build_ext # run the install python setup.py install ``` -------------------------------- ### Run dogpile_caching examples as Python modules Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/orm/examples.rst Run these commands to execute the dogpile.cache examples in order of complexity. Both SQLAlchemy and dogpile.cache must be installed or on the current PYTHONPATH. The demo creates a local datafiles directory, inserts initial data, and runs; a second run uses existing cache files and emits exactly one SQL statement against two tables, while the displayed result uses dozens of lazyloads that all pull from cache. ```shell $ python -m examples.dogpile_caching.helloworld $ python -m examples.dogpile_caching.relationship_caching $ python -m examples.dogpile_caching.advanced $ python -m examples.dogpile_caching.local_session_caching ``` -------------------------------- ### Run performance example with default settings Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/orm/examples.rst Run a performance example using default settings. This is the basic command to execute a performance test module. ```bash $ python -m examples.performance bulk_inserts ``` -------------------------------- ### Run performance example with options Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/orm/examples.rst Run a performance example with custom database URL, profiling, and iteration count. Use --dburl to specify the database, --profile to enable profiling, and --num to set iterations. ```bash $ python -m examples.performance bulk_inserts \ --dburl mysql+mysqldb://scott:tiger@localhost/test \ --profile --num 1000 ``` -------------------------------- ### Run Space Invaders example Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/orm/examples.rst Runs the Space Invaders example using ASCII art in a textual console. Requires Python 3. ```bash $ python -m examples.space_invaders.space_invaders ``` -------------------------------- ### Install SQLAlchemy with asyncio Extra Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/faq/installation.rst Installs SQLAlchemy along with the greenlet dependency needed for asyncio support. Use this when encountering errors indicating that greenlet is not installed. ```text pip install sqlalchemy[asyncio] ``` -------------------------------- ### Legacy Session.bulk_insert_mappings example Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/orm/queryguide/dml.rst Legacy bulk insert method that lacks RETURNING support and session-synchronization. Shown here as the starting point for porting to the new API. ```python session.bulk_insert_mappings(User, [{"name": "u1"}, {"name": "u2"}, {"name": "u3"}]) ``` -------------------------------- ### Query with Dogpile Caching using FromCache and RelationshipCache Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/orm/examples.rst Use this pattern to cache ORM query results and relationship loads with dogpile.cache. Requires the examples.dogpile_caching setup and the FromCache and RelationshipCache options. ```python # query for Person objects, specifying cache stmt = select(Person).options(FromCache("default")) # specify that each Person's "addresses" collection comes from # cache too stmt = stmt.options(RelationshipCache(Person.addresses, "default")) # execute and results result = session.execute(stmt) print(result.scalars().all()) ``` -------------------------------- ### Directed Graphs Example Usage Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/orm/examples.rst Illustrates creating nodes, adding a neighbor, and printing higher neighbors. ```python n2 = Node(2) n5 = Node(5) n2.add_neighbor(n5) print(n2.higher_neighbors()) ``` -------------------------------- ### Define declarative models for duplicate join examples Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/changelog/migration_10.rst Setup mapping for tables A and B with a relationship between them to test duplicate join behavior. ```python from sqlalchemy import Integer, Column, String, ForeignKey from sqlalchemy.orm import Session, relationship from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class A(Base): __tablename__ = "a" id = Column(Integer, primary_key=True) bs = relationship("B") class B(Base): __tablename__ = "b" id = Column(Integer, primary_key=True) a_id = Column(ForeignKey("a.id")) ``` -------------------------------- ### Install SQLAlchemy Manually from Source Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/intro.rst Installs SQLAlchemy from the source distribution using setup.py. It will attempt to build Cython extensions if tools are available and fall back to pure Python otherwise. ```shell python setup.py install ``` -------------------------------- ### Run versioning example tests with pytest Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/orm/examples.rst Runs the unit test module test_versioning.py using SQLAlchemy's internal pytest plugin. ```bash $ pytest test/base/test_examples.py ``` -------------------------------- ### Run all tests with timing output Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/orm/examples.rst Run all tests in a performance example and display timing results for each test. This is the default form of run. ```bash $ python -m examples.performance single_inserts Tests to run: test_orm_commit, test_bulk_save, test_bulk_insert_dictionaries, test_core, test_core_query_caching, test_dbapi_raw_w_connect, test_dbapi_raw_w_pool test_orm_commit : Individual INSERT/COMMIT pairs via the ORM (10000 iterations); total time 13.690218 sec test_bulk_save : Individual INSERT/COMMIT pairs using the "bulk" API (10000 iterations); total time 11.290371 sec test_bulk_insert_dictionaries : Individual INSERT/COMMIT pairs using the "bulk" API with dictionaries (10000 iterations); total time 10.814626 sec test_core : Individual INSERT/COMMIT pairs using Core. (10000 iterations); total time 9.665620 sec test_core_query_caching : Individual INSERT/COMMIT pairs using Core with query caching (10000 iterations); total time 9.209010 sec test_dbapi_raw_w_connect : Individual INSERT/COMMIT pairs w/ DBAPI + connection each time (10000 iterations); total time 9.551103 sec test_dbapi_raw_w_pool : Individual INSERT/COMMIT pairs w/ DBAPI + connection pool (10000 iterations); total time 8.001813 sec ``` -------------------------------- ### Install SQLAlchemy with asyncio extra Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/orm/extensions/asyncio.rst Installs SQLAlchemy with the [asyncio] setuptools extra, which includes the greenlet dependency. Use this to ensure greenlet is installed for the asyncio extension. ```text pip install sqlalchemy[asyncio] ``` -------------------------------- ### SQL output for aggregate_order_by example Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/dialects/postgresql.rst The SQL expression represented by the aggregate_order_by example. ```sql SELECT array_agg(a ORDER BY b DESC) FROM table; ``` -------------------------------- ### Tail Space Invaders SQL log Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/orm/examples.rst While the Space Invaders example runs, watch the SQL output in the log. ```bash $ tail -f space_invaders.log ``` -------------------------------- ### Define User and Book mappings and insert column loading fixture data Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/orm/queryguide/_deferred_setup.rst Sets up the DeclarativeBase schema for User and Book models and populates an in-memory SQLite database with sample records for column loading query guide examples. ```python >>> from typing import List >>> from typing import Optional >>> >>> from sqlalchemy import Column >>> from sqlalchemy import create_engine >>> from sqlalchemy import ForeignKey >>> from sqlalchemy import LargeBinary >>> from sqlalchemy import Table >>> from sqlalchemy import Text >>> from sqlalchemy.orm import DeclarativeBase >>> from sqlalchemy.orm import Mapped >>> from sqlalchemy.orm import mapped_column >>> from sqlalchemy.orm import relationship >>> from sqlalchemy.orm import Session >>> >>> >>> class Base(DeclarativeBase): ... pass >>> class User(Base): ... __tablename__ = "user_account" ... id: Mapped[int] = mapped_column(primary_key=True) ... name: Mapped[str] ... fullname: Mapped[Optional[str]] ... books: Mapped[List["Book"]] = relationship(back_populates="owner") ... ... def __repr__(self) -> str: ... return f"User(id={self.id!r}, name={self.name!r}, fullname={self.fullname!r})" >>> class Book(Base): ... __tablename__ = "book" ... id: Mapped[int] = mapped_column(primary_key=True) ... owner_id: Mapped[int] = mapped_column(ForeignKey("user_account.id")) ... title: Mapped[str] ... summary: Mapped[str] = mapped_column(Text) ... cover_photo: Mapped[bytes] = mapped_column(LargeBinary) ... owner: Mapped["User"] = relationship(back_populates="books") ... ... def __repr__(self) -> str: ... return f"Book(id={self.id!r}, title={self.title!r})" >>> engine = create_engine("sqlite+pysqlite:///:memory:", echo=True) >>> Base.metadata.create_all(engine) BEGIN ... >>> conn = engine.connect() >>> session = Session(conn) >>> session.add_all( ... [ ... User( ... name="spongebob", ... fullname="Spongebob Squarepants", ... books=[ ... Book( ... title="100 Years of Krabby Patties", ... summary="some long summary", ... cover_photo=b"binary_image_data", ... ), ... Book( ... title="Sea Catch 22", ... summary="another long summary", ... cover_photo=b"binary_image_data", ... ), ... Book( ... title="The Sea Grapes of Wrath", ... summary="yet another summary", ... cover_photo=b"binary_image_data", ... ), ... ], ... ), ... User( ... name="sandy", ... fullname="Sandy Cheeks", ... books=[ ... Book( ... title="A Nut Like No Other", ... summary="some long summary", ... cover_photo=b"binary_image_data", ... ), ... Book( ... title="Geodesic Domes: A Retrospective", ... summary="another long summary", ... cover_photo=b"binary_image_data", ... ), ... Book( ... title="Rocketry for Squirrels", ... summary="yet another summary", ... cover_photo=b"binary_image_data", ... ), ... ], ... ), ... ] ... ) >>> session.commit() BEGIN ... COMMIT >>> session.close() >>> conn.begin() BEGIN ... ``` -------------------------------- ### Install SQLAlchemy via pip Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/intro.rst Downloads and installs the latest released version of SQLAlchemy from PyPI. For most common platforms, a prebuilt wheel with native Cython/C extensions is installed. ```shell pip install sqlalchemy ``` -------------------------------- ### Imports for logging example Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/core/connections.rst These imports are used in the logging example to demonstrate cache performance estimation. They include Core and ORM components. ```python from sqlalchemy import Column from sqlalchemy import create_engine from sqlalchemy import ForeignKey from sqlalchemy import Integer from sqlalchemy import select from sqlalchemy import String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from sqlalchemy.orm import Session ``` -------------------------------- ### JSONB usage example Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/dialects/postgresql.rst Example of using JSONB in a table definition and inserting data. ```python data_table = Table( "data_table", metadata, Column("id", Integer, primary_key=True), Column("data", JSONB), ) with engine.connect() as conn: conn.execute( data_table.insert(), data={"key1": "value1", "key2": "value2"} ) ``` -------------------------------- ### Adjacency List Example Usage Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/orm/examples.rst Shows how to create a TreeNode, append child nodes, add to a session, commit, and dump the tree. ```python node = TreeNode("rootnode") node.append("node1") node.append("node3") session.add(node) session.commit() dump_tree(node) ``` -------------------------------- ### Create DOMAIN examples Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/dialects/postgresql.rst Examples of creating DOMAIN types with constraints. PositiveInt restricts values to be greater than 0 and not null; UsPostalCode restricts values to match US postal code patterns. ```python PositiveInt = DOMAIN("pos_int", Integer, check="VALUE > 0", not_null=True) UsPostalCode = DOMAIN( "us_postal_code", Text, check="VALUE ~ '^\d{5}$' OR VALUE ~ '^\d{5}-\d{4}$'", ) ``` -------------------------------- ### Create a Table with columns Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/core/metadata.rst Example of constructing a Table with columns using MetaData. ```python from sqlalchemy import Table, MetaData, Integer, String, Column metadata = MetaData() mytable = Table( "mytable", metadata, Column("mytable_id", Integer, primary_key=True), Column("value", String(50)), ) ``` -------------------------------- ### Import uuid for custom naming convention token Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/core/constraints.rst Start of an example for adding a custom token to a naming convention using a GUID scheme. The import is the only code shown. ```python import uuid ``` -------------------------------- ### Performance Suite Command Line Help Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/orm/examples.rst Shows the command line help output for running performance suites. ```bash $ python -m examples.performance --help usage: python -m examples.performance [-h] [--test TEST] [--dburl DBURL] [--num NUM] [--profile] [--dump] [--echo] {bulk_inserts,large_resultsets,single_inserts} positional arguments: {bulk_inserts,large_resultsets,single_inserts} suite to run ``` -------------------------------- ### Setup imports and Base class for relationship examples Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/orm/basic_relationships.rst Common imports and declarative Base class used throughout the relationship pattern examples. ```python from __future__ import annotations from typing import List from sqlalchemy import ForeignKey from sqlalchemy import Integer from sqlalchemy.orm import Mapped from sqlalchemy.orm import mapped_column from sqlalchemy.orm import DeclarativeBase from sqlalchemy.orm import relationship class Base(DeclarativeBase): pass ``` -------------------------------- ### Register entry points in setup.py Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/README.dialects.rst Configures setuptools entry points to expose dialect plugins so they can be loaded by create_engine(). ```python entry_points = { "sqlalchemy.dialects": [ "access.pyodbc = sqlalchemy_access.pyodbc:AccessDialect_pyodbc", ] } ``` -------------------------------- ### Execute an ORM SELECT with Session and get entity rows Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/tutorial/data_select.rst Use Session.execute() with a select() against an ORM class to get Row objects that contain ORM entities. The example shows the emitted SQL and the returned row containing a User instance. ```python >>> stmt = select(User).where(User.name == "spongebob") >>> with Session(engine) as session: ... for row in session.execute(stmt): ... print(row) {execsql}BEGIN (implicit) SELECT user_account.id, user_account.name, user_account.fullname FROM user_account WHERE user_account.name = ? [...] ('spongebob',){stop} (User(id=1, name='spongebob', fullname='Spongebob Squarepants'),) {execsql}ROLLBACK{stop} ``` -------------------------------- ### Chain contains_eager for nested relationships Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/orm/queryguide/relationships.rst For a full path from the starting entity, chain contains_eager calls. Example loads User->orders->Order->items->Item. ```python stmt = select(User).options(contains_eager(User.orders).contains_eager(Order.items)) ``` -------------------------------- ### Instantiate engine using dialect entry point URL Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/README.dialects.rst Demonstrates connecting with create_engine using the registered entry point URL scheme. ```python create_engine("access+pyodbc://user:pw@dsn") ``` -------------------------------- ### DOMAIN.__init__ method Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/dialects/postgresql.rst Construct a DOMAIN. ```python def DOMAIN.__init__(self, name: str, data_type: _TypeEngineArgument[Any], *, collation: Optional[str]=None, collation_schema: Optional[str]=None, default: Union[elements.TextClause, str, None]=None, constraint_name: Optional[str]=None, not_null: Optional[bool]=None, check: Union[elements.TextClause, str, None]=None, create_type: bool=True, **kw: Any) ``` -------------------------------- ### Inspect an AliasedClass to get AliasedInsp Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/orm/queryguide/api.rst Use sqlalchemy.inspect on an AliasedClass instance to obtain an AliasedInsp object. This example imports both inspect and aliased. ```python from sqlalchemy import inspect from sqlalchemy.orm import aliased my_alias = aliased(MyMappedClass) insp = inspect(my_alias) ``` -------------------------------- ### Legacy Session.bulk_update_mappings example Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/orm/queryguide/dml.rst The legacy bulk_update_mappings method performs bulk update but lacks session-synchronization features. This example shows the legacy form. ```python session.bulk_update_mappings( User, [ {"id": 1, "name": "scheeks", "manager_name": "Sandy Cheeks, President"}, {"id": 2, "name": "eugene", "manager_name": "Eugene H. Krabs, VP Marketing"}, ], ) ``` -------------------------------- ### Using inspect() to get InstanceState and attribute history Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/orm/internals.rst Example of acquiring an InstanceState object via inspect() and accessing attribute history. ```python >>> from sqlalchemy import inspect >>> insp = inspect(some_mapped_object) >>> insp.attrs.nickname.history History(added=['new nickname'], unchanged=(), deleted=['nickname']) ``` -------------------------------- ### Configure MariaDB Docker container for testing Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/README.unittests.rst Starts a MariaDB Docker container configured with utf8mb4 encoding, sets up the test_schema database, and grants permissions to user scott. ```bash # create the container with the proper configuration for sqlalchemy docker run --rm -e MARIADB_USER='scott' -e MARIADB_PASSWORD='tiger' -e MARIADB_DATABASE='test' -e MARIADB_ROOT_PASSWORD='password' -p 127.0.0.1:3306:3306 -d --name mariadb mariadb --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci # configure the database sleep 20 docker exec -ti mariadb mariadb -u root -ppassword -w -e "CREATE DATABASE test_schema CHARSET utf8mb4; GRANT ALL ON test_schema.* TO scott;" # To stop the container. It will also remove it. docker stop mariadb ``` -------------------------------- ### Define Book model with DeclarativeBase Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/orm/queryguide/columns.rst Defines a Book ORM class with columns and a foreign key. Used as setup for examples in this section. ```python >>> class Base(DeclarativeBase): ... pass >>> class Book(Base): ... __tablename__ = "book" ... id: Mapped[int] = mapped_column(primary_key=True) ... owner_id: Mapped[int] = mapped_column(ForeignKey("user_account.id")) ... title: Mapped[str] ... summary: Mapped[str] = mapped_column(Text) ... cover_photo: Mapped[bytes] = mapped_column(LargeBinary) ... ... def __repr__(self) -> str: ... return f"Book(id={self.id!r}, title={self.title!r})" ``` -------------------------------- ### Get History object using inspect Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/orm/session_api.rst Example showing how to obtain a History object for a particular attribute on an object using the inspect function. ```python from sqlalchemy import inspect hist = inspect(myobject).attrs.myattribute.history ``` -------------------------------- ### Configure MySQL Docker container for testing Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/README.unittests.rst Starts a MySQL Docker container configured with utf8mb4 encoding, creates the test_schema database, and grants permissions to user scott. ```bash # create the container with the proper configuration for sqlalchemy docker run --rm -e MYSQL_USER='scott' -e MYSQL_PASSWORD='tiger' -e MYSQL_DATABASE='test' -e MYSQL_ROOT_PASSWORD='password' -p 127.0.0.1:3306:3306 -d --name mysql mysql --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci # configure the database sleep 20 docker exec -ti mysql mysql -u root -ppassword -w -e "CREATE DATABASE test_schema CHARSET utf8mb4; GRANT ALL ON test_schema.* TO scott;" # To stop the container. It will also remove it. docker stop mysql ``` -------------------------------- ### Open and Begin Session Simultaneously with sessionmaker.begin() Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/orm/session_transaction.rst Uses sessionmaker.begin() as a context manager to instantiate the session, begin a transaction, and commit upon exiting. ```python with Session.begin() as session: session.add(some_object) ``` -------------------------------- ### Define User and Book models with DeclarativeBase Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/orm/queryguide/columns.rst Defines User and Book ORM classes with relationships and columns. Used as setup for examples in this section. ```python >>> class Base(DeclarativeBase): ... pass >>> class User(Base): ... __tablename__ = "user_account" ... id: Mapped[int] = mapped_column(primary_key=True) ... name: Mapped[str] ... fullname: Mapped[Optional[str]] ... books: Mapped[List["Book"]] = relationship(back_populates="owner") ... ... def __repr__(self) -> str: ... return f"User(id={self.id!r}, name={self.name!r}, fullname={self.fullname!r})" >>> class Book(Base): ... __tablename__ = "book" ... id: Mapped[int] = mapped_column(primary_key=True) ... owner_id: Mapped[int] = mapped_column(ForeignKey("user_account.id")) ... title: Mapped[str] ... summary: Mapped[str] = mapped_column(Text) ... cover_photo: Mapped[bytes] = mapped_column(LargeBinary) ... owner: Mapped["User"] = relationship(back_populates="books") ... ... def __repr__(self) -> str: ... return f"Book(id={self.id!r}, title={self.title!r})" ``` -------------------------------- ### Registering a dialect in-process with registry.register Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/core/connections.rst Use the registry.register() function to register a dialect within the current process, bypassing separate installation. This example registers 'mysql.foodialect' to load MyMySQLDialect from myapp.dialect. ```python from sqlalchemy.dialects import registry registry.register("mysql.foodialect", "myapp.dialect", "MyMySQLDialect") ``` -------------------------------- ### Create custom performance test suite Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/orm/examples.rst Define a custom performance test suite using the Profiler class. This example sets up a parent-child relationship and initializes the profiler with a test name and default number of items. ```python from examples.performance import Profiler from sqlalchemy import Integer, Column, create_engine, ForeignKey from sqlalchemy.orm import relationship, joinedload, subqueryload, Session from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() engine = None session = None class Parent(Base): __tablename__ = "parent" id = Column(Integer, primary_key=True) children = relationship("Child") class Child(Base): __tablename__ = "child" id = Column(Integer, primary_key=True) parent_id = Column(Integer, ForeignKey("parent.id")) # Init with name of file, default number of items Profiler.init("test_loads", 1000) @Profiler.setup_once def setup_once(dburl, echo, num): "setup once. create an engine, insert fixture data" global engine engine = create_engine(dburl, echo=echo) Base.metadata.drop_all(engine) Base.metadata.create_all(engine) sess = Session(engine) sess.add_all( … ``` -------------------------------- ### Transaction usage example Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/core/connections.rst Shows how to begin a transaction, execute a statement, and commit using the Transaction object. ```python from sqlalchemy import create_engine engine = create_engine("postgresql+psycopg2://scott:tiger@localhost/test") connection = engine.connect() trans = connection.begin() connection.execute(text("insert into x (a, b) values (1, 2)")) trans.commit() ``` -------------------------------- ### Execute a SELECT statement with Connection and iterate rows Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/tutorial/data_select.rst Pass the SELECT statement to Connection.execute() and iterate the Result to get Row objects. The example shows the emitted SQL and the returned row. ```python >>> with engine.connect() as conn: ... for row in conn.execute(stmt): ... print(row) {execsql}BEGIN (implicit) SELECT user_account.id, user_account.name, user_account.fullname FROM user_account WHERE user_account.name = ? [...] ('spongebob',){stop} (1, 'spongebob', 'Spongebob Squarepants') {execsql}ROLLBACK{stop} ``` -------------------------------- ### Insert fixture data for joined inheritance example Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/orm/queryguide/_inheritance_setup.rst Creates a Session bound to a connection and adds a Company with Manager and Engineer employees, including paperwork for the manager. Commits the transaction. ```python >>> conn = engine.connect() >>> from sqlalchemy.orm import Session >>> session = Session(conn) >>> session.add( ... Company( ... name="Krusty Krab", ... employees=[ ... Manager( ... name="Mr. Krabs", ... manager_name="Eugene H. Krabs", ... paperwork=[ ... Paperwork(document_name="Secret Recipes"), ... Paperwork(document_name="Krabby Patty Orders"), ... ], ... ), ... Engineer(name="SpongeBob", engineer_info="Krabby Patty Master"), ... Engineer( ... name="Squidward", ... engineer_info="Senior Customer Engagement Engineer", ... ), ... ], ... ) ... ) >>> session.commit() BEGIN ... ``` -------------------------------- ### Setup SQLite database engine and session Source: https://github.com/sqlalchemy/sqlalchemy/wiki/imported_issue_attachments/3108/nested_rollback.rst Initializes an in-memory SQLite engine, creates mapped database schema tables, and instantiates a sessionmaker session. ```python >>> engine = create_engine("sqlite:///") >>> Base.metadata.create_all(engine) >>> Session = sessionmaker(engine) >>> session = Session() ``` -------------------------------- ### Registering a new dialect via setup.cfg entry point Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/core/connections.rst Define a custom dialect entry point in setup.cfg under [options.entry_points] with the sqlalchemy.dialects group. This example registers a dialect named 'foodialect'. ```ini [options.entry_points] sqlalchemy.dialects = foodialect = foodialect.dialect:FooDialect ``` -------------------------------- ### Using return_none_on to return None when all composite columns are None Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/changelog/migration_21.rst The return_none_on parameter accepts a callable that returns True if the composite should be None. This example returns None for start and end when both composite columns are None. ```python class Vertex(Base): __tablename__ = "vertices" id: Mapped[int] = mapped_column(primary_key=True) start: Mapped[Point] = composite( mapped_column("x1"), mapped_column("y1"), return_none_on=lambda x, y: x is None and y is None, ) end: Mapped[Point] = composite( mapped_column("x2"), mapped_column("y2"), return_none_on=lambda x, y: x is None and y is None, ) ``` -------------------------------- ### Install SQLAlchemy in virtual environment with pip install Source: https://github.com/sqlalchemy/sqlalchemy/wiki/imported_issue_attachments/3761/issue.txt Attempts to install SQLAlchemy in a virtualenv, resulting in a setup.py bdist_wheel build failure. ```shell (venv) C:\Users\fmoor>pip install sqlalchemy Collecting sqlalchemy Using cached SQLAlchemy-1.0.14.tar.gz Building wheels for collected packages: sqlalchemy Running setup.py bdist_wheel for sqlalchemy ... error Complete output from command c:\users\fmoor\venv\scripts\python.exe -u -c "import setuptools, tokenize;__file__='c:\\u sers\\fmoor\\appdata\\local\\temp\\pip-build-frbkyi\\sqlalchemy\\setup.py';exec(compile(getattr(tokenize, 'open', open)( __file__).read().replace('\r\n', '\n'), __file__, 'exec'))" bdist_wheel -d c:\users\fmoor\appdata\local\temp\tmpsf3aaspi p-wheel- --python-tag cp27: running bdist_wheel running build running build_py creating build creating build\lib.win32-2.7 creating build\lib.win32-2.7\sqlalchemy copying lib\sqlalchemy\events.py -> build\lib.win32-2.7\sqlalchemy copying lib\sqlalchemy\exc.py -> build\lib.win32-2.7\sqlalchemy copying lib\sqlalchemy\inspection.py -> build\lib.win32-2.7\sqlalchemy copying lib\sqlalchemy\interfaces.py -> build\lib.win32-2.7\sqlalchemy copying lib\sqlalchemy\log.py -> build\lib.win32-2.7\sqlalchemy copying lib\sqlalchemy\pool.py -> build\lib.win32-2.7\sqlalchemy copying lib\sqlalchemy\processors.py -> build\lib.win32-2.7\sqlalchemy copying lib\sqlalchemy\schema.py -> build\lib.win32-2.7\sqlalchemy copying lib\sqlalchemy\types.py -> build\lib.win32-2.7\sqlalchemy copying lib\sqlalchemy\__init__.py -> build\lib.win32-2.7\sqlalchemy creating build\lib.win32-2.7\sqlalchemy\connectors copying lib\sqlalchemy\connectors\mxodbc.py -> build\lib.win32-2.7\sqlalchemy\connectors copying lib\sqlalchemy\connectors\pyodbc.py -> build\lib.win32-2.7\sqlalchemy\connectors copying lib\sqlalchemy\connectors\zxJDBC.py -> build\lib.win32-2.7\sqlalchemy\connectors copying lib\sqlalchemy\connectors\__init__.py -> build\lib.win32-2.7\sqlalchemy\connectors creating build\lib.win32-2.7\sqlalchemy\databases copying lib\sqlalchemy\databases\__init__.py -> build\lib.win32-2.7\sqlalchemy\databases creating build\lib.win32-2.7\sqlalchemy\dialects copying lib\sqlalchemy\dialects\postgres.py -> build\lib.win32-2.7\sqlalchemy\dialects copying lib\sqlalchemy\dialects\__init__.py -> build\lib.win32-2.7\sqlalchemy\dialects creating build\lib.win32-2.7\sqlalchemy\dialects\firebird copying lib\sqlalchemy\dialects\firebird\base.py -> build\lib.win32-2.7\sqlalchemy\dialects\firebird copying lib\sqlalchemy\dialects\firebird\fdb.py -> build\lib.win32-2.7\sqlalchemy\dialects\firebird copying lib\sqlalchemy\dialects\firebird\kinterbasdb.py -> build\lib.win32-2.7\sqlalchemy\dialects\firebird copying lib\sqlalchemy\dialects\firebird\__init__.py -> build\lib.win32-2.7\sqlalchemy\dialects\firebird creating build\lib.win32-2.7\sqlalchemy\dialects\mssql copying lib\sqlalchemy\dialects\mssql\adodbapi.py -> build\lib.win32-2.7\sqlalchemy\dialects\mssql copying lib\sqlalchemy\dialects\mssql\base.py -> build\lib.win32-2.7\sqlalchemy\dialects\mssql copying lib\sqlalchemy\dialects\mssql\information_schema.py -> build\lib.win32-2.7\sqlalchemy\dialects\mssql copying lib\sqlalchemy\dialects\mssql\mxodbc.py -> build\lib.win32-2.7\sqlalchemy\dialects\mssql copying lib\sqlalchemy\dialects\mssql\pymssql.py -> build\lib.win32-2.7\sqlalchemy\dialects\mssql copying lib\sqlalchemy\dialects\mssql\pyodbc.py -> build\lib.win32-2.7\sqlalchemy\dialects\mssql copying lib\sqlalchemy\dialects\mssql\zxjdbc.py -> build\lib.win32-2.7\sqlalchemy\dialects\mssql copying lib\sqlalchemy\dialects\mssql\__init__.py -> build\lib.win32-2.7\sqlalchemy\dialects\mssql creating build\lib.win32-2.7\sqlalchemy\dialects\mysql copying lib\sqlalchemy\dialects\mysql\base.py -> build\lib.win32-2.7\sqlalchemy\dialects\mysql copying lib\sqlalchemy\dialects\mysql\cymysql.py -> build\lib.win32-2.7\sqlalchemy\dialects\mysql copying lib\sqlalchemy\dialects\mysql\gaerdbms.py -> build\lib.win32-2.7\sqlalchemy\dialects\mysql copying lib\sqlalchemy\dialects\mysql\mysqlconnector.py -> build\lib.win32-2.7\sqlalchemy\dialects\mysql copying lib\sqlalchemy\dialects\mysql\mysqldb.py -> build\lib.win32-2.7\sqlalchemy\dialects\mysql copying lib\sqlalchemy\dialects\mysql\oursql.py -> build\lib.win32-2.7\sqlalchemy\dialects\mysql copying lib\sqlalchemy\dialects\mysql\pymysql.py -> build\lib.win32-2.7\sqlalchemy\dialects\mysql ``` -------------------------------- ### Cross-compatible transaction management with begin() blocks Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/changelog/migration_20.rst Illustrates 1.x and 2.0 cross-compatible execution using engine.begin() or connection-level with conn.begin() context blocks. ```python with engine.begin() as conn: conn.execute(some_table.insert().values(foo="bar")) conn.execute(some_other_table.insert().values(bat="hoho")) with engine.connect() as conn: with conn.begin(): conn.execute(some_table.insert().values(foo="bar")) conn.execute(some_other_table.insert().values(bat="hoho")) with engine.begin() as conn: conn.execute(text("EXEC my_procedural_thing()")) ``` -------------------------------- ### Use sessionmaker.begin context manager Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/changelog/migration_20.rst Creates a Session and manages the transaction lifecycle within a single context block. ```python from sqlalchemy.orm import sessionmaker Session = sessionmaker(engine) with Session.begin() as session: session.add(MyObject()) ``` -------------------------------- ### Configure create_engine URLs for PostgreSQL, MySQL, Oracle, and MSSQL Source: https://github.com/sqlalchemy/sqlalchemy/wiki/imported_issue_attachments/1850/dbengine.txt Demonstrates URL connection strings for standard relational database backends specifying dialects, DBAPI drivers, credentials, hosts, ports, database names, or DSNs. If drivername is omitted, the dialect's default DBAPI driver is loaded. ```python # postgresql - psycopg2 is the default driver. pg_db = create_engine('postgresql://scott:tiger@localhost/mydatabase') pg_db = create_engine('postgresql+psycopg2://scott:tiger@localhost/mydatabase') pg_db = create_engine('postgresql+pg8000://scott:tiger@localhost/mydatabase') # postgresql on Jython pg_db = create_engine('postgresql+zxjdbc://scott:tiger@localhost/mydatabase') # mysql - MySQLdb (mysql-python) is the default driver mysql_db = create_engine('mysql://scott:tiger@localhost/foo') mysql_db = create_engine('mysql+mysqldb://scott:tiger@localhost/foo') # mysql on Jython mysql_db = create_engine('mysql+zxjdbc://localhost/foo') # mysql with pyodbc (buggy) mysql_db = create_engine('mysql+pyodbc://scott:tiger@some_dsn') # oracle - cx_oracle is the default driver oracle_db = create_engine('oracle://scott:tiger@127.0.0.1:1521/sidname') # oracle via TNS name oracle_db = create_engine('oracle+cx_oracle://scott:tiger@tnsname') # mssql using ODBC datasource names. PyODBC is the default driver. mssql_db = create_engine('mssql://mydsn') mssql_db = create_engine('mssql+pyodbc://mydsn') mssql_db = create_engine('mssql+adodbapi://mydsn') mssql_db = create_engine('mssql+pyodbc://username:password@mydsn') ``` -------------------------------- ### Manage Transactions with Commit-as-You-Go Pattern Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/orm/session_transaction.rst Demonstrates autobeginning transactions and managing commits, flushes, and rollbacks explicitly on a Session instance. ```python session = Session(engine) session.add(some_object()) session.add(some_other_object()) session.commit() # commits # will automatically begin again result = session.execute(text("< some select statement >")) session.add_all([more_objects, ...]) session.commit() # commits session.add(still_another_object) session.flush() # flush still_another_object session.rollback() # rolls back still_another_object ``` -------------------------------- ### Modern Core Execution with engine.begin Context Manager Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/changelog/migration_13.rst Shows modern Core usage utilizing the engine.begin context manager to automatically manage connections, commits, and rollbacks. ```python with engine.begin() as conn: conn.execute(table.insert(), parameters) result = conn.execute(table.select()) conn.execute(table.update(), parameters) ``` -------------------------------- ### Configure test framework settings in setup.cfg Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/README.dialects.rst Contains pytest options, sqla_testing configuration, and database connection strings for the compliance test suite. ```text [tool:pytest] addopts= --tb native -v -r fxX --maxfail=25 -p no:warnings python_files=test/*test_*.py [sqla_testing] requirement_cls=sqlalchemy_access.requirements:Requirements profile_file=test/profiles.txt [db] default=access+pyodbc://admin@access_test sqlite=sqlite:///:memory: ``` -------------------------------- ### Install psycopg driver Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/changelog/migration_21.rst Install psycopg directly with the binary extra or via SQLAlchemy's postgresql extra, which now installs psycopg. ```text # install psycopg directly pip install "psycopg[binary]" # or use SQLAlchemy's postgresql extra (now installs psycopg) pip install sqlalchemy[postgresql] ``` -------------------------------- ### Using Session with autobegin and explicit begin in 2.0 Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/changelog/migration_20.rst Shows modern session usage where transactions are either explicitly started using `sess.begin()` or automatically initiated via autobegin. ```python from sqlalchemy.orm import Session sess = Session(engine) sess.begin() # begin explicitly; if not called, will autobegin # when database access is needed sess.add(obj) sess.commit() ``` -------------------------------- ### between usage example Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/core/sqlelement.rst Example of using between to create a BETWEEN predicate. ```python from sqlalchemy import between ``` -------------------------------- ### Vertical attribute mapping example Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/orm/examples.rst Illustrates vertical table mappings where individual attributes are stored as distinct rows. The example shows setting attributes and querying using any(). ```python shrew = Animal("shrew") shrew["cuteness"] = 5 shrew["weasel-like"] = False shrew["poisonous"] = True session.add(shrew) session.flush() q = session.query(Animal).filter( Animal.facts.any( and_(AnimalFact.key == "weasel-like", AnimalFact.value == True) ) ) print("weasel-like animals", q.all()) ``` -------------------------------- ### Instantiate a Session with an Engine Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/orm/session_transaction.rst Demonstrates initializing an ORM Session bound to a specific engine instance. ```python from sqlalchemy.orm import Session session = Session(engine) ``` -------------------------------- ### Begin Once context with Engine Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/orm/session_transaction.rst Uses engine.begin() to obtain a Connection managed by a begin/commit/rollback context that commits and closes automatically. ```python engine = create_engine("postgresql+psycopg2://user:pass@host/dbname") with engine.begin() as conn: conn.execute( some_table.insert(), [ {"data": "some data one"}, {"data": "some data two"}, {"data": "some data three"}, ], ) # commits and closes automatically ``` -------------------------------- ### Check Installed SQLAlchemy Version Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/intro.rst Checks the installed SQLAlchemy library version from an interactive Python session. ```python >>> import sqlalchemy >>> sqlalchemy.__version__ # doctest: +SKIP 2.1.0 ``` -------------------------------- ### count_from_n_factory Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/orm/extensions/orderinglist.rst Numbering function: consecutive integers starting at arbitrary start. ```APIDOC ## count_from_n_factory ### Description Numbering function: consecutive integers starting at arbitrary start. ### Signature ```python def count_from_n_factory(start: int) -> OrderingFunc[Any] ``` ``` -------------------------------- ### Configure Oracle Free Docker container for testing Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/README.unittests.rst Runs an Oracle Free 23-slim Docker container with the specified test database and scott application user configuration. ```bash # create the container with the proper configuration for sqlalchemy docker run --rm --name oracle -p 127.0.0.1:1521:1521 -d -e ORACLE_PASSWORD=tiger -e ORACLE_DATABASE=test -e APP_USER=scott -e APP_USER_PASSWORD=tiger gvenzl/oracle-free:23-slim ``` -------------------------------- ### Install oracledb directly or via sqlalchemy[oracle] extra Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/changelog/migration_21.rst Install the oracledb DBAPI driver directly with pip, or use SQLAlchemy's oracle extra, which now installs oracledb. ```text # install oracledb directly pip install oracledb # or use SQLAlchemy's oracle extra (now installs oracledb) pip install sqlalchemy[oracle] ``` -------------------------------- ### Connection.begin Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/core/connections.rst Begin a transaction prior to autobegin occurring. ```APIDOC ## Connection.begin ### Description Begin a transaction prior to autobegin occurring. ### Method Connection.begin ### Response - **RootTransaction** - The transaction handle. ``` -------------------------------- ### TString usage example Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/core/sqlelement.rst Example of creating and executing a TString using the tstring() function. ```python from sqlalchemy import tstring, column a = 5 b = 10 stmt = tstring(t"select {a}, {b}") result = connection.execute(stmt) ``` -------------------------------- ### Instantiate Session and Open Transaction for SAVEPOINTs Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/orm/session_transaction.rst Sets up a sessionmaker and opens a transaction block prior to delineating SAVEPOINT transactions. ```python Session = sessionmaker() with Session.begin() as session: session.add(u1) session.add(u2) ``` -------------------------------- ### Configure PostgreSQL Docker container for testing Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/README.unittests.rst Runs a PostgreSQL Docker container, initializes test schemas and extensions, and optionally configures max prepared transactions. ```bash # create the container with the proper configuration for sqlalchemy docker run --rm -e POSTGRES_USER='scott' -e POSTGRES_PASSWORD='tiger' -e POSTGRES_DB='test' -p 127.0.0.1:5432:5432 -d --name postgres postgres # configure the database sleep 10 docker exec -ti postgres psql -U scott -c 'CREATE SCHEMA test_schema; CREATE SCHEMA test_schema_2;CREATE EXTENSION hstore;CREATE EXTENSION citext;' test # this last command is optional docker exec -ti postgres sed -i 's/#max_prepared_transactions = 0/max_prepared_transactions = 10/g' /var/lib/postgresql/data/postgresql.conf # To stop the container. It will also remove it. docker stop postgres ``` -------------------------------- ### asc usage example Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/core/sqlelement.rst Example of using asc to order by a column in ascending order. ```python from sqlalchemy import asc stmt = select(users_table).order_by(asc(users_table.c.name)) ``` -------------------------------- ### InstanceEvents load listener example Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/orm/events.rst Example of listening to the 'load' event on a mapped class. ```python from sqlalchemy import event def my_load_listener(target, context): print("on load!") event.listen(SomeClass, "load", my_load_listener) ``` -------------------------------- ### Example DATE string representation Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/dialects/sqlite.rst An example of a date string in the default storage format. ```text 2011-03-15 ``` -------------------------------- ### Execute statements with commit-as-you-go using create_engine Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/changelog/migration_20.rst Demonstrates connecting with an Engine and performing explicit commits using conn.commit() without relying on implicit autocommit. ```python from sqlalchemy import create_engine engine = create_engine("postgresql+psycopg2:///") with engine.connect() as conn: conn.execute(text("insert into table (x) values (:some_x)"), {"some_x": 10}) conn.commit() # commit as you go ``` -------------------------------- ### Example DATETIME string representation Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/dialects/sqlite.rst An example of a datetime string in the default storage format. ```text 2021-03-15 12:05:57.105542 ``` -------------------------------- ### Recommended Core transaction block with engine.begin() Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/changelog/migration_20.rst Shows the recommended explicit transaction pattern for Core use cases in SQLAlchemy 2.0. ```python with engine.begin() as conn: conn.execute(some_table.insert().values(foo="bar")) ``` -------------------------------- ### grouping_sets() usage example Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/core/functions.rst Example of using func.grouping_sets() in a GROUP BY clause. ```python stmt = select( func.sum(table.c.value), table.c.col_1, table.c.col_2 ).group_by(func.grouping_sets(table.c.col_1, table.c.col_2)) ``` -------------------------------- ### delete() example Source: https://github.com/sqlalchemy/sqlalchemy/blob/main/doc/build/core/dml.rst Example of using delete() to create a DELETE statement. ```python from sqlalchemy import delete stmt = delete(user_table).where(user_table.c.id == 5) ```