-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
error_screening.go
92 lines (80 loc) · 2.58 KB
/
error_screening.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
// Copyright 2020 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package schemachange
import (
"fmt"
"strings"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/jackc/pgx"
)
func tableExists(tx *pgx.Tx, tableName *tree.TableName) (bool, error) {
return scanBool(tx, `SELECT EXISTS (
SELECT table_name
FROM information_schema.tables
WHERE table_schema = $1
AND table_name = $2
)`, tableName.Schema(), tableName.Object())
}
func viewExists(tx *pgx.Tx, tableName *tree.TableName) (bool, error) {
return scanBool(tx, `SELECT EXISTS (
SELECT table_name
FROM information_schema.views
WHERE table_schema = $1
AND table_name = $2
)`, tableName.Schema(), tableName.Object())
}
func columnExistsOnTable(tx *pgx.Tx, tableName *tree.TableName, columnName string) (bool, error) {
return scanBool(tx, `SELECT EXISTS (
SELECT column_name
FROM information_schema.columns
WHERE table_schema = $1
AND table_name = $2
AND column_name = $3
)`, tableName.Schema(), tableName.Object(), columnName)
}
func typeExists(tx *pgx.Tx, typ tree.ResolvableTypeReference) (bool, error) {
if !strings.Contains(typ.SQLString(), "enum") {
return true, nil
}
return scanBool(tx, `SELECT EXISTS (
SELECT typname
FROM pg_catalog.pg_type
WHERE typname = $1
)`, typ.SQLString())
}
func tableHasRows(tx *pgx.Tx, tableName *tree.TableName) (bool, error) {
return scanBool(tx, fmt.Sprintf(`SELECT EXISTS (SELECT * FROM %s)`, tableName.String()))
}
func scanBool(tx *pgx.Tx, query string, args ...interface{}) (b bool, err error) {
err = tx.QueryRow(query, args...).Scan(&b)
return b, err
}
func schemaExists(tx *pgx.Tx, schemaName string) (bool, error) {
return scanBool(tx, `SELECT EXISTS (
SELECT schema_name
FROM information_schema.schemata
WHERE schema_name = $1
)`, schemaName)
}
func tableHasDependencies(tx *pgx.Tx, tableName *tree.TableName) (bool, error) {
return scanBool(tx, `SELECT EXISTS (
SELECT fd.descriptor_name
FROM crdb_internal.forward_dependencies AS fd
WHERE fd.descriptor_id =
(
SELECT c.oid
FROM pg_catalog.pg_class AS c
JOIN pg_catalog.pg_namespace AS ns
ON ns.oid = c.relnamespace
WHERE c.relname = $1
AND ns.nspname = $2
)
)`, tableName.Object(), tableName.Schema())
}