const std = @import("std"); const schema_system = @import("../schema/system.zig"); const schema_types = @import("../schema/types.zig"); const sql_buf = @import("buf.zig"); const SqlBuf = sql_buf.SqlBuf; const SqlList = sql_buf.SqlList; /// One ZyncBase-managed index definition for a table. /// The single source of truth shared by DDL generation and migration /// detection/execution so their notion of "managed index" cannot drift. pub const ManagedIndex = union(enum) { namespace, owner, created_at, users_identity, /// Index into `table.userFields()` for a field marked `indexed` or carrying `references`. field: usize, /// Index into `table.unique_constraints` (user-defined, schema order). unique: usize, pub fn isUnique(self: ManagedIndex) bool { return switch (self) { .created_at, .users_identity, .unique => true, else => false, }; } /// Appends the deterministic quoted index name. pub fn appendName(self: ManagedIndex, allocator: std.mem.Allocator, buf: *SqlBuf, table: *const schema_types.Table) !void { switch (self) { .namespace => try buf.appendManagedIndexName(allocator, false, table.name, "namespace", null), .owner => try buf.appendManagedIndexName(allocator, false, table.name, "owner", null), .created_at => try buf.appendManagedIndexName(allocator, true, table.name, "created_at", null), .users_identity => try buf.appendManagedIndexName(allocator, true, table.name, "identity", null), .field => |fi| try buf.appendManagedIndexName(allocator, false, table.name, "field", table.userFields()[fi].name), .unique => |ui| { var ordinal_buf: [20]u8 = undefined; const ordinal = std.fmt.bufPrint(&ordinal_buf, "{d}", .{ui}) catch @panic("usize ordinal exceeds 20 digits"); try buf.appendManagedIndexName(allocator, true, table.name, "constraint", ordinal); }, } } /// Number of indexed columns in declaration order. pub fn columnCount(self: ManagedIndex, table: *const schema_types.Table) usize { return switch (self) { .namespace, .owner, .created_at, .field => 1, .users_identity => 2, .unique => |ui| 1 + table.unique_constraints[ui].field_indexes.len, }; } /// Copies the ordered unquoted logical column names into `out` /// (`out.len >= columnCount(table)`). pub fn columns(self: ManagedIndex, table: *const schema_types.Table, out: [][]const u8) void { switch (self) { .namespace => out[0] = "namespace_id", .owner => out[0] = "owner_id", .created_at => out[0] = "created_at", .users_identity => { out[0] = "namespace_id"; out[1] = "external_id"; }, .field => |fi| out[0] = table.userFields()[fi].name, .unique => |ui| { out[0] = "namespace_id"; for (table.unique_constraints[ui].field_indexes, 0..) |field_index, i| { out[i + 1] = table.userFields()[field_index].name; } }, } } /// Appends the ordered quoted column list `(a, b, ...)`. pub fn appendColumnList(self: ManagedIndex, allocator: std.mem.Allocator, buf: *SqlBuf, table: *const schema_types.Table) !void { var list = SqlList.init(buf, ", "); switch (self) { .namespace => try list.appendItemSlice(allocator, schema_system.quoted_namespace_id), .owner => try list.appendItemSlice(allocator, schema_system.quoted_owner_id), .created_at => try list.appendItemSlice(allocator, schema_system.quoted_created_at), .users_identity => { try list.appendItemSlice(allocator, schema_system.quoted_namespace_id); try list.appendItemSlice(allocator, schema_system.quoted_external_id); }, .field => |fi| try list.appendItemSlice(allocator, table.userFields()[fi].name_quoted), .unique => |ui| { // namespace_id is always the first indexed column. try list.appendItemSlice(allocator, schema_system.quoted_namespace_id); for (table.unique_constraints[ui].field_indexes) |field_index| { try list.appendItemSlice(allocator, table.userFields()[field_index].name_quoted); } }, } } }; /// Allocation-free iterator over every managed index of one table, in the /// deterministic emission order: namespace, owner, created_at, users identity, ordinary /// field/reference indexes, then user-defined unique indexes in schema order. pub const ManagedIndexIterator = struct { table: *const schema_types.Table, pos: usize = 0, const header_count: usize = 4; pub fn init(table: *const schema_types.Table) ManagedIndexIterator { return .{ .table = table }; } pub fn next(self: *ManagedIndexIterator) ?ManagedIndex { const user_fields = self.table.userFields(); const field_end = header_count + user_fields.len; const total = field_end + self.table.unique_constraints.len; while (self.pos < total) { const pos = self.pos; self.pos += 1; if (pos == 0) return .namespace; if (pos == 1) return .owner; if (pos == 2) return .created_at; if (pos == 3) { if (self.table.is_users_table) return .users_identity; continue; } if (pos < field_end) { const field = user_fields[pos - header_count]; if (field.indexed or field.references != null) return .{ .field = pos - header_count }; continue; } return .{ .unique = pos - field_end }; } return null; } }; pub const DDLGenerator = struct { allocator: std.mem.Allocator, pub fn init(allocator: std.mem.Allocator) DDLGenerator { return .{ .allocator = allocator }; } /// Generate only the `CREATE TABLE ... STRICT;` statement, without managed /// indexes. Migration steps create indexes after loading data. Caller owns the result. pub fn generateCreateTable(self: *DDLGenerator, table: schema_types.Table) ![]const u8 { var buf = SqlBuf.init(); defer buf.deinit(self.allocator); try emitCreateTable(self.allocator, &buf, table); try buf.append(self.allocator, ';'); return buf.toOwnedSlice(self.allocator); } /// Generate the single statement for one managed index. Caller owns the result. pub fn generateIndexDDL(self: *DDLGenerator, table: schema_types.Table, managed_index: ManagedIndex) ![]const u8 { var buf = SqlBuf.init(); defer buf.deinit(self.allocator); try emitManagedIndex(self.allocator, &buf, &table, managed_index); try buf.append(self.allocator, ';'); return buf.toOwnedSlice(self.allocator); } /// Generate `ALTER TABLE ... ADD COLUMN ...;` for an optional user field. /// Reference fields carry a column-level `REFERENCES` clause, which SQLite /// reports through `PRAGMA foreign_key_list` exactly like the table-level /// constraint emitted by `generateCreateTable`. SQLite cannot add a `NOT NULL` /// column without a default, so required fields need a table rebuild. /// Caller owns the result. pub fn generateAddColumn(self: *DDLGenerator, table: schema_types.Table, field: schema_types.Field) ![]const u8 { if (field.required) return error.RequiredColumnNeedsRebuild; var buf = SqlBuf.init(); defer buf.deinit(self.allocator); try buf.appendSlice(self.allocator, "ALTER TABLE "); try buf.appendSlice(self.allocator, table.name_quoted); try buf.appendSlice(self.allocator, " ADD COLUMN "); try emitUserColumn(self.allocator, &buf, field); if (field.references) |ref| { try buf.appendSlice(self.allocator, " REFERENCES "); try buf.appendQuoted(self.allocator, ref); try buf.append(self.allocator, '('); try buf.appendSlice(self.allocator, schema_system.quoted_id); try buf.append(self.allocator, ')'); try emitOnDelete(self.allocator, &buf, field.on_delete orelse .restrict); } try buf.append(self.allocator, ';'); return buf.toOwnedSlice(self.allocator); } }; /// True when both tables produce exactly the same set of managed index /// statements (names, uniqueness, and ordered columns). pub fn managedIndexesEqual(allocator: std.mem.Allocator, a: *const schema_types.Table, b: *const schema_types.Table) !bool { var gen = DDLGenerator.init(allocator); var a_statements = try collectManagedIndexStatements(allocator, &gen, a); defer freeStatements(allocator, &a_statements); var b_statements = try collectManagedIndexStatements(allocator, &gen, b); defer freeStatements(allocator, &b_statements); if (a_statements.items.len != b_statements.items.len) return false; outer: for (a_statements.items) |statement| { for (b_statements.items) |candidate| { if (std.mem.eql(u8, statement, candidate)) continue :outer; } return false; } return true; } fn collectManagedIndexStatements( allocator: std.mem.Allocator, gen: *DDLGenerator, table: *const schema_types.Table, ) !std.ArrayListUnmanaged([]const u8) { var statements = std.ArrayListUnmanaged([]const u8).empty; errdefer freeStatements(allocator, &statements); var iter = ManagedIndexIterator.init(table); while (iter.next()) |managed_index| { const statement = try gen.generateIndexDDL(table.*, managed_index); statements.append(allocator, statement) catch |err| { allocator.free(statement); return err; }; } return statements; } fn freeStatements(allocator: std.mem.Allocator, statements: *std.ArrayListUnmanaged([]const u8)) void { for (statements.items) |statement| allocator.free(statement); statements.deinit(allocator); } fn emitCreateTable(allocator: std.mem.Allocator, buf: *SqlBuf, table: schema_types.Table) !void { try buf.appendSlice(allocator, "CREATE TABLE "); try buf.appendSlice(allocator, table.name_quoted); try buf.appendSlice(allocator, " (\n"); try emitFixedLeadingColumns(allocator, buf, table); try emitUserColumns(allocator, buf, table); try emitFixedTrailingColumns(allocator, buf); try emitForeignKeys(allocator, buf, table); try buf.appendSlice(allocator, "\n) STRICT"); } fn emitFixedLeadingColumns(allocator: std.mem.Allocator, buf: *SqlBuf, table: schema_types.Table) !void { try buf.appendSlice(allocator, " "); try buf.appendSlice(allocator, schema_system.quoted_id); try buf.appendSlice(allocator, " BLOB NOT NULL CHECK(length("); try buf.appendSlice(allocator, schema_system.quoted_id); try buf.appendSlice(allocator, ") = 16),\n"); try buf.appendSlice(allocator, " "); try buf.appendSlice(allocator, schema_system.quoted_namespace_id); try buf.appendSlice(allocator, " INTEGER NOT NULL,\n "); try buf.appendSlice(allocator, schema_system.quoted_owner_id); try buf.appendSlice(allocator, " BLOB NOT NULL CHECK(length("); try buf.appendSlice(allocator, schema_system.quoted_owner_id); try buf.appendSlice(allocator, ") = 16)"); if (table.is_users_table) { try buf.appendSlice(allocator, ",\n "); try buf.appendSlice(allocator, schema_system.quoted_external_id); try buf.appendSlice(allocator, " TEXT NOT NULL"); } } fn emitUserColumns(allocator: std.mem.Allocator, buf: *SqlBuf, table: schema_types.Table) !void { for (table.userFields()) |field| { try buf.appendSlice(allocator, ",\n "); try emitUserColumn(allocator, buf, field); } } /// `"name" TYPE [NOT NULL] [CHECK(length("name") = 16)]` fn emitUserColumn(allocator: std.mem.Allocator, buf: *SqlBuf, field: schema_types.Field) !void { try buf.appendSlice(allocator, field.name_quoted); try buf.append(allocator, ' '); try buf.appendSlice(allocator, field.storage_type.toSqlType()); if (field.required) { try buf.appendSlice(allocator, " NOT NULL"); } if (field.needsLengthCheck()) { try buf.appendSlice(allocator, " CHECK(length("); try buf.appendSlice(allocator, field.name_quoted); try buf.appendSlice(allocator, ") = 16)"); } } fn emitFixedTrailingColumns(allocator: std.mem.Allocator, buf: *SqlBuf) !void { try buf.appendSlice(allocator, ",\n "); try buf.appendSlice(allocator, schema_system.quoted_created_at); try buf.appendSlice(allocator, " INTEGER NOT NULL"); try buf.appendSlice(allocator, ",\n "); try buf.appendSlice(allocator, schema_system.quoted_updated_at); try buf.appendSlice(allocator, " INTEGER NOT NULL"); try buf.appendSlice(allocator, ",\n PRIMARY KEY ("); try buf.appendSlice(allocator, schema_system.quoted_id); try buf.append(allocator, ')'); } fn emitForeignKeys(allocator: std.mem.Allocator, buf: *SqlBuf, table: schema_types.Table) !void { for (table.userFields()) |field| { if (field.references) |ref| { try buf.appendSlice(allocator, ",\n FOREIGN KEY ("); try buf.appendSlice(allocator, field.name_quoted); try buf.appendSlice(allocator, ") REFERENCES "); try buf.appendQuoted(allocator, ref); try buf.appendSlice(allocator, "("); try buf.appendSlice(allocator, schema_system.quoted_id); try buf.append(allocator, ')'); try emitOnDelete(allocator, buf, field.on_delete orelse .restrict); } } } fn emitOnDelete(allocator: std.mem.Allocator, buf: *SqlBuf, od: schema_types.OnDelete) !void { try buf.appendSlice(allocator, onDeleteSql(od).clause); } pub const OnDeleteSql = struct { action: []const u8, clause: []const u8, }; pub fn onDeleteSql(od: schema_types.OnDelete) OnDeleteSql { return switch (od) { .cascade => .{ .action = "CASCADE", .clause = " ON DELETE CASCADE" }, .restrict => .{ .action = "RESTRICT", .clause = " ON DELETE RESTRICT" }, .set_null => .{ .action = "SET NULL", .clause = " ON DELETE SET NULL" }, }; } /// Emit one managed-index statement: `CREATE [UNIQUE] INDEX ...` fn emitManagedIndex(allocator: std.mem.Allocator, buf: *SqlBuf, table: *const schema_types.Table, managed_index: ManagedIndex) !void { if (managed_index.isUnique()) { try buf.appendSlice(allocator, "CREATE UNIQUE INDEX "); } else { try buf.appendSlice(allocator, "CREATE INDEX "); } try managed_index.appendName(allocator, buf, table); try buf.appendSlice(allocator, " ON "); try buf.appendSlice(allocator, table.name_quoted); try buf.append(allocator, '('); try managed_index.appendColumnList(allocator, buf, table); try buf.append(allocator, ')'); }