alter_table_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. package executor
  2. import (
  3. "errors"
  4. "sync"
  5. "testing"
  6. "github.com/danfragoso/pizzasql-next/pkg/storage"
  7. )
  8. // ADD COLUMN with a constant DEFAULT materializes the value into rows that
  9. // already exist, so the column reads the default everywhere.
  10. func TestAlterTableAddColumnBackfillsPopulatedTable(t *testing.T) {
  11. _, schema, table := newTestDB(t)
  12. e := newExec(schema, table)
  13. execMust(t, e, "CREATE TABLE t (id INTEGER PRIMARY KEY)")
  14. execMust(t, e, "INSERT INTO t (id) VALUES (1), (2)")
  15. execMust(t, e, "ALTER TABLE t ADD COLUMN note TEXT DEFAULT 'later'")
  16. res := execMust(t, e, "SELECT id, note FROM t ORDER BY id")
  17. if res.RowCount != 2 {
  18. t.Fatalf("row count = %d, want 2", res.RowCount)
  19. }
  20. for _, row := range res.Rows {
  21. if row[1] != "later" {
  22. t.Fatalf("existing row %v note = %v, want later", row[0], row[1])
  23. }
  24. }
  25. execMust(t, e, "INSERT INTO t (id) VALUES (3)")
  26. res = execMust(t, e, "SELECT note FROM t WHERE id = 3")
  27. if got := res.Rows[0][0]; got != "later" {
  28. t.Fatalf("new row note = %v, want later", got)
  29. }
  30. }
  31. // A DEFAULT declared on an empty table has no rows to rewrite; later INSERTs
  32. // that omit the column take it, and an explicit NULL still wins.
  33. func TestAlterTableAddColumnDefaultOnEmptyTable(t *testing.T) {
  34. _, schema, table := newTestDB(t)
  35. e := newExec(schema, table)
  36. execMust(t, e, "CREATE TABLE t (id INTEGER PRIMARY KEY)")
  37. execMust(t, e, "ALTER TABLE t ADD COLUMN note TEXT DEFAULT 'later'")
  38. execMust(t, e, "INSERT INTO t (id) VALUES (1)")
  39. execMust(t, e, "INSERT INTO t (id, note) VALUES (2, NULL)")
  40. res := execMust(t, e, "SELECT id, note FROM t ORDER BY id")
  41. if len(res.Rows) != 2 || res.Rows[0][1] != "later" || res.Rows[1][1] != nil {
  42. t.Fatalf("rows = %v, want [[1 later] [2 NULL]]", res.Rows)
  43. }
  44. }
  45. // ADD COLUMN without a DEFAULT leaves existing rows NULL.
  46. func TestAlterTableAddColumnWithoutDefaultLeavesExistingRowsNull(t *testing.T) {
  47. _, schema, table := newTestDB(t)
  48. e := newExec(schema, table)
  49. execMust(t, e, "CREATE TABLE t (id INTEGER PRIMARY KEY)")
  50. execMust(t, e, "INSERT INTO t (id) VALUES (1), (2)")
  51. execMust(t, e, "ALTER TABLE t ADD COLUMN note TEXT")
  52. res := execMust(t, e, "SELECT id, note FROM t ORDER BY id")
  53. if res.RowCount != 2 {
  54. t.Fatalf("row count = %d, want 2", res.RowCount)
  55. }
  56. for _, row := range res.Rows {
  57. if row[1] != nil {
  58. t.Fatalf("existing row %v note = %v, want NULL", row[0], row[1])
  59. }
  60. }
  61. }
  62. // A NOT NULL column with a constant DEFAULT backfills existing rows, so the
  63. // constraint holds for rows that predate the statement.
  64. func TestAlterTableAddColumnNotNullWithDefaultBackfills(t *testing.T) {
  65. _, schema, table := newTestDB(t)
  66. e := newExec(schema, table)
  67. execMust(t, e, "CREATE TABLE t (id INTEGER PRIMARY KEY)")
  68. execMust(t, e, "INSERT INTO t (id) VALUES (1), (2)")
  69. execMust(t, e, "ALTER TABLE t ADD COLUMN status TEXT NOT NULL DEFAULT 'pending'")
  70. fresh := newExec(schema, table)
  71. res := execMust(t, fresh, "SELECT status FROM t ORDER BY id")
  72. if res.RowCount != 2 {
  73. t.Fatalf("row count = %d, want 2", res.RowCount)
  74. }
  75. for _, row := range res.Rows {
  76. if row[0] != "pending" {
  77. t.Fatalf("existing status = %v, want pending", row[0])
  78. }
  79. }
  80. execMust(t, e, "INSERT INTO t (id) VALUES (3)")
  81. res = execMust(t, e, "SELECT status FROM t WHERE id = 3")
  82. if got := res.Rows[0][0]; got != "pending" {
  83. t.Fatalf("new row status = %v, want pending", got)
  84. }
  85. }
  86. // A NOT NULL column without a DEFAULT has nothing to write into existing rows
  87. // and must not report the table as migrated.
  88. func TestAlterTableAddColumnNotNullWithoutDefaultRejectsPopulatedTable(t *testing.T) {
  89. _, schema, table := newTestDB(t)
  90. e := newExec(schema, table)
  91. execMust(t, e, "CREATE TABLE t (id INTEGER PRIMARY KEY)")
  92. execMust(t, e, "INSERT INTO t (id) VALUES (1)")
  93. _, err := execSQL(e, "ALTER TABLE t ADD COLUMN status TEXT NOT NULL")
  94. var violation *storage.NotNullViolationError
  95. if !errors.As(err, &violation) {
  96. t.Fatalf("error = %v, want NotNullViolationError", err)
  97. }
  98. s, err := schema.GetSchema("t")
  99. if err != nil {
  100. t.Fatalf("get schema: %v", err)
  101. }
  102. if _, exists := s.GetColumn("status"); exists {
  103. t.Fatal("rejected ADD COLUMN left the column in the schema")
  104. }
  105. if rows := execMust(t, e, "SELECT id FROM t").Rows; len(rows) != 1 {
  106. t.Fatalf("rows = %v, want the existing row untouched", rows)
  107. }
  108. }
  109. // The same statement is legal on an empty table; the constraint is then
  110. // enforced on the INSERTs that follow.
  111. func TestAlterTableAddColumnNotNullWithoutDefaultOnEmptyTable(t *testing.T) {
  112. _, schema, table := newTestDB(t)
  113. e := newExec(schema, table)
  114. execMust(t, e, "CREATE TABLE t (id INTEGER PRIMARY KEY)")
  115. execMust(t, e, "ALTER TABLE t ADD COLUMN status TEXT NOT NULL")
  116. _, err := execSQL(e, "INSERT INTO t (id) VALUES (1)")
  117. var violation *storage.NotNullViolationError
  118. if !errors.As(err, &violation) {
  119. t.Fatalf("insert without status error = %v, want NotNullViolationError", err)
  120. }
  121. execMust(t, e, "INSERT INTO t (id, status) VALUES (1, 'active')")
  122. res := execMust(t, e, "SELECT status FROM t WHERE id = 1")
  123. if got := res.Rows[0][0]; got != "active" {
  124. t.Fatalf("status = %v, want active", got)
  125. }
  126. }
  127. // Backfilling one constant into several rows would duplicate the value, so the
  128. // UNIQUE constraint must reject the ALTER instead of creating a silently
  129. // non-unique column.
  130. func TestAlterTableAddColumnUniqueWithDefaultRejectsPopulatedTable(t *testing.T) {
  131. _, schema, table := newTestDB(t)
  132. e := newExec(schema, table)
  133. execMust(t, e, "CREATE TABLE t (id INTEGER PRIMARY KEY)")
  134. execMust(t, e, "INSERT INTO t (id) VALUES (1), (2)")
  135. _, err := execSQL(e, "ALTER TABLE t ADD COLUMN code TEXT DEFAULT 'same' UNIQUE")
  136. var violation *storage.UniqueViolationError
  137. if !errors.As(err, &violation) {
  138. t.Fatalf("error = %v, want UniqueViolationError", err)
  139. }
  140. s, err := schema.GetSchema("t")
  141. if err != nil {
  142. t.Fatalf("get schema: %v", err)
  143. }
  144. if _, exists := s.GetColumn("code"); exists {
  145. t.Fatal("rejected ADD COLUMN left the column in the schema")
  146. }
  147. indexes, err := schema.ListTableIndexes("t")
  148. if err != nil {
  149. t.Fatalf("list indexes: %v", err)
  150. }
  151. if len(indexes) != 0 {
  152. t.Fatalf("indexes = %v, want none", indexes)
  153. }
  154. }
  155. // A single-row table can take a UNIQUE column with a default, and the
  156. // constraint is enforced for every later INSERT that omits the column.
  157. func TestAlterTableAddColumnUniqueWithDefaultEnforcesLaterInserts(t *testing.T) {
  158. _, schema, table := newTestDB(t)
  159. e := newExec(schema, table)
  160. execMust(t, e, "CREATE TABLE t (id INTEGER PRIMARY KEY)")
  161. execMust(t, e, "INSERT INTO t (id) VALUES (1)")
  162. execMust(t, e, "ALTER TABLE t ADD COLUMN code TEXT DEFAULT 'same' UNIQUE")
  163. _, err := execSQL(e, "INSERT INTO t (id) VALUES (2)")
  164. var violation *storage.UniqueViolationError
  165. if !errors.As(err, &violation) {
  166. t.Fatalf("insert with duplicated default error = %v, want UniqueViolationError", err)
  167. }
  168. execMust(t, e, "INSERT INTO t (id, code) VALUES (2, 'other')")
  169. res := execMust(t, e, "SELECT code FROM t ORDER BY id")
  170. if len(res.Rows) != 2 || res.Rows[0][0] != "same" || res.Rows[1][0] != "other" {
  171. t.Fatalf("codes = %v, want [same other]", res.Rows)
  172. }
  173. }
  174. // IF NOT EXISTS stays idempotent on a populated table: the second statement is
  175. // a no-op even when it declares a different default.
  176. func TestAlterTableAddColumnIfNotExistsKeepsBackfilledValues(t *testing.T) {
  177. _, schema, table := newTestDB(t)
  178. e := newExec(schema, table)
  179. execMust(t, e, "CREATE TABLE t (id INTEGER PRIMARY KEY)")
  180. execMust(t, e, "INSERT INTO t (id) VALUES (1)")
  181. execMust(t, e, "ALTER TABLE t ADD COLUMN IF NOT EXISTS note TEXT DEFAULT 'first'")
  182. execMust(t, e, "ALTER TABLE t ADD COLUMN IF NOT EXISTS note TEXT DEFAULT 'second'")
  183. res := execMust(t, e, "SELECT note FROM t WHERE id = 1")
  184. if got := res.Rows[0][0]; got != "first" {
  185. t.Fatalf("note = %v, want the first default to stand", got)
  186. }
  187. s, err := schema.GetSchema("t")
  188. if err != nil {
  189. t.Fatalf("get schema: %v", err)
  190. }
  191. count := 0
  192. for _, col := range s.Columns {
  193. if col.Name == "note" {
  194. count++
  195. }
  196. }
  197. if count != 1 {
  198. t.Fatalf("column note appears %d times, want 1", count)
  199. }
  200. }
  201. func TestAlterTableAddColumnIfNotExistsIsIdempotent(t *testing.T) {
  202. _, schema, table := newTestDB(t)
  203. e := newExec(schema, table)
  204. execMust(t, e, "CREATE TABLE t (id INTEGER PRIMARY KEY)")
  205. execMust(t, e, "ALTER TABLE t ADD COLUMN IF NOT EXISTS c TEXT")
  206. execMust(t, e, "ALTER TABLE t ADD COLUMN IF NOT EXISTS c TEXT")
  207. s, err := schema.GetSchema("t")
  208. if err != nil {
  209. t.Fatalf("get schema: %v", err)
  210. }
  211. count := 0
  212. for _, col := range s.Columns {
  213. if col.Name == "c" {
  214. count++
  215. }
  216. }
  217. if count != 1 {
  218. t.Fatalf("column c appears %d times, want 1", count)
  219. }
  220. }
  221. // Concurrent IF NOT EXISTS ADD COLUMN on one engine instance must not duplicate
  222. // metadata; the schema manager serializes the check-and-append.
  223. func TestAlterTableAddColumnIfNotExistsConcurrent(t *testing.T) {
  224. _, schema, table := newTestDB(t)
  225. e := newExec(schema, table)
  226. execMust(t, e, "CREATE TABLE t (id INTEGER PRIMARY KEY)")
  227. var wg sync.WaitGroup
  228. for i := 0; i < 8; i++ {
  229. wg.Add(1)
  230. go func() {
  231. defer wg.Done()
  232. session := newExec(schema, table)
  233. if _, err := execSQL(session, "ALTER TABLE t ADD COLUMN IF NOT EXISTS c TEXT"); err != nil {
  234. t.Errorf("add column: %v", err)
  235. }
  236. }()
  237. }
  238. wg.Wait()
  239. s, err := schema.GetSchema("t")
  240. if err != nil {
  241. t.Fatalf("get schema: %v", err)
  242. }
  243. count := 0
  244. for _, col := range s.Columns {
  245. if col.Name == "c" {
  246. count++
  247. }
  248. }
  249. if count != 1 {
  250. t.Fatalf("column c appears %d times, want 1", count)
  251. }
  252. }
  253. // DROP COLUMN rewrites every remaining row so the removed value does not stay
  254. // in durable storage.
  255. func TestAlterTableDropColumnRewritesPopulatedRows(t *testing.T) {
  256. _, schema, table := newTestDB(t)
  257. e := newExec(schema, table)
  258. execMust(t, e, "CREATE TABLE t (id INTEGER PRIMARY KEY, keep TEXT, dropme TEXT)")
  259. execMust(t, e, "INSERT INTO t (id, keep, dropme) VALUES (1, 'a', 'secret'), (2, 'b', 'secret')")
  260. execMust(t, e, "ALTER TABLE t DROP COLUMN dropme")
  261. res := execMust(t, e, "SELECT * FROM t ORDER BY id")
  262. if len(res.Columns) != 2 || res.Columns[0] != "id" || res.Columns[1] != "keep" {
  263. t.Fatalf("columns after drop = %v, want [id keep]", res.Columns)
  264. }
  265. if res.RowCount != 2 || res.Rows[0][1] != "a" || res.Rows[1][1] != "b" {
  266. t.Fatalf("rows after drop = %v", res.Rows)
  267. }
  268. if _, err := execSQL(e, "SELECT dropme FROM t"); err == nil {
  269. t.Fatal("expected dropped column to be unknown")
  270. }
  271. }
  272. // RENAME COLUMN rewrites row keys but deliberately leaves index metadata
  273. // unchanged. Documented guidance: drop and recreate indexes after a rename.
  274. func TestAlterTableRenameColumnLeavesIndexMetadataStale(t *testing.T) {
  275. _, schema, table := newTestDB(t)
  276. e := newExec(schema, table)
  277. execMust(t, e, "CREATE TABLE t (id INTEGER PRIMARY KEY, a TEXT)")
  278. execMust(t, e, "INSERT INTO t (id, a) VALUES (1, 'x')")
  279. execMust(t, e, "CREATE INDEX idx_a ON t(a)")
  280. execMust(t, e, "ALTER TABLE t RENAME COLUMN a TO aa")
  281. res := execMust(t, e, "SELECT aa FROM t WHERE id = 1")
  282. if got := res.Rows[0][0]; got != "x" {
  283. t.Fatalf("renamed value = %v, want x", got)
  284. }
  285. names, err := schema.ListIndexes()
  286. if err != nil {
  287. t.Fatalf("list indexes: %v", err)
  288. }
  289. found := false
  290. for _, name := range names {
  291. if name == "idx_a" {
  292. found = true
  293. }
  294. }
  295. if !found {
  296. t.Fatalf("indexes = %v, want idx_a to still exist (rename does not rewrite index metadata)", names)
  297. }
  298. }