composite_primary_key_test.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package executor
  2. import (
  3. "strings"
  4. "testing"
  5. )
  6. func TestCreateTablePrimaryKeyConstraints(t *testing.T) {
  7. tests := []struct {
  8. name string
  9. sql string
  10. wantErr string
  11. wantPrimaryKey string
  12. }{
  13. {
  14. name: "composite table-level primary key is rejected",
  15. sql: "CREATE TABLE t (a TEXT, b TEXT, PRIMARY KEY (a, b))",
  16. wantErr: "composite primary key",
  17. },
  18. {
  19. name: "duplicate column composite primary key is rejected",
  20. sql: "CREATE TABLE t (a TEXT, PRIMARY KEY (a, a))",
  21. wantErr: "composite primary key",
  22. },
  23. {
  24. name: "single-column table-level primary key is accepted",
  25. sql: "CREATE TABLE t (a TEXT, PRIMARY KEY (a))",
  26. wantPrimaryKey: "a",
  27. },
  28. {
  29. name: "inline primary key is accepted",
  30. sql: "CREATE TABLE t (a TEXT PRIMARY KEY)",
  31. wantPrimaryKey: "a",
  32. },
  33. }
  34. for _, tt := range tests {
  35. t.Run(tt.name, func(t *testing.T) {
  36. _, schema, table := newTestDB(t)
  37. e := newExec(schema, table)
  38. _, err := execSQL(e, tt.sql)
  39. if tt.wantErr != "" {
  40. if err == nil {
  41. t.Fatalf("expected %q to fail", tt.sql)
  42. }
  43. if !strings.Contains(err.Error(), tt.wantErr) {
  44. t.Fatalf("error = %q, want it to contain %q", err, tt.wantErr)
  45. }
  46. if schema.TableExists("t") {
  47. t.Fatal("rejected CREATE TABLE left a schema behind")
  48. }
  49. if _, err := execSQL(e, "SELECT * FROM t"); err == nil {
  50. t.Fatal("rejected CREATE TABLE left a usable table behind")
  51. }
  52. return
  53. }
  54. if err != nil {
  55. t.Fatalf("exec %q: %v", tt.sql, err)
  56. }
  57. got, err := schema.GetSchema("t")
  58. if err != nil {
  59. t.Fatalf("get schema: %v", err)
  60. }
  61. if got.PrimaryKey != tt.wantPrimaryKey {
  62. t.Fatalf("PrimaryKey = %q, want %q", got.PrimaryKey, tt.wantPrimaryKey)
  63. }
  64. execMust(t, e, "INSERT INTO t (a) VALUES ('x')")
  65. })
  66. }
  67. }