Skip to content

Commit 165666b

Browse files
committed
Add PHPUnit tests workflow for Turso DB
1 parent 11cb7f2 commit 165666b

12 files changed

Lines changed: 2339 additions & 0 deletions
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
#!/usr/bin/env python3
2+
"""
3+
Neutralize Turso's stub! macro (bindings/c/src/lib.rs).
4+
5+
Many SQLite C API functions are stubbed out via `stub!()`, which expands
6+
to `todo!("X is not implemented")`. pdo_sqlite hits one during PDO
7+
construction (sqlite3_set_authorizer) and the panic aborts the PHP
8+
process. Rewrite the body to return a zeroed value of the function's
9+
return type (0 / SQLITE_OK for ints, NULL for pointers) instead.
10+
"""
11+
12+
import sys
13+
14+
PATH = 'bindings/c/src/lib.rs'
15+
OLD = 'todo!("{} is not implemented", stringify!($fn));'
16+
NEW = 'return unsafe { std::mem::zeroed() };'
17+
18+
with open(PATH) as f:
19+
src = f.read()
20+
if OLD not in src:
21+
sys.exit(f'{PATH}: stub! todo!() body not found')
22+
n = src.count(OLD)
23+
src = src.replace(OLD, NEW)
24+
with open(PATH, 'w') as f:
25+
f.write(src)
26+
print(f'patched stub! macro ({n} occurrence{"s" if n != 1 else ""})')
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
#!/usr/bin/env python3
2+
"""
3+
sqlite3_column_* — early-return when no row is present (bindings/c/src/lib.rs).
4+
5+
The sqlite3_column_* functions `.expect()` that a row is present, but
6+
pdo_sqlite legitimately calls them on statements that have not yet
7+
stepped to SQLITE_ROW (e.g. for column metadata). Replace the expect
8+
with an early return of the type's "null" value, matching SQLite's
9+
actual behaviour.
10+
"""
11+
12+
import re
13+
import sys
14+
15+
PATH = 'bindings/c/src/lib.rs'
16+
17+
DEFAULTS = {
18+
'sqlite3_column_type': 'SQLITE_NULL',
19+
'sqlite3_column_int': '0',
20+
'sqlite3_column_int64': '0',
21+
'sqlite3_column_double': '0.0',
22+
'sqlite3_column_blob': 'std::ptr::null()',
23+
'sqlite3_column_bytes': '0',
24+
'sqlite3_column_text': 'std::ptr::null()',
25+
}
26+
27+
PATTERN = re.compile(
28+
r'(pub unsafe extern "C" fn (sqlite3_column_\w+)\([^)]*\)[^{]*\{)'
29+
r'((?:[^{}]|\{[^{}]*\})*?)'
30+
r'(let row = stmt\s*\.stmt\s*\.row\(\)\s*'
31+
r'\.expect\("Function should only be called after `SQLITE_ROW`"\);)',
32+
re.DOTALL,
33+
)
34+
35+
36+
def repl(m):
37+
header, name, body, _ = m.group(1), m.group(2), m.group(3), m.group(4)
38+
default = DEFAULTS.get(name, '0')
39+
guarded = (
40+
'let row = match stmt.stmt.row() {\n'
41+
' Some(r) => r,\n'
42+
f' None => return {default},\n'
43+
' };'
44+
)
45+
return header + body + guarded
46+
47+
48+
with open(PATH) as f:
49+
src = f.read()
50+
src, n = PATTERN.subn(repl, src)
51+
if n == 0:
52+
sys.exit(f'{PATH}: no sqlite3_column_* expect-row blocks matched')
53+
with open(PATH, 'w') as f:
54+
f.write(src)
55+
print(f'patched {n} sqlite3_column_* functions')
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
#!/usr/bin/env python3
2+
"""
3+
create_function_v2 — don't fire the old destroy callback on slot reuse (bindings/c/src/lib.rs).
4+
5+
Turso's create_function_v2 invokes the previous FuncSlot's destroy
6+
callback when re-registering a UDF with the same name. In practice
7+
(PHPUnit) this means:
8+
- setUp #1 opens PDO A, registers 44 UDFs, each with a destroy
9+
callback + p_app pointing to A.
10+
- tearDown closes PDO A — Turso's sqlite3_close doesn't clear those
11+
FuncSlots.
12+
- setUp #2 opens PDO B, re-registers the same 44 names. Turso invokes
13+
the OLD destroy callback with the now-dangling A p_app, which trips
14+
pdo_sqlite and hangs the process.
15+
16+
Discard the old slot without invoking its destroy callback. Since Turso
17+
then has no safe point at which to invoke the callback, stop retaining it;
18+
the callback still fires at real PDO-destruction time from the PHP side.
19+
"""
20+
21+
import sys
22+
23+
PATH = 'bindings/c/src/lib.rs'
24+
OLD_FIELD = (
25+
' destroy: usize, // Option<unsafe extern "C" fn(*mut c_void)> stored as usize for Send\n'
26+
)
27+
OLD_APP_FIELD = ' p_app: usize, // *mut c_void stored as usize for Send\n'
28+
NEW_APP_FIELD = ' p_app: usize, // *mut c_void stored as usize for Send\n'
29+
OLD_COMMENT = (
30+
' // Allocate a bridge slot. Reuse an existing slot with the same name\n'
31+
' // (invoking the old destroy callback) before falling back to a free slot.\n'
32+
)
33+
NEW_COMMENT = (
34+
' // Allocate a bridge slot. Reuse an existing slot with the same name\n'
35+
' // before falling back to a free slot.\n'
36+
)
37+
OLD_CAST = (
38+
' // Cast the destroy callback.\n'
39+
' let destroy_fn: Option<unsafe extern "C" fn(*mut ffi::c_void)> =\n'
40+
' _destroy.map(|f| std::mem::transmute(f));\n'
41+
'\n'
42+
)
43+
OLD = (
44+
' // Reuse existing slot — invoke old destroy callback on old user data.\n'
45+
' if let Some(old) = slots[id].take() {\n'
46+
' if old.destroy != 0 {\n'
47+
' let old_destroy: unsafe extern "C" fn(*mut ffi::c_void) =\n'
48+
' std::mem::transmute(old.destroy);\n'
49+
' old_destroy(old.p_app as *mut ffi::c_void);\n'
50+
' }\n'
51+
' }\n'
52+
)
53+
NEW = (
54+
" // Don't invoke the old destroy callback here — in PDO\n"
55+
" // usage the previous slot's p_app often belongs to a db\n"
56+
' // that has already been closed, so the callback UAFs.\n'
57+
' let _ = slots[id].take();\n'
58+
)
59+
OLD_STORE = ' destroy: destroy_fn.map_or(0, |f| f as usize),\n'
60+
61+
with open(PATH) as f:
62+
s = f.read()
63+
if OLD_FIELD not in s:
64+
sys.exit(f'{PATH}: FuncSlot destroy field not found')
65+
s = s.replace(OLD_FIELD, '', 1)
66+
if OLD_APP_FIELD not in s:
67+
sys.exit(f'{PATH}: FuncSlot p_app field not found')
68+
s = s.replace(OLD_APP_FIELD, NEW_APP_FIELD, 1)
69+
if OLD_COMMENT not in s:
70+
sys.exit(f'{PATH}: bridge slot allocation comment not found')
71+
s = s.replace(OLD_COMMENT, NEW_COMMENT, 1)
72+
if OLD_CAST not in s:
73+
sys.exit(f'{PATH}: destroy callback cast not found')
74+
s = s.replace(OLD_CAST, '', 1)
75+
if OLD not in s:
76+
sys.exit(f'{PATH}: slot destroy block not found')
77+
s = s.replace(OLD, NEW, 1)
78+
if OLD_STORE not in s:
79+
sys.exit(f'{PATH}: FuncSlot destroy assignment not found')
80+
s = s.replace(OLD_STORE, '', 1)
81+
with open(PATH, 'w') as f:
82+
f.write(s)
83+
print('patched slot-reuse destroy invocation')
Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
#!/usr/bin/env python3
2+
"""
3+
sqlite3_finalize / stmt_run_to_completion — try_lock to dodge GC re-entry deadlock.
4+
5+
sqlite3_finalize uses a non-reentrant std::sync::Mutex on the db. PHP's
6+
cycle GC can fire a PDO statement destructor while another statement's
7+
sqlite3_step is in progress (i.e., from inside a UDF callback whose
8+
bridge re-enters PHP). The outer step holds the mutex, the inner
9+
finalize blocks on it, and we deadlock.
10+
11+
Fix: use try_lock; on contention, skip the stmt_list unlink and the
12+
drain. The list is only traversed by sqlite3_next_stmt (which
13+
pdo_sqlite doesn't call) and dropped on sqlite3_close, so a stale entry
14+
is harmless; the stmt's own Box is still freed below.
15+
"""
16+
17+
import sys
18+
19+
PATH = 'bindings/c/src/lib.rs'
20+
21+
OLD_FINALIZE = (
22+
' if !stmt_ref.db.is_null() {\n'
23+
' let db = &mut *stmt_ref.db;\n'
24+
' let mut db_inner = db.inner.lock().unwrap();\n'
25+
'\n'
26+
' if db_inner.stmt_list == stmt {\n'
27+
' db_inner.stmt_list = stmt_ref.next;\n'
28+
' } else {\n'
29+
' let mut current = db_inner.stmt_list;\n'
30+
' while !current.is_null() {\n'
31+
' let current_ref = &mut *current;\n'
32+
' if current_ref.next == stmt {\n'
33+
' current_ref.next = stmt_ref.next;\n'
34+
' break;\n'
35+
' }\n'
36+
' current = current_ref.next;\n'
37+
' }\n'
38+
' }\n'
39+
' }\n'
40+
)
41+
NEW_FINALIZE = (
42+
' if !stmt_ref.db.is_null() {\n'
43+
' let db = &mut *stmt_ref.db;\n'
44+
' // try_lock to avoid deadlock when finalize is invoked\n'
45+
' // re-entrantly (GC destructor during UDF callback).\n'
46+
' if let Ok(mut db_inner) = db.inner.try_lock() {\n'
47+
' if db_inner.stmt_list == stmt {\n'
48+
' db_inner.stmt_list = stmt_ref.next;\n'
49+
' } else {\n'
50+
' let mut current = db_inner.stmt_list;\n'
51+
' while !current.is_null() {\n'
52+
' let current_ref = &mut *current;\n'
53+
' if current_ref.next == stmt {\n'
54+
' current_ref.next = stmt_ref.next;\n'
55+
' break;\n'
56+
' }\n'
57+
' current = current_ref.next;\n'
58+
' }\n'
59+
' }\n'
60+
' }\n'
61+
' }\n'
62+
)
63+
64+
OLD_DRAIN = (
65+
'unsafe fn stmt_run_to_completion(stmt: *mut sqlite3_stmt) -> ffi::c_int {\n'
66+
' let stmt_ref = &mut *stmt;\n'
67+
' while stmt_ref.stmt.execution_state().is_running() {\n'
68+
' let result = sqlite3_step(stmt);\n'
69+
' if result != SQLITE_DONE && result != SQLITE_ROW {\n'
70+
' return result;\n'
71+
' }\n'
72+
' }\n'
73+
' SQLITE_OK\n'
74+
'}\n'
75+
)
76+
NEW_DRAIN = (
77+
'unsafe fn stmt_run_to_completion(stmt: *mut sqlite3_stmt) -> ffi::c_int {\n'
78+
' let stmt_ref = &mut *stmt;\n'
79+
" // Skip drain if we can't acquire the db mutex: we're\n"
80+
" // re-entering from a UDF callback's GC destructor, and\n"
81+
' // sqlite3_step would block forever. The stmt will be\n'
82+
' // freed anyway by the caller.\n'
83+
' if !stmt_ref.db.is_null() {\n'
84+
' let db = &*stmt_ref.db;\n'
85+
' if db.inner.try_lock().is_err() {\n'
86+
' return SQLITE_OK;\n'
87+
' }\n'
88+
' }\n'
89+
' while stmt_ref.stmt.execution_state().is_running() {\n'
90+
' let result = sqlite3_step(stmt);\n'
91+
' if result != SQLITE_DONE && result != SQLITE_ROW {\n'
92+
' return result;\n'
93+
' }\n'
94+
' }\n'
95+
' SQLITE_OK\n'
96+
'}\n'
97+
)
98+
99+
with open(PATH) as f:
100+
s = f.read()
101+
if OLD_FINALIZE not in s:
102+
sys.exit(f'{PATH}: sqlite3_finalize stmt_list block not found')
103+
s = s.replace(OLD_FINALIZE, NEW_FINALIZE, 1)
104+
if OLD_DRAIN not in s:
105+
sys.exit(f'{PATH}: stmt_run_to_completion block not found')
106+
s = s.replace(OLD_DRAIN, NEW_DRAIN, 1)
107+
with open(PATH, 'w') as f:
108+
f.write(s)
109+
print('patched sqlite3_finalize + stmt_run_to_completion for GC re-entry')
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
#!/usr/bin/env python3
2+
"""
3+
Bump MAX_CUSTOM_FUNCS from 32 to 64 (bindings/c/src/lib.rs).
4+
5+
Turso's custom-function registry is capped at 32 pre-generated bridge
6+
trampolines; the driver registers 44 UDFs, so the last 12 silently fail.
7+
Bump to 64 by adding 32 more func_bridge!/FUNC_BRIDGES entries.
8+
"""
9+
10+
import re
11+
import sys
12+
13+
PATH = 'bindings/c/src/lib.rs'
14+
15+
with open(PATH) as f:
16+
s = f.read()
17+
18+
OLD_MAX = 'const MAX_CUSTOM_FUNCS: usize = 32;'
19+
NEW_MAX = 'const MAX_CUSTOM_FUNCS: usize = 64;'
20+
if OLD_MAX not in s:
21+
sys.exit(f'{PATH}: MAX_CUSTOM_FUNCS not found')
22+
s = s.replace(OLD_MAX, NEW_MAX, 1)
23+
24+
# Inject 32 more func_bridge! declarations after func_bridge_31.
25+
bridge_marker = 'func_bridge!(31, func_bridge_31);\n'
26+
if bridge_marker not in s:
27+
sys.exit(f'{PATH}: func_bridge_31 marker not found')
28+
extra_bridges = ''.join(
29+
f'func_bridge!({i}, func_bridge_{i});\n' for i in range(32, 64)
30+
)
31+
s = s.replace(bridge_marker, bridge_marker + extra_bridges, 1)
32+
33+
# Extend the FUNC_BRIDGES array: find the closing `];` of the static
34+
# and inject the extra entries before it.
35+
pat = re.compile(
36+
r'(static FUNC_BRIDGES: \[ScalarFunction; MAX_CUSTOM_FUNCS\] = \[\n'
37+
r'(?:\s*func_bridge_\d+,\n)+)(\];\n)'
38+
)
39+
m = pat.search(s)
40+
if m is None:
41+
sys.exit(f'{PATH}: FUNC_BRIDGES array not found')
42+
extra_entries = ''.join(f' func_bridge_{i},\n' for i in range(32, 64))
43+
s = s[:m.start(2)] + extra_entries + s[m.start(2):]
44+
45+
with open(PATH, 'w') as f:
46+
f.write(s)
47+
print('patched MAX_CUSTOM_FUNCS 32 -> 64')
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
#!/usr/bin/env python3
2+
"""
3+
Alias MySQL collation names to the nearest Turso built-in (core/translate/collate.rs).
4+
5+
Turso recognizes built-in and ICU locale collation names. Driver-emitted
6+
SQL references MySQL collations like `utf8mb4_bin` (byte-compare) and
7+
`utf8mb4_0900_ai_ci` (case-insensitive), which are not ICU locale names.
8+
Map these to the closest built-in at lookup time.
9+
"""
10+
11+
import sys
12+
13+
PATH = 'core/translate/collate.rs'
14+
15+
OLD = (
16+
' pub fn new(collation: &str) -> crate::Result<Self> {\n'
17+
' match crate::util::normalize_ident(collation).as_str() {\n'
18+
' "binary" => return Ok(Self::Binary),\n'
19+
' "nocase" => return Ok(Self::NoCase),\n'
20+
' "rtrim" => return Ok(Self::Rtrim),\n'
21+
' _ => {}\n'
22+
' }\n'
23+
'\n'
24+
' LocaleCollationRegistry::global()\n'
25+
' .get_or_register(collation)\n'
26+
' .map(Self::Locale)\n'
27+
' }\n'
28+
)
29+
NEW = (
30+
' pub fn new(collation: &str) -> crate::Result<Self> {\n'
31+
' // Alias common MySQL collation names to the nearest\n'
32+
' // Turso built-in before ICU locale parsing rejects them.\n'
33+
' match crate::util::normalize_ident(collation).as_str() {\n'
34+
' "binary" | "utf8mb4_bin" | "utf8_bin" | "ascii_bin" | "latin1_bin" => {\n'
35+
' return Ok(Self::Binary)\n'
36+
' }\n'
37+
' "nocase" | "utf8mb4_0900_ai_ci" | "utf8mb4_general_ci" | "utf8_general_ci"\n'
38+
' | "latin1_general_ci" | "latin1_swedish_ci" => return Ok(Self::NoCase),\n'
39+
' "rtrim" => return Ok(Self::Rtrim),\n'
40+
' _ => {}\n'
41+
' }\n'
42+
'\n'
43+
' LocaleCollationRegistry::global()\n'
44+
' .get_or_register(collation)\n'
45+
' .map(Self::Locale)\n'
46+
' }\n'
47+
)
48+
49+
with open(PATH) as f:
50+
s = f.read()
51+
if OLD not in s:
52+
sys.exit(f'{PATH}: CollationSeq::new body not found')
53+
with open(PATH, 'w') as f:
54+
f.write(s.replace(OLD, NEW, 1))
55+
print('patched CollationSeq to alias MySQL collations')

0 commit comments

Comments
 (0)