Coverage for downtify/db/sql.py: 100%
50 statements
« prev ^ index » next coverage.py v7.17.4, created at 2026-11-21 22:18 +0000
« prev ^ index » next coverage.py v7.17.4, created at 2026-11-21 22:18 +0000
1"""Translate SQLite-style SQL into psycopg3 pyformat SQL."""
3from __future__ import annotations
5import functools
8def _double(text: str) -> str:
9 """Escape literal percent signs for psycopg's pyformat parser."""
10 return text.replace('%', '%%')
13def _copy_quoted(sql: str, start: int, quote: str, out: list[str]) -> int:
14 """Copy a quoted run beginning at ``start``; return the index after it.
16 A doubled quote character inside the run is an escaped quote. An
17 unterminated run is copied to the end of the string.
18 """
19 out.append(quote)
20 i = start + 1
21 n = len(sql)
22 while i < n:
23 ch = sql[i]
24 if ch == quote:
25 if i + 1 < n and sql[i + 1] == quote:
26 out.append(quote * 2)
27 i += 2
28 continue
29 out.append(quote)
30 return i + 1
31 out.append(_double(ch))
32 i += 1
33 return i
36def _copy_line_comment(sql: str, start: int, out: list[str]) -> int:
37 """Copy a ``--`` comment up to (not including) the newline."""
38 end = sql.find('\n', start)
39 if end == -1:
40 end = len(sql)
41 out.append(_double(sql[start:end]))
42 return end
45def _copy_block_comment(sql: str, start: int, out: list[str]) -> int:
46 """Copy a ``/* ... */`` comment; an unterminated one runs to the end."""
47 end = sql.find('*/', start + 2)
48 end = len(sql) if end == -1 else end + 2
49 out.append(_double(sql[start:end]))
50 return end
53@functools.lru_cache(maxsize=2048)
54def to_pyformat(sql: str) -> str:
55 """Convert SQLite qmark SQL to psycopg3 pyformat SQL.
57 Every literal ``%`` becomes ``%%`` (psycopg parses placeholders
58 everywhere, including inside literals and comments). Outside string
59 literals, quoted identifiers and comments, each ``?`` becomes ``%s``.
60 Everything else is copied unchanged. An unterminated quote or comment
61 is copied through to the end of the string without raising.
63 Apply this only when parameters are passed (even an empty tuple). A
64 no-parameter script (for example ``executescript``) must NOT be
65 translated: psycopg does not unescape ``%%`` when no params are given.
66 """
67 out: list[str] = []
68 i = 0
69 n = len(sql)
70 while i < n:
71 ch = sql[i]
72 if ch in {"'", '"'}:
73 i = _copy_quoted(sql, i, ch, out)
74 elif ch == '-' and sql.startswith('--', i):
75 i = _copy_line_comment(sql, i, out)
76 elif ch == '/' and sql.startswith('/*', i):
77 i = _copy_block_comment(sql, i, out)
78 elif ch == '?':
79 out.append('%s')
80 i += 1
81 else:
82 out.append(_double(ch))
83 i += 1
84 return ''.join(out)