upsert_test.go 1.5 KB

12345678910111213141516171819202122232425262728293031
  1. package executor
  2. import "testing"
  3. // TestOnConflictUniqueIndexUpsert reproduces Vikunja's task_buckets upsert:
  4. // INSERT ... ON CONFLICT (a, b) DO UPDATE SET col = excluded.col against a
  5. // unique index that is not the primary key.
  6. func TestOnConflictUniqueIndexUpsert(t *testing.T) {
  7. _, schema, table := newTestDB(t)
  8. e := newExec(schema, table)
  9. execMust(t, e, "CREATE TABLE task_buckets (id INTEGER PRIMARY KEY AUTOINCREMENT, task_id INTEGER, project_view_id INTEGER, bucket_id INTEGER)")
  10. execMust(t, e, "CREATE UNIQUE INDEX uq_tb ON task_buckets (task_id, project_view_id)")
  11. execMust(t, e, "INSERT INTO task_buckets (task_id, project_view_id, bucket_id) VALUES (1, 12, 9)")
  12. execMust(t, e, "INSERT INTO task_buckets (task_id, project_view_id, bucket_id) VALUES (1, 12, 7) ON CONFLICT (task_id, project_view_id) DO UPDATE SET bucket_id = excluded.bucket_id")
  13. res := execMust(t, e, "SELECT bucket_id FROM task_buckets WHERE task_id = 1 AND project_view_id = 12")
  14. if res.RowCount != 1 {
  15. t.Fatalf("expected 1 row, got %d: %v", res.RowCount, res.Rows)
  16. }
  17. if res.Rows[0][0] != int64(7) {
  18. t.Fatalf("bucket_id = %v, want 7", res.Rows[0][0])
  19. }
  20. // A different (task_id, project_view_id) inserts a new row.
  21. execMust(t, e, "INSERT INTO task_buckets (task_id, project_view_id, bucket_id) VALUES (2, 12, 5) ON CONFLICT (task_id, project_view_id) DO UPDATE SET bucket_id = excluded.bucket_id")
  22. res = execMust(t, e, "SELECT count(*) FROM task_buckets")
  23. if res.Rows[0][0] != int64(2) {
  24. t.Fatalf("expected 2 rows, got %v", res.Rows[0][0])
  25. }
  26. }