agronholm/sqlacodegen
agronholm/sqlacodegen has 2,372 GitHub stars and 284 forks. GitHot measured +1 stars in 24 hours and -1 in 7 days. Last checked 2026-11-11 10:34 UTC. Last push 2026-10-05.
Comment ces chiffres sont mesurés
Automatic model code generator for SQLAlchemy
What you can do
- Supports SQLAlchemy 2.x
- Produces declarative code that almost looks like it was hand written
- Produces PEP 8_ compliant code
- Accurately determines relationships, including many-to-many, one-to-one
Progression mesurée des étoiles
- in 24h
- +1
- in 7 days
- -1
- in 15 days
- Mise à jour retardée
- in 1 month
- Mise à jour retardée
Variations nettes sur des périodes qui se chevauchent, pas des totaux quotidiens. Les mesures absentes restent vides. Les étoiles indiquent l’intérêt, pas la qualité.
README.md
Original.. image:: https://github.com/agronholm/sqlacodegen/actions/workflows/test.yml/badge.svg :target: https://github.com/agronholm/sqlacodegen/actions/workflows/test.yml :alt: Build Status .. image:: https://coveralls.io/repos/github/agronholm/sqlacodegen/badge.svg?branch=master :target: https://coveralls.io/github/agronholm/sqlacodegen?branch=master :alt: Code Coverage .. image:: https://tidelift.com/badges/package/pypi/sqlacodegen :target: https://tidelift.com/subscription/pkg/pypi-sqlacodegen :alt: Tidelift
This is a tool that reads the structure of an existing database and generates the appropriate SQLAlchemy model code, using the declarative style if possible.
This tool was written as a replacement for sqlautocode_, which was suffering from
several issues (including, but not limited to, incompatibility with Python 3 and the
latest SQLAlchemy version).
.. _sqlautocode: http://code.google.com/p/sqlautocode/
Features
- Supports SQLAlchemy 2.x
- Produces declarative code that almost looks like it was hand written
- Produces
PEP 8_ compliant code - Accurately determines relationships, including many-to-many, one-to-one
- Automatically detects joined table inheritance
- Excellent test coverage
.. _PEP 8: http://www.python.org/dev/peps/pep-0008/
Installation
To install, do::
pip install sqlacodegen
To include support for the PostgreSQL CITEXT extension type (which should be
considered as tested only under a few environments) specify the citext extra::
pip install sqlacodegen[citext]
To include support for the PostgreSQL GEOMETRY, GEOGRAPHY, and RASTER types
(which should be considered as tested only under a few environments) specify the
geoalchemy2 extra:
To include support for the PostgreSQL PGVECTOR extension type, specify the
pgvector extra::
pip install sqlacodegen[pgvector]
.. code-block:: bash
pip install sqlacodegen[geoalchemy2]
Quickstart
At the minimum, you have to give sqlacodegen a database URL. The URL is passed directly
to SQLAlchemy's create_engine()_ method so please refer to
SQLAlchemy's documentation_ for instructions on how to construct a proper URL.
Examples::
sqlacodegen postgresql:///some_local_db
sqlacodegen --generator tables mysql+pymysql://user:password@localhost/dbname
sqlacodegen --generator dataclasses sqlite:///database.db
# --engine-arg values are parsed with ast.literal_eval
sqlacodegen oracle+oracledb://user:[email protected]:1521/XE --engine-arg thick_mode=True
sqlacodegen oracle+oracledb://user:[email protected]:1521/XE --engine-arg thick_mode=True --engine-arg connect_args='{"user": "user", "dsn": "..."}'
To see the list of generic options::
sqlacodegen --help
.. _create_engine(): http://docs.sqlalchemy.org/en/latest/core/engines.html#sqlalchemy.create_engine .. _SQLAlchemy's documentation: http://docs.sqlalchemy.org/en/latest/core/engines.html
Available generators
The selection of a generator determines the
The following built-in generators are available:
tables(only generatesTableobjects, for those who don't want to use the ORM)declarative(the default; generates classes inheriting fromdeclarative_base()dataclasses(generates dataclass-based models; v1.4+ only)sqlmodels(generates model classes for SQLModel_)
.. _SQLModel: https://sqlmodel.tiangolo.com/
Generator-specific options
The following options can be turned on by passing them using --options (multiple
values must be delimited by commas, e.g. --options noconstraints,nobidi):
tablesnoconstraints: ignore constraints (foreign key, unique etc.)nocomments: ignore table/column commentsnoindexes: ignore indexesnonativeenums: don't generate Python enum classes for native database ENUM types (e.g., PostgreSQL ENUM); use plain string mapping insteadnosyntheticenums: don't generate Python enum classes from CHECK constraints with IN clauses (e.g.,column IN ('value1', 'value2', ...)); preserves CHECK constraints as-isnoidsuffix: prevent the special naming logic for single column many-to-one and one-to-one relationships (seeRelationship naming logic_ for details)include_dialect_options: render a table' dialect options, such asstarrocks_partitionfor StarRocks' specific options.keep_dialect_types: preserve dialect-specific column types instead of adapting to generic SQLAlchemy types.
declarative- all the options from
tables use_inflect: use theinflectlibrary when naming classes and relationships (turning plural names into singular; see below for details)nojoined: don't try to detect joined-class inheritance (see below for details)nobidi: generate relationships in a unidirectional fashion, so only the many-to-one or first side of many-to-many relationships gets a relationship attribute, as on v2.Xnofknames: disable improved relationship naming when multiple FKs or junction tables connect to the same target. By default, uses FK column names for one-to-many (e.g.,simple_items_parent_container) and junction table names for many-to-many (e.g.,students_enrollments). Reverts to underscore suffixes (simple_items_,student_).
- all the options from
dataclasses- all the options from
declarative
- all the options from
sqlmodels- all the options from
declarative nolinktables: don't render many-to-many association tables as link model classes (Relationship(link_model=...)); render them as plainTableobjects referenced viasecondaryinstead
- all the options from
Model class generators
The code generators that generate classes try to generate model classes whenever
possible. There are two circumstances in which a Table is generated instead:
- the table has no primary key constraint (which is required by SQLAlchemy for every model class)
- the table is an association table between two other tables (see below for the specifics)
Model class naming logic ++++++++++++++++++++++++
By default, table names are converted to valid PEP 8 compliant class names by replacing
all characters unsuitable for Python identifiers with _. Then, each valid parts
(separated by underscores) are title cased and then joined together, eliminating the
underscores. So, example_name becomes ExampleName.
If the use_inflect option is used, the table name (which is assumed to be in
English) is converted to singular form using the "inflect" library. For example,
sales_invoices becomes SalesInvoice. Since table names are not always in
English, and the inflection process is far from perfect, inflection is disabled by
default.
Relationship detection logic ++++++++++++++++++++++++++++
Relationships are detected based on existing foreign key constraints as follows:
- many-to-one: a foreign key constraint exists on the table
- one-to-one: same as many-to-one, but a unique constraint exists on the column(s) involved
- many-to-many: an association table is found to exist between two tables (the
sqlmodelsgenerator renders association tables that have a primary key as link model classes, passed to the relationships vialink_model=)
A table is considered an association table if it satisfies all of the following conditions:
#. has exactly two foreign key constraints #. all its columns are involved in said constraints
Relationship naming logic +++++++++++++++++++++++++
Relationships are typically named based on the table name of the opposite class.
For example, if a class has a relationship to another class with the table named
companies, the relationship would be named companies (unless the use_inflect
option was enabled, in which case it would be named company in the case of a
many-to-one or one-to-one relationship).
A special case for single column many-to-one and one-to-one relationships, however, is
if the column is named like employer_id. Then the relationship is named employer
due to that _id suffix.
For self referential relationships, the reverse side of the relationship will be named
with the _reverse suffix appended to it.
When multiple foreign keys or junction tables connect to the same target table,
relationships use qualifiers for disambiguation. One-to-many relationships use FK
column names (e.g., simple_items_parent_container, simple_items_top_container).
Many-to-many relationships use junction table names (e.g., students_enrollments,
students_waitlist), except for self-referential cases which use FK column names
(e.g., parent, child). The nofknames option reverts to underscore suffixes
(simple_items_, student_).
Customizing code generation logic
If the built-in generators with all their options don't quite do what you want, you can
customize the logic by subclassing one of the existing code generator classes. Override
whichever methods you need, and then add an entry point_ in the
sqlacodegen.generators namespace that points to your new class. Once the entry point
is in place (you typically have to install the project with pip install), you can
use --generator <yourentrypoint> to invoke your custom code generator.
For examples, you can look at sqlacodegen's own entry points in its pyproject.toml_.
.. _entry point: https://setuptools.readthedocs.io/en/latest/userguide/entry_point.html .. _pyproject.toml: https://github.com/agronholm/sqlacodegen/blob/master/pyproject.toml
Getting help
If you have problems or other questions, you should start a discussion on the
sqlacodegen discussion forum. As an alternative, you could also try your luck on the
sqlalchemy room on Gitter.
.. _sqlacodegen discussion forum: https://github.com/agronholm/sqlacodegen/discussions/categories/q-a .. _sqlalchemy: https://app.gitter.im/#/room/#sqlalchemy_community:gitter.im
Security contact information
To report a security vulnerability, please use the Tidelift security contact_.
Tidelift will coordinate the fix and disclosure.
.. _Tidelift security contact: https://tidelift.com/security
Explorer des projets similaires
Asabeneh/30-Days-Of-Python
Le défi de programmation 30 Days of Python est un guide pas à pas pour apprendre le langage de programmation Python en 30 jours. Ce défi peut prendre plus de 100 jours. Avancez à votre rythme. Ces vidéos peuvent aussi vous aider : https://www.youtube.com/channel/UC7PNRuno1rzYPb1xLa4yktw
78,560 étoilesgrafana/grafana
Plateforme ouverte et composable d’observabilité et de visualisation de données. Visualise les métriques, les journaux et les traces issus de plusieurs sources, comme Prometheus, Loki, Elasticsearch, InfluxDB, Postgres et bien d’autres.
77,830 étoilesredis/redis
Pour les développeurs qui créent des applications en temps réel pilotées par les données, Redis est le cache, le serveur de structures de données et le moteur de requêtes documentaires et vectorielles préféré, le plus rapide et le plus riche en fonctionnalités.
77,395 étoilesapache/superset
Apache Superset est une plateforme de visualisation et d'exploration de données.
75,473 étoiles