"""Pure subquery LIMIT/OFFSET injection for paging (non-destructive). Unlike `_inject_limit` (which uses AST rewriting and adds +1 for truncation detection), `inject_limit_offset` wraps the query as a subquery and applies LIMIT/OFFSET verbatim. This preserves any existing LIMIT that was part of the user's query (it becomes part of the inner subquery), and adds paging on top. """ def inject_limit_offset(sql: str, *, limit: int, offset: int = 0) -> str: """Wrap query as subquery and apply LIMIT/OFFSET non-destructively. The original query (including any user LIMIT) becomes the inner subquery, so no existing LIMIT clause is overwritten. OFFSET clause is omitted when offset == 0 to keep the SQL clean. """ inner = sql.strip().rstrip(";") clause = f"LIMIT {int(limit)}" if offset: clause += f" OFFSET {int(offset)}" return f"SELECT * FROM (\n{inner}\n) AS _tht_page {clause}"