Something went wrong. Try again.
Dev fork of jetzig jetzig.dev
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713const std = @import("std");const Arena = std.heap.ArenaAllocator;const Allocator = std.mem.Allocator;const ArrayList = std.ArrayList;const Io = std.Io;const Dir = Io.Dir;const ArrayListManaged = std.array_list.Managed;const Writer = Io.Writer;
const jet_fields = @import("fields.zig");
name: []const u8,options: MigrationOptions,
const Migration = @This();
const MigrationOptions = struct { migrations_path: ?[]const u8 = null, command: ?[]const u8 = null,};
pub fn init(name: []const u8, options: MigrationOptions) Migration { return .{ .name = name, .options = options, };}
const Command = struct { command: []const u8,
const Action = enum { create, drop, alter, rename };
const Modifier = enum { action, name, rename, type, index, unique, reference, optional, };
pub const DataType = enum { string, integer, float, decimal, boolean, datetime, text, };
pub const Token = union(enum) { table: Table, column: Column,
pub const Table = struct { name: ?[]const u8 = null, rename: ?[]const u8 = null, action: ?Action = null,
pub fn writeUp(self: Table, columns: []const Column, writer: *Writer) !void { switch (self.action orelse .create) { .create => try self.writeCreateTable(columns, writer), .drop => try self.writeDropTable(writer), .alter => try self.writeAlterTable(columns, writer), .rename => {}, // Covered by alterTable } }
pub fn writeDown(self: Table, writer: *Writer) !void { if ((self.action orelse .create) == .create) return try writer.print( \\try repo.dropTable("{s}", .{{}}); \\ , .{self.name orelse return error.MissingTableName}, ); try writer.writeAll("_ = repo;"); }
fn writeCreateTable(self: Table, columns: []const Column, writer: *Writer) !void { try writer.print( \\try repo.createTable("{s}", , .{ self.name orelse return error.MissingTableName, });
try writer.writeAll("&.{");
try writer.writeAll( \\t.primaryKey("id", .{}), ); for (columns) |column| try writeColumn(column, writer); try writer.writeAll("t.timestamps(.{}),"); try writer.writeAll("},"); try writer.writeAll(".{},);"); }
fn writeDropTable(self: Table, writer: *Writer) !void { try writer.print( \\try repo.dropTable("{s}", .{{}}); , .{self.name orelse return error.MissingTableName}); }
fn writeAlterTable(self: Table, columns: []const Column, writer: *Writer) !void { try writer.print( \\try repo.alterTable("{s}", .{{ , .{self.name orelse return error.MissingTableName});
const has_columns = for (columns) |column| { switch (column.action orelse .create) { .create, .drop, .rename => break true, else => unreachable, } } else false;
if (has_columns) try writer.writeAll(".columns = .{");
if (self.rename) |rename_table| try writer.print( \\.rename = "{s}"{s} , .{ rename_table, if (has_columns) "," else "" });
try writeAlterAddColumns(columns, writer); try writeAlterDropColumns(columns, writer); try writeAlterRenameColumns(columns, writer); if (has_columns) try writer.writeAll("},");
try writer.writeAll("});"); }
fn writeAlterAddColumns(columns: []const Column, writer: *Writer) !void { const has_add_column = for (columns) |column| { if (column.action orelse .create == .create) break true; } else false;
if (has_add_column) try writer.writeAll(".add = &.{");
for (columns) |column| if (column.action orelse .create == .create) try writeColumn(column, writer);
if (has_add_column) try writer.writeAll("},"); }
fn writeAlterDropColumns(columns: []const Column, writer: *Writer) !void { const has_drop_column = for (columns) |column| { if (column.action orelse .create == .drop) break true; } else false;
if (has_drop_column) try writer.writeAll(".drop = &.{");
for (columns) |column| { if (column.action orelse .create == .drop) { try writer.print( \\"{s}," , .{column.name orelse return error.MissingColumnName}, ); } }
if (has_drop_column) try writer.writeAll("},"); }
fn writeAlterRenameColumns(columns: []const Column, writer: *Writer) !void { var count: usize = 0; for (columns) |column| { if (column.action orelse .create == .rename) { try writer.print( \\.rename = .{{ .from = "{s}", .to = "{s}" }}, , .{ column.name orelse return error.MissingColumnName, column.rename orelse return error.MissingColumnName, }, ); count += 1; } }
if (count > 1) { std.log.err( "Multiple column renames are not permitted. " ++ "Create separate migrations to rename multiple columns.", .{}, ); } }
fn writeColumn(column: Column, writer: *Writer) !void { var column_type: DataType = undefined; if (column.type) |tp| { column_type = tp; } else if (column.reference_column != null) { column_type = .integer; } else { column_type = .string; }
try writer.print( \\t.column("{s}", .{s}, .{{ , .{ column.name orelse return error.MissingColumnName, @tagName(column_type), }); var options_count: usize = 0; inline for (comptime std.enums.values(Column.options)) |tag| { if (tag != .default) { if (@field(column, @tagName(tag))) |option| { if (option) options_count += 1; } } else if (column.default != null) { options_count += 1; } }
if (column.reference_column) |_| options_count += 1;
var index: usize = 0; inline for (comptime std.enums.values(Column.options)) |field| { if (field != .default) { if (@field(column, @tagName(field))) |option| { if (option) { const sep = if (index + 1 < options_count) "," else ""; try writer.print(".{s} = true{s}", .{ @tagName(field), sep }); index += 1; } } } else if (column.default) |default_value| { const sep = if (index + 1 < options_count) "," else ""; try writer.print(".default = \"{s}\"{s}", .{ default_value, sep }); index += 1; } }
if (try column.referenceInfo()) |reference_info| { try writer.print( \\.reference = .{{"{s}", "{s}"}} , .{ reference_info[0], reference_info[1] }); }
try writer.writeAll("}),"); } };
pub const Column = struct { name: ?[]const u8 = null, rename: ?[]const u8 = null, action: ?Action = null, type: ?DataType = null, index: ?bool = null, unique: ?bool = null, optional: ?bool = null, reference: ?bool = null, reference_column: ?[]const u8 = null, default: ?[]const u8 = null,
pub const options = enum { unique, optional, index, default };
pub fn referenceInfo(self: Column) !?[2][]const u8 { if (self.reference_column == null) return null;
var info: [2][]const u8 = undefined; var it = std.mem.tokenizeScalar(u8, self.reference_column.?, '.'); var index: usize = 0; while (it.next()) |identifier| : (index += 1) { std.debug.assert(index < 2); info[index] = identifier; } std.debug.assert(index == 2); return info; } };
pub fn hasName(self: Token) bool { return switch (self) { inline else => |token| blk: { if (@hasField(@TypeOf(token), "name")) { break :blk token.name != null; } else { // If we don't have a name field, return true to allow other attributes // to be assigned (name always takes precedence as we expect it as the // first token after the object designator, e.g. // `column:foobar:index:unique` - `foobar` is the name. break :blk true; } }, }; }
pub fn hasAction(self: Token) bool { return switch (self) { inline else => |token| token.action != null, }; }
pub fn isRename(self: Token) bool { return switch (self) { inline else => |token| token.action orelse .create == .rename, }; }
pub fn hasRename(self: Token) bool { return switch (self) { inline else => |token| token.rename != null, }; }
pub fn set(self: *Token, modifier: Modifier, value: anytype) void { switch (self.*) { inline else => |*token| { const T = @TypeOf(token.*); inline for (jet_fields.structFields(T)) |field| { if (comptime hasField(T, field.name, @TypeOf(value))) { if (std.mem.eql(u8, field.name, @tagName(modifier))) { @field(token, field.name) = @field(token, field.name) orelse value; } } else if (comptime hasEnum(T, field.name, @TypeOf(value))) { inline for (comptime std.enums.values(FieldType(T, field.name))) |tag| { if (std.mem.eql(u8, @tagName(tag), value)) { @field(token, field.name) = tag; } } } } }, } } };
fn isAction(modifier: []const u8) bool { for (std.enums.values(Action)) |action| { if (std.mem.eql(u8, @tagName(action), modifier)) return true; } return false; }
const TokenIterator = struct { arg_iterator: *std.mem.TokenIterator(u8, .any),
pub fn next(self: TokenIterator) !?Token { while (self.arg_iterator.next()) |arg| { var modifiers_it = std.mem.tokenizeScalar(u8, arg, ':'); var maybe_token: ?Token = null; while (modifiers_it.next()) |modifier| { if (maybe_token) |*token| { if (!token.hasAction() and isAction(modifier)) { token.set(.action, modifier); } else if (!token.hasName()) { token.set(.name, modifier); } else if (modifierToken(modifier)) |modifier_token| { token.set(modifier_token, true); } else if (isType(modifier)) { token.set(.type, modifier); } else if (token.isRename() and !token.hasRename()) { token.set(.rename, modifier); } else if (token.* == .column and token.*.column.reference == true) { token.column.reference_column = modifier; } else if (token.* == .column and std.mem.eql(u8, modifier, "default")) { token.column.default = ""; // Set it to empty string to mark it needs a value } else if (token.* == .column and token.column.default != null and token.column.default.?.len == 0) { token.column.default = modifier; } else { return error.InvalidMigrationCommand; } } else { maybe_token = if (std.mem.eql(u8, modifier, "table")) Token{ .table = .{} } else if (std.mem.eql(u8, modifier, "column")) Token{ .column = .{} } else if (std.mem.eql(u8, modifier, "rename")) Token{ .table = .{ .action = .alter, .rename = modifier } } else { return error.InvalidMigrationCommand; }; } } return maybe_token; } return null; }
fn modifierToken(modifier: []const u8) ?Modifier { inline for (comptime std.enums.values(Modifier)) |value| { if (std.mem.eql(u8, @tagName(value), modifier)) return value; } return null; } };
pub fn write(self: Command, allocator: Allocator, writer: *Writer) !void { var arg_iterator = std.mem.tokenizeAny(u8, self.command, &std.ascii.whitespace); var token_iterator = TokenIterator{ .arg_iterator = &arg_iterator };
var up_buf: Writer.Allocating = .init(allocator); defer up_buf.deinit(); const up_writer = &up_buf.writer;
var down_buf: Writer.Allocating = .init(allocator); defer down_buf.deinit(); const down_writer = &down_buf.writer;
var columns: ArrayList(Command.Token.Column) = .empty; defer columns.deinit(allocator); var maybe_table: ?Command.Token.Table = null;
while (try token_iterator.next()) |token| switch (token) { .table => |table| maybe_table = table, .column => |column| try columns.append(allocator, column), };
if (maybe_table) |table| { try table.writeUp(columns.items, up_writer); try table.writeDown(down_writer); } try writer.print( migration_template, .{ up_buf.writer.buffered(), down_buf.writer.buffered() }, ); }};
const migration_template = \\const std = @import("std"); \\const jetquery = @import("jetquery"); \\const t = jetquery.schema.table; \\ \\pub fn up(repo: anytype) !void {{ \\{s} \\}} \\ \\pub fn down(repo: anytype) !void {{ \\{s} \\}} \\;const default_migration = std.fmt.comptimePrint(migration_template, .{ \\ // The `up` function runs when a migration is applied. \\ // \\ // This example migration creates a table named `my_table` with the following columns: \\ // * `id` \\ // * `my_string` \\ // * `my_integer` \\ // * `created_at` \\ // * `updated_at` \\ // \\ // When present, `created_at` and `updated_at` are automatically populated by JetQuery \\ // when a record is created/modified. \\ // \\ // See https://www.jetzig.dev/documentation/sections/database/migrations for more details. \\ // \\ // Run `jetzig database migrate` to apply migrations. \\ // \\ // Then run `jetzig database reflect` to auto-generate `src/app/database/Schema.zig` \\ // (or manually edit the Schema to include your new table). \\ // \\ try repo.createTable( \\ "my_table", \\ &.{ \\ t.primaryKey("id", .{}), \\ t.column("my_string", .string, .{}), \\ t.column("my_integer", .integer, .{}), \\ t.timestamps(.{}), \\ }, \\ .{}, \\ ); , \\ // The `down` function runs when a migration is rolled back. \\ // In this case, we drop our example table `my_table`. \\ // \\ // Run `jetzig database rollback` to roll back a migration. \\ // \\ try repo.dropTable("my_table", .{});});
pub fn save(self: Migration, io: Io, allocator: Allocator) ![]const u8 { const content = try self.render(io);
var dir = if (self.options.migrations_path) |path| try Dir.openDirAbsolute(io, path, .{}) else try Dir.openDir("migrations", io, .{}); defer dir.close(io);
var timestamp_buf: [19]u8 = undefined; const prefix = try timestamp(io, ×tamp_buf); const filename = try std.mem.concat(self.allocator, u8, &.{ prefix, "_", self.name, ".zig" }); const migration_file = try dir.createFile(io, filename, .{ .exclusive = true }); defer migration_file.close(io);
var write_buffer: [1024]u8 = undefined; var writer = migration_file.writer(&write_buffer); try writer.interface.writeAll(content); const realpath = try dir.realpathAlloc(allocator, filename);
return realpath;}
pub fn render(self: Migration, io: Io, allocator: Allocator) ![]const u8 { var buf: Writer.Allocating = .init(allocator); defer buf.deinit(); const writer = &buf.writer;
if (self.options.command) |cmd| { const command = Command{ .command = cmd }; try command.write(allocator, writer); } else try writer.writeAll(default_migration); return try @import("util.zig").zig( io, allocator, buf.writer.buffered(), "Found errors in generated migration.", );}
fn timestamp(io: Io, buf: []u8) ![]const u8 { const datetime = @import("jetzig_datetime").DateTime.now(io); const date = datetime.date(); const time = datetime.time(); const writer: Writer = .fixed(buf); try writer.print( "{d:04}-{d:02}-{d:02}_{d:02}-{d:02}-{d:02}", .{ date.year, @intFromEnum(date.month), date.day, time.hour, time.min, time.sec }, ); return writer.buffered();}
inline fn FieldType(T: type, comptime name: []const u8) type { const F = comptime blk: { for (jet_fields.structFields(T)) |f| { if (std.mem.eql(u8, f.name, name)) break :blk f; } @compileError("field not found: " ++ name); }; return switch (@typeInfo(F.type)) { .optional => |info| info.child, else => F.type, };}
inline fn hasField(T: type, comptime name: []const u8, VT: type) bool { return @hasField(T, name) and FieldType(T, name) == VT;}
inline fn hasEnum(T: type, comptime name: []const u8, VT: type) bool { if (VT != []const u8) return false; if (!@hasField(T, name)) return false;
const FT = FieldType(T, name);
return @typeInfo(FT) == .@"enum";}
inline fn isType(name: []const u8) bool { inline for (comptime std.enums.values(Command.DataType)) |tag| if (std.mem.eql(u8, name, @tagName(tag))) return true; return false;}
const t = std.testing;test "default migration" { const migration: Migration = .init("test_migration", .{});
const rendered = try migration.render(t.io, t.allocator); defer t.allocator.free(rendered);
try t.expectEqualStrings(default_migration, rendered);}
test "migration from command line: create table" { const command = "table:create:cats column:name:string:index:unique column:paws:integer:default:4 column:bio:text:default:friendly_cat column:is_active:boolean:default:true column:no_default:string:optional column:human_id:index:optional:reference:humans.id";
const migration: Migration = .init("test_migration", .{ .command = command }); const rendered = try migration.render(t.io, t.allocator); defer t.allocator.free(rendered);
try t.expectEqualStrings( \\const std = @import("std"); \\const jetquery = @import("jetquery"); \\const t = jetquery.schema.table; \\ \\pub fn up(repo: anytype) !void { \\ try repo.createTable( \\ "cats", \\ &.{ \\ t.primaryKey("id", .{}), \\ t.column("name", .string, .{ .unique = true, .index = true }), \\ t.column("paws", .integer, .{ .default = "4" }), \\ t.column("bio", .text, .{ .default = "friendly_cat" }), \\ t.column("is_active", .boolean, .{ .default = "true" }), \\ t.column("no_default", .string, .{ .optional = true }), \\ t.column("human_id", .integer, .{ .optional = true, .index = true, .reference = .{ "humans", "id" } }), \\ t.timestamps(.{}), \\ }, \\ .{}, \\ ); \\} \\ \\pub fn down(repo: anytype) !void { \\ try repo.dropTable("cats", .{}); \\} \\ , rendered);
// Verify that no DEFAULT clause appears for the no_default field try t.expect(!std.mem.containsAtLeast( u8, rendered, 1, "\"no_default\", .string, .{ .optional = true, .default", ));}
test "migration from command line: create table with default values of various types" { const command = "table:create:defaults_test column:name:string:default:John column:count:integer:default:42 column:active:boolean:default:true column:no_default:string:optional column:price:decimal:default:19.99 column:last_update:datetime:default:now()";
const migration: Migration = .init("test_defaults", .{ .command = command }); const rendered = try migration.render(t.io, t.allocator); defer t.allocator.free(rendered);
try t.expectEqualStrings( \\const std = @import("std"); \\const jetquery = @import("jetquery"); \\const t = jetquery.schema.table; \\ \\pub fn up(repo: anytype) !void { \\ try repo.createTable( \\ "defaults_test", \\ &.{ \\ t.primaryKey("id", .{}), \\ t.column("name", .string, .{ .default = "John" }), \\ t.column("count", .integer, .{ .default = "42" }), \\ t.column("active", .boolean, .{ .default = "true" }), \\ t.column("no_default", .string, .{ .optional = true }), \\ t.column("price", .decimal, .{ .default = "19.99" }), \\ t.column("last_update", .datetime, .{ .default = "now()" }), \\ t.timestamps(.{}), \\ }, \\ .{}, \\ ); \\} \\ \\pub fn down(repo: anytype) !void { \\ try repo.dropTable("defaults_test", .{}); \\} \\ , rendered);}
test "migration from command line: drop table" { const command = "table:drop:cats";
const migration: Migration = .init("test_migration", .{ .command = command }); const rendered = try migration.render(t.io, t.allocator); defer t.allocator.free(rendered);
try t.expectEqualStrings( \\const std = @import("std"); \\const jetquery = @import("jetquery"); \\const t = jetquery.schema.table; \\ \\pub fn up(repo: anytype) !void { \\ try repo.dropTable("cats", .{}); \\} \\ \\pub fn down(repo: anytype) !void { \\ _ = repo; \\} \\ , rendered);}
test "migration from command line: alter table" { // XXX: This is an incoherent migration (renaming table while adding columns not permitted) // but it tests a lot of variations all in one command. We let the database fail if the // migration is not coherent. const command = "table:alter:cats column:color:string:index:unique column:rename:paws:feet column:drop:name rename:dogs";
const migration: Migration = .init("test_migration", .{ .command = command }); const rendered = try migration.render(t.io, t.allocator); defer t.allocator.free(rendered);
try t.expectEqualStrings( \\const std = @import("std"); \\const jetquery = @import("jetquery"); \\const t = jetquery.schema.table; \\ \\pub fn up(repo: anytype) !void { \\ try repo.alterTable("dogs", .{ \\ .columns = .{ \\ .rename = "rename", \\ .add = &.{ \\ t.column("color", .string, .{ .unique = true, .index = true }), \\ }, \\ .drop = &.{"name,"}, \\ .rename = .{ .from = "paws", .to = "feet" }, \\ }, \\ }); \\} \\ \\pub fn down(repo: anytype) !void { \\ _ = repo; \\} \\ , rendered);}