-
Notifications
You must be signed in to change notification settings - Fork 2
/
DB_init.go
439 lines (361 loc) · 12.3 KB
/
DB_init.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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
package drugdose
import (
"context"
"errors"
"fmt"
"os"
"path"
"database/sql"
// MySQL driver needed for sql module
_ "github.com/go-sql-driver/mysql"
// SQLite driver needed for sql module
_ "modernc.org/sqlite"
)
// InitDBFileStructure creates the basic file structure for the database.
// This should be run only once!
// This is currently only useful for sqlite.
// If Config.DBDriver is not set to "sqlite" it will exit the program.
func (cfg *Config) InitDBFileStructure() {
const printN string = "InitDBFileStructure()"
dbFileLocat := cfg.DBSettings[cfg.DBDriver].Path
_, err := os.Stat(dbFileLocat)
if err == nil {
printNameVerbose(cfg.VerbosePrinting, printN, dbFileLocat+" exists.")
return
}
if cfg.DBDriver != SqliteDriver {
printName(printN, "Database file can only be created for sqlite.")
exitProgram(printN)
}
if errors.Is(err, os.ErrNotExist) == false {
printName(printN, err)
exitProgram(printN)
}
dirOnly := path.Dir(cfg.DBSettings[cfg.DBDriver].Path)
err = os.Mkdir(dirOnly, 0700)
if err != nil && errors.Is(err, os.ErrExist) == false {
printName(printN, "os.Mkdir(): Error creating directory for DB:", dirOnly, ":", err)
exitProgram(printN)
}
file, err := os.Create(dbFileLocat)
if err != nil {
printName(printN, "os.Create(): Error creating drug info DB file:", dbFileLocat, ":", err)
exitProgram(printN)
}
err = file.Close()
if err != nil {
printName(printN, "file.Close(): Can't close DB file:", dbFileLocat, ":", err)
exitProgram(printN)
}
printName(printN, "Initialised the DB file structure without errors.")
}
// InitInfoTable creates the table for the currently configured source if it
// doesn't exist. It will use the source's name to set the table's name.
// It's called "Info", because it stores general information like dosages and
// timings for every route of administration.
//
// db - open database connection
//
// ctx - context to be passed to sql queries
func (cfg *Config) InitInfoTable(db *sql.DB, ctx context.Context) error {
const printN string = "InitInfoTable()"
ret := cfg.CheckTables(db, ctx, cfg.UseSource)
if ret {
return nil
}
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return fmt.Errorf("%s%w", sprintName(printN, "db.BeginTx(): "), err)
}
caseInsensitive := " "
if cfg.DBDriver == SqliteDriver {
caseInsensitive = " COLLATE NOCASE "
}
initDBsql := "create table " + cfg.UseSource + " (drugName varchar(255)" + caseInsensitive + "not null," +
"drugRoute varchar(255)" + caseInsensitive + "not null," +
"threshold real," +
"lowDoseMin real," +
"lowDoseMax real," +
"mediumDoseMin real," +
"mediumDoseMax real," +
"highDoseMin real," +
"highDoseMax real," +
"doseUnits text" + caseInsensitive + "," +
"onsetMin real," +
"onsetMax real," +
"onsetUnits text" + caseInsensitive + "," +
"comeUpMin real," +
"comeUpMax real," +
"comeUpUnits text" + caseInsensitive + "," +
"peakMin real," +
"peakMax real," +
"peakUnits text" + caseInsensitive + "," +
"offsetMin real," +
"offsetMax real," +
"offsetUnits text" + caseInsensitive + "," +
"totalDurMin real," +
"totalDurMax real," +
"totalDurUnits text" + caseInsensitive + "," +
"timeOfFetch bigint not null," +
"primary key (drugName, drugRoute));"
_, err = tx.Exec(initDBsql)
err = handleErrRollbackSeq(err, tx, printN, "tx.Exec(): ")
if err != nil {
return err
}
err = tx.Commit()
err = handleErrRollbackSeq(err, tx, printN, "tx.Commit(): ")
if err != nil {
return err
}
printNameVerbose(cfg.VerbosePrinting, printN, "Created: '"+cfg.UseSource+"' table for drug info in database.")
return nil
}
const LogStartTimeCol string = "timeOfDoseStart"
const LogEndTimeCol string = "timeOfDoseEnd"
const LogDrugNameCol string = "drugName"
const LogDoseCol string = "dose"
const LogDoseUnitsCol string = "doseUnits"
const LogDrugRouteCol string = "drugRoute"
const LogCostCol string = "cost"
const LogCostCurrencyCol string = "costCurrency"
func validLogCols() []string {
return []string{LogStartTimeCol, LogEndTimeCol, LogDrugNameCol, LogDoseCol, LogDoseUnitsCol,
LogDrugRouteCol, LogCostCol, LogCostCurrencyCol}
}
const InfoDrugNameCol string = "drugName"
const InfoRouteCol string = "drugRoute"
func validInfoCols() []string {
return []string{InfoDrugNameCol, InfoRouteCol}
}
// InitLogsTable creates the table for all user drug logs if it doesn't exist.
//
// db - open database connection
//
// ctx - context to be passed to sql queries
func (cfg *Config) InitLogsTable(db *sql.DB, ctx context.Context) error {
const printN string = "InitLogsTable()"
ret := cfg.CheckTables(db, ctx, loggingTableName)
if ret {
return nil
}
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return fmt.Errorf("%s%w", sprintName(printN, "db.BeginTx(): "), err)
}
caseInsensitive := " "
if cfg.DBDriver == SqliteDriver {
caseInsensitive = " COLLATE NOCASE "
}
initDBsql := "create table " + loggingTableName + " (timeOfDoseStart bigint not null," +
"username varchar(255) not null," +
"timeOfDoseEnd bigint default 0 not null," +
LogDrugNameCol + " text" + caseInsensitive + "not null," +
LogDoseCol + " real not null," +
LogDoseUnitsCol + " text" + caseInsensitive + "not null," +
LogDrugRouteCol + " text" + caseInsensitive + "not null," +
LogCostCol + " real default 0 not null," +
LogCostCurrencyCol + " text" + caseInsensitive + "default '' not null," +
"primary key (timeOfDoseStart, username));"
_, err = tx.Exec(initDBsql)
err = handleErrRollbackSeq(err, tx, printN, "tx.Exec(): ")
if err != nil {
return err
}
err = tx.Commit()
err = handleErrRollbackSeq(err, tx, printN, "tx.Commit(): ")
if err != nil {
return err
}
printNameVerbose(cfg.VerbosePrinting, printN, "Created: 'userLogs' table in database.")
return nil
}
// InitUserSetTable creates the table for all user settings if it doesn't exist.
//
// db - open database connection
//
// ctx - context to be passed to sql queries
func (cfg *Config) InitUserSetTable(db *sql.DB, ctx context.Context) error {
const printN string = "InitUserSetTable()"
ret := cfg.CheckTables(db, ctx, userSetTableName)
if ret {
return nil
}
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return fmt.Errorf("%s%w", sprintName(printN, "db.BeginTx(): "), err)
}
initDBsql := "create table " + userSetTableName + " (username varchar(255) not null," +
"useIDForRemember bigint not null," +
"primary key (username));"
_, err = tx.Exec(initDBsql)
err = handleErrRollbackSeq(err, tx, printN, "tx.Exec(): ")
if err != nil {
return err
}
err = tx.Commit()
err = handleErrRollbackSeq(err, tx, printN, "tx.Commit(): ")
if err != nil {
return err
}
printNameVerbose(cfg.VerbosePrinting, printN, "Created: 'userSettings' table in database.")
return nil
}
// InitNamesAltTables creates all alternative names tables if they don't exist.
// Alternative names are names like "weed" instead of "cannabis" and etc.
// There are global tables which are used for any source. There are also source
// specific names which "replace" the global names.
//
// db - open database connection
//
// ctx - context to be passed to sql queries
//
// replace - if true, creates the tables for the currently configured source
// only, meaning for alt names specific to the source
func (cfg *Config) InitNamesAltTables(db *sql.DB, ctx context.Context, replace bool) error {
const printN string = "InitNamesAltTables()"
tableSuffix := ""
if replace {
tableSuffix = "_" + cfg.UseSource
}
subsExists := false
routesExists := false
unitsExists := false
convUnitsExists := false
ret := cfg.CheckTables(db, ctx, altNamesSubsTableName+tableSuffix)
if ret {
subsExists = true
}
ret = cfg.CheckTables(db, ctx, altNamesRouteTableName+tableSuffix)
if ret {
routesExists = true
}
ret = cfg.CheckTables(db, ctx, altNamesUnitsTableName+tableSuffix)
if ret {
unitsExists = true
}
ret = cfg.CheckTables(db, ctx, altNamesConvUnitsTableName+tableSuffix)
if ret {
convUnitsExists = true
}
if subsExists && routesExists && unitsExists && convUnitsExists {
return nil
}
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return fmt.Errorf("%s%w", sprintName(printN, "db.BeginTx(): "), err)
}
caseInsensitive := " "
if cfg.DBDriver == SqliteDriver {
caseInsensitive = " COLLATE NOCASE "
}
if !subsExists {
initDBsql := "create table " + altNamesSubsTableName + tableSuffix +
" (localName varchar(255)" + caseInsensitive + "not null," +
"alternativeName varchar(255)" + caseInsensitive + "not null," +
"primary key (localName, alternativeName));"
_, err = tx.Exec(initDBsql)
err = handleErrRollbackSeq(err, tx, printN, "tx.Exec(): ")
if err != nil {
return err
}
printNameVerbose(cfg.VerbosePrinting, printN, "Created: '"+altNamesSubsTableName+tableSuffix+"' table in database.")
}
if !routesExists {
initDBsql := "create table " + altNamesRouteTableName + tableSuffix +
" (localName varchar(255)" + caseInsensitive + "not null," +
"alternativeName varchar(255)" + caseInsensitive + "not null," +
"primary key (localName, alternativeName));"
_, err = tx.Exec(initDBsql)
err = handleErrRollbackSeq(err, tx, printN, "tx.Exec(): ")
if err != nil {
return err
}
printNameVerbose(cfg.VerbosePrinting, printN, "Created: '"+altNamesRouteTableName+tableSuffix+"' table in database.")
}
if !unitsExists {
initDBsql := "create table " + altNamesUnitsTableName + tableSuffix +
" (localName varchar(255)" + caseInsensitive + "not null," +
"alternativeName varchar(255)" + caseInsensitive + "not null," +
"primary key (localName, alternativeName));"
_, err = tx.Exec(initDBsql)
err = handleErrRollbackSeq(err, tx, printN, "tx.Exec(): ")
if err != nil {
return err
}
printNameVerbose(cfg.VerbosePrinting, printN, "Created: '"+altNamesUnitsTableName+tableSuffix+"' table in database.")
}
if !convUnitsExists {
initDBsql := "create table " + altNamesConvUnitsTableName + tableSuffix +
" (localName varchar(255)" + caseInsensitive + "not null," +
"alternativeName varchar(255)" + caseInsensitive + "not null," +
"primary key (localName, alternativeName));"
_, err = tx.Exec(initDBsql)
err = handleErrRollbackSeq(err, tx, printN, "tx.Exec(): ")
if err != nil {
return err
}
printNameVerbose(cfg.VerbosePrinting, printN, "Created: '"+altNamesConvUnitsTableName+tableSuffix+"' table in database.")
}
err = tx.Commit()
err = handleErrRollbackSeq(err, tx, printN, "tx.Commit(): ")
if err != nil {
return err
}
return nil
}
// InitAllDBTables creates all tables needed to run the program properly.
// This function should be sufficient on it's own for most use cases.
// Even if the function is called every time the program is started, it should
// not be an issue, since all called functions first check if the tables they're
// trying to create already exist.
//
// db - open database connection
//
// ctx - context to be passed to sql queries
func (cfg *Config) InitAllDBTables(db *sql.DB, ctx context.Context) error {
const printN string = "InitAllDBTables()"
err := cfg.InitInfoTable(db, ctx)
if err != nil {
return fmt.Errorf("%s%w", sprintName(printN), err)
}
err = cfg.InitLogsTable(db, ctx)
if err != nil {
return fmt.Errorf("%s%w", sprintName(printN), err)
}
err = cfg.InitUserSetTable(db, ctx)
if err != nil {
return fmt.Errorf("%s%w", sprintName(printN), err)
}
err = cfg.InitNamesAltTables(db, ctx, false)
if err != nil {
return fmt.Errorf("%s%w", sprintName(printN), err)
}
err = cfg.InitNamesAltTables(db, ctx, true)
if err != nil {
return fmt.Errorf("%s%w", sprintName(printN), err)
}
printNameVerbose(cfg.VerbosePrinting, printN, "Ran through all tables for initialisation.")
return nil
}
// InitAllDB initializes the DB file structure if needed and all tables.
// It will stop the program if it encounters an error.
//
// ctx - context to be passed to sql queries
func (cfg *Config) InitAllDB(ctx context.Context) {
const printN string = "InitAllDB()"
if cfg.DBDriver != MysqlDriver && cfg.DBDriver != SqliteDriver {
printName(printN, "No proper driver selected. Choose "+SqliteDriver+" or "+MysqlDriver+"!")
exitProgram(printN)
}
if cfg.DBDriver == SqliteDriver {
cfg.InitDBFileStructure()
}
db := cfg.OpenDBConnection(ctx)
defer db.Close()
err := cfg.InitAllDBTables(db, ctx)
if err != nil {
printName(printN, "Database didn't get initialised, because of an error, exiting: ", err)
exitProgram(printN)
}
}