forked from muety/wakapi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.go
87 lines (70 loc) · 2.17 KB
/
db.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
package utils
import (
"fmt"
"reflect"
"strings"
"gorm.io/gorm"
"log/slog"
)
func IsCleanDB(db *gorm.DB) bool {
if db.Dialector.Name() == "sqlite" {
var count int64
if err := db.Raw("SELECT count(*) from sqlite_master WHERE type = 'table'").Scan(&count).Error; err != nil {
slog.Error("failed to check if database is clean", "error", err)
return false
}
return count == 0
}
slog.Warn("IsCleanDB is not yet implemented for dialect", "dialect", db.Dialector.Name())
return false
}
func HasConstraints(db *gorm.DB) bool {
if db.Dialector.Name() == "sqlite" {
var count int64
if err := db.Raw("SELECT count(*) from sqlite_master WHERE sql LIKE '%CONSTRAINT%'").Scan(&count).Error; err != nil {
slog.Error("failed to check if database has constraints", "error", err)
return false
}
return count != 0
}
slog.Warn("HasForeignKeyConstraints is not yet implemented for dialect", "dialect", db.Dialector.Name())
return false
}
func WhereNullable(query *gorm.DB, col string, val any) *gorm.DB {
if val == nil || reflect.ValueOf(val).IsNil() {
return query.Where(fmt.Sprintf("%s is null", col))
}
return query.Where(fmt.Sprintf("%s = ?", col), val)
}
func WithPaging(query *gorm.DB, limit, skip int) *gorm.DB {
if limit >= 0 {
query = query.Limit(limit)
}
if skip >= 0 {
query = query.Offset(skip)
}
return query
}
type stringWriter struct {
*strings.Builder
}
func (s stringWriter) WriteByte(c byte) error {
return s.Builder.WriteByte(c)
}
func (s stringWriter) WriteString(str string) (int, error) {
return s.Builder.WriteString(str)
}
// QuoteDbIdentifier quotes a column name used in a query.
func QuoteDbIdentifier(db *gorm.DB, identifier string) string {
builder := stringWriter{Builder: &strings.Builder{}}
db.Dialector.QuoteTo(builder, identifier)
return builder.Builder.String()
}
// QuoteSql quotes a SQL statement with the given identifiers.
func QuoteSql(db *gorm.DB, queryTemplate string, identifiers ...string) string {
quotedIdentifiers := make([]interface{}, len(identifiers))
for i, identifier := range identifiers {
quotedIdentifiers[i] = QuoteDbIdentifier(db, identifier)
}
return fmt.Sprintf(queryTemplate, quotedIdentifiers...)
}