v004-add-category.vala 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. using InvercargillSql;
  2. using InvercargillSql.Migrations;
  3. /**
  4. * Migration to add category support to products.
  5. *
  6. * Demonstrates ALTER TABLE with foreign keys:
  7. * - Creating a new reference table (categories)
  8. * - Adding an FK column to an existing table
  9. * - Using .on_delete_set_null() to preserve products when category is deleted
  10. * - Using drop_foreign_key_on() in down() for auto-generated FK names
  11. */
  12. public class V004_AddCategory : Migration {
  13. public override string migration_namespace { get { return "app"; } }
  14. public override uint64 serial { get { return 4; } }
  15. public override string name { get { return "AddCategory"; } }
  16. public override void up(MigrationBuilder b) throws SqlError {
  17. // First create the categories table
  18. b.create_table("categories", t => {
  19. t.column<int64?>("id")
  20. .primary_key()
  21. .auto_increment();
  22. t.column<string>("name")
  23. .not_null();
  24. });
  25. // Then add the FK column to products
  26. // on_delete_set_null keeps products when their category is deleted
  27. b.alter_table("products", t => {
  28. t.add_column<int64?>("category_id")
  29. .references("categories", "id")
  30. .on_delete_set_null();
  31. });
  32. }
  33. public override void down(MigrationBuilder b) throws SqlError {
  34. // Drop the FK first using drop_foreign_key_on (handles auto-generated name)
  35. b.alter_table("products", t => {
  36. t.drop_foreign_key_on("category_id");
  37. t.drop_column("category_id");
  38. });
  39. b.drop_table("categories");
  40. }
  41. }