Skip to content

SQL objects from get_sql() have no parsed expression, breaking select_with_total() #283

@cofin

Description

@cofin

Description

SQL objects loaded from .sql files via db_manager.get_sql('query-name') have expression=None, but select_with_total() requires a parsed expression to create COUNT queries.

Steps to Reproduce

  1. Load SQL files with db_manager.load_sql_files('/path/to/sql')
  2. Get a SQL object with sql = db_manager.get_sql('my-query')
  3. Call driver.select_with_total(sql, *filters, schema_type=MySchema)

Expected Behavior

The SQL object should either:

  • Have its expression attribute populated by parsing the SQL string
  • Or _create_count_query() should handle raw SQL strings without a parsed expression

Actual Behavior

sql = db_manager.get_sql('list-users')
print(sql.sql)  # Returns valid SQL string: 'SELECT id, email... FROM user_account'
print(sql.expression)  # Returns: None

When select_with_total() is called, it fails with:

sqlspec.exceptions.ImproperConfigurationError: Cannot create COUNT query from empty SQL expression

The error comes from _create_count_query() in driver/_common.py:

def _create_count_query(self, original_sql: "SQL") -> "SQL":
    if not original_sql.expression:
        msg = "Cannot create COUNT query from empty SQL expression"
        raise ImproperConfigurationError(msg)

Environment

  • SQLSpec version: 0.32.0 (from main branch)
  • Python: 3.12

Workaround

None known - SQL file-based queries cannot use select_with_total()/pagination with count.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions