### Database URL Examples for CLI Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/configuration.md Examples of different database URL formats supported by the sqlacodegen CLI for various database systems. ```bash sqlacodegen postgresql://localhost/mydb ``` ```bash sqlacodegen postgresql:///mydb # Unix socket ``` ```bash sqlacodegen mysql+pymysql://root:password@localhost/mydb ``` ```bash sqlacodegen sqlite:///database.db ``` ```bash sqlacodegen oracle+oracledb://user:pass@host:1521/XE ``` -------------------------------- ### SQLAlchemy Codegen Example Usage Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/api-reference.md Examples demonstrating how to use the sqlacodegen CLI with different database URLs, generators, options, and output files. ```bash # From CLI sqlacodegen postgresql:///mydb ``` ```bash sqlacodegen --generator dataclasses mysql+pymysql://user:pass@host/db ``` ```bash sqlacodegen sqlite:///db.sqlite --options use_inflect,nobidi --outfile models.py ``` -------------------------------- ### Example: Generating Table Definitions Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/api-reference.md Demonstrates how to use the TablesGenerator to reflect a database schema and generate Python code for table definitions. Ensure you have a database connection string and SQLAlchemy installed. ```python from sqlalchemy import MetaData, create_engine from sqlacodegen.generators import TablesGenerator engine = create_engine("postgresql://localhost/mydb") metadata = MetaData() metadata.reflect(bind=engine) generator = TablesGenerator(metadata, engine, []) code = generator.generate() print(code) ``` -------------------------------- ### Install sqlacodegen Source: https://github.com/agronholm/sqlacodegen/blob/master/README.rst Install the package using pip. To include support for PostgreSQL CITEXT extension, specify the 'citext' extra. ```bash pip install sqlacodegen ``` ```bash pip install sqlacodegen[citext] ``` -------------------------------- ### Render Index Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/advanced-features.md Example of rendering an index on multiple columns. ```python Index('idx_user_email', 'user_id', 'email') ``` -------------------------------- ### Install sqlacodegen with PGVector support Source: https://github.com/agronholm/sqlacodegen/blob/master/README.rst To include support for the PostgreSQL PGVECTOR extension type, specify the 'pgvector' extra during installation. ```bash pip install sqlacodegen[pgvector] ``` -------------------------------- ### Inflection Example (Singularization) Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/naming-conventions.md Illustrates the optional use of the inflect library to singularize names before capitalization. ```text users → user → User products → product → Product data → data (already singular) ``` -------------------------------- ### Install sqlacodegen with GeoAlchemy2 support Source: https://github.com/agronholm/sqlacodegen/blob/master/README.rst To include support for PostgreSQL GEOMETRY, GEOGRAPHY, and RASTER types, specify the 'geoalchemy2' extra during installation. ```bash pip install sqlacodegen[geoalchemy2] ``` -------------------------------- ### Instantiate and Generate SQLModel Code Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/api-reference.md Example of how to instantiate SQLModelGenerator and generate SQLModel table models. Ensure you have metadata and an engine configured. ```python generator = SQLModelGenerator(metadata, engine, ["use_inflect"]) code = generator.generate() # Output includes SQLModel table models ``` -------------------------------- ### CamelCase Conversion Example Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/naming-conventions.md Shows the conversion of snake_case to PascalCase, capitalizing each underscore-separated part. ```text user_accounts → UserAccounts account_status → AccountStatus ``` -------------------------------- ### Render Multi-Column FK Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/advanced-features.md Example of rendering a multi-column foreign key constraint as a separate constraint. ```python ForeignKeyConstraint(['user_id', 'org_id'], ['users.id', 'orgs.id']) ``` -------------------------------- ### Render Check Constraint Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/advanced-features.md Example of rendering a check constraint. ```python CheckConstraint('age > 0') ``` -------------------------------- ### Instantiate and Use DeclarativeGenerator Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/api-reference.md Example of instantiating DeclarativeGenerator and generating ORM model classes. Requires metadata and engine objects. ```python from sqlacodegen.generators import DeclarativeGenerator generator = DeclarativeGenerator(metadata, engine, ["use_inflect"]) code = generator.generate() # Output includes Base class and ORM model classes ``` -------------------------------- ### CLI Engine Argument Examples Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/configuration.md Demonstrates how to pass custom arguments to SQLAlchemy's create_engine function using the --engine-arg option for advanced connection customization. ```bash sqlacodegen postgresql://localhost/mydb --engine-arg connect_args='{"connect_timeout": 5}' ``` ```bash sqlacodegen oracle+oracledb://user:pass@host:1521/XE \ --engine-arg thick_mode=True \ --engine-arg connect_args='{"user": "scott", "dsn": "MYDSN"}' ``` ```bash sqlacodegen mysql+pymysql://user:pass@host/db --engine-arg charset=utf8mb4 ``` ```bash sqlacodegen postgresql://localhost/mydb --engine-arg echo=True ``` -------------------------------- ### Instantiate and Use DataclassGenerator Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/api-reference.md Example of instantiating DataclassGenerator and generating ORM models with dataclass mapping. Requires metadata and engine objects. ```python generator = DataclassGenerator(metadata, engine, ["use_inflect"]) code = generator.generate() # Output includes dataclass-mapped ORM models ``` -------------------------------- ### SQLModelGenerator Usage Example Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/api-reference.md Demonstrates how to use the SQLModelGenerator to generate SQLModel table models from database metadata. ```APIDOC ## `SQLModelGenerator` Example ### Description Demonstrates how to use the SQLModelGenerator to generate SQLModel table models from database metadata. ### Example ```python from sqlacodegen.generators import SQLModelGenerator from sqlalchemy import MetaData, create_engine # Assuming 'engine' is a SQLAlchemy Engine instance metadata = MetaData() engine = create_engine("sqlite:///mydatabase.db") generator = SQLModelGenerator(metadata, engine, ["use_inflect"]) code = generator.generate() # 'code' will contain the generated SQLModel table models print(code) ``` ``` -------------------------------- ### Render Unique Constraint (Multiple Columns) Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/advanced-features.md Example of rendering a unique constraint on multiple columns. ```python UniqueConstraint('email', 'org_id') ``` -------------------------------- ### Render Single-Column FK Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/advanced-features.md Example of rendering a single-column foreign key constraint on its own column. ```python Column('user_id', Integer, ForeignKey('users.id')) ``` -------------------------------- ### PostgreSQL BIGINT Adaptation Example Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/advanced-features.md Shows how PostgreSQL's BIGINT is adapted to SQLAlchemy's BigInteger. ```python # PostgreSQL BIGINT → SQLAlchemy BigInteger PostgreSQLBigInteger().adapt(BigInteger) → BigInteger() ``` -------------------------------- ### MySQL INTEGER Adaptation Example Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/advanced-features.md Demonstrates adapting MySQL's INTEGER(11) to SQLAlchemy's Integer type. ```python # MySQL INTEGER(11) → SQLAlchemy Integer MySQLInteger(display_width=11).adapt(Integer) → Integer() ``` -------------------------------- ### Conflict Resolution Example Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/naming-conventions.md Explains how suffixes are appended to avoid conflicts with Python keywords, reserved names, or existing class names. ```text from_ (Python keyword `from`) metadata_ (reserved name) User_ (collision with existing class) ``` -------------------------------- ### Invalid Character Replacement Example Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/naming-conventions.md Demonstrates replacing non-identifier characters with underscores. ```text user-accounts → user_accounts user.profile → user_profile ``` -------------------------------- ### Class Naming With Inflection Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/naming-conventions.md Examples of generated class names when inflection is enabled using `use_inflect`. ```text users → User (users→user inflection, then capitalized) products → Product categories → Category addresses → Address invoices → Invoice ``` -------------------------------- ### Render Unique Constraint (Single Column) Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/advanced-features.md Example of rendering a unique constraint on a single column. ```python Column('email', String, unique=True) ``` -------------------------------- ### SQLModel-Compatible Model Generation Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/generators-details.md Example of generated SQLModel classes for users and orders, demonstrating ORM mapping and Pydantic validation. This structure is ideal for FastAPI applications. ```python from sqlmodel import SQLModel, Field, Session class User(SQLModel, table=True): id: int | None = Field(default=None, primary_key=True) name: str = Field(sa_column=Column(String(100))) email: str | None = Field(default=None, sa_column=Column(String(255), unique=True)) orders: list['Order'] = Relationship(back_populates='user') class Order(SQLModel, table=True): id: int | None = Field(default=None, primary_key=True) user_id: int = Field(foreign_key='users.id', sa_column=Column(Integer)) user: User = Relationship(back_populates='orders') ``` -------------------------------- ### Alembic Migrations Setup Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/utilities-and-examples.md Configure Alembic for automatic database migrations by setting the target_metadata to the Base.metadata from your generated models. This allows Alembic to detect schema changes. ```python # In alembic/env.py from models import Base target_metadata = Base.metadata # Then Alembic detects models automatically # alembic revision --autogenerate ``` -------------------------------- ### Sample SQLAlchemy Dataclass Model Definitions Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/utilities-and-examples.md This Python code shows generated SQLAlchemy models using dataclasses. It includes examples of model instantiation and assertions for equality. ```python from sqlalchemy.orm import DeclarativeBase, MappedAsDataclass, mapped_column from dataclasses import dataclass, field class Base(MappedAsDataclass, DeclarativeBase): pass @dataclass class User(Base): __tablename__ = 'users' id: Mapped[int] = mapped_column(primary_key=True) name: Mapped[str] = mapped_column(String(100)) email: Mapped[str | None] = mapped_column(default=None) age: Mapped[int | None] = mapped_column(default=None) # Can now use as regular dataclass user = User(id=1, name='Alice', email='alice@example.com') print(f"User {user.name} ({user.email})") # Automatic repr/eq/init user2 = User(id=1, name='Alice', email='alice@example.com') assert user == user2 ``` -------------------------------- ### Class Naming Without Inflection Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/naming-conventions.md Examples of generated class names when inflection is disabled. ```text users → Users user_accounts → UserAccounts product_categories → ProductCategories ``` -------------------------------- ### Model Class Structure Example Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/advanced-features.md Defines the standard structure for model classes generated by DeclarativeGenerator, including table name, column definitions (nullable and non-nullable), and relationships. ```python class ClassName(BaseClass): __tablename__ = 'table_name' __table_args__ = (...) # If constraints/indexes/schema # Non-nullable columns (sorted) col1: Mapped[int] col2: Mapped[str] # Nullable columns (sorted) col3: Mapped[int | None] col4: Mapped[str | None] # Relationships rel1: Mapped['TargetClass'] rel2: Mapped[list['TargetClass']] ``` -------------------------------- ### Usage of Generated Core Tables Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/utilities-and-examples.md Example of how to use the generated SQLAlchemy Core Table objects for performing database operations like inserts and queries. ```python from models import metadata, t_users, t_posts with engine.connect() as conn: # Insert stmt = t_users.insert().values(username='alice', email='alice@example.com') conn.execute(stmt) # Query stmt = select(t_posts).where(t_posts.c.user_id == 1) posts = conn.execute(stmt).fetchall() ``` -------------------------------- ### FastAPI Usage with SQLModel Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/utilities-and-examples.md Example of integrating generated SQLModel classes into a FastAPI application for creating and managing users. Pydantic validation is handled automatically by SQLModel. ```python from fastapi import FastAPI app = FastAPI() @app.post("/users/", response_model=User) def create_user(user: User, session: Session = Depends(get_session)): session.add(user) session.commit() session.refresh(user) return user # Pydantic validation already done # User model works for both ORM queries and API responses ``` -------------------------------- ### Generate SQLAlchemy Dataclass Models Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/generators-details.md Example of generating SQLAlchemy models with dataclass mapping using MappedAsDataclass. This is useful for projects using SQLAlchemy 2.0+ that desire dataclass features like automatic __init__, __repr__, and __eq__ methods. ```python from sqlalchemy.orm import DeclarativeBase, MappedAsDataclass, mapped_column from dataclasses import dataclass, field class Base(MappedAsDataclass, DeclarativeBase): pass @dataclass class User(Base): __tablename__ = 'users' id: Mapped[int] = mapped_column(primary_key=True) name: Mapped[str] = mapped_column(String(100)) email: Mapped[str | None] = mapped_column(default=None) ``` -------------------------------- ### One-to-Many Reverse Relationships with Multi-FK Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/generators-details.md When multiple foreign keys reference the same table, reverse relationships are qualified to disambiguate them. This example shows how 'parent_container_id' and 'top_container_id' both referencing 'container' result in distinct relationship names. ```python class Item(Base): parent_container_id: Mapped[int] = mapped_column(ForeignKey('container.id')) top_container_id: Mapped[int] = mapped_column(ForeignKey('container.id')) class Container(Base): items_parent_container: Mapped[list['Item']] items_top_container: Mapped[list['Item']] ``` -------------------------------- ### Display help for sqlacodegen Source: https://github.com/agronholm/sqlacodegen/blob/master/README.rst To view a list of all available generic command-line options for sqlacodegen, use the --help flag. ```bash sqlacodegen --help ``` -------------------------------- ### Get Qualified Table Name Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/utilities-and-examples.md Use `qualified_table_name` to get the fully qualified name of a SQLAlchemy `Table` object, including the schema if specified. ```python from sqlalchemy import Table, MetaData metadata = MetaData(schema='public') table = Table('users', metadata) from sqlacodegen.utils import qualified_table_name name = qualified_table_name(table) # Returns: 'public.users' table2 = Table('products', MetaData()) # No schema name2 = qualified_table_name(table2) # Returns: 'products' ``` -------------------------------- ### Basic CLI Model Generation Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/configuration.md Use the command line to generate SQLAlchemy models from a PostgreSQL database with default options. Output is redirected to a file. ```bash sqlacodegen postgresql://localhost/mydb > models.py ``` -------------------------------- ### Options Tracking Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/advanced-features.md Stores configuration options as a set of strings and boolean flags. ```python self.options: set[str] # Set of option strings self.include_dialect_options_and_info: bool # include_dialect_options flag self.keep_dialect_types: bool # keep_dialect_types flag ``` -------------------------------- ### Process Specific Tables and Schemas via CLI Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/configuration.md Generate models for a subset of tables and schemas, applying specific options. ```bash sqlacodegen postgresql://localhost/mydb \ --schemas public,staging \ --tables users,orders,products \ --options use_inflect,nobidi ``` -------------------------------- ### PostgreSQL Sequence Handling Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/advanced-features.md Demonstrates how PostgreSQL sequences used in nextval() defaults are detected and generated. The server_default is cleared after reflection. ```python # Reflection finds: # server_default: nextval('user_id_seq'::regclass) # Generated as: Column('id', Integer, default=Sequence('user_id_seq', schema='public')) # The column.server_default is then cleared (removed) ``` -------------------------------- ### Extract Column Names from Constraint Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/api-reference.md Use this function to get a list of column names from a ColumnCollectionConstraint object. ```python def get_column_names(constraint: ColumnCollectionConstraint) -> list[str]: ``` -------------------------------- ### Generate SQLModel Classes via CLI Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/configuration.md Generate models using the SQLModel generator and specify an output file. ```bash sqlacodegen --generator sqlmodels postgresql://localhost/mydb --outfile models.py ``` -------------------------------- ### Create a Base Instance for Declarative Models Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/types.md Instantiate `Base` to configure the generation of a declarative base class, specifying imports and class structure. ```python from sqlacodegen.generators import Base, LiteralImport base = Base( literal_imports=[LiteralImport("sqlalchemy.orm", "DeclarativeBase")], declarations=[ "class Base(DeclarativeBase):", " pass" ], metadata_ref="Base.metadata", decorator=None, table_metadata_declaration=None ) ``` -------------------------------- ### Use RelationshipType Enum Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/types.md Example of how to use the RelationshipType enum when generating ORM relationships. Checks the type of a relationship to apply specific logic. ```python from sqlacodegen.models import RelationshipType, RelationshipAttribute # In relationship generation if relationship_type == RelationshipType.MANY_TO_ONE: # Handle many-to-one with uselist=True pass elif relationship_type == RelationshipType.ONE_TO_ONE: # Add uselist=False parameter pass ``` -------------------------------- ### CLI Optional Arguments for Code Generation Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/configuration.md Illustrates the use of optional arguments to control the code generation process, such as specifying the generator, tables, schemas, output file, and more. ```bash sqlacodegen postgresql://localhost/mydb --generator declarative --tables "table1,table2" --outfile models.py ``` -------------------------------- ### Get Constraint Sort Key Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/utilities-and-examples.md The `get_constraint_sort_key` function provides a deterministic string key for sorting SQLAlchemy constraints, ensuring consistent ordering. ```python from sqlacodegen.utils import get_constraint_sort_key constraints = [ck1, pk1, fk1, uq1] sorted_constraints = sorted(constraints, key=get_constraint_sort_key) # Consistent ordering across runs ``` -------------------------------- ### Basic CLI Usage with Database URL Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/configuration.md Specify the SQLAlchemy database URL as a required argument for the sqlacodegen CLI. ```bash sqlacodegen ``` -------------------------------- ### Generate Dataclass Models with Inflection via CLI Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/configuration.md Generate dataclass models and enable inflection for naming conventions. ```bash sqlacodegen --generator dataclasses \ --options use_inflect \ postgresql://localhost/mydb ``` -------------------------------- ### Get Fully Qualified Table Name Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/api-reference.md Returns the complete name of a SQLAlchemy table, including its schema if specified. This ensures correct referencing in SQL. ```python def qualified_table_name(table: Table) -> str: ``` -------------------------------- ### Class/Attribute Naming Conventions Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/INDEX.md Illustrates how database table and foreign key column names are mapped to Python class and attribute names, including the effect of the `use_inflect` option. ```text Database Table → Python Class users → Users (or User with use_inflect) user_accounts → UserAccounts Database FK Column → Python Attribute user_id → user (relationship, _id stripped) employer_id → employer (relationship) created_at → created_at (column, unchanged) ``` -------------------------------- ### Handle Column Lookup Failure Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/advanced-features.md Attempt to get a column attribute for a nonexistent column to trigger a LookupError. This is useful for debugging missing column definitions. ```python model_class.get_column_attribute('nonexistent_column') # Raises: LookupError("Cannot find column attribute for 'nonexistent_column'") ``` -------------------------------- ### Oracle Connection with Thick Mode via CLI Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/configuration.md Generate models from an Oracle database, specifying thick mode and connection arguments. ```bash sqlacodegen oracle+oracledb://scott:tiger@localhost:1521/xe \ --engine-arg thick_mode=True \ --engine-arg connect_args='{"dsn": "ORACLESID"}' \ --outfile oracle_models.py ``` -------------------------------- ### Use Custom Generator via Command Line Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/advanced-features.md Use the --generator option with your registered custom generator name to generate code with your customized logic. ```bash sqlacodegen --generator custom postgresql://localhost/mydb ``` -------------------------------- ### SQLModelGenerator Constructor Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/api-reference.md Initializes the SQLModelGenerator. Use this to set up the generator with metadata, a database connection, and generation options. The base_class_name can be customized. ```python class SQLModelGenerator(DeclarativeGenerator): def __init__( self, metadata: MetaData, bind: Connection | Engine, options: Sequence[str], *, indentation: str = " ", base_class_name: str = "SQLModel", ) -> None: ... ``` -------------------------------- ### Get Standard Library Module Names Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/utilities-and-examples.md The `get_stdlib_module_names` function returns a set of strings representing the names of Python's standard library modules, useful for import grouping. ```python from sqlacodegen.utils import get_stdlib_module_names stdlib = get_stdlib_module_names() 'sys' in stdlib # True 'sqlalchemy' in stdlib # False ``` -------------------------------- ### sqlacodegen CLI Entry Point Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/api-reference.md The main entry point for the sqlacodegen command-line interface. It parses arguments, connects to the database, reflects the schema, and generates SQLAlchemy model code. ```APIDOC ## `sqlacodegen.cli.main()` ### Description The CLI entry point for sqlacodegen. Parses command-line arguments to determine database URL, generator type, and options, then connects to the database, loads the schema, instantiates the selected generator, and writes the generated code. ### Method CLI Command ### Parameters #### CLI Arguments - **url** (string) - Required - SQLAlchemy database URL - **--generator** (choice) - Optional - Generator class: `tables`, `declarative`, `dataclasses`, `sqlmodels` (default: `declarative`) - **--tables** (string) - Optional - Comma-delimited table names to process (default: all) - **--schemas** (string) - Optional - Comma-delimited schema names to load - **--options** (string) - Optional - Generator options (comma-delimited) - **--engine-arg** (string) - Optional - Engine arguments in key=value format (repeatable); values parsed with `ast.literal_eval` - **--noviews** (flag) - Optional - Ignore views (always true for sqlmodels generator) - **--outfile** (string) - Optional - Output file path (default: stdout) - **--version** (flag) - Optional - Print version and exit ### Example Usage ```bash sqlacodegen postgresql:///mydb sqlacodegen --generator dataclasses mysql+pymysql://user:pass@host/db sqlacodegen sqlite:///db.sqlite --options use_inflect,nobidi --outfile models.py ``` ``` -------------------------------- ### SQLAlchemy 'nobidi' Option Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/naming-conventions.md When the 'nobidi' option is used, reverse relationships are not generated. This example shows a User class without an 'orders' relationship and an Order class with a 'user' relationship that is forward-only. ```python class User(Base): # No orders relationship class Order(Base): user_id: int user: User # Forward only, no back_populates ``` -------------------------------- ### Generate Code with Backward Compatibility Options Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/configuration.md Apply `nobidi` and `noidsuffix` options for maximum backward compatibility in generated code. ```bash --options nobidi,noidsuffix ``` -------------------------------- ### Define Identity Column with Server Default Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/generators-details.md Renders identity columns with their non-default parameters, such as start and increment values for sequences. This is used for auto-generating primary keys or other sequentially numbered fields. ```python Column('id', Integer, server_default=Identity(start=1, increment=1)) ``` -------------------------------- ### SQLAlchemy 'use_inflect' Option Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/naming-conventions.md The 'use_inflect' option singularizes class names and pluralizes collections. This example shows a User class with a plural 'orders' collection and an Order class with a singular 'user' reference. ```python # Table: users, orders class User(Base): orders: list[Order] # Plural (collection) class Order(Base): user: User # Singular (FK reference) ``` -------------------------------- ### Defining Constraints and Indexes in __table_args__ Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/generators-details.md Shows how to define multi-column indexes, unique constraints, check constraints, and schema information within the `__table_args__` attribute for a SQLAlchemy model. ```python class Order(Base): __tablename__ = 'orders' __table_args__ = ( Index('idx_user_date', 'user_id', 'order_date'), UniqueConstraint('order_number', name='uq_order_number'), CheckConstraint('amount > 0', name='ck_amount_positive'), {'schema': 'public'}, ) ``` -------------------------------- ### Generate Minimal Schema (No Constraints) Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/utilities-and-examples.md Generates models from an Oracle database, excluding constraints, indexes, and comments using the `--options noconstraints,noindexes,nocomments`. Useful for a quick schema overview. ```bash sqlacodegen oracle+oracledb://user:pass@host:1521/db \ --options noconstraints,noindexes,nocomments \ --outfile models.py ``` -------------------------------- ### Include Dialect Options for Column and Table Info Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/generators-details.md Includes dialect-specific options, such as `info` dictionaries, for columns and tables. This allows for storing metadata like descriptions or labels directly within the table and column definitions. ```python Column('status', String, info={'description': 'User status'}) ``` ```python Table('users', metadata, ..., info={'label': 'Users table'}) ``` -------------------------------- ### Many-to-Many Junction Table Naming Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/generators-details.md For many-to-many relationships, junction tables are used. This example demonstrates how distinct junction tables ('student_enrollments', 'student_waitlist') lead to uniquely named relationships ('enrollments', 'waitlist') on the 'Student' model. ```python # With tables: student_enrollments, student_waitlist class Student(Base): enrollments: Mapped[list['Enrollment']] # from student_enrollments waitlist: Mapped[list['Enrollment']] # from student_waitlist ``` -------------------------------- ### Register Custom Generator Entry Point Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/advanced-features.md Register your custom generator as an entry point in pyproject.toml to make it discoverable by sqlacodegen. This allows you to use your custom generator via the command line. ```toml [project.entry-points."sqlacodegen.generators"] custom = "mypackage.generators:CustomDeclarativeGenerator" ``` -------------------------------- ### SQLAlchemy 'nofknames' Option with Multi-FK Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/naming-conventions.md When 'nofknames' is used with multiple foreign keys, underscore suffixes are appended to relationship names for disambiguation. This example shows an Item class with 'containers_' and 'containers__' relationships derived from 'parent_container_id' and 'top_container_id'. ```python class Item(Base): parent_container_id: int top_container_id: int containers_: Container # Underscore suffixes containers__: Container ``` -------------------------------- ### Sample SQLAlchemy Core Table Definitions Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/utilities-and-examples.md This Python code shows the generated SQLAlchemy MetaData and Table objects. These are suitable for direct use with SQLAlchemy Core for database operations. ```python from sqlalchemy import MetaData, Table, Column, String, Integer, DateTime metadata = MetaData() t_users = Table( 'users', metadata, Column('id', Integer, primary_key=True), Column('username', String(50), nullable=False, unique=True), Column('email', String(100), nullable=False), Column('created_at', DateTime, server_default=text('CURRENT_TIMESTAMP')), ) t_posts = Table( 'posts', metadata, Column('id', Integer, primary_key=True), Column('user_id', Integer, ForeignKey('users.id')), Column('title', String(200)), Column('content', String), ) ``` -------------------------------- ### SQLAlchemy 'noidsuffix' Option Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/naming-conventions.md The 'noidsuffix' option prevents stripping '_id' from foreign key columns when generating relationship names. This example shows an Order class where the 'users' relationship is named from the table name ('users') rather than the column name ('user_id'). ```python # Column: user_id class Order(Base): user_id: int users: Order # Name from table name, not from column class User(Base): orders: list[Order] # Reverse ``` -------------------------------- ### Generate Complex Schema with Options Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/utilities-and-examples.md Generates models for multiple schemas and tables from a large database. Options like `use_inflect`, `nobidi`, and `nofknames` customize the generated code for clarity and specific needs. ```bash sqlacodegen postgresql://prod_db \ --generator declarative \ --schemas public,staging \ --tables users,orders,products,order_items \ --options use_inflect,nobidi,nofknames \ --outfile generated_models.py ``` -------------------------------- ### Generate SQLAlchemy models from a PostgreSQL database Source: https://github.com/agronholm/sqlacodegen/blob/master/README.rst Provide the database URL to sqlacodegen to generate models. The URL is passed to SQLAlchemy's create_engine(). ```bash sqlacodegen postgresql:///some_local_db ``` -------------------------------- ### SQL Schema for Projects with User Relationships Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/naming-conventions.md Defines the SQL schema for projects, including foreign keys to users for manager and creator roles. ```sql CREATE TABLE projects ( id SERIAL PRIMARY KEY, manager_id INTEGER REFERENCES users(id), creator_id INTEGER REFERENCES users(id) ); ``` -------------------------------- ### Dataclass Field Ordering Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/generators-details.md Demonstrates how dataclass fields are ordered, with non-nullable fields appearing before nullable ones. This ensures a consistent and predictable constructor signature. ```python @dataclass class User(Base): # Non-nullable fields first id: Mapped[int] = mapped_column(primary_key=True) name: Mapped[str] = mapped_column(String(100)) # Nullable fields after email: Mapped[str | None] = mapped_column(default=None) phone: Mapped[str | None] = mapped_column(default=None) ``` -------------------------------- ### Echo SQL Statements for Debugging Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/advanced-features.md Run sqlacodegen with the --engine-arg echo=True option to display all reflection queries sent to the database. This is useful for understanding database interaction during metadata reflection. ```bash sqlacodegen postgresql://localhost/mydb --engine-arg echo=True ``` -------------------------------- ### Module Import Tracking Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/types.md Demonstrates the set used to track module-level imports, which are then rendered as top-level import statements. ```python TablesGenerator.module_imports: set[str] ``` ```python {"enum", "uuid"} # Results in: import enum; import uuid ``` -------------------------------- ### Import Tracking Structure Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/types.md Illustrates the internal dictionary structure used to track package names and the specific symbols to be imported from them. ```python TablesGenerator.imports: dict[str, set[str]] ``` ```python { "sqlalchemy": {"Column", "String", "Integer", "ForeignKey"}, "sqlalchemy.orm": {"DeclarativeBase", "Mapped", "relationship"}, } ``` -------------------------------- ### Sample SQLAlchemy ORM Model Definitions Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/utilities-and-examples.md This Python code demonstrates the generated SQLAlchemy ORM models, including relationships between tables. These models are based on a declarative base. ```python from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship from sqlalchemy import String, Integer, DateTime, Boolean class Base(DeclarativeBase): pass class User(Base): __tablename__ = 'users' id: Mapped[int] = mapped_column(primary_key=True) username: Mapped[str] = mapped_column(String(50), unique=True) email: Mapped[str] = mapped_column(String(100)) is_active: Mapped[bool] = mapped_column(default=True) posts: Mapped[list['Post']] = relationship('Post', back_populates='author') class Post(Base): __tablename__ = 'posts' id: Mapped[int] = mapped_column(primary_key=True) title: Mapped[str] = mapped_column(String(200)) content: Mapped[str] author_id: Mapped[int] = mapped_column(ForeignKey('users.id')) author: Mapped['User'] = relationship('User', back_populates='posts') comments: Mapped[list['Comment']] = relationship('Comment', back_populates='post') class Comment(Base): __tablename__ = 'comments' id: Mapped[int] = mapped_column(primary_key=True) content: Mapped[str] post_id: Mapped[int] = mapped_column(ForeignKey('posts.id')) post: Mapped['Post'] = relationship('Post', back_populates='comments') ``` -------------------------------- ### Column Naming Conventions Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/naming-conventions.md Demonstrates how sqlacodegen maps database column names to Python identifiers, showing unchanged names, keyword conflicts, and built-in type conflicts. ```python id → id # unchanged first_name → first_name # unchanged email_address → email_address # unchanged class → class_ # keyword suffix from → from_ # keyword suffix type → type_ # builtin suffix (infrequently) ``` -------------------------------- ### Multiple FK Columns to Same Table (Default Naming) Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/naming-conventions.md Illustrates how SQLAlchemy names relationships when multiple foreign key columns point to the same target table, using qualified names derived from FK column prefixes. ```python class Item(Base): parent_container_id: int top_container_id: int parent_container: Container # Qualified: container + parent top_container: Container # Qualified: container + top class Container(Base): items_parent_container: list[Item] # Reverse side items_top_container: list[Item] # Reverse side ``` -------------------------------- ### Handling Already CamelCase Table Names Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/naming-conventions.md Shows how names that are already in CamelCase are processed, including the effect of inflection. ```text UserAccounts → Useraccounts → With inflection: Useraccount ``` -------------------------------- ### SQL Schema for Users and Orders Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/naming-conventions.md Defines the basic SQL schema for users and their associated orders. ```sql CREATE TABLE users ( id SERIAL PRIMARY KEY, name VARCHAR(100) NOT NULL ); CREATE TABLE orders ( id SERIAL PRIMARY KEY, user_id INTEGER REFERENCES users(id), total DECIMAL ); ``` -------------------------------- ### Handling Numbers in Names Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/naming-conventions.md Demonstrates the naming convention for identifiers containing numbers. ```text user_2fa → User2fa 2fa_user → _2faUser (adjusted for leading digit) ``` -------------------------------- ### One-to-Many Reverse Relationships (with Inflection) Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/naming-conventions.md Shows how the `use_inflect` option pluralizes reverse relationships in one-to-many associations, changing the naming from singular to plural. ```text users_table (table) ↓ User class order_table (table) ↓ Order class ← orders (plural) ``` -------------------------------- ### SQLAlchemy Codegen CLI Entry Point Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/api-reference.md The main function for the sqlacodegen command-line interface. It parses arguments, connects to the database, reflects the schema, selects a generator, and outputs the code. ```python def main() -> None: ``` -------------------------------- ### SQLModelGenerator Parameters Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/configuration.md Parameters for the SQLModelGenerator, including base parameters, indentation, and base class name. ```python def __init__( self, metadata: MetaData, bind: Connection | Engine, options: Sequence[str], *, indentation: str = " ", base_class_name: str = "SQLModel", ) -> None: pass ``` -------------------------------- ### Metadata Imports Tracking Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/advanced-features.md Tracks package-to-symbol mappings and module-level imports. ```python self.imports: dict[str, set[str]] # Package → {symbol names} self.module_imports: set[str] # Module-level imports (import x) ``` -------------------------------- ### Multiple FK Columns to Same Table (nofknames Option) Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/naming-conventions.md Shows relationship naming with the `nofknames` option enabled, resulting in underscore-suffixed names for relationships originating from multiple foreign key columns. ```python class Item(Base): parent_container_id: int top_container_id: int containers_: list[Container] # Underscore suffix containers__: list[Container] # Double underscore class Container(Base): items_: list[Item] # Reverse: underscore suffix items__: list[Item] # Reverse: double underscore ``` -------------------------------- ### Enable Inflection, Disable Joined Inheritance and Bidirectional Relationships Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/configuration.md Configure the generator with `use_inflect`, `nojoined`, and `nobidi` options for advanced naming and relationship handling. ```bash sqlacodegen postgresql://localhost/mydb \ --options use_inflect,nojoined,nobidi ``` -------------------------------- ### Omit Constraints and Comments Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/configuration.md Use the `--options` flag to specify `noconstraints` and `nocomments` when generating code to exclude constraint and comment definitions. ```bash sqlacodegen postgresql://localhost/mydb \ --options noconstraints,nocomments ``` -------------------------------- ### Default SQLAlchemy ORM Models for Projects Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/naming-conventions.md Generates default Python ORM models for the projects table, inferring relationships to the User model. ```python class Project(Base): manager_id: Mapped[int] creator_id: Mapped[int] manager: Mapped['User'] # Qualified: users + manager creator: Mapped['User'] # Qualified: users + creator class User(Base): projects_manager: Mapped[list['Project']] # Reverse, qualified projects_creator: Mapped[list['Project']] # Reverse, qualified ``` -------------------------------- ### Include or Exclude Views Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/advanced-features.md Control view reflection using the 'views' argument. Views are included by default unless explicitly excluded. ```python # Include views metadata.reflect(bind=engine, views=True) # Exclude views (CLI: --noviews) metadata.reflect(bind=engine, views=False) ``` -------------------------------- ### Pytest Integration for Testing Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/utilities-and-examples.md Set up a Pytest fixture to provide an in-memory SQLite database for testing. This fixture creates the database schema from generated models and yields a session for test functions. ```python import pytest from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker # Use generated models from models import Base @pytest.fixture def db(): engine = create_engine("sqlite:///:memory:") Base.metadata.create_all(engine) Session = sessionmaker(bind=engine) session = Session() yield session session.close() def test_user_creation(db): from models import User user = User(username='test', email='test@example.com') db.add(user) db.commit() assert user.id is not None ``` -------------------------------- ### Generate Dataclass Models from MySQL Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/utilities-and-examples.md Command to generate SQLAlchemy models as Python dataclasses from a MySQL database. This combines the convenience of dataclasses with SQLAlchemy mapping. ```bash sqlacodegen mysql+pymysql://user:pass@localhost/mydb \ --generator dataclasses \ --options use_inflect \ --outfile models.py ``` -------------------------------- ### Generate SQLAlchemy ORM Models from PostgreSQL Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/utilities-and-examples.md Command to generate SQLAlchemy ORM models from a PostgreSQL database, suitable for use in applications like FastAPI. The `--use_inflect` option helps with pluralization. ```bash sqlacodegen postgresql://localhost/myapp_dev \ --generator declarative \ --options use_inflect \ --outfile app/models.py ``` -------------------------------- ### Generate Code with Aggressive Singularization and Clean Names Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/configuration.md Use `use_inflect` and `nofknames` options to achieve aggressive singularization and cleaner relationship names. ```bash --options use_inflect,nofknames ``` -------------------------------- ### Create a LiteralImport Instance Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/types.md Instantiate `LiteralImport` to define an import, such as `from sqlalchemy.orm import DeclarativeBase`. ```python from sqlacodegen.generators import LiteralImport import_spec = LiteralImport("sqlalchemy.orm", "DeclarativeBase") ``` -------------------------------- ### Generate Code with Minimal Schema Intrusion Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/configuration.md Combine `noconstraints`, `noindexes`, and `nocomments` options to minimize schema intrusion in the generated code. ```bash --options noconstraints,noindexes,nocomments ``` -------------------------------- ### SQLAlchemy Async Integration Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/utilities-and-examples.md Integrate generated models with SQLAlchemy's asynchronous capabilities for non-blocking database operations. Ensure models are imported and an async engine is configured. ```python from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession from sqlalchemy.orm import sessionmaker # Use same models generated by sqlacodegen from models import Base, User, Post engine = create_async_engine("postgresql+asyncpg://localhost/db") async_session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False) async def get_user(user_id: int): async with async_session() as session: user = await session.get(User, user_id) return user # Models work seamlessly with async SQLAlchemy ``` -------------------------------- ### Generate models with Oracle specific engine arguments Source: https://github.com/agronholm/sqlacodegen/blob/master/README.rst Pass engine-specific arguments to SQLAlchemy's create_engine() using the --engine-arg option. Values are parsed with ast.literal_eval. ```bash sqlacodegen oracle+oracledb://user:pass@127.0.0.1:1521/XE --engine-arg thick_mode=True ``` ```bash sqlacodegen oracle+oracledb://user:pass@127.0.0.1:1521/XE --engine-arg thick_mode=True --engine-arg connect_args='{"user": "user", "dsn": "..."}' ``` -------------------------------- ### Generate SQLAlchemy Core Tables from SQLite Source: https://github.com/agronholm/sqlacodegen/blob/master/_autodocs/utilities-and-examples.md Use this command to generate Python code for SQLAlchemy Core Table objects from an existing SQLite database. The output can be used for low-level SQL interaction. ```bash sqlacodegen sqlite:///my_database.db --generator tables --outfile models.py ```