Source file
src/tawesoft.co.uk/go/sqlp/db.go
Documentation:
src/tawesoft.co.uk/go/sqlp/db.go
1 package sqlp
2
3 import (
4 "context"
5 "database/sql"
6 "fmt"
7 "strings"
8 "syscall"
9 )
10
11
12
13 type Queryable interface {
14 Exec(query string, args ...interface{}) (sql.Result, error)
15 ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
16 Query(query string, args ...interface{}) (*sql.Rows, error)
17 QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
18 QueryRow(query string, args ...interface{}) *sql.Row
19 QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row
20 }
21
22
23
24
25 type Transactionable interface {
26 Queryable
27 Begin() (*sql.Tx, error)
28 BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error)
29 }
30
31
32
33 type Features struct {
34 EscapeIdentifier func(s string) (string, error)
35 EscapeString func(s string) (string, error)
36 IsUniqueConstraintError func(err error) bool
37 }
38
39
40
41
42
43 func IsUniqueConstraintError(f *Features, err error) bool {
44 if f.IsUniqueConstraintError == nil { return false }
45 return f.IsUniqueConstraintError(err)
46 }
47
48
49
50 func EscapeIdentifier(f *Features, s string) (string, error) {
51 if f.EscapeIdentifier == nil { return s, fmt.Errorf("not implemented") }
52 return f.EscapeIdentifier(s)
53 }
54
55
56 func EscapeString(f *Features, s string) (string, error) {
57 if f.EscapeString == nil { return s, fmt.Errorf("not implemented") }
58 return f.EscapeString(s)
59 }
60
61
62
63
64
65
66
67 func OpenMode(
68 driverName string,
69 dataSource string,
70 mode int,
71 Opener func(string, string) (*sql.DB, error),
72 ) (*sql.DB, error) {
73 oldMask := syscall.Umask(mode)
74 defer syscall.Umask(oldMask)
75
76 db, err := Opener(driverName, dataSource)
77 if err != nil {
78 return nil, fmt.Errorf("error opening %s database %s: %+v",
79 driverName, dataSource, err)
80 }
81
82
83
84 err = db.Ping()
85 if err != nil {
86 db.Close()
87 return nil, fmt.Errorf("error connecting to %s database %s: %+v",
88 driverName, dataSource, err)
89 }
90
91 return db, nil
92 }
93
94
95
96
97
98
99
100
101
102 func RowsAffectedBetween(result sql.Result, min int, max int) (int64, bool) {
103 affected, err := result.RowsAffected()
104 if err != nil { return -1, false }
105 if affected < int64(min) { return affected, false }
106 if affected > int64(max) { return affected, false }
107 return 0, true
108 }
109
110
111
112
113
114 func RepeatString(x string, n int) string {
115 if n <= 0 { return "" }
116 return strings.Repeat(x + ", ", n - 1) + " " + x
117 }
118
View as plain text