-
Notifications
You must be signed in to change notification settings - Fork 3
/
simplemaria.go
821 lines (752 loc) · 20.4 KB
/
simplemaria.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
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
// Package simplemaria offers a simple way to use a MySQL/MariaDB database.
// This database backend is interchangeable with xyproto/simpleredis and
// xyproto/simplebolt, since they all use xyproto/pinterface.
package simplemaria
import (
"errors"
"fmt"
"log"
"strconv"
"github.com/xyproto/env/v2"
"database/sql"
_ "github.com/go-mysql-org/go-mysql/driver"
)
const (
// Version number. Stable API within major version numbers.
Version = 3.2
)
// Host represents a specific database at a database host
type Host struct {
db *sql.DB
dbname string
rawUTF8 bool
}
// Common for each of the db datastructures used here
type dbDatastructure struct {
host *Host
table string
}
type (
List dbDatastructure
Set dbDatastructure
HashMap dbDatastructure
KeyValue dbDatastructure
)
const (
// The default "username:password@host:port/database" that the database is running at
defaultDatabaseServer = "localhost" // "username:password@server:port/"
defaultDatabaseName = "test" // "main"
defaultStringType = "TEXT" // "VARCHAR(65535)"
defaultPort = 3306
defaultUser = "user"
// Requires MySQL >= 5.53 and MariaDB >= ? for utf8mb4
charset = "utf8mb4" // "utf8"
// Column names
listCol = "a_list"
setCol = "a_set"
keyCol = "property"
valCol = "value"
ownerCol = "owner"
)
// Test if the local database server is up and running.
func TestConnection() (err error) {
return TestConnectionHost(defaultDatabaseServer)
}
// Test if a given database server is up and running.
// connectionString may be on the form "username:password@host:port/database".
func TestConnectionHost(connectionString string) (err error) {
newConnectionString, _ := rebuildConnectionString(connectionString)
// Connect to the given host:port
db, err := sql.Open("mysql", newConnectionString)
if err != nil {
return err
}
defer db.Close()
err = db.Ping()
if Verbose {
if err != nil {
log.Println("Ping: failed")
} else {
log.Println("Ping: ok")
}
}
return err
}
// Test if a given database server is up and running.
func TestConnectionHostWithDSN(connectionString string) (err error) {
// Connect to the given host:port
db, err := sql.Open("mysql", connectionString)
if err != nil {
return err
}
defer db.Close()
err = db.Ping()
if Verbose {
if err != nil {
log.Println("Ping: failed")
} else {
log.Println("Ping: ok")
}
}
return err
}
/* --- Host functions --- */
// Create a new database connection.
// connectionString may be on the form "username:password@host:port/database".
func NewHost(connectionString string) *Host {
// Use env.Str to fetch environment variables with defaults
hostname := env.Str("MARIADB_HOST", defaultDatabaseServer)
port := env.Str("MARIADB_PORT", strconv.Itoa(defaultPort))
user := env.Str("MARIADB_USER", defaultUser)
password := env.Str("MARIADB_PASSWORD")
dbname := env.Str("MARIADB_DBNAME", defaultDatabaseName)
// Rebuild the connection string with potential new values from environment
var newConnectionString string
if password != "" {
newConnectionString = fmt.Sprintf("%s:%s@%s:%s/%s", user, password, hostname, port, dbname)
} else {
newConnectionString = fmt.Sprintf("%s@%s:%s/%s", user, hostname, port, dbname)
}
db, err := sql.Open("mysql", newConnectionString)
if err != nil {
log.Fatalln("Could not connect to " + newConnectionString + "!")
}
host := &Host{db, dbname, false}
if err := host.Ping(); err != nil {
log.Fatalln("Host does not reply to ping: " + err.Error())
}
if err := host.createDatabase(); err != nil {
log.Fatalln("Could not create database " + host.dbname + ": " + err.Error())
}
if err := host.useDatabase(); err != nil {
panic("Could not use database " + host.dbname + ": " + err.Error())
}
return host
}
// Create a new database connection with a valid DSN.
func NewHostWithDSN(connectionString string, dbname string) *Host {
db, err := sql.Open("mysql", connectionString)
if err != nil {
log.Fatalln("Could not connect to " + connectionString + "!")
}
host := &Host{db, dbname, false}
if err := host.Ping(); err != nil {
log.Fatalln("Host does not reply to ping: " + err.Error())
}
if err := host.createDatabase(); err != nil {
log.Fatalln("Could not create database " + host.dbname + ": " + err.Error())
}
if err := host.useDatabase(); err != nil {
panic("Could not use database " + host.dbname + ": " + err.Error())
}
return host
}
// The default database connection
func New() *Host {
user := env.Str("MARIADB_USER", defaultUser)
password := env.Str("MARIADB_PASSWORD")
host := env.Str("MARIADB_HOST", defaultDatabaseServer)
port := env.Str("MARIADB_PORT", strconv.Itoa(defaultPort))
dbname := env.Str("MARIADB_DBNAME", defaultDatabaseName)
// Build the connection string based on whether a password is provided
var connectionString string
if password == "" {
connectionString = fmt.Sprintf("%s@%s:%s/%s", user, host, port, dbname)
} else {
connectionString = fmt.Sprintf("%s:%s@%s:%s/%s", user, password, host, port, dbname)
}
return NewHost(connectionString)
}
// Should the UTF-8 data be raw, and not hex encoded and compressed?
func (host *Host) SetRawUTF8(enabled bool) {
host.rawUTF8 = enabled
}
// Select a different database. Create the database if needed.
func (host *Host) SelectDatabase(dbname string) error {
host.dbname = dbname
if err := host.createDatabase(); err != nil {
return err
}
if err := host.useDatabase(); err != nil {
return err
}
return nil
}
// Will create the database if it does not already exist
func (host *Host) createDatabase() error {
if _, err := host.db.Exec("CREATE DATABASE IF NOT EXISTS " + host.dbname + " CHARACTER SET = " + charset); err != nil {
return err
}
if Verbose {
log.Println("Created database " + host.dbname)
}
return nil
}
// Use the host.dbname database
func (host *Host) useDatabase() error {
if _, err := host.db.Exec("USE " + host.dbname); err != nil {
return err
}
if Verbose {
log.Println("Using database " + host.dbname)
}
return nil
}
// Close the connection
func (host *Host) Close() {
host.db.Close()
}
// Ping the host
func (host *Host) Ping() error {
return host.db.Ping()
}
/* --- List functions --- */
// Create a new list. Lists are ordered.
func NewList(host *Host, name string) (*List, error) {
l := &List{host, name}
if _, err := l.host.db.Exec("CREATE TABLE IF NOT EXISTS " + name + " (id INT PRIMARY KEY AUTO_INCREMENT, " + listCol + " " + defaultStringType + ")"); err != nil {
return nil, err
}
if Verbose {
log.Println("Created table " + name + " in database " + host.dbname)
}
return l, nil
}
// Add an element to the list
func (l *List) Add(value string) error {
if !l.host.rawUTF8 {
Encode(&value)
}
_, err := l.host.db.Exec("INSERT INTO "+l.table+" ("+listCol+") VALUES (?)", value)
return err
}
// Get all elements of a list
func (l *List) All() ([]string, error) {
rows, err := l.host.db.Query("SELECT " + listCol + " FROM " + l.table + " ORDER BY id")
if err != nil {
return []string{}, err
}
defer rows.Close()
var (
values []string
value string
)
for rows.Next() {
err = rows.Scan(&value)
if !l.host.rawUTF8 {
Decode(&value)
}
values = append(values, value)
if err != nil {
// Unusual, worthy of panic
panic(err.Error())
}
}
if err := rows.Err(); err != nil {
// Unusual, worthy of panic
panic(err.Error())
}
return values, nil
}
// Deprecated, please use .All() instead
func (l *List) GetAll() ([]string, error) {
return l.All()
}
// Get the last element of a list
func (l *List) Last() (string, error) {
// Fetches the item with the largest id.
// Faster than "ORDER BY id DESC limit 1" for large tables.
rows, err := l.host.db.Query("SELECT " + listCol + " FROM " + l.table + " WHERE id = (SELECT MAX(id) FROM " + l.table + ")")
if err != nil {
return "", err
}
defer rows.Close()
var value string
// Get the value. Will only loop once.
for rows.Next() {
err = rows.Scan(&value)
if err != nil {
// Unusual, worthy of panic
panic(err.Error())
}
}
if err := rows.Err(); err != nil {
// Unusual, worthy of panic
panic(err.Error())
}
if !l.host.rawUTF8 {
Decode(&value)
}
return value, nil
}
// Deprecated, please use .Last() instead
func (l *List) GetLast() (string, error) {
return l.Last()
}
// Get the last N elements of a list
func (l *List) LastN(n int) ([]string, error) {
rows, err := l.host.db.Query("SELECT " + listCol + " FROM (SELECT * FROM " + l.table + " ORDER BY id DESC limit " + strconv.Itoa(n) + ")sub ORDER BY id ASC")
if err != nil {
return []string{}, err
}
defer rows.Close()
var (
values []string
value string
)
for rows.Next() {
err = rows.Scan(&value)
if !l.host.rawUTF8 {
Decode(&value)
}
values = append(values, value)
if err != nil {
// Unusual, worthy of panic
panic(err.Error())
}
}
if err := rows.Err(); err != nil {
// Unusual, worthy of panic
panic(err.Error())
}
if len(values) < n {
return []string{}, errors.New("Too few elements in table at GetLastN")
}
return values, nil
}
// Deprecated, please use .LastN(n) instead
func (l *List) GetLastN(n int) ([]string, error) {
return l.LastN(n)
}
// Remove this list
func (l *List) Remove() error {
// Remove the table
_, err := l.host.db.Exec("DROP TABLE " + l.table)
return err
}
// Clear the list contents
func (l *List) Clear() error {
// Clear the table
_, err := l.host.db.Exec("TRUNCATE TABLE " + l.table)
return err
}
/* --- Set functions --- */
// Create a new set
func NewSet(host *Host, name string) (*Set, error) {
s := &Set{host, name}
if _, err := s.host.db.Exec("CREATE TABLE IF NOT EXISTS " + name + " (" + setCol + " " + defaultStringType + ")"); err != nil {
return nil, err
}
if Verbose {
log.Println("Created table " + name + " in database " + host.dbname)
}
return s, nil
}
// Add an element to the set
func (s *Set) Add(value string) error {
originalValue := value
if !s.host.rawUTF8 {
Encode(&value)
}
// Check if the value is not already there before adding
has, err := s.Has(originalValue)
if !has && (err == nil) {
_, err = s.host.db.Exec("INSERT INTO "+s.table+" ("+setCol+") VALUES (?)", value)
}
return err
}
// Check if a given value is in the set
func (s *Set) Has(value string) (bool, error) {
if !s.host.rawUTF8 {
Encode(&value)
}
rows, err := s.host.db.Query("SELECT "+setCol+" FROM "+s.table+" WHERE "+setCol+" = ?", value)
if err != nil {
return false, err
}
defer rows.Close()
var scanValue string
// Get the value. Should not loop more than once.
counter := 0
for rows.Next() {
err = rows.Scan(&scanValue)
if err != nil {
// Unusual, worthy of panic
panic(err.Error())
}
counter++
}
if err := rows.Err(); err != nil {
// Unusual, worthy of panic
panic(err.Error())
}
if counter > 1 {
panic("Duplicate members in set! " + value)
}
return counter > 0, nil
}
// Get all elements of the set
func (s *Set) All() ([]string, error) {
rows, err := s.host.db.Query("SELECT " + setCol + " FROM " + s.table)
if err != nil {
return []string{}, err
}
defer rows.Close()
var (
values []string
value string
)
for rows.Next() {
err = rows.Scan(&value)
if !s.host.rawUTF8 {
Decode(&value)
}
values = append(values, value)
if err != nil {
// Unusual, worthy of panic
panic(err.Error())
}
}
if err := rows.Err(); err != nil {
// Unusual, worthy of panic
panic(err.Error())
}
return values, nil
}
// Deprecated, please use .All() instead
func (s *Set) GetAll() ([]string, error) {
return s.All()
}
// Remove an element from the set
func (s *Set) Del(value string) error {
if !s.host.rawUTF8 {
Encode(&value)
}
// Remove a value from the table
_, err := s.host.db.Exec("DELETE FROM "+s.table+" WHERE "+setCol+" = ?", value)
return err
}
// Remove this set
func (s *Set) Remove() error {
// Remove the table
_, err := s.host.db.Exec("DROP TABLE " + s.table)
return err
}
// Clear the list contents
func (s *Set) Clear() error {
// Clear the table
_, err := s.host.db.Exec("TRUNCATE TABLE " + s.table)
return err
}
/* --- HashMap functions --- */
// Create a new hashmap
func NewHashMap(host *Host, name string) (*HashMap, error) {
h := &HashMap{host, name}
// Using three columns: element id, key and value
query := fmt.Sprintf("CREATE TABLE IF NOT EXISTS %s (%s %s, %s %s, %s %s)", name, ownerCol, defaultStringType, keyCol, defaultStringType, valCol, defaultStringType)
if _, err := h.host.db.Exec(query); err != nil {
return nil, err
}
if Verbose {
log.Println("Created table " + name + " in database " + host.dbname)
}
return h, nil
}
// Set a value in a hashmap given the element id (for instance a user id) and the key (for instance "password")
func (h *HashMap) Set(owner, key, value string) error {
if !h.host.rawUTF8 {
Encode(&value)
}
// See if the owner and key already exists
ok, err := h.Has(owner, key)
if err != nil {
return err
}
if Verbose {
log.Printf("%s/%s exists? %v\n", owner, key, ok)
}
if ok {
_, err = h.host.db.Exec("UPDATE "+h.table+" SET "+valCol+" = ? WHERE "+ownerCol+" = ? AND "+keyCol+" = ?", value, owner, key)
if Verbose {
log.Println("Updated the table: " + h.table)
}
} else {
_, err = h.host.db.Exec("INSERT INTO "+h.table+" ("+ownerCol+", "+keyCol+", "+valCol+") VALUES (?, ?, ?)", owner, key, value)
if Verbose {
log.Println("Added to the table: " + h.table)
}
}
return err
}
// Get a value from a hashmap given the element id (for instance a user id) and the key (for instance "password").
func (h *HashMap) Get(owner, key string) (string, error) {
rows, err := h.host.db.Query("SELECT "+valCol+" FROM "+h.table+" WHERE "+ownerCol+" = ? AND "+keyCol+" = ?", owner, key)
if err != nil {
return "", err
}
defer rows.Close()
var value string
// Get the value. Should only loop once.
counter := 0
for rows.Next() {
err = rows.Scan(&value)
if err != nil {
// Unusual, worthy of panic
panic(err.Error())
}
counter++
}
if err := rows.Err(); err != nil {
// Unusual, worthy of panic
panic(err.Error())
}
if counter == 0 {
return "", errors.New("No such owner/key: " + owner + "/" + key)
}
if !h.host.rawUTF8 {
Decode(&value)
}
return value, nil
}
// Check if a given owner + key is in the hash map
func (h *HashMap) Has(owner, key string) (bool, error) {
rows, err := h.host.db.Query("SELECT "+valCol+" FROM "+h.table+" WHERE "+ownerCol+" = ? AND "+keyCol+" = ?", owner, key)
if err != nil {
return false, err
}
defer rows.Close()
var value string
// Get the value. Should only loop once.
counter := 0
for rows.Next() {
err = rows.Scan(&value)
if err != nil {
// Unusual, worthy of panic
panic(err.Error())
}
counter++
}
if err := rows.Err(); err != nil {
// Unusual, worthy of panic
panic(err.Error())
}
if counter > 1 {
panic("Duplicate keys in hash map! " + value)
}
return counter > 0, nil
}
// Check if a given owner exists as a hash map at all
func (h *HashMap) Exists(owner string) (bool, error) {
rows, err := h.host.db.Query("SELECT "+valCol+" FROM "+h.table+" WHERE "+ownerCol+" = ?", owner)
if err != nil {
return false, err
}
defer rows.Close()
var value string
// Get the value. Should only loop once.
counter := 0
for rows.Next() {
err = rows.Scan(&value)
if err != nil {
// Unusual, worthy of panic
panic(err.Error())
}
counter++
}
if err := rows.Err(); err != nil {
// Unusual, worthy of panic
panic(err.Error())
}
return counter > 0, nil
}
// Get all owners (not keys, not values) for all hash elements
func (h *HashMap) All() ([]string, error) {
rows, err := h.host.db.Query("SELECT " + ownerCol + " FROM " + h.table)
if err != nil {
return []string{}, err
}
defer rows.Close()
var (
values []string
value string
)
for rows.Next() {
err = rows.Scan(&value)
values = append(values, value)
if err != nil {
// Unusual, worthy of panic
panic(err.Error())
}
}
if err := rows.Err(); err != nil {
// Unusual, worthy of panic
panic(err.Error())
}
return values, nil
}
// Deprecated, please use .All() instead
func (h *HashMap) GetAll() ([]string, error) {
return h.All()
}
// Get all keys for a given owner
func (h *HashMap) Keys(owner string) ([]string, error) {
rows, err := h.host.db.Query("SELECT "+keyCol+" FROM "+h.table+" WHERE "+ownerCol+"= ?", owner)
if err != nil {
return []string{}, err
}
defer rows.Close()
var (
values []string
value string
)
for rows.Next() {
err = rows.Scan(&value)
values = append(values, value)
if err != nil {
// Unusual, worthy of panic
panic(err.Error())
}
}
if err := rows.Err(); err != nil {
// Unusual, worthy of panic
panic(err.Error())
}
return values, nil
}
// Remove a key for an entry in a hashmap (for instance the email field for a user)
func (h *HashMap) DelKey(owner, key string) error {
// Remove a key from the hashmap
_, err := h.host.db.Exec("DELETE FROM "+h.table+" WHERE "+ownerCol+" = ? AND "+keyCol+" = ?", owner, key)
return err
}
// Remove an element (for instance a user)
func (h *HashMap) Del(owner string) error {
// Remove an element id from the table
results, err := h.host.db.Exec("DELETE FROM "+h.table+" WHERE "+ownerCol+" = ?", owner)
if err != nil {
return err
}
n, err := results.RowsAffected()
if err != nil {
return err
}
if Verbose {
log.Println(n, "rows were deleted with Del("+owner+")!")
}
return nil
}
// Remove this hashmap
func (h *HashMap) Remove() error {
// Remove the table
_, err := h.host.db.Exec("DROP TABLE " + h.table)
return err
}
// Clear the contents
func (h *HashMap) Clear() error {
// Clear the table
_, err := h.host.db.Exec("TRUNCATE TABLE " + h.table)
return err
}
/* --- KeyValue functions --- */
// Create a new key/value
func NewKeyValue(host *Host, name string) (*KeyValue, error) {
kv := &KeyValue{host, name}
query := fmt.Sprintf("CREATE TABLE IF NOT EXISTS %s (%s %s, %s %s)", name, keyCol, defaultStringType, valCol, defaultStringType)
if _, err := kv.host.db.Exec(query); err != nil {
return nil, err
}
if Verbose {
log.Println("Created table " + name + " in database " + host.dbname)
}
return kv, nil
}
// Set a key and value
func (kv *KeyValue) Set(key, value string) error {
if !kv.host.rawUTF8 {
Encode(&value)
}
if _, err := kv.Get(key); err != nil {
// Key does not exist, create it
_, err = kv.host.db.Exec("INSERT INTO "+kv.table+" ("+keyCol+", "+valCol+") VALUES (?, ?)", key, value)
return err
}
// Key exists, update the value
_, err := kv.host.db.Exec("UPDATE "+kv.table+" SET "+valCol+" = ? WHERE "+keyCol+" = ?", value, key)
return err
}
// Get a value given a key
func (kv *KeyValue) Get(key string) (string, error) {
rows, err := kv.host.db.Query("SELECT "+valCol+" FROM "+kv.table+" WHERE "+keyCol+" = ?", key)
if err != nil {
return "", err
}
defer rows.Close()
var value string
// Get the value. Should only loop once.
counter := 0
for rows.Next() {
err = rows.Scan(&value)
if err != nil {
// Unusual, worthy of panic
panic(err.Error())
}
counter++
}
if err := rows.Err(); err != nil {
// Unusual, worthy of panic
panic(err.Error())
}
if counter != 1 {
return "", errors.New("Wrong number of keys in KeyValue table: " + kv.table)
}
if !kv.host.rawUTF8 {
Decode(&value)
}
return value, nil
}
// Increase the value of a key, returns the new value
// Returns an empty string if there were errors,
// or "0" if the key does not already exist.
func (kv *KeyValue) Inc(key string) (string, error) {
// Retreieve the current value, if any
num := 0
// See if we can fetch an existing value. NOTE: "== nil"
if val, err := kv.Get(key); err == nil {
// See if we can convert the value to a number. NOTE: "== nil"
if converted, err2 := strconv.Atoi(val); err2 == nil {
num = converted
}
} else {
// The key does not exist, create a new one.
// This is to reflect the behavior of INCR in Redis.
NewKeyValue(kv.host, kv.table)
}
// Num is now either 0 or the previous numeric value
num++
// Convert the new value to a string
val := strconv.Itoa(num)
// Store the new number
if err := kv.Set(key, val); err != nil {
// Saving the value failed
return "0", err
}
// Success
return val, nil
}
// Remove a key
func (kv *KeyValue) Del(key string) error {
_, err := kv.host.db.Exec("DELETE FROM "+kv.table+" WHERE "+keyCol+" = ?", key)
return err
}
// Remove this key/value
func (kv *KeyValue) Remove() error {
// Remove the table
_, err := kv.host.db.Exec("DROP TABLE " + kv.table)
return err
}
// Clear this key/value
func (kv *KeyValue) Clear() error {
// Remove the table
_, err := kv.host.db.Exec("TRUNCATE TABLE " + kv.table)
return err
}