Simple DDL Parser to parse SQL & dialects like HQL, TSQL (MSSQL), Oracle, AWS Redshift, Snowflake, MySQL, PostgreSQL, etc ddl files to json/python dict with full information about columns: types, defaults, primary keys, etc.; sequences, alters, custom types & other entities from ddl.
Maintained.Last release 8 months ago, commits in 0 of the last 26 weeks. Weaker on commit activity and security practices.
As maintainer, I guarantee that any backward incompatible changes will not be done in patch or minor version. But! Pay attention that sometimes output in keywords can be changed in minor version because of fixing wrong behaviour in past.
The full list of updates can be found in the Changelog below (at the end of README).
Version 1.0.0 was released due to significant changes in the output structure and a stricter approach regarding the scope of the produced output. Now, you must provide the argument 'output_mode=name_of_your_dialect' if you wish to see arguments/properties specific to a particular dialect
How does it work?
Parser supports:
SQL
HQL (Hive)
MSSQL dialect
Oracle dialect
MySQL dialect
PostgreSQL dialect
BigQuery
Redshift
Snowflake
SparkSQL
IBM DB2 dialect
Informix/GBase 8s dialect
You can check dialects sections after Supported Statements section to get more information that statements from dialects already supported by parser. If you need to add more statements or new dialects - feel free to open the issue.
Feel free to open Issue with DDL sample
Pay attentions that I'm adding functional tests for all supported statement, so if you see that your statement is failed and you didn't see it in the test 99,9% that I did n't have sample with such SQL statement - so feel free to open the issue and I will add support for it.
If you need some statement, that not supported by parser yet: please provide DDL example & information about that is it SQL dialect or DB.
Types that are used in your DB does not matter, so parser must also work successfully to any DDL for SQL DB. Parser is NOT case sensitive, it did not expect that all queries will be in upper case or lower case. So you can write statements like this:
Alter Table Persons ADD CONSTRAINT CHK_PersonAge CHECK (Age>=18 AND City='Sandnes');
It will be parsed as is without errors.
If you have samples that cause an error - please open the issue (but don't forget to add ddl example), I will be glad to fix it.
Extract additional information from HQL (& other dialects)
In some dialects like HQL there is a lot of additional information about table like, fore example, is it external table, STORED AS, location & etc. This property will be always empty in 'classic' SQL DB like PostgreSQL or MySQL and this is the reason, why by default this information are 'hidden'.
Also some fields hidden in HQL, because they are simple not exists in HIVE, for example 'deferrable_initially'
To get this 'hql' specific details about table in output please use 'output_mode' argument in run() method.
example:
ddl = """
CREATE TABLE IF NOT EXISTS default.salesorderdetail(
SalesOrderID int,
ProductID int,
OrderQty int,
LineTotal decimal
)
PARTITIONED BY (batch_id int, batch_id2 string, batch_32 some_type)
LOCATION 's3://datalake/table_name/v1'
ROW FORMAT DELIMITED
FIELDS TERMINATED BY ','
COLLECTION ITEMS TERMINATED BY '\002'
MAP KEYS TERMINATED BY '\003'
STORED AS TEXTFILE
"""
result = DDLParser(ddl).run(output_mode="hql")
print(result)
And you will get output with additional keys 'stored_as', 'location', 'external', etc.
DDLParser(ddl).run()
.run() method contains several arguments, that impact changing output result. As you can saw upper exists argument output_mode that allow you to set dialect and get more fields in output relative to chosen dialect, for example 'hql'. Possible output_modes: ['redshift', 'spark_sql', 'mysql', 'bigquery', 'mssql', 'databricks', 'sqlite', 'vertics', 'ibm_db2', 'postgres', 'oracle', 'hql', 'snowflake', 'sql']
Argument custom_output_schema allows you to reshape output into a schema format. Built-in support currently includes bigquery (JSON schema array), and you can register your own schema converters.
When custom_output_schema="bigquery" is used, the parser will default to output_mode="bigquery" for dialect-specific syntax.
from simple_ddl_parser import DDLParser, register_custom_output_schema
ddl = "CREATE TABLE users (id INT NOT NULL, email VARCHAR(255));"
bigquery_schema = DDLParser(ddl).run(custom_output_schema="bigquery")
def to_custom_schema(output):
return [{"custom": True, "tables": len(output)}]
register_custom_output_schema("custom", to_custom_schema)
custom_schema = DDLParser(ddl).run(custom_output_schema="custom")
Also in .run() method exists argument group_by_type (by default: False). By default output of parser looks like a List with Dicts where each dict == one entity from ddl (table, sequence, type, etc). And to understand that is current entity you need to check Dict like: if 'table_name' in dict - this is a table, if 'type_name' - this is a type & etc.
To make work little bit easy you can set group_by_type=True and you will get output already sorted by types, like:
DROP COLUMN - with or without COLUMN keyword (Oracle style)
MODIFY COLUMN - with or without COLUMN keyword (Oracle style)
ALTER COLUMN - SQL Server style
RENAME COLUMN
ADD FOREIGN KEY - with or without CONSTRAINT
ADD PRIMARY KEY - with or without CONSTRAINT
ADD UNIQUE
ADD CHECK
ADD DEFAULT
Multiple operations can be combined in a single ALTER statement using commas:
ALTER TABLE my_table ADD col1 int, ADD col2 varchar;
ALTER TABLE my_table DROP COLUMN col1, DROP COLUMN col2;
ALTER TABLE my_table MODIFY COLUMN col1 int, MODIFY COLUMN col2 varchar;
All ALTER statements are parsed and information is stored in the 'alter' key of the table's dict.
For example, please check alter statement tests - tests/test_alter_statements.py
More examples & tests
You can find in tests/ folder.
Dump result in json
To dump result in json use argument .run(dump=True)
You also can provide a path where you want to have a dumps with schema with argument .run(dump_path='folder_that_use_for_dumps/')
Raise error if DDL cannot be parsed by Parser
By default Parser does not raise the error if some statement cannot be parsed - and just skip & produce empty output.
To change this behavior you can pass 'silent=False' argumen to main parser class, like:
DDLParser(.., silent=False)
Normalize names
Use DDLParser(.., normalize_names=True)flag that change output of parser:
If flag is True (default 'False') then all identifiers will be returned without '[', '"' and other delimiters that used in different SQL dialects to separate custom names from reserved words & statements.
For example, if flag set 'True' and you pass this input:
CREATE TABLE [dbo].[TO_Requests](
[Request_ID] [int] IDENTITY(1,1) NOT NULL,
[user_id] [int]
In output you will have names like 'dbo' and 'TO_Requests', not '[dbo]' and '[TO_Requests]'.
Supported Statements
CREATE [OR REPLACE] TABLE [ IF NOT EXISTS ] + columns definition, columns attributes: column name + type + type size(for example, varchar(255)), UNIQUE, PRIMARY KEY, DEFAULT, CHECK, NULL/NOT NULL, REFERENCES, ON DELETE, ON UPDATE, NOT DEFERRABLE, DEFERRABLE INITIALLY, GENERATED ALWAYS / GENERATED BY DEFAULT AS IDENTITY, STORED, COLLATE, inline -- comments
STATEMENTS: PRIMARY KEY, CHECK, FOREIGN KEY in table definitions (in create table();)
ALTER TABLE STATEMENTS: ADD CHECK (with CONSTRAINT), ADD FOREIGN KEY (with CONSTRAINT), MySQL-style ADD CONSTRAINT ... FOREIGN KEY constraint_name (...), DROP FOREIGN KEY, ADD UNIQUE, ADD DEFAULT FOR, ALTER TABLE ONLY, ALTER TABLE IF EXISTS; ALTER .. PRIMARY KEY; ALTER .. USING INDEX TABLESPACE; ALTER .. ADD; ALTER .. MODIFY; ALTER .. ALTER COLUMN; multiple ADD / DROP / MODIFY operations in one statement; etc
PARTITION BY statement
Includes PostgreSQL/Greenplum-style child partition definitions after PARTITION BY, for example PARTITION BY col(id) (PARTITION a VALUES('12') WITH (...), ...)
CREATE TYPE statement: AS TABLE, AS ENUM, AS OBJECT, INTERNALLENGTH, INPUT, OUTPUT
LIKE statement (in this and only in this case to output will be added 'like' keyword with information about table from that we did like - 'like': {'schema': None, 'table_name': 'Old_Users'}).
CREATE TABLE ... AS SELECT ... FROM source_table statement, when the source table is defined in the same DDL script. Supported for a single source table with SELECT * or an explicit column list; the new table gets copied column definitions for the selected columns only.
AUTO_INCREMENT in column definitions and table properties
COLLATE, COMMENT, CHARACTER SET / CHARSET table options
INDEX statements in table definitions, including VISIBLE / INVISIBLE indexes
UNIQUE KEY (...), named or unnamed KEY (...) / INDEX (...), and MySQL index prefix lengths such as column(32) inside table definitions
DROP TABLE IF EXISTS is parsed as a statement in output, and MySQL dump-style inline comments like /*$wgDBprefix*/table_name are handled in DDL files
DROP DATABASE [IF EXISTS] is parsed as a statement in output
ALTER TABLE ... AUTO_INCREMENT = ... updates MySQL table output and is tracked in alter["auto_increments"]
ALTER TABLE ... DEFAULT CHARACTER SET ... COLLATE ... updates MySQL table charset/collation, and ALTER TABLE ... CHANGE old_col new_col type ... applies MySQL column changes from upgrade/dump scripts
Common dump/admin statements such as PRAGMA, BEGIN TRANSACTION, LOCK/UNLOCK TABLES, and CREATE/DROP USER are ignored so mixed schema dump files parse without strict-mode errors
MSSQL
CONSTRAINT [CLUSTERED]... PRIMARY KEY
CONSTRAINT ... WITH statement
PERIOD FOR SYSTEM_TIME in CREATE TABLE statement
ON [PRIMARY] after CREATE TABLE statement (sample in test files test_mssql_specific.py)
HQL/Spark SQL nested complex types like ARRAY<STRUCT<... COMMENT '...'> now parse correctly when inner STRUCT fields include COMMENT '...', instead of failing in strict mode. https://github.com/xnuinside/simple-ddl-parser/issues/137
MySQL dump-style DDL files now parse more reliably: DROP TABLE IF EXISTS is supported in parser output and no longer fails in strict mode, inline /*...*/ comment placeholders inside identifiers are handled, and table-level KEY / UNIQUE KEY definitions with prefix lengths like column(32) are supported. https://github.com/xnuinside/simple-ddl-parser/issues/148
MySQL-style ALTER TABLE ... ADD CONSTRAINT ... FOREIGN KEY constraint_name (...) REFERENCES ... statements now parse correctly instead of failing on the duplicated foreign key name. ALTER TABLE ... DROP FOREIGN KEY ... is also supported, and simple DROP VIEW / CREATE VIEW ... AS ... statements are now recognized in parser output. https://github.com/xnuinside/simple-ddl-parser/issues/149
Mixed SQLite/MySQL dump files now ignore wrapper/admin statements such as PRAGMA, BEGIN TRANSACTION, LOCK/UNLOCK TABLES, and CREATE/DROP USER instead of failing in strict mode. DROP DATABASE [IF EXISTS] is now parsed as its own output statement, and MySQL ALTER TABLE ... AUTO_INCREMENT = ... updates table output plus alter["auto_increments"]. https://github.com/xnuinside/simple-ddl-parser/issues/146
MySQL issue-style upgrade scripts now parse ALTER TABLE ... DEFAULT CHARACTER SET ... COLLATE ... without failing in strict mode, and MySQL ALTER TABLE ... CHANGE old_col new_col type ... applies modified column metadata in parser output. https://github.com/xnuinside/simple-ddl-parser/issues/145
PostgreSQL/Greenplum-style PARTITION BY ... (PARTITION ... VALUES(...) WITH (...)) table definitions no longer return an empty result when partition definitions follow PARTITION BY. https://github.com/xnuinside/simple-ddl-parser/issues/118
Expanded README coverage for supported parser features, including the same-DDL CREATE TABLE ... AS SELECT ... limitation and recently added dialect features.
PostgreSQL GENERATED ALWAYS AS (...) STORED now parses complex CASE expressions with regex/casts and nested function calls (for example ~ '^\d+$'::text with lpad(...)). https://github.com/xnuinside/simple-ddl-parser/issues/267 (Fix #267)