const std = @import("std"); const sqlite = @import("sqlite"); const schema_system = @import("../schema/system.zig"); const schema_types = @import("../schema/types.zig"); const build = @import("../sql/build.zig"); const typed_codec = @import("../typed/codec.zig"); const typed_doc_id = @import("../typed/doc_id.zig"); const typed = @import("../typed/types.zig"); const errors = @import("errors.zig"); const SqlBuf = @import("../sql/buf.zig").SqlBuf; const SqlList = @import("../sql/buf.zig").SqlList; const Allocator = std.mem.Allocator; /// A schema field index + typed value pair for storage inserts/updates. pub const ColumnValue = struct { index: usize, value: typed.Value, }; /// A single-field relative update: `SET field = field + delta`. pub const IncrementValue = struct { field_index: usize, delta: i64, }; /// Specialized cache for sqlite3_stmt objects to avoid parsing overhead. /// Implements a fixed-size LRU eviction policy using intrusive DoublyLinkedList. const Entry = struct { key: u64, stmt: *sqlite.c.sqlite3_stmt, node: std.DoublyLinkedList.Node = .{}, }; /// Not thread-safe. Each thread must have its own instance. pub const StatementCache = struct { const LruList = std.DoublyLinkedList; map: std.AutoHashMapUnmanaged(u64, *LruList.Node), list: LruList, count: usize, cache_limit: usize, pub fn init(self: *StatementCache, allocator: Allocator, cache_limit: usize) void { _ = allocator; self.* = .{ .map = .empty, .list = .{}, .count = 0, .cache_limit = cache_limit, }; } pub fn deinit(self: *StatementCache, allocator: Allocator) void { self.clear(allocator); self.map.deinit(allocator); } /// Finalizes all cached statements and clears the cache. fn clear(self: *StatementCache, allocator: Allocator) void { var it = self.list.first; while (it) |node| { const next = node.next; const entry: *Entry = @fieldParentPtr("node", node); _ = sqlite.c.sqlite3_finalize(entry.stmt); allocator.destroy(entry); it = next; } self.map.clearRetainingCapacity(); self.list = LruList{}; self.count = 0; } /// Retrieves a prepared statement matched by u64 key. /// Updates LRU on hit. The 64-bit hash collision probability (~10^-16) /// is low enough that no secondary verification is needed. fn get(self: *StatementCache, key: u64) ?*sqlite.c.sqlite3_stmt { const node = self.map.get(key) orelse return null; const entry: *Entry = @fieldParentPtr("node", node); // Move to front (Most Recently Used) self.list.remove(node); self.list.prepend(node); // Reset and clear bindings for fresh use _ = sqlite.c.sqlite3_reset(entry.stmt); _ = sqlite.c.sqlite3_clear_bindings(entry.stmt); return entry.stmt; } /// Adds a new statement to the cache. Evicts LRU if capacity exceeded. /// On key collision, replaces the old entry. fn put(self: *StatementCache, allocator: Allocator, key: u64, stmt: *sqlite.c.sqlite3_stmt) !void { // If the key already exists, replace the old entry. if (self.map.get(key)) |existing_node| { const old_entry: *Entry = @fieldParentPtr("node", existing_node); self.list.remove(existing_node); _ = sqlite.c.sqlite3_finalize(old_entry.stmt); allocator.destroy(old_entry); self.count -= 1; } // Evict LRU if at capacity if (self.count >= self.cache_limit) { if (self.list.last) |old_node| { const old_entry: *Entry = @fieldParentPtr("node", old_node); self.list.remove(old_node); _ = self.map.remove(old_entry.key); _ = sqlite.c.sqlite3_finalize(old_entry.stmt); allocator.destroy(old_entry); self.count -= 1; } } const entry = try allocator.create(Entry); errdefer allocator.destroy(entry); entry.* = .{ .key = key, .stmt = stmt, .node = .{}, }; try self.map.put(allocator, key, &entry.node); self.list.prepend(&entry.node); self.count += 1; } /// High-level helper to get a statement or prepare one if missing. /// `cache_key` is a u64 hash identifying the SQL template. /// `sql_fallback` is only used on cache miss to prepare a new statement. /// Returns a ManagedStmt which ensures the statement is reset upon release. pub fn acquire(self: *StatementCache, allocator: Allocator, db: *sqlite.Db, cache_key: u64, sql_fallback: []const u8) !ManagedStmt { if (self.get(cache_key)) |stmt| { return ManagedStmt{ .stmt = stmt }; } const stmt = (try db.prepareDynamic(sql_fallback)).stmt; errdefer _ = sqlite.c.sqlite3_finalize(stmt); try self.put(allocator, cache_key, stmt); return ManagedStmt{ .stmt = stmt }; } }; /// RAII-like wrapper for cached statements to ensure they are clean when returned to the cache. pub const ManagedStmt = struct { stmt: *sqlite.c.sqlite3_stmt, pub fn release(self: *ManagedStmt) void { _ = sqlite.c.sqlite3_reset(self.stmt); _ = sqlite.c.sqlite3_clear_bindings(self.stmt); } }; /// Reset + clear bindings on a static (pre-prepared) stmt and return a `ManagedStmt`. /// The stmt must outlive the returned wrapper. Caller releases when done. /// Returns `error.StatementNotPrepared` if `stmt_opt` is null (e.g. setup phase /// before `StorageEngine.start()` has prepared static stmts). pub fn acquireStaticStmt(stmt_opt: ?*sqlite.c.sqlite3_stmt) !ManagedStmt { const stmt = stmt_opt orelse return error.StatementNotPrepared; _ = sqlite.c.sqlite3_reset(stmt); _ = sqlite.c.sqlite3_clear_bindings(stmt); return ManagedStmt{ .stmt = stmt }; } /// Prepare one stmt per table from `table.select_document_sql`. Returned slice /// is indexed by `table.index`. Caller owns the slice and must `finalizeStaticStmts` /// before freeing it. Null entries indicate a prepare failure for that table; /// caller may treat any null as fatal since schema is locked at prepare time. pub fn prepareSelectDocumentStmts( allocator: Allocator, db: *sqlite.Db, schema: *const schema_types.Schema, ) ![]?*sqlite.c.sqlite3_stmt { const stmts = try allocator.alloc(?*sqlite.c.sqlite3_stmt, schema.tables.len); var prepared: usize = 0; errdefer { for (stmts[0..prepared]) |s| { if (s) |stmt| _ = sqlite.c.sqlite3_finalize(stmt); } allocator.free(stmts); } for (schema.tables) |t| { const dynamic = try db.prepareDynamic(t.select_document_sql); stmts[t.index] = dynamic.stmt; prepared += 1; } return stmts; } /// Finalize all non-null stmts in `stmts`. Does not free the slice — caller owns it. pub fn finalizeStaticStmts(stmts: []?*sqlite.c.sqlite3_stmt) void { for (stmts) |s| { if (s) |stmt| _ = sqlite.c.sqlite3_finalize(stmt); } } /// Safe bind helpers to avoid alignment errors with TSAN on ARM. pub fn bindTextTransient(stmt: ?*sqlite.c.sqlite3_stmt, index: c_int, value: []const u8) c_int { return sqlite.c.sqlite3_bind_text(stmt, index, value.ptr, @intCast(value.len), sqlite.c.sqliteTransientAsDestructor()); } pub fn bindBlobTransient(stmt: ?*sqlite.c.sqlite3_stmt, index: c_int, value: []const u8) c_int { return sqlite.c.sqlite3_bind_blob(stmt, index, value.ptr, @intCast(value.len), sqlite.c.sqliteTransientAsDestructor()); } pub const JsonBuf = struct { buf: std.ArrayListUnmanaged(u8) = .empty, allocator: Allocator, pub fn init(allocator: Allocator) JsonBuf { return .{ .allocator = allocator }; } pub fn deinit(self: *JsonBuf) void { self.buf.deinit(self.allocator); } }; pub fn bindValue(typed_value: typed.Value, db: *sqlite.Db, stmt: *sqlite.c.sqlite3_stmt, index: c_int, json_buf: *JsonBuf) !void { const rc = switch (typed_value) { .scalar => |s| switch (s) { .doc_id => |id| blk: { const bytes = typed_doc_id.toBytes(id); break :blk bindBlobTransient(stmt, index, &bytes); }, .integer => |v| sqlite.c.sqlite3_bind_int64(stmt, index, v), .real => |v| sqlite.c.sqlite3_bind_double(stmt, index, v), .text => |s_val| bindTextTransient(stmt, index, s_val), .boolean => |b| sqlite.c.sqlite3_bind_int(stmt, index, if (b) 1 else 0), .binary => |bytes| bindBlobTransient(stmt, index, bytes), }, .nil => sqlite.c.sqlite3_bind_null(stmt, index), .array => |items| blk: { json_buf.buf.clearRetainingCapacity(); try typed_codec.writeJsonToBuf(&json_buf.buf, json_buf.allocator, .{ .array = items }); break :blk bindTextTransient(stmt, index, json_buf.buf.items); }, }; if (rc != sqlite.c.SQLITE_OK) return errors.classifyStepError(db); } /// Bind a document id blob at `index` and a namespace id integer at `index + 1`. /// The common id+namespace prefix used by select/delete statements. pub fn bindDocIdNamespace( stmt: *sqlite.c.sqlite3_stmt, db: *sqlite.Db, index: c_int, id: typed_doc_id.DocId, namespace_id: i64, ) !void { const id_bytes = typed_doc_id.toBytes(id); if (bindBlobTransient(stmt, index, &id_bytes) != sqlite.c.SQLITE_OK) return errors.classifyStepError(db); if (sqlite.c.sqlite3_bind_int64(stmt, index + 1, namespace_id) != sqlite.c.SQLITE_OK) return errors.classifyStepError(db); } pub fn typedValueFromColumn(allocator: Allocator, stmt: *sqlite.c.sqlite3_stmt, i: c_int, field: schema_types.Field) !typed.Value { const col_type = sqlite.c.sqlite3_column_type(stmt, i); return switch (col_type) { sqlite.c.SQLITE_BLOB => blk: { const ptr = sqlite.c.sqlite3_column_blob(stmt, i); const len: usize = @intCast(sqlite.c.sqlite3_column_bytes(stmt, i)); const bytes = if (ptr != null) @as([*]const u8, @ptrCast(ptr))[0..len] else &[_]u8{}; if (field.storage_type == .doc_id) { break :blk typed.Value{ .scalar = .{ .doc_id = try typed_doc_id.fromBytes(bytes) } }; } else if (field.storage_type == .bytes) { break :blk typed.Value{ .scalar = .{ .binary = try allocator.dupe(u8, bytes) } }; } break :blk .nil; }, sqlite.c.SQLITE_INTEGER => { const val = sqlite.c.sqlite3_column_int64(stmt, i); if (field.storage_type == .boolean) { return typed.Value{ .scalar = .{ .boolean = val != 0 } }; } return typed.Value{ .scalar = .{ .integer = val } }; }, sqlite.c.SQLITE_FLOAT => typed.Value{ .scalar = .{ .real = sqlite.c.sqlite3_column_double(stmt, i) } }, sqlite.c.SQLITE_TEXT => blk: { const ptr = sqlite.c.sqlite3_column_text(stmt, i); const len: usize = @intCast(sqlite.c.sqlite3_column_bytes(stmt, i)); if (field.storage_type == .array) { const s = if (ptr != null) ptr[0..len] else "[]"; const parsed = try std.json.parseFromSlice(std.json.Value, allocator, s, .{}); defer parsed.deinit(); break :blk typed_codec.fromJson(allocator, field.storage_type, field.items_type, parsed.value); } else { const s = if (ptr != null) ptr[0..len] else ""; break :blk typed.Value{ .scalar = .{ .text = try allocator.dupe(u8, s) } }; } }, else => .nil, }; } fn decodeRecord( allocator: Allocator, stmt: *sqlite.c.sqlite3_stmt, table_metadata: *const schema_types.Table, ) !typed.Record { const col_count: usize = @intCast(sqlite.c.sqlite3_column_count(stmt)); if (col_count != table_metadata.fields.len) return errors.StorageError.ColumnCountMismatch; var values = try allocator.alloc(typed.Value, col_count); var i: usize = 0; errdefer { for (values[0..i]) |value| value.deinit(allocator); allocator.free(values); } while (i < col_count) : (i += 1) { const field = table_metadata.fields[i]; const val = try typedValueFromColumn(allocator, stmt, @intCast(i), field); errdefer val.deinit(allocator); values[i] = val; } return typed.Record{ .values = values, }; } pub fn fetchRecord( allocator: Allocator, db: *sqlite.Db, stmt: *sqlite.c.sqlite3_stmt, table_metadata: *const schema_types.Table, ) !?typed.Record { const rc = sqlite.c.sqlite3_step(stmt); if (rc == sqlite.c.SQLITE_ROW) return try decodeRecord(allocator, stmt, table_metadata); if (rc != sqlite.c.SQLITE_DONE and rc != sqlite.c.SQLITE_ROW) return errors.classifyStepError(db); return null; } /// Step the cursor once without decoding. Returns true if another row is available. pub fn stepHasMore(db: *sqlite.Db, stmt: *sqlite.c.sqlite3_stmt) !bool { const rc = sqlite.c.sqlite3_step(stmt); if (rc == sqlite.c.SQLITE_ROW) return true; if (rc != sqlite.c.SQLITE_DONE) return errors.classifyStepError(db); return false; } pub fn ensureNamespaceTable(db: *sqlite.Db) !void { db.exec( "CREATE TABLE IF NOT EXISTS _zync_namespaces (id INTEGER PRIMARY KEY, name TEXT NOT NULL UNIQUE) STRICT", .{}, .{}, ) catch |err| return errors.classifyError(err); db.exec( "INSERT OR IGNORE INTO _zync_namespaces (id, name) VALUES (0, '$global')", .{}, .{}, ) catch |err| return errors.classifyError(err); } pub const resolve_namespace_sql = \\INSERT INTO _zync_namespaces (name) \\VALUES (?) \\ON CONFLICT(name) DO UPDATE SET name = excluded.name \\RETURNING id ; pub const resolve_user_sql = \\INSERT INTO "users" ("id", "namespace_id", "owner_id", "external_id", "created_at", "updated_at") \\VALUES (?, ?, ?, ?, ?, ?) \\ON CONFLICT("namespace_id", "external_id") DO UPDATE SET "external_id" = excluded."external_id" \\RETURNING "id" ; pub fn resolveNamespaceId( db: *sqlite.Db, stmt_raw: *sqlite.c.sqlite3_stmt, namespace: []const u8, ) !i64 { var mstmt = try acquireStaticStmt(stmt_raw); defer mstmt.release(); const stmt = mstmt.stmt; if (bindTextTransient(stmt, 1, namespace) != sqlite.c.SQLITE_OK) return errors.classifyStepError(db); const rc = sqlite.c.sqlite3_step(stmt); if (rc == sqlite.c.SQLITE_ROW) return sqlite.c.sqlite3_column_int64(stmt, 0); if (rc != sqlite.c.SQLITE_DONE) return errors.classifyStepError(db); return errors.StorageError.InvalidOperation; } pub fn resolveUserId( io: std.Io, db: *sqlite.Db, stmt_raw: *sqlite.c.sqlite3_stmt, namespace_id: i64, external_id: []const u8, timestamp: i64, ) !typed_doc_id.DocId { var mstmt = try acquireStaticStmt(stmt_raw); defer mstmt.release(); const stmt = mstmt.stmt; const new_user_id = try typed_doc_id.generateUuidV7(io); const id_bytes = typed_doc_id.toBytes(new_user_id); if (bindBlobTransient(stmt, 1, &id_bytes) != sqlite.c.SQLITE_OK) return errors.classifyStepError(db); if (sqlite.c.sqlite3_bind_int64(stmt, 2, namespace_id) != sqlite.c.SQLITE_OK) return errors.classifyStepError(db); if (bindBlobTransient(stmt, 3, &id_bytes) != sqlite.c.SQLITE_OK) return errors.classifyStepError(db); if (bindTextTransient(stmt, 4, external_id) != sqlite.c.SQLITE_OK) return errors.classifyStepError(db); if (sqlite.c.sqlite3_bind_int64(stmt, 5, timestamp) != sqlite.c.SQLITE_OK) return errors.classifyStepError(db); if (sqlite.c.sqlite3_bind_int64(stmt, 6, timestamp) != sqlite.c.SQLITE_OK) return errors.classifyStepError(db); const rc = sqlite.c.sqlite3_step(stmt); if (rc == sqlite.c.SQLITE_ROW) { const ptr = sqlite.c.sqlite3_column_blob(stmt, 0); const len: usize = @intCast(sqlite.c.sqlite3_column_bytes(stmt, 0)); const bytes = if (ptr != null) @as([*]const u8, @ptrCast(ptr))[0..len] else &[_]u8{}; return typed_doc_id.fromBytes(bytes) catch return errors.StorageError.TypeMismatch; } if (rc != sqlite.c.SQLITE_DONE) return errors.classifyStepError(db); return errors.StorageError.InvalidOperation; } pub fn buildUpsertDocumentSql( allocator: Allocator, table_metadata: *const schema_types.Table, columns: []const ColumnValue, guard_sql: ?[]const u8, ) ![]const u8 { var buf = SqlBuf.init(); defer buf.deinit(allocator); try appendInsertColumnList(allocator, &buf, table_metadata, columns); try appendValuePlaceholders(allocator, &buf, table_metadata, columns); try appendOnConflictUpdateSet(allocator, &buf, table_metadata, columns); try appendUpsertWhereClause(allocator, &buf, table_metadata, guard_sql); try buf.appendSlice(allocator, " RETURNING "); try build.appendProjectedColumnsSql(allocator, &buf, table_metadata); return buf.toOwnedSlice(allocator); } fn appendInsertColumnList( allocator: Allocator, buf: *SqlBuf, table_metadata: *const schema_types.Table, columns: []const ColumnValue, ) !void { try buf.appendSlice(allocator, "INSERT INTO "); try buf.appendSlice(allocator, table_metadata.name_quoted); try buf.appendSlice(allocator, " ("); var list = SqlList.init(buf, ", "); try list.appendItemSlice(allocator, schema_system.quoted_id); try list.appendItemSlice(allocator, schema_system.quoted_namespace_id); try list.appendItemSlice(allocator, schema_system.quoted_owner_id); if (table_metadata.is_users_table) { try list.appendItemSlice(allocator, schema_system.quoted_external_id); } for (columns) |col| { const field = try getColumnField(table_metadata, col); try list.appendItemSlice(allocator, field.name_quoted); } try list.appendItemSlice(allocator, schema_system.quoted_created_at); try list.appendItemSlice(allocator, schema_system.quoted_updated_at); } fn appendValuePlaceholders( allocator: Allocator, buf: *SqlBuf, table_metadata: *const schema_types.Table, columns: []const ColumnValue, ) !void { // Fixed leading placeholders: id, namespace_id, owner_id (+ external_id for users) try buf.appendSlice(allocator, ") VALUES (?, ?, ?"); if (table_metadata.is_users_table) { try buf.appendSlice(allocator, ", ?"); } for (columns) |col| { const field = try getColumnField(table_metadata, col); if (field.storage_type == .array) { try buf.appendSlice(allocator, ", jsonb(?)"); } else { try buf.appendSlice(allocator, ", ?"); } } // created_at and updated_at placeholders try buf.appendSlice(allocator, ", ?, ?)"); } fn appendOnConflictUpdateSet( allocator: Allocator, buf: *SqlBuf, table_metadata: *const schema_types.Table, columns: []const ColumnValue, ) !void { try buf.appendSlice(allocator, " ON CONFLICT("); try buf.appendSlice(allocator, schema_system.quoted_id); try buf.appendSlice(allocator, ") DO UPDATE SET "); var list = SqlList.init(buf, ", "); for (columns) |col| { const field = try getColumnField(table_metadata, col); try list.maybeSep(allocator); try buf.appendSlice(allocator, field.name_quoted); try buf.appendSlice(allocator, " = excluded."); try buf.appendSlice(allocator, field.name_quoted); } // Always update updated_at try list.maybeSep(allocator); try buf.appendSlice(allocator, schema_system.quoted_updated_at); try buf.appendSlice(allocator, " = excluded."); try buf.appendSlice(allocator, schema_system.quoted_updated_at); } fn appendUpsertWhereClause( allocator: Allocator, buf: *SqlBuf, table_metadata: *const schema_types.Table, guard_sql: ?[]const u8, ) !void { try buf.appendSlice(allocator, " WHERE "); try buf.appendSlice(allocator, table_metadata.name_quoted); try buf.appendSlice(allocator, "."); try buf.appendSlice(allocator, schema_system.quoted_namespace_id); try buf.appendSlice(allocator, " = excluded."); try buf.appendSlice(allocator, schema_system.quoted_namespace_id); if (guard_sql) |fragment| { try buf.appendSlice(allocator, fragment); } } fn getColumnField( table_metadata: *const schema_types.Table, col: ColumnValue, ) !schema_types.Field { if (col.index >= table_metadata.fields.len) return errors.StorageError.UnknownField; return table_metadata.fields[col.index]; } pub fn buildUpdateDocumentSql( allocator: Allocator, table_metadata: *const schema_types.Table, columns: []const ColumnValue, increments: []const IncrementValue, guard_sql: ?[]const u8, precondition_sql: ?[]const u8, ) ![]const u8 { var buf = SqlBuf.init(); defer buf.deinit(allocator); try buf.appendSlice(allocator, "UPDATE "); try buf.appendSlice(allocator, table_metadata.name_quoted); try buf.appendSlice(allocator, " SET "); try appendUpdateColumnSet(allocator, &buf, table_metadata, columns, increments); try appendDocIdNamespaceWhere(allocator, &buf, guard_sql, precondition_sql); try appendIncrementGuards(allocator, &buf, table_metadata, increments); try buf.appendSlice(allocator, " RETURNING "); try build.appendProjectedColumnsSql(allocator, &buf, table_metadata); return buf.toOwnedSlice(allocator); } fn appendUpdateColumnSet( allocator: Allocator, buf: *SqlBuf, table_metadata: *const schema_types.Table, columns: []const ColumnValue, increments: []const IncrementValue, ) !void { var list = SqlList.init(buf, ", "); for (columns) |col| { const field = try getColumnField(table_metadata, col); try list.maybeSep(allocator); try buf.appendSlice(allocator, field.name_quoted); try buf.appendSlice(allocator, " = "); if (field.storage_type == .array) { try buf.appendSlice(allocator, "jsonb(?)"); } else { try buf.appendSlice(allocator, "?"); } } for (increments) |inc| { if (inc.field_index >= table_metadata.fields.len) return errors.StorageError.UnknownField; const field = table_metadata.fields[inc.field_index]; try list.maybeSep(allocator); try buf.appendSlice(allocator, field.name_quoted); try buf.appendSlice(allocator, " = "); try buf.appendSlice(allocator, field.name_quoted); try buf.appendSlice(allocator, " + ?"); } try list.maybeSep(allocator); try buf.appendSlice(allocator, schema_system.quoted_updated_at); try buf.appendSlice(allocator, " = ?"); } /// Emits the per-increment guards. Placeholder order per increment is: /// delta (typeof operand), then delta again when a range bound exists, /// followed by minimum and maximum. The caller binds the same order after the /// guard/precondition values. fn appendIncrementGuards( allocator: Allocator, buf: *SqlBuf, table_metadata: *const schema_types.Table, increments: []const IncrementValue, ) !void { for (increments) |inc| { if (inc.field_index >= table_metadata.fields.len) return errors.StorageError.UnknownField; const field = table_metadata.fields[inc.field_index]; try buf.appendSlice(allocator, " AND typeof("); try buf.appendSlice(allocator, field.name_quoted); try buf.appendSlice(allocator, ") = 'integer' AND typeof("); try buf.appendSlice(allocator, field.name_quoted); try buf.appendSlice(allocator, " + ?) = 'integer'"); const constraints = field.constraints orelse continue; const has_min = constraints.minimum != null; const has_max = constraints.maximum != null; if (has_min and has_max) { try buf.appendSlice(allocator, " AND ("); try buf.appendSlice(allocator, field.name_quoted); try buf.appendSlice(allocator, " + ?) BETWEEN ? AND ?"); } else if (has_min) { try buf.appendSlice(allocator, " AND ("); try buf.appendSlice(allocator, field.name_quoted); try buf.appendSlice(allocator, " + ?) >= ?"); } else if (has_max) { try buf.appendSlice(allocator, " AND ("); try buf.appendSlice(allocator, field.name_quoted); try buf.appendSlice(allocator, " + ?) <= ?"); } } } fn appendDocIdNamespaceWhere( allocator: Allocator, buf: *SqlBuf, guard_sql: ?[]const u8, precondition_sql: ?[]const u8, ) !void { try buf.appendSlice(allocator, " WHERE "); try buf.appendSlice(allocator, schema_system.quoted_id); try buf.appendSlice(allocator, "=? AND "); try buf.appendSlice(allocator, schema_system.quoted_namespace_id); try buf.appendSlice(allocator, "=?"); if (guard_sql) |fragment| { try buf.appendSlice(allocator, fragment); } if (precondition_sql) |fragment| { try buf.appendSlice(allocator, fragment); } }