/
processors.go
101 lines (91 loc) · 2.21 KB
/
processors.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package processors
import (
"database/sql"
"errors"
"fmt"
"time"
)
type ZeroCoreProcessor struct {
transaction *sql.Tx
prepares map[string]*sql.Stmt
}
func (processor *ZeroCoreProcessor) Build(transaction *sql.Tx) {
processor.transaction = transaction
processor.prepares = make(map[string]*sql.Stmt)
}
func (processor *ZeroCoreProcessor) Exec(execsql string) (sql.Result, error) {
return processor.transaction.Exec(execsql)
}
func (processor *ZeroCoreProcessor) Parser(rows *sql.Rows) []map[string]interface{} {
columns, err := rows.Columns()
if err != nil {
panic(err)
}
values := make([]interface{}, len(columns))
for index := range values {
var value interface{}
values[index] = &value
}
var rowsArray []map[string]interface{}
for rows.Next() {
err = rows.Scan(values...)
if err != nil {
panic(err)
}
rowmap := make(map[string]interface{})
for i, data := range values {
rowmap[columns[i]] = *data.(*interface{})
}
rowsArray = append(rowsArray, rowmap)
}
if err != nil {
panic(err)
}
return rowsArray
}
func (processor *ZeroCoreProcessor) registeyPreparedStatement(preparedSQL string) error {
stmt, err := processor.transaction.Prepare(preparedSQL)
if err != nil {
return err
}
processor.prepares[preparedSQL] = stmt
return nil
}
func (processor *ZeroCoreProcessor) existsPreparedStatement(preparedSQL string) bool {
_, ok := processor.prepares[preparedSQL]
return ok
}
func (processor *ZeroCoreProcessor) PreparedStmt(preparedSQL string) *sql.Stmt {
if !processor.existsPreparedStatement(preparedSQL) {
err := processor.registeyPreparedStatement(preparedSQL)
if err != nil {
panic(err)
}
}
stmt, ok := processor.prepares[preparedSQL]
if !ok {
return nil
}
return stmt
}
func (processor *ZeroCoreProcessor) DatabaseDatetime() (*time.Time, error) {
const FETCH_DATE_SQL = "SELECT current_timestamp"
rows, err := processor.PreparedStmt(FETCH_DATE_SQL).Query()
defer func() {
if rows != nil {
rows.Close()
}
}()
if err != nil {
return nil, err
}
if !rows.Next() {
return nil, errors.New(fmt.Sprintf("query -> %s result error", FETCH_DATE_SQL))
}
var datetime time.Time
err = rows.Scan(&datetime)
if err != nil {
return nil, err
}
return &datetime, nil
}