forked from areski/cdr-pusher
-
Notifications
You must be signed in to change notification settings - Fork 3
/
database_fetcher.go
267 lines (243 loc) · 6.99 KB
/
database_fetcher.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
package main
// # TODO
// ------
// Using an ORM would have a huge advantage for the database fetcher as
// we will be able to use the same code over several DBMS.
// https://github.com/go-gorp/gorp
// gorp and other ORM are great but we need the ability to define our structure based
// on the configuration file.
// gorp support MySQL, PostgreSQL, sqlite3, Oracle & SQL Server
import (
"bytes"
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
_ "github.com/mattn/go-sqlite3"
// "github.com/coopernurse/gorp"
"errors"
log "github.com/Sirupsen/logrus"
"text/template"
)
// SQLFetcher is a database sql fetcher for CDRS, records will be retrieved
// from SQLFetcher and later pushed to the Pusher.
// SQLFetcher structure keeps tracks DB file, table, results and further data
// needed to fetch.
type SQLFetcher struct {
db *sql.DB
DBFile string
DNS string
DBType string
DBTable string
DBFlagField string
MaxFetchBatch int
numFetched int
cdrFields []ParseFields
results map[int][]string
sqlQuery string
listIDs string
IDField string
}
// FetchSQL is used to build the SQL query to fetch on the Database source
type FetchSQL struct {
ListFields string
Table string
Limit string
Clause string
Order string
}
// UpdateCDR is used to build the SQL query to update the Database source and
// track the records imported
type UpdateCDR struct {
Table string
Fieldname string
Status int
CDRids string
IDField string
}
// Init is a constructor for SQLFetcher
// It will help setting DBFile, DBTable, MaxFetchBatch and cdrFields
func (f *SQLFetcher) Init(DBFile string, DBTable string, MaxFetchBatch int, cdrFields []ParseFields,
DBFlagField string, DBType string, DNS string) {
f.db = nil
f.DBFile = DBFile
f.DBTable = DBTable
f.DBType = DBType
f.DNS = DNS
f.MaxFetchBatch = MaxFetchBatch
f.numFetched = 0
f.cdrFields = cdrFields
f.results = nil
f.sqlQuery = ""
f.DBFlagField = DBFlagField
f.IDField = "id"
}
// func NewSQLFetcher(DBFile string, DBTable string, MaxFetchBatch int, cdrFields []ParseFields) *SQLFetcher {
// db, _ := sql.Open("sqlite3", "./sqlitedb/cdr.db")
// return &SQLFetcher{db: db, DBFile: DBFile, DBTable: DBTable, sqlQuery: "", MaxFetchBatch, 0, cdrFields, nil}
// }
// Connect will help to connect to the DBMS, here we implemented the connection to SQLite
func (f *SQLFetcher) Connect() error {
var err error
if f.DBType == "sqlite3" {
f.IDField = "rowid"
f.db, err = sql.Open("sqlite3", f.DBFile)
if err != nil {
log.Error("Failed to connect", err)
return err
}
} else if f.DBType == "mysql" {
f.db, err = sql.Open("mysql", f.DNS)
if err != nil {
log.Error("Failed to connect", err)
return err
}
} else {
log.Error("DBType not supported!")
return errors.New("DBType not supported!")
}
return nil
}
// PrepareQuery method will build the fetching SQL query
func (f *SQLFetcher) PrepareQuery() error {
strFields := getFieldSelect(f.IDField, f.cdrFields)
// parse the string cdrFields
const tsql = "SELECT {{.ListFields}} FROM {{.Table}} {{.Clause}} {{.Order}} {{.Limit}}"
var strSQL bytes.Buffer
slimit := fmt.Sprintf("LIMIT %d", f.MaxFetchBatch)
clause := "WHERE " + f.DBFlagField + "<>1"
sqlb := FetchSQL{ListFields: strFields, Table: f.DBTable, Limit: slimit, Clause: clause}
t := template.Must(template.New("sql").Parse(tsql))
err := t.Execute(&strSQL, sqlb)
if err != nil {
panic(err)
}
f.sqlQuery = strSQL.String()
log.Debug("SELECT_SQL: ", f.sqlQuery)
return nil
}
// DBClose is helping defering the closing of the DB connector
func (f *SQLFetcher) DBClose() error {
defer f.db.Close()
return nil
}
// ScanResult method will scan the results and build the 2 propreties
// 'results' and 'listIDs'.
// - 'results' will held a map[int][]string that will contain all records
// - 'listIDs' will held a list of IDs from the results as a string
func (f *SQLFetcher) ScanResult() error {
// Init numFetched to 0
f.numFetched = 0
rows, err := f.db.Query(f.sqlQuery)
if err != nil {
log.Error("Failed to run query:", err.Error())
return err
}
defer rows.Close()
cols, err := rows.Columns()
if err != nil {
log.Error("Failed to get columns:", err.Error())
return err
}
// Result is your slice string.
f.results = make(map[int][]string)
f.listIDs = ""
rawResult := make([][]byte, len(cols))
result := make([]string, len(cols))
dest := make([]interface{}, len(cols)) // A temporary interface{} slice
for i := range rawResult {
dest[i] = &rawResult[i] // Put pointers to each string in the interface slice
}
k := 0
for rows.Next() {
err = rows.Scan(dest...)
if err != nil {
log.Error("Failed to scan row", err)
return err
}
for i, raw := range rawResult {
if i == 0 {
f.listIDs = f.listIDs + string(raw) + ", "
}
if raw == nil {
result[i] = "\\N"
} else {
result[i] = string(raw)
}
f.results[k] = append(f.results[k], result[i])
}
k++
}
f.numFetched = k
log.Info("Total fetched from database: ", f.numFetched)
// Remove last ', ' from f.listIDs
if f.listIDs != "" {
f.listIDs = f.listIDs[0 : len(f.listIDs)-2]
}
return nil
}
// UpdateCdrTable method is used to mark the record that has been imported
func (f *SQLFetcher) UpdateCdrTable(status int) error {
const tsql = "UPDATE {{.Table}} SET {{.Fieldname}}={{.Status}} WHERE {{.IDField}} IN ({{.CDRids}})"
var strSQL bytes.Buffer
if len(f.listIDs) > 0 {
sqlb := UpdateCDR{Table: f.DBTable, Fieldname: f.DBFlagField, Status: status, IDField: f.IDField, CDRids: f.listIDs}
t := template.Must(template.New("sql").Parse(tsql))
err := t.Execute(&strSQL, sqlb)
log.Debug("UPDATE TABLE: ", &strSQL)
if err != nil {
return err
}
if _, err := f.db.Exec(strSQL.String()); err != nil {
return err
}
} else {
log.Debug("No IDs to update...")
}
return nil
}
// AddFieldTrackImport method will add a new field to your DB schema to track the import
func (f *SQLFetcher) AddFieldTrackImport() error {
const tsql = "ALTER TABLE {{.Table}} ADD {{.Fieldname}} INTEGER DEFAULT 0"
var strSQL bytes.Buffer
sqlb := UpdateCDR{Table: f.DBTable, Fieldname: f.DBFlagField, Status: 0}
t := template.Must(template.New("sql").Parse(tsql))
err := t.Execute(&strSQL, sqlb)
log.Debug("ALTER TABLE: ", &strSQL)
if err != nil {
return err
}
if _, err := f.db.Exec(strSQL.String()); err != nil {
return err
}
return nil
}
// Fetch is the main method that will connect to the DB, add field for import tracking,
// prepare query and finally build the results
func (f *SQLFetcher) Fetch() error {
// Connect to DB
err := f.Connect()
if err != nil {
return err
}
defer f.db.Close()
err = f.AddFieldTrackImport()
if err != nil {
log.Debug("Exec err (expected error if the field exist):", err.Error())
}
// Prepare SQL query
err = f.PrepareQuery()
if err != nil {
return err
}
// Get Results
err = f.ScanResult()
if err != nil {
return err
}
err = f.UpdateCdrTable(1)
if err != nil {
return err
}
log.Debug("RESULT:", f.results)
return nil
}