CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-simple-ddl-parser

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.

Pending
Overview
Eval results
Files

exceptions.mddocs/

Exception Handling

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.

Capabilities

Base Exception Class

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
    """

Backward Compatibility Alias

Alias for the base exception class to maintain backward compatibility with older code.

DDLParserError = SimpleDDLParserException

Usage Examples

Basic Exception Handling

from simple_ddl_parser import DDLParser, SimpleDDLParserException

try:
    parser = DDLParser("INVALID DDL SYNTAX")
    result = parser.run()
except SimpleDDLParserException as e:
    print(f"Parsing error: {e}")

Using Backward Compatible Alias

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}")

Silent Mode vs Exception Mode

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}")

File Parsing Exception Handling

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")

Comprehensive Error Handling

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")

Common Error Scenarios

Invalid DDL Syntax

# 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")

Unsupported SQL Constructs

# 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}")

Configuration Errors

try:
    # Invalid log level
    parser = DDLParser(ddl, log_level="INVALID_LEVEL")
except (ValueError, SimpleDDLParserException) as e:
    print(f"Configuration error: {e}")

Debugging with Exceptions

Enable Debug Mode for Better Error Messages

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 context

Exception Chaining

def 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 results

Best Practices

Gradual Error Handling

  1. Start with silent mode to get partial results
  2. Switch to non-silent mode if no results for detailed errors
  3. Enable debug mode for complex parsing issues
  4. Use logging to capture detailed parsing information

Production Error Handling

import 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 errors

Install with Tessl CLI

npx tessl i tessl/pypi-simple-ddl-parser

docs

cli.md

core-parsing.md

exceptions.md

index.md

input-dialects.md

output-formatting.md

tile.json