-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathintrospect.go
More file actions
89 lines (80 loc) · 2.26 KB
/
Copy pathintrospect.go
File metadata and controls
89 lines (80 loc) · 2.26 KB
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
package postgres
import (
"github.com/tinywasm/ddl"
"github.com/tinywasm/storage"
)
type querier interface {
Query(query string, args ...any) (storage.Rows, error)
}
func tables(q querier) ([]string, error) {
rows, err := q.Query(`
SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'public'
AND table_type = 'BASE TABLE'
ORDER BY table_name
`)
if err != nil {
return nil, err
}
defer rows.Close()
var tbls []string
for rows.Next() {
var name string
if err := rows.Scan(&name); err != nil {
return nil, err
}
tbls = append(tbls, name)
}
return tbls, rows.Err()
}
func columns(q querier, table string) ([]ddl.ColumnInfo, error) {
rows, err := q.Query(`
SELECT
c.column_name,
c.data_type,
c.is_nullable = 'NO' AS not_null,
COALESCE(
(SELECT true
FROM information_schema.table_constraints tc
JOIN information_schema.key_column_usage kcu
ON tc.constraint_name = kcu.constraint_name
AND tc.table_name = kcu.table_name
WHERE tc.constraint_type = 'PRIMARY KEY'
AND kcu.table_name = c.table_name
AND kcu.column_name = c.column_name
LIMIT 1),
false
) AS is_pk
FROM information_schema.columns c
WHERE c.table_schema = 'public'
AND c.table_name = $1
ORDER BY c.ordinal_position
`, table)
if err != nil {
return nil, err
}
defer rows.Close()
var cols []ddl.ColumnInfo
for rows.Next() {
var col ddl.ColumnInfo
var notNull, pk bool
if err := rows.Scan(&col.Name, &col.Type, ¬Null, &pk); err != nil {
return nil, err
}
col.NotNull = notNull
col.PK = pk
cols = append(cols, col)
}
return cols, rows.Err()
}
// Tables returns all user-defined table names in the current schema.
func (p *PostgresAdapter) Tables() ([]string, error) {
return tables(p)
}
// Columns returns full column metadata for the given table.
func (p *PostgresAdapter) Columns(table string) ([]ddl.ColumnInfo, error) {
return columns(p, table)
}
// Ensure PostgresAdapter implements ddl.SchemaInspector
var _ ddl.SchemaInspector = (*PostgresAdapter)(nil)