Package: omymodels
O! My ModelsTry in Web-UITry the online O!MyModels converter or simply use it online:https://archon-omymodels-online.hf.space/(A big thanks for that goes tohttps://github.com/archongum)ExamplesYou can find usage examples in the example/ folder on GitHub:https://github.com/xnuinside/omymodels/tree/main/exampleAbout libraryO! My Models (omymodels) is a library that allow you togeneratedifferent ORM & pure Python models from SQL DDL orconvertone models type to another (exclude SQLAlchemy Table, it does not supported yet by py-models-parser).Supported Models:SQLAlchemy (https://docs.sqlalchemy.org/en/14/orm/),SQLAlchemy Core (Tables) (https://docs.sqlalchemy.org/en/14/core/metadata.html#accessing-tables-and-columns),GinoORM (https://python-gino.org/),Pydantic (https://pydantic-docs.helpmanual.io/),Python Enum (https://docs.python.org/3/library/enum.html) - generated only from DDL SQL Types,Python Dataclasses (dataclasses module) (https://docs.python.org/3/library/dataclasses.html),How to installpipinstallomymodelsHow to useFrom Python codeCreate Models from DDLBy default methodcreate_modelsgenerate GinoORM models, to get Pydantic models output use the argumentmodels_type='pydantic'(‘sqlalchemy’ for SQLAlchemy models; ‘dataclass’ for Dataclasses; ‘sqlalchemy_core’ for Sqlalchemy Core Tables).A lot of examples in tests/ -https://github.com/xnuinside/omymodels/tree/main/tests.For example,fromomymodelsimportcreate_modelsddl="""
CREATE table user_history (
     runid                 decimal(21) null
    ,job_id                decimal(21)  null
    ,id                    varchar(100) not null
    ,user              varchar(100) not null
    ,status                varchar(10) not null
    ,event_time            timestamp not null default now()
    ,comment           varchar(1000) not null default 'none'
    ) ;


"""result=create_models(ddl,models_type='pydantic')['code']# and output will be:importdatetimefromtypingimportOptionalfrompydanticimportBaseModelclassUserHistory(BaseModel):runid:Optional[int]job_id:Optional[int]id:struser:strstatus:strevent_time:datetime.datetimecomment:strTo generate Dataclasses from DDL use argumentmodels_type='dataclass'for example:#  (same DDL as in Pydantic sample)result=create_models(ddl,schema_global=False,models_type='dataclass')['code']# and result will be:importdatetimefromdataclassesimportdataclass@dataclassclassUserHistory:id:struser:strstatus:strrunid:int=Nonejob_id:int=Noneevent_time:datetime.datetime=datetime.datetime.now()comment:str='none'GinoORM example. If you provide an input like:CREATETABLE"users"("id"SERIALPRIMARYKEY,"name"varchar,"created_at"timestamp,"updated_at"timestamp,"country_code"int,"default_language"int);CREATETABLE"languages"("id"intPRIMARYKEY,"code"varchar(2)NOTNULL,"name"varcharNOTNULL);and you will get output:fromginoimportGinodb=Gino()classUsers(db.Model):__tablename__='users'id=db.Column(db.Integer(),autoincrement=True,primary_key=True)name=db.Column(db.String())created_at=db.Column(db.TIMESTAMP())updated_at=db.Column(db.TIMESTAMP())country_code=db.Column(db.Integer())default_language=db.Column(db.Integer())classLanguages(db.Model):__tablename__='languages'id=db.Column(db.Integer(),primary_key=True)code=db.Column(db.String(2))name=db.Column(db.String())From cliommpath/to/your.ddl# for exampleommtests/test_two_tables.sqlYou can define target path where to save models with-t,–targetflag:# for exampleommtests/test_two_tables.sql-ttest_path/test_models.pyIf you want generate the Pydantic or Dataclasses models - just use flag-mor–models_type=’pydantic’/–models_type=’dataclass’omm/path/to/your.ddl-mdataclass# oromm/path/to/your.ddl--models_typepydanticSmall library is used for parse DDL-https://github.com/xnuinside/simple-ddl-parser.What to do if types not supported in O!MyModels and you cannot wait until PR will be approvedFirst of all, to parse types correct from DDL to models - they must be in types mypping, for Gino it exitst in this file:omymodels/gino/types.pytypes_mappingIf you need to use fast type that not exist in mapping - just do a path before call code with types_mapping.update()for example:fromomymodels.models.ginoimporttypesfromomymodelsimportcreate_modelstypes.types_mapping.update({'your_type_from_ddl':'db.TypeInGino'})ddl="YOUR DDL with your custom your_type_from_ddl"models=create_models(ddl)#### And similar for Pydantic typesfromomymodels.models.pydanticimporttypestypes_mappingfromomymodelsimportcreate_modelstypes.types_mapping.update({'your_type_from_ddl':'db.TypeInGino'})ddl="YOUR DDL with your custom your_type_from_ddl"models=create_models(ddl,models_type='pydantic')Schema defenitionThere is 2 ways how to define schema in Models:Globally in Gino() class and it will be like this:fromginoimportGinodb=Gino(schema="schema_name")And this is a default way for put schema during generation - it takes first schema in tables and use it.But if you work with tables in different schemas, you need to define schema in each model in table_args. O!MyModels can do this also. Just use flag--no-global-schemaif you use cli or put argument ‘schema_global=False’ to create_models() function if you use library from code. Like this:ddl="""
CREATE TABLE "prefix--schema-name"."table" (
_id uuid PRIMARY KEY,
one_more_id int
);
    create unique index table_pk on "prefix--schema-name"."table" (one_more_id) ;
    create index table_ix2 on "prefix--schema-name"."table" (_id) ;
"""result=create_models(ddl,schema_global=False)And result will be this:fromsqlalchemy.dialects.postgresqlimportUUIDfromsqlalchemy.schemaimportUniqueConstraintfromsqlalchemyimportIndexfromginoimportGinodb=Gino()classTable(db.Model):__tablename__='table'_id=db.Column(UUID,primary_key=True)one_more_id=db.Column(db.Integer())__table_args__=(UniqueConstraint(one_more_id,name='table_pk'),Index('table_ix2',_id),dict(schema="prefix--schema-name"))TODO in next releasesAdd Sequence generation in Models (Gino, SQLAlchemy)Add support for pure Python Classes (https://docs.python.org/3/tutorial/classes.html#class-objects)Add support for Tortoise ORM (https://tortoise-orm.readthedocs.io/en/latest/),Add support for DjangoORM ModelsAdd support for Pydal ModelsAdd support for Encode/orm ModelsHow to contributePlease describe issue that you want to solve and open the PR, I will review it as soon as possible.Any questions? Ping me in Telegram:https://t.me/xnuinsideor mailxnuinside@gmail.comIf you see any bugs or have any suggestions - feel free to open the issue. Any help will be appritiated.Appretiation & thanksOne more time, big ‘thank you!’ goes tohttps://github.com/archongumfor Web-version:https://archon-omymodels-online.hf.space/Changelogv0.15.1UpdatesForeign Key processing updates -https://github.com/xnuinside/omymodels/pull/55Move to simple-ddl-parser version 1.Xv0.14.0UpdatesPython 3.11 support.v0.13.0New featureAdded argument ‘schema_global=’ to support SQLAlchemy & Gino different table schemashttps://github.com/xnuinside/omymodels/issues/41v0.12.1Improvementscurrent_timestamp function processed now same was as “now()” function from ddlv0.12.0FixesNow named arguments always went after positional. Fix forhttps://github.com/xnuinside/omymodels/issues/35New feature:Availability to disable auto-name convertion -https://github.com/xnuinside/omymodels/issues/36.
Now, if you want to keep names 1-to-1 as in your DDL file, you can set argumentno_auto_snake_case=Trueand O!MyModels will do nothing with the table or column names.v0.11.1Improvements:added bytes type to pydantic -https://github.com/xnuinside/omymodels/pull/31parser version updated to the latestv0.11.0Fixes:MSSQL column & tables names in [] now is parsed validly  -https://github.com/xnuinside/omymodels/issues/28names like ‘users_WorkSchedule’ now converted correctly to PascalCase like UsersWorkSchedulev0.10.1Update simple-ddl-parser version to 0.21.2v0.10.0Improvements:Meta models moved to separate package -https://github.com/xnuinside/table-metacommonmodule renamed tofrom_ddl, but anyway please use public API as imports from main module:from omymodels import create_modelsorfrom omymodels import convert_modelsFixes:Fixed bunch of bugs in converter, but it stil in ‘beta’.Previously you can generate models if was any tables in ddl. Now you can also generate Enum models if in ddl you have only CREATE TYPE statements.String enums now in any models types will be inherit from (str, Enum)Features:Added converter feature to convert one model type to another (excluding SQLAlchemy Core (Tables)).
Now with more tests for supported models, but still in Beta with bucnh of issues.v0.9.0Features:Added beta models converter from one type of models to another.
To use models convertor:fromomymodelsimportconvert_modelsmodels_from="""

class MaterialType(str, Enum):

    article = "article"
    video = "video"


@dataclass
class Material:

    id: int
    title: str
    description: str
    link: str
    type: MaterialType
    additional_properties: Union[dict, list]
    created_at: datetime.datetime
    updated_at: datetime.datetime

"""result=convert_models(models_from,models_type="gino")print(result)wheremodels_type- type of models that you want to get as a resultNow if O!MyModels does not know how to convert type - he just leave it as is.Fixes:In Dataclass & Pydantic generators now Decimals & Floats converted to float (previously was int).v0.8.4Now if tables was not found in input DDL - models generator raise NoTable error. if you want to have still silent exit if no tables, please use flag: exit_silentv0.8.3Added fundamental concept of TableMetaModel - class that unifies metadata parsed from different classes/ORM models types/DDLs to one standard to allow easy way convert one models to another
in next releases it will be used for converter from one type of models to another.Fixed issue:https://github.com/xnuinside/omymodels/issues/18“NOW() not recognized as now()”Fixed issue:https://github.com/xnuinside/omymodels/issues/19“Default value of now() always returns same time, use field for dataclass”v0.8.1Parser version is updated (fixed several issues with generation)Fixed issue with Unique Constraint after schema in SQLAlchemy Corev0.8.0Fix –defaults-off flag in cliAdded support for SQLAlchemy Core Tables generatingAdded examples folder in githubomymodels/exampleFix issue with ForeignKey in SQLAlchemyv0.7.0Added generation for SQLAlchemy models (defaults from DDLs are setting up as ‘server_default’)Added defaults for Pydantic modelsAdded flag to generate Pydantic & Dataclass models WITHOUT defaultsdefaults_off=True(by default it is False). And cli flag –defaults-offFixed issue with Enum types with lower case names in DDLsFixed several issues with Dataclass generation (default with datetime & Enums)‘”’ do not remove from defaults nowv0.6.0O!MyModels now also can generate python Dataclass from DDL. Use argument models_type=’dataclass’ or if you use the cli flag –models_type dataclass or -m dataclassAdded ForeignKey generation to GinoORM Models, added support for ondelete and onupdatev0.5.0Added Enums/IntEnums types for Gino & PydanticAdded UUID typeAdded keyschema_globalin create_models method (by default schema_global = True).
If you set schema_global=False schema if it exists in ddl will be defined for each table (model) in table args.
This way you can have differen schemas per model (table). By default schema_global=True - this mean for all
table only one schema and it is defined indb =Gino(schema="prefix--schema-name").If column is a primary key (primary_key=True) nullable argument not showed, because primary keys always are not null.To cli was added flag ‘–no-global-schema’ to set schema in table_args.v0.4.1Added correct work with table names contains multiple ‘-’v0.4.0Added generation for Pydantic models from ddlMain method create_gino_models renamed to create_modelsv0.3.0Generated Index for ‘index’ statement intable_args(not unique constrait as previously)Fix issue with column size as tuple (4,2)v0.2.0Valid generating columns in models: autoincrement, default, type, arrays, unique, primary key and etc.Added creatingtable_argsfor indexes