-
Notifications
You must be signed in to change notification settings - Fork 0
/
sql.go
47 lines (42 loc) · 975 Bytes
/
sql.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
package gofixtures
import (
"database/sql"
"fmt"
"strings"
)
type sqlsContext struct {
sqls []string
truncateTables []string
}
func isPostgres(db *sql.DB) bool {
var version string
err := db.QueryRow(`select version()`).Scan(&version)
if err != nil {
panic(err)
}
if strings.Contains(version, "PostgreSQL") {
return true
}
return false
}
func (ic *sqlsContext) truncatePutOnce(db *sql.DB, truncatedTables map[string]bool) {
truncateTablesIfNotYet(db, ic.truncateTables, truncatedTables)
for _, sql := range ic.sqls {
_, err := db.Exec(sql)
if err != nil {
panic(err)
}
}
if isPostgres(db) {
for _, t := range ic.truncateTables {
db.Exec(fmt.Sprintf(`SELECT setval('%s_id_seq', (SELECT max(id) FROM %s))`, t, t))
}
}
}
func Sql(sqls string, truncateTables []string) (c *sqlsContext) {
c = &sqlsContext{
sqls: mergeInsertValues(splitSqls(strings.NewReader(sqls))),
truncateTables: truncateTables,
}
return
}