v004-add-category.vala 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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 int version { get { return 4; } }
  14. public override string name { get { return "AddCategory"; } }
  15. public override void up(MigrationBuilder b) throws SqlError {
  16. // First create the categories table
  17. b.create_table("categories", t => {
  18. t.column<int64?>("id")
  19. .primary_key()
  20. .auto_increment();
  21. t.column<string>("name")
  22. .not_null();
  23. });
  24. // Then add the FK column to products
  25. // on_delete_set_null keeps products when their category is deleted
  26. b.alter_table("products", t => {
  27. t.add_column<int64?>("category_id")
  28. .references("categories", "id")
  29. .on_delete_set_null();
  30. });
  31. }
  32. public override void down(MigrationBuilder b) throws SqlError {
  33. // Drop the FK first using drop_foreign_key_on (handles auto-generated name)
  34. b.alter_table("products", t => {
  35. t.drop_foreign_key_on("category_id");
  36. t.drop_column("category_id");
  37. });
  38. b.drop_table("categories");
  39. }
  40. }