master
go 64 lines 1.41 KB
Raw
1 // SPDX-License-Identifier: GPL-3.0-or-later
2
3 package sqlquery
4
5 import (
6 "context"
7 "fmt"
8 )
9
10 type PlaceholderStyle int
11
12 const (
13 PlaceholderQuestion PlaceholderStyle = iota
14 PlaceholderDollar
15 )
16
17 func tableColumnsQuery(style PlaceholderStyle) (string, error) {
18 switch style {
19 case PlaceholderQuestion:
20 return `
21 SELECT COLUMN_NAME
22 FROM information_schema.COLUMNS
23 WHERE TABLE_SCHEMA = ?
24 AND TABLE_NAME = ?`, nil
25 case PlaceholderDollar:
26 return `
27 SELECT COLUMN_NAME
28 FROM information_schema.COLUMNS
29 WHERE TABLE_SCHEMA = $1
30 AND TABLE_NAME = $2`, nil
31 default:
32 return "", fmt.Errorf("unsupported placeholder style: %d", style)
33 }
34 }
35
36 // FetchTableColumns returns the set of column names for schema.table.
37 // If transform is non-nil, it is applied to each column name before insertion.
38 func FetchTableColumns(ctx context.Context, q Queryer, schema, table string, style PlaceholderStyle, transform func(string) string) (map[string]bool, error) {
39 query, err := tableColumnsQuery(style)
40 if err != nil {
41 return nil, err
42 }
43 rows, err := q.QueryContext(ctx, query, schema, table)
44 if err != nil {
45 return nil, err
46 }
47 defer func() { _ = rows.Close() }()
48
49 cols := make(map[string]bool)
50 for rows.Next() {
51 var name string
52 if err := rows.Scan(&name); err != nil {
53 return nil, err
54 }
55 if transform != nil {
56 name = transform(name)
57 }
58 cols[name] = true
59 }
60 if err := rows.Err(); err != nil {
61 return nil, err
62 }
63 return cols, nil
64 }