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
|
package postgres
import (
"database/sql"
"fmt"
"strings"
)
// sql query
type sqlQuery struct {
query string
params []interface{}
}
func (q *sqlQuery) Exec(conn *sql.DB) (err error) {
_, err = conn.Exec(q.query, q.params...)
return
}
func (q *sqlQuery) QueryRow(conn *sql.DB, visitor func(*sql.Row) error) (err error) {
err = visitor(conn.QueryRow(q.query, q.params))
return
}
func (q *sqlQuery) Query(conn *sql.DB, visitor func(*sql.Rows) error) (err error) {
var rows *sql.Rows
rows, err = conn.Query(q.query, q.params...)
if err == sql.ErrNoRows {
err = nil
} else if err == nil {
err = visitor(rows)
rows.Close()
}
return
}
// make a createQuery that creates an index for column on table
func createIndex(table, column string) sqlQuery {
return sqlQuery{
query: fmt.Sprintf("CREATE INDEX IF NOT EXISTS ON %s %s ", table, column),
}
}
// make a createQuery that creates a trigraph index on a table for multiple columns
func createTrigraph(table string, columns ...string) sqlQuery {
return sqlQuery{
query: fmt.Sprintf("CREATE INDEX IF NOT EXISTS ON %s USING gin(%s gin_trgm_ops)", table, strings.Join(columns, ", ")),
}
}
// defines table creation info
type createTable struct {
name string // Table's name
columns tableColumns // Table's columns
preCreate []sqlQuery // Queries to run before table is ensrued
postCreate []sqlQuery // Queries to run after table is ensured
}
func (t createTable) String() string {
return fmt.Sprintf("CREATE TABLE %s IF NOT EXISTS ( %s )", t.name, t.columns)
}
func (t createTable) Exec(conn *sql.DB) (err error) {
// pre queries
for idx := range t.preCreate {
err = t.preCreate[idx].Exec(conn)
if err != nil {
return
}
}
// table definition
_, err = conn.Exec(t.String())
if err != nil {
return
}
// post queries
for idx := range t.postCreate {
err = t.postCreate[idx].Exec(conn)
if err != nil {
return
}
}
return
}
// tableColumns is a list of columns for a table to be created
type tableColumns []string
func (def tableColumns) String() string {
return strings.Join(def, ", ")
}
|