-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.go
737 lines (633 loc) · 19.6 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
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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
package main
import (
"database/sql"
"fmt"
"log"
"time"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
)
type sqlStore struct {
db *sql.DB
// mutex sync.RWMutex
}
func (st *sqlStore) Close() {
err := st.db.Close()
if err != nil {
log.Printf("could not close database properly: %v\n", err)
}
}
type closable interface {
Close() error
}
func close(c closable) {
err := c.Close()
if err != nil {
log.Printf("could not close stmt or rows properly: %v\n", err)
}
}
func newSQLStore(databaseFile string) *sqlStore {
st := &sqlStore{}
var err error
st.db, err = sql.Open("sqlite3", databaseFile)
if err != nil {
log.Fatalf("could not open database: %v", err)
}
if err := st.db.Ping(); err != nil {
log.Fatalf("could not open database: %v", err)
}
schema := `
CREATE TABLE IF NOT EXISTS poll(
ID INTEGER PRIMARY KEY ASC,
UserID INTEGER,
LastSaved INTEGER,
CreatedAt INTEGER,
Type INTEGER,
Private INTEGER,
Inactive INTEGER,
Question TEXT);
CREATE TABLE IF NOT EXISTS pollmsg(
MessageID INTEGER PRIMARY KEY,
ChatId INTEGER,
PollID INTEGER);
CREATE TABLE IF NOT EXISTS pollinlinemsg(
InlineMessageID TEXT PRIMARY KEY,
PollID INTEGER);
CREATE TABLE IF NOT EXISTS answer(
ID INTEGER PRIMARY KEY ASC,
PollID INTEGER,
OptionID INTEGER,
LastSaved INTEGER,
CreatedAt INTEGER,
UserID INTEGER);
CREATE TABLE IF NOT EXISTS option(
ID INTEGER PRIMARY KEY ASC,
PollID INTEGER,
Ctr INTEGER,
Text TEXT);
CREATE TABLE IF NOT EXISTS dialog(
UserID INTEGER PRIMARY KEY,
PollId INTEGER,
state INTEGER);
CREATE TABLE IF NOT EXISTS user(
ID INTEGER PRIMARY KEY,
FirstName TEXT,
LastName Text,
LastSaved INTEGER,
CreatedAt INTEGER,
UserName TEXT);
CREATE INDEX IF NOT EXISTS poll_index ON poll(ID);
CREATE INDEX IF NOT EXISTS pollmsg_index ON pollmsg(MessageID);
CREATE INDEX IF NOT EXISTS answer_index ON answer(PollID);
CREATE INDEX IF NOT EXISTS option_index ON option(PollID);
`
if _, err := st.db.Exec(schema); err != nil {
log.Fatalf("could not create schema: %v", err)
}
//st.db.SetMaxOpenConns(1)
return st
}
func (st *sqlStore) GetUser(userid int) (*tgbotapi.User, error) {
// st.mutex.RLock()
// defer st.mutex.RUnlock()
u := &tgbotapi.User{ID: userid}
row := st.db.QueryRow("SELECT FirstName, LastName, UserName FROM user WHERE ID = ?", userid)
if err := row.Scan(&u.FirstName, &u.LastName, &u.UserName); err != nil {
return u, fmt.Errorf(`could not scan user "%d": %v`, u.ID, err)
}
return u, nil
}
func (st *sqlStore) GetPoll(pollid int) (*poll, error) {
// st.mutex.RLock()
// defer st.mutex.RUnlock()
p := &poll{ID: pollid}
var err error
row := st.db.QueryRow("SELECT UserID, Question, Inactive, Type FROM poll WHERE ID = ?", pollid)
if err := row.Scan(&p.UserID, &p.Question, &p.Inactive, &p.Type); err != nil {
return p, fmt.Errorf("could not scan poll #%d: %v", p.ID, err)
}
p.Options, err = st.GetOptions(p.ID)
if err != nil {
return p, fmt.Errorf("could not query options: %v", err)
}
p.Answers, err = st.GetAnswers(p.ID)
if err != nil {
return p, fmt.Errorf("could not query answers: %v", err)
}
return p, nil
}
func (st *sqlStore) GetPollNewer(pollid int, userid int) (*poll, error) {
// st.mutex.RLock()
// defer st.mutex.RUnlock()
p := &poll{}
var err error
row := st.db.QueryRow("SELECT UserID, ID, Question, Inactive, Type FROM poll WHERE ID > ? AND UserID = ? ORDER BY ID ASC LIMIT 1", pollid, userid)
if err := row.Scan(&p.UserID, &p.ID, &p.Question, &p.Inactive, &p.Type); err != nil {
return p, fmt.Errorf("could not scan poll #%d: %v", p.ID, err)
}
p.Options, err = st.GetOptions(p.ID)
if err != nil {
return p, fmt.Errorf("could not query options: %v", err)
}
p.Answers, err = st.GetAnswers(p.ID)
if err != nil {
return p, fmt.Errorf("could not query answers: %v", err)
}
return p, nil
}
func (st *sqlStore) GetPollOlder(pollid int, userid int) (*poll, error) {
// st.mutex.RLock()
// defer st.mutex.RUnlock()
p := &poll{}
var err error
row := st.db.QueryRow("SELECT UserID, ID, Question, Inactive, Type FROM poll WHERE ID < ? AND UserID = ? ORDER BY ID DESC LIMIT 1", pollid, userid)
if err := row.Scan(&p.UserID, &p.ID, &p.Question, &p.Inactive, &p.Type); err != nil {
return p, fmt.Errorf("could not scan poll #%d: %v", p.ID, err)
}
p.Options, err = st.GetOptions(p.ID)
if err != nil {
return p, fmt.Errorf("could not query options: %v", err)
}
p.Answers, err = st.GetAnswers(p.ID)
if err != nil {
return p, fmt.Errorf("could not query answers: %v", err)
}
return p, nil
}
func (st *sqlStore) GetState(userid int) (state int, pollid int, err error) {
// st.mutex.RLock()
// defer st.mutex.RUnlock()
row := st.db.QueryRow("SELECT state, pollid FROM dialog WHERE UserID = ?", userid)
if err := row.Scan(&state, &pollid); err != nil {
return state, pollid, fmt.Errorf("could not scan state from row: %v", err)
}
return state, pollid, nil
}
func (st *sqlStore) SaveState(userid int, pollid int, state int) (err error) {
res, err := st.db.Exec("UPDATE dialog SET state = ? WHERE UserID = ?", userid, state)
if err != nil {
return fmt.Errorf("could not update state in database: %v", err)
}
if aff, err := res.RowsAffected(); aff == 0 || err != nil {
_, err = st.db.Exec("INSERT OR REPLACE INTO dialog(UserID, pollid, state) values(?, ?, ?)", userid, pollid, state)
if err != nil {
return fmt.Errorf("could not insert or replace state database entry: %v", err)
}
}
return nil
}
func (st *sqlStore) GetPollsByUser(userid int) ([]*poll, error) {
// st.mutex.RLock()
// defer st.mutex.RUnlock()
polls := make([]*poll, 0)
var err error
row, err := st.db.Query("SELECT ID, UserID, Question, Inactive, Type FROM poll WHERE UserID = ? ORDER BY ID DESC LIMIT 3", userid)
if err != nil {
return polls, fmt.Errorf("could not query polls for userid #%d: %v", userid, err)
}
for row.Next() {
p := &poll{UserID: userid}
if err := row.Scan(&p.ID, &p.UserID, &p.Question, &p.Inactive, &p.Type); err != nil {
return polls, fmt.Errorf("could not scan poll for userid #%d: %v", userid, err)
}
p.Options, err = st.GetOptions(p.ID)
if err != nil {
return polls, fmt.Errorf("could not query options: %v", err)
}
p.Answers, err = st.GetAnswers(p.ID)
if err != nil {
return polls, fmt.Errorf("could not query answers: %v", err)
}
polls = append(polls, p)
}
return polls, nil
}
func (st *sqlStore) GetPollID(messageid int) (int, error) {
// st.mutex.RLock()
// defer st.mutex.RUnlock()
var pollid int
rows, err := st.db.Query("SELECT PollID FROM pollmsg WHERE MessageID = ?", messageid)
if err != nil {
return pollid, fmt.Errorf("could not query pollid: %v", err)
}
defer close(rows)
for rows.Next() {
err = rows.Scan(&pollid)
if err != nil {
return pollid, fmt.Errorf("could not scan pollid: %v", err)
}
}
return pollid, nil
}
type pollident struct {
MessageID int
InlineMessageID string
ChatID int64
}
func (st *sqlStore) GetAllPollMsg(pollid int) ([]pollident, error) {
// st.mutex.RLock()
// defer st.mutex.RUnlock()
msgs := make([]pollident, 0)
rows, err := st.db.Query("SELECT MessageID, ChatID FROM pollmsg WHERE PollID = ?", pollid)
if err != nil {
return msgs, fmt.Errorf("could not query pollmsgs: %v", err)
}
defer close(rows)
var msg pollident
for rows.Next() {
err = rows.Scan(&msg.MessageID, &msg.ChatID)
if err != nil {
return msgs, fmt.Errorf("could not scan pollmsgs: %v", err)
}
msgs = append(msgs, msg)
}
return msgs, nil
}
func (st *sqlStore) GetAllPollInlineMsg(pollid int) ([]pollident, error) {
// st.mutex.RLock()
// defer st.mutex.RUnlock()
msgs := make([]pollident, 0)
rows, err := st.db.Query("SELECT InlineMessageID FROM pollinlinemsg WHERE PollID = ?", pollid)
if err != nil {
return msgs, fmt.Errorf("could not query pollinlinemsg: %v", err)
}
defer close(rows)
var msg pollident
for rows.Next() {
err = rows.Scan(&msg.InlineMessageID)
if err != nil {
return msgs, fmt.Errorf("could not scan pollid: %v", err)
}
msgs = append(msgs, msg)
}
return msgs, nil
}
func (st *sqlStore) GetOptions(pollid int) ([]option, error) {
// st.mutex.RLock()
// defer st.mutex.RUnlock()
options := make([]option, 0)
rows, err := st.db.Query("SELECT Ctr, PollID, ID, Text FROM option WHERE PollID = ?", pollid)
if err != nil {
return options, fmt.Errorf("could not query options: %v", err)
}
defer close(rows)
var o option
for rows.Next() {
err = rows.Scan(&o.Ctr, &o.PollID, &o.ID, &o.Text)
if err != nil {
return options, fmt.Errorf("could not scan option: %v", err)
}
options = append(options, o)
}
return options, nil
}
func (st *sqlStore) GetAnswers(pollid int) ([]answer, error) {
// st.mutex.RLock()
// defer st.mutex.RUnlock()
answers := make([]answer, 0)
rows, err := st.db.Query("SELECT ID, PollID, OptionID, UserID FROM answer WHERE PollID = ?", pollid)
if err != nil {
return answers, fmt.Errorf("could not query answers: %v", err)
}
defer close(rows)
var a answer
for rows.Next() {
err = rows.Scan(&a.ID, &a.PollID, &a.OptionID, &a.UserID)
if err != nil {
return answers, fmt.Errorf("could not scan answer: %v", err)
}
answers = append(answers, a)
}
return answers, nil
}
func (st *sqlStore) SaveAnswer(p *poll, a answer) (unvoted bool, err error) {
// st.mutex.Lock()
// defer st.mutex.Unlock()
tx, err := st.db.Begin()
if err != nil {
return false, fmt.Errorf("could not begin database transaction: %v", err)
}
defer func() {
if err != nil {
if err := tx.Rollback(); err != nil {
log.Printf("could not rollback database change: %v", err)
}
return
}
err = tx.Commit()
}()
// find previous votes in this poll
stmt, err := tx.Prepare("SELECT OptionID FROM answer WHERE PollID = ? AND UserID = ?")
if err != nil {
return false, fmt.Errorf("could not prepare sql statement: %v", err)
}
defer close(stmt)
rows, err := stmt.Query(a.PollID, a.UserID)
if err != nil {
return false, fmt.Errorf("could not query option rows: %v", err)
}
defer close(rows)
var optionid int
prevOpts := make([]int, 0) // len should be 0 or 1
for rows.Next() {
err = rows.Scan(&optionid)
if err != nil {
return false, fmt.Errorf("could not scan optionid: %v", err)
}
prevOpts = append(prevOpts, optionid)
}
if len(prevOpts) > 0 { // user voted before
// user clicked the same answer again
if contains(prevOpts, a.OptionID) {
stmt, err = tx.Prepare("DELETE FROM answer where PollID = ? AND UserID = ? AND OptionID = ?")
if err != nil {
return false, fmt.Errorf("could not prepare sql statement: %v", err)
}
_, err = stmt.Exec(a.PollID, a.UserID, a.OptionID)
if err != nil {
return false, fmt.Errorf("could not delete previous answer: %v", err)
}
// decrement previously selected option(s)
stmt, err = tx.Prepare("UPDATE option SET Ctr = Ctr - 1 WHERE Ctr > 0 AND ID = ?")
if err != nil {
return false, fmt.Errorf("could not prepare sql statement: %v", err)
}
if _, err = stmt.Exec(a.OptionID); err != nil {
return false, fmt.Errorf("could not decrement option: %v", err)
}
return true, nil
}
if !isMultipleChoice(p) {
// decrement previously selected option(s)
stmt, err = tx.Prepare("UPDATE option SET Ctr = Ctr - 1 WHERE ID = ? AND Ctr > 0")
if err != nil {
return false, fmt.Errorf("could not prepare sql statement: %v", err)
}
for _, o := range prevOpts {
if _, err = stmt.Exec(o); err != nil {
return false, fmt.Errorf("could not decrement option: %v", err)
}
}
// update answer
stmt, err = tx.Prepare("UPDATE answer SET OptionID = ?, LastSaved = ? WHERE UserID = ? AND PollID = ?")
if err != nil {
return false, fmt.Errorf("could not prepare sql statement: %v", err)
}
_, err = stmt.Exec(a.OptionID, time.Now().UTC().Unix(), a.UserID, a.PollID)
if err != nil {
return false, fmt.Errorf("could not update vote: %v", err)
}
} else {
// new vote
stmt, err = tx.Prepare("INSERT INTO answer(PollID, OptionID, UserID, LastSaved, CreatedAt) values(?, ?, ?, ?, ?)")
if err != nil {
return false, fmt.Errorf("could not prepare sql statement: %v", err)
}
_, err = stmt.Exec(a.PollID, a.OptionID, a.UserID, time.Now().UTC().Unix(), time.Now().UTC().Unix())
if err != nil {
return false, fmt.Errorf("could not insert answer: %v", err)
}
}
} else {
// new vote
stmt, err = tx.Prepare("INSERT INTO answer(PollID, OptionID, UserID, LastSaved, CreatedAt) values(?, ?, ?, ?, ?)")
if err != nil {
return false, fmt.Errorf("could not prepare sql statement: %v", err)
}
_, err = stmt.Exec(a.PollID, a.OptionID, a.UserID, time.Now().UTC().Unix(), time.Now().UTC().Unix())
if err != nil {
return false, fmt.Errorf("could not insert answer: %v", err)
}
}
// increment counter for option
stmt, err = tx.Prepare("UPDATE option set Ctr = Ctr + 1 WHERE ID = ?")
if err != nil {
return false, fmt.Errorf("could not prepare sql statement: %v", err)
}
_, err = stmt.Exec(a.OptionID)
if err != nil {
return false, fmt.Errorf("could not increment option counter: %v", err)
}
return false, nil
}
func (st *sqlStore) AddMsgToPoll(pollid int, messageid int, chatid int64) error {
// st.mutex.Lock()
// defer st.mutex.Unlock()
tx, err := st.db.Begin()
if err != nil {
return fmt.Errorf("could not begin database transaction: %v", err)
}
defer func() {
if err != nil {
if err := tx.Rollback(); err != nil {
log.Printf("could not rollback database change: %v", err)
}
return
}
err = tx.Commit()
}()
stmt, err := tx.Prepare("INSERT OR REPLACE INTO pollmsg(PollID, MessageID, ChatID) values(?, ?, ?)")
if err != nil {
return fmt.Errorf("could not build sql insert statement: %v", err)
}
defer close(stmt)
_, err = stmt.Exec(pollid, messageid, chatid)
if err != nil {
return fmt.Errorf("could not add message to poll: %v", err)
}
return nil
}
func (st *sqlStore) AddInlineMsgToPoll(pollid int, inlinemessageid string) error {
// st.mutex.Lock()
// defer st.mutex.Unlock()
tx, err := st.db.Begin()
if err != nil {
return fmt.Errorf("could not begin database transaction: %v", err)
}
defer func() {
if err != nil {
if err := tx.Rollback(); err != nil {
log.Printf("could not rollback database change: %v", err)
}
return
}
err = tx.Commit()
}()
// InlineMessageId is the primary key
stmt, err := tx.Prepare("INSERT OR REPLACE INTO pollinlinemsg(PollID, InlineMessageID) values(?, ?)")
if err != nil {
return fmt.Errorf("could not build sql insert statement: %v", err)
}
defer close(stmt)
_, err = stmt.Exec(pollid, inlinemessageid)
if err != nil {
return fmt.Errorf("could not add message to poll: %v", err)
}
return nil
}
func (st *sqlStore) RemoveInlineMsg(inlinemessageid string) error {
// st.mutex.Lock()
// defer st.mutex.Unlock()
tx, err := st.db.Begin()
if err != nil {
return fmt.Errorf("could not begin database transaction: %v", err)
}
defer func() {
if err != nil {
if err := tx.Rollback(); err != nil {
log.Printf("could not rollback database change: %v", err)
}
return
}
err = tx.Commit()
}()
stmt, err := tx.Prepare("DELETE FROM pollinlinemsg WHERE InlineMessageID = ?")
if err != nil {
return fmt.Errorf("could not build sql insert statement: %v", err)
}
defer close(stmt)
_, err = stmt.Exec(inlinemessageid)
if err != nil {
return fmt.Errorf("could not remove inline message: %v", err)
}
return nil
}
func (st *sqlStore) SaveOptions(options []option) error {
// option gets passed by value as we only change id numbers
// and do not append new elements this should be fine
// st.mutex.Lock()
// defer st.mutex.Unlock()
tx, err := st.db.Begin()
if err != nil {
return fmt.Errorf("could not begin database transaction: %v", err)
}
defer func() {
if err != nil {
if err := tx.Rollback(); err != nil {
log.Printf("could not rollback database change: %v", err)
}
return
}
err = tx.Commit()
}()
stmt, err := tx.Prepare("INSERT OR REPLACE INTO option(PollID, Ctr, Text) values(?, ?, ?)")
if err != nil {
return fmt.Errorf("could not prepare insert sql statement for options: %v", err)
}
defer close(stmt)
var res sql.Result
var id64 int64
for i := 0; i < len(options); i++ {
res, err = stmt.Exec(options[i].PollID, options[i].Ctr, options[i].Text)
if err != nil {
return fmt.Errorf("could not insert option into sql database: %v", err)
}
id64, err = res.LastInsertId()
if err != nil {
return fmt.Errorf("could not get id of last insert: %v", err)
}
options[i].ID = int(id64)
}
return nil
}
func (st *sqlStore) SaveUser(u *tgbotapi.User) error {
// st.mutex.Lock()
// defer st.mutex.Unlock()
tx, err := st.db.Begin()
if err != nil {
return fmt.Errorf("could not begin database transaction: %v", err)
}
defer func() {
if err != nil {
if err := tx.Rollback(); err != nil {
log.Printf("could not rollback database change: %v", err)
}
return
}
err = tx.Commit()
}()
stmt, err := tx.Prepare("SELECT count(1) FROM user WHERE ID = ?")
if err != nil {
return fmt.Errorf("could not prepare sql statement: %v", err)
}
defer close(stmt)
var cnt int
err = stmt.QueryRow(u.ID).Scan(&cnt)
if err != nil {
return fmt.Errorf("could not check if user '%s' exists: %v", u.UserName, err)
}
if cnt != 0 {
stmt, err = tx.Prepare("UPDATE user SET FirstName = ?, LastName = ?, UserName = ?, LastSaved = ? WHERE ID = ?")
if err != nil {
return fmt.Errorf("could not prepare sql statement: %v", err)
}
_, err = stmt.Exec(u.FirstName, u.LastName, u.UserName, time.Now().UTC().Unix(), u.ID)
if err != nil {
return fmt.Errorf("could not update user entry: %v", err)
}
return nil
}
stmt, err = tx.Prepare("INSERT INTO user(ID, FirstName, LastName, UserName, LastSaved, CreatedAt) values(?, ?, ?, ?, ?, ?)")
if err != nil {
return fmt.Errorf("could not prepare sql insert statement: %v", err)
}
defer close(stmt)
_, err = stmt.Exec(u.ID, u.FirstName, u.LastName, u.UserName, time.Now().UTC().Unix(), time.Now().UTC().Unix())
if err != nil {
return fmt.Errorf("could not execute sql insert statement: %v", err)
}
return nil
}
func (st *sqlStore) SavePoll(p *poll) (id int, err error) {
// st.mutex.Lock()
// defer st.mutex.Unlock()
tx, err := st.db.Begin()
if err != nil {
return int(id), fmt.Errorf("could not begin database transaction: %v", err)
}
defer func() {
if err != nil {
if err := tx.Rollback(); err != nil {
log.Printf("could not rollback database change: %v", err)
}
return
}
err = tx.Commit()
}()
if p.ID != 0 {
var stmt *sql.Stmt
stmt, err = tx.Prepare("UPDATE poll SET UserID = ?, Question = ?, Inactive = ?, Private = ?, Type = ?, LastSaved = ?, CreatedAt = ? WHERE ID = ?")
if err != nil {
return id, fmt.Errorf("could not prepare sql statement: %v", err)
}
defer close(stmt)
_, err = stmt.Exec(p.UserID, p.Question, p.Inactive, p.Private, p.Type, time.Now().UTC().Unix(), time.Now().UTC().Unix(), p.ID)
if err != nil {
return id, fmt.Errorf("could not update user entry: %v", err)
}
return id, nil
}
stmt, err := tx.Prepare("INSERT INTO poll(UserID, Question, Inactive, Private, Type, LastSaved, CreatedAt) values(?, ?, ?, ?, ?, ?, ?)")
if err != nil {
return id, fmt.Errorf("could not prepare sql insert statement: %v", err)
}
defer close(stmt)
var res sql.Result
res, err = stmt.Exec(p.UserID, p.Question, p.Inactive, p.Private, p.Type, time.Now().UTC().Unix(), time.Now().UTC().Unix())
if err != nil {
return id, fmt.Errorf("could not execute sql insert statement: %v", err)
}
id64, err := res.LastInsertId()
if err != nil {
return id, fmt.Errorf("could not get id of last insert: %v", err)
}
id = int(id64)
return id, nil
}
func contains(slice []int, n int) bool {
for _, i := range slice {
if i == n {
return true
}
}
return false
}