github.com/acoshift/pgsql@v0.15.3/error_test.go (about) 1 package pgsql_test 2 3 import ( 4 "context" 5 "testing" 6 "time" 7 8 "github.com/lib/pq" 9 "github.com/stretchr/testify/assert" 10 11 "github.com/acoshift/pgsql" 12 ) 13 14 func TestIsUniqueViolation(t *testing.T) { 15 t.Parallel() 16 17 assert.True(t, pgsql.IsUniqueViolation(&pq.Error{ 18 Severity: "Error", 19 Code: "23505", 20 Message: "", 21 Table: "users", 22 Constraint: "users_email_key", 23 })) 24 25 assert.True(t, pgsql.IsUniqueViolation(&pq.Error{ 26 Severity: "Error", 27 Code: "23505", 28 Message: "", 29 Table: "users", 30 Constraint: "users_email_key", 31 }, "pkey", "users_email_key")) 32 33 assert.False(t, pgsql.IsUniqueViolation(&pq.Error{ 34 Severity: "Error", 35 Code: "23505", 36 Message: "", 37 Table: "users", 38 Constraint: "users_email_key", 39 }, "pkey")) 40 41 assert.False(t, pgsql.IsUniqueViolation(&pq.Error{ 42 Severity: "Error", 43 Code: "23503", 44 Message: "", 45 Table: "users", 46 Constraint: "users_email_key", 47 })) 48 } 49 50 func TestIsForeignKeyViolation(t *testing.T) { 51 t.Parallel() 52 53 assert.True(t, pgsql.IsForeignKeyViolation(&pq.Error{ 54 Severity: "Error", 55 Code: "23503", 56 Message: "", 57 Table: "b", 58 Constraint: "b_a_id_fkey", 59 })) 60 61 assert.True(t, pgsql.IsForeignKeyViolation(&pq.Error{ 62 Severity: "Error", 63 Code: "23503", 64 Message: "", 65 Table: "b", 66 Constraint: "b_a_id_fkey", 67 }, "pkey", "b_a_id_fkey")) 68 69 assert.True(t, pgsql.IsForeignKeyViolation(&pq.Error{ 70 Severity: "Error", 71 Code: "23503", 72 Message: `insert or update on table "b" violates foreign key constraint "b_a_id_fkey"`, 73 Table: "b", 74 Constraint: "", 75 }, "pkey", "b_a_id_fkey")) 76 77 assert.True(t, pgsql.IsForeignKeyViolation(&pq.Error{ 78 Severity: "Error", 79 Code: "23503", 80 Message: `foreign key violation: value ['b'] not found in a@primary [id] (txn=e3f9af56-5f73-4899-975c-4bb1de800402)`, 81 Table: "b", 82 Constraint: "", 83 }, "pkey", "b_a_id_fkey", "a@primary")) 84 } 85 86 func TestIsQueryCanceled(t *testing.T) { 87 t.Parallel() 88 89 db := open(t) 90 defer db.Close() 91 92 ctx := context.Background() 93 ctx, cancel := context.WithCancel(ctx) 94 time.AfterFunc(100*time.Millisecond, cancel) 95 _, err := db.ExecContext(ctx, "select pg_sleep(1)") 96 assert.True(t, pgsql.IsQueryCanceled(err)) 97 }