sql-metadata is a Python library that parses SQL queries to extract metadata such as table names, column names, query type (e.g., SELECT, INSERT, UPDATE, DELETE), and more. It leverages the tokenized query output from the `sqlparse` library. The current version is 2.20.0, and it maintains an active release cadence, often releasing minor versions to improve parsing accuracy and update its `sqlparse` dependency.
pip install sql-metadataVerified import paths — ran on the pinned version, not inferred.
Initialize a Parser object with a SQL string to extract various metadata attributes.
Upgrade Python to 3.9 or newer, or downgrade sql-metadata to <2.16.0.
If 'source' is expected as the last column, verify results on v2.20.0. Consider restructuring the query or inspecting `parser.tokens` directly for more granular control if this specific edge case causes issues.
Ensure you are using the latest version of `sql-metadata` to benefit from the most recent parsing improvements and bug fixes, especially for complex or less common SQL constructs.
When `sql-metadata` updates its `sqlparse` dependency (often noted in release logs), review `sqlparse`'s changelog for any potential regressions or behavior changes that might affect your SQL parsing.
First, ensure installation: `pip install sql-metadata`. Then, use the correct import statement: `from sql_metadata.parser import Parser`.
Access the metadata directly as attributes: `from sql_metadata.parser import Parser sql_query = 'SELECT col1 FROM my_table' parser = Parser(sql_query) query_type = parser.query_type tables = parser.tables`
Ensure that the argument passed to the `Parser` constructor is a string representing the SQL query: `from sql_metadata.parser import Parser sql_query = "SELECT col1 FROM my_table" # Must be a string parser = Parser(sql_query)`
Ensure your SQL query is syntactically correct and adheres to standard SQL. If the query is complex but valid, try simplifying it. Also, ensure both `sql-metadata` and `sqlparse` are updated to their latest versions: `pip install --upgrade sql-metadata sqlparse`.