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.
—
Comprehensive error handling and exception classes for robust DDL parsing with detailed error reporting and debugging capabilities. The exception system provides clear error messages and maintains backward compatibility.
Primary exception class for all simple-ddl-parser related errors with comprehensive error information.
class SimpleDDLParserException(Exception):
"""
Base exception for simple DDL parser library.
Raised when DDL parsing encounters errors such as:
- Invalid DDL syntax
- Unsupported SQL constructs
- Parsing conflicts or ambiguities
- File reading errors
- Configuration errors
Inherits from: Exception
"""Alias for the base exception class to maintain backward compatibility with older code.
DDLParserError = SimpleDDLParserExceptionfrom simple_ddl_parser import DDLParser, SimpleDDLParserException
try:
parser = DDLParser("INVALID DDL SYNTAX")
result = parser.run()
except SimpleDDLParserException as e:
print(f"Parsing error: {e}")from simple_ddl_parser import DDLParser, DDLParserError
try:
parser = DDLParser(malformed_ddl)
result = parser.run()
except DDLParserError as e:
print(f"DDL parsing failed: {e}")from simple_ddl_parser import DDLParser
# Silent mode (default): Suppresses exceptions, returns partial results
parser = DDLParser(problematic_ddl, silent=True)
result = parser.run() # Returns what it could parse, no exception
# Non-silent mode: Raises exceptions on parsing errors
parser = DDLParser(problematic_ddl, silent=False)
try:
result = parser.run()
except SimpleDDLParserException as e:
print(f"Parsing failed with error: {e}")from simple_ddl_parser import parse_from_file, SimpleDDLParserException
try:
result = parse_from_file("schema.sql", parser_settings={"silent": False})
except FileNotFoundError:
print("DDL file not found")
except SimpleDDLParserException as e:
print(f"DDL parsing error: {e}")
except UnicodeDecodeError:
print("File encoding error - try specifying encoding parameter")from simple_ddl_parser import DDLParser, SimpleDDLParserException
import logging
# Configure logging for detailed error information
logging.basicConfig(level=logging.DEBUG)
def robust_ddl_parsing(ddl_content):
"""Robust DDL parsing with comprehensive error handling."""
try:
# Try with silent mode first for partial results
parser = DDLParser(ddl_content, silent=True, debug=True)
result = parser.run()
if not result:
# If no results, try non-silent mode for detailed error
parser = DDLParser(ddl_content, silent=False, debug=True)
result = parser.run()
return result
except SimpleDDLParserException as e:
print(f"DDL parsing failed: {e}")
return None
except Exception as e:
print(f"Unexpected error during DDL parsing: {e}")
return None
# Usage
parsed_data = robust_ddl_parsing(complex_ddl)
if parsed_data:
print("Parsing successful")
else:
print("Parsing failed - check logs for details")# This will raise SimpleDDLParserException in non-silent mode
invalid_ddl = "CREATE INVALID SYNTAX"
parser = DDLParser(invalid_ddl, silent=False)
try:
result = parser.run()
except SimpleDDLParserException:
print("Invalid DDL syntax detected")# Some advanced SQL features might not be supported
advanced_ddl = """
CREATE TABLE test (
id INT,
data JSON CHECK (JSON_VALID(data)) -- Complex check constraint
);
"""
parser = DDLParser(advanced_ddl, silent=False)
try:
result = parser.run()
except SimpleDDLParserException as e:
print(f"Unsupported SQL construct: {e}")try:
# Invalid log level
parser = DDLParser(ddl, log_level="INVALID_LEVEL")
except (ValueError, SimpleDDLParserException) as e:
print(f"Configuration error: {e}")from simple_ddl_parser import DDLParser
# Enable debug mode for detailed error information
parser = DDLParser(
problematic_ddl,
silent=False,
debug=True,
log_file="parser_debug.log",
log_level="DEBUG"
)
try:
result = parser.run()
except SimpleDDLParserException as e:
print(f"Detailed error: {e}")
# Check parser_debug.log for additional contextdef parse_schema_files(file_list):
"""Parse multiple schema files with error aggregation."""
results = []
errors = []
for file_path in file_list:
try:
result = parse_from_file(file_path, parser_settings={"silent": False})
results.append({"file": file_path, "data": result})
except SimpleDDLParserException as e:
errors.append({"file": file_path, "error": str(e)})
if errors:
error_summary = "; ".join([f"{err['file']}: {err['error']}" for err in errors])
raise SimpleDDLParserException(f"Multiple parsing errors: {error_summary}")
return resultsimport logging
from simple_ddl_parser import DDLParser, SimpleDDLParserException
logger = logging.getLogger(__name__)
def production_ddl_parse(ddl_content, strict=False):
"""Production-ready DDL parsing with proper error handling."""
try:
parser = DDLParser(
ddl_content,
silent=not strict, # Silent mode unless strict parsing required
log_level=logging.WARNING
)
result = parser.run()
if not result and not strict:
logger.warning("DDL parsing returned no results")
return result
except SimpleDDLParserException as e:
logger.error(f"DDL parsing failed: {e}")
if strict:
raise # Re-raise in strict mode
return None
except Exception as e:
logger.error(f"Unexpected parsing error: {e}")
raise # Always re-raise unexpected errorsInstall with Tessl CLI
npx tessl i tessl/pypi-simple-ddl-parser