-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathhandlers_v1.go
1591 lines (1453 loc) · 46.6 KB
/
handlers_v1.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
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"fmt"
"log"
"net/http"
"net/url"
"os"
"path/filepath"
"sort"
"github.com/gin-gonic/gin"
sqlite "github.com/gwenn/gosqlite"
com "github.com/sqlitebrowser/dbhub.io/common"
"github.com/sqlitebrowser/dbhub.io/common/config"
"github.com/sqlitebrowser/dbhub.io/common/database"
)
// APIJSONColumn is a copy of the Column type from github.com/gwenn/gosqlite, but including JSON field name info
type APIJSONColumn struct {
Cid int `json:"column_id"`
Name string `json:"name"`
DataType string `json:"data_type"`
NotNull bool `json:"not_null"`
DfltValue string `json:"default_value"`
Pk int `json:"primary_key"`
}
// collectInfo is an internal function which xtracts the database owner, name, and commit ID from the request
// and checks the permissions
func collectInfo(c *gin.Context) (loggedInUser, dbOwner, dbName, commitID string, httpStatus int, err error) {
// Get user name
loggedInUser = c.MustGet("user").(string)
// Extract the database owner name, database name, and (optional) commit ID for the database from the request
dbOwner, dbName, commitID, err = com.GetFormODC(c.Request)
if err != nil {
httpStatus = http.StatusInternalServerError
return
}
// Store database path for later logging
c.Set("owner", dbOwner)
c.Set("database", dbName)
// Check if the user has access to the requested database
// Check if the requested database exists
exists, err := database.CheckDBPermissions(loggedInUser, dbOwner, dbName, false)
if err != nil {
httpStatus = http.StatusInternalServerError
return
}
if !exists {
httpStatus = http.StatusNotFound
err = fmt.Errorf("Database does not exist, or user isn't authorised to access it")
return
}
return
}
// branchesHandler returns the list of branches for a database
// This can be run from the command line using curl, like this:
//
// $ curl -F apikey="YOUR_API_KEY_HERE" \
// -F dbowner="justinclift" \
// -F dbname="Join Testing.sqlite" \
// https://api.dbhub.io/v1/branches
// * "apikey" is one of your API keys. These can be generated from your Settings page once logged in
// * "dbowner" is the owner of the database
// * "dbname" is the name of the database
func branchesHandler(c *gin.Context) {
// Do auth check, grab request info
_, dbOwner, dbName, _, httpStatus, err := collectInfo(c)
if err != nil {
c.JSON(httpStatus, gin.H{
"error": err.Error(),
})
return
}
// If the database is a live database, we return an error message
isLive, _, err := database.CheckDBLive(dbOwner, dbName)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": err.Error(),
})
return
}
if isLive {
c.JSON(http.StatusBadRequest, gin.H{
"error": "That database is a live database. It doesn't have branches.",
})
return
}
// Retrieve the branch list for the database
brList, err := com.BranchListResponse(dbOwner, dbName)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": err.Error(),
})
return
}
// Return the list as JSON
c.JSON(http.StatusOK, brList)
}
// columnsHandler returns the list of columns in a table or view
// This can be run from the command line using curl, like this:
//
// $ curl -F apikey="YOUR_API_KEY_HERE" \
// -F dbowner="justinclift" \
// -F dbname="Join Testing.sqlite" \
// -F table="table1" https://api.dbhub.io/v1/columns
// * "apikey" is one of your API keys. These can be generated from your Settings page once logged in
// * "dbowner" is the owner of the database
// * "dbname" is the name of the database
// * "table" is the name of the table or view
func columnsHandler(c *gin.Context) {
// Do auth check, grab request info
loggedInUser, dbOwner, dbName, _, httpStatus, err := collectInfo(c)
if err != nil {
c.JSON(httpStatus, gin.H{
"error": err.Error(),
})
return
}
// Extract the table name
table, err := com.GetFormTable(c.Request, false)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": err.Error(),
})
return
}
// Make sure a table name was provided
if table == "" {
c.JSON(http.StatusBadRequest, gin.H{
"error": "Missing table name",
})
return
}
// Check if the database is a live database, and get the node/queue to send the request to
isLive, liveNode, err := database.CheckDBLive(dbOwner, dbName)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": err.Error(),
})
return
}
// If a live database has been uploaded but doesn't have a live node handling its requests, then error out as this
// should never happen
if isLive && liveNode == "" {
c.JSON(http.StatusInternalServerError, gin.H{
"error": "No job queue node available for request",
})
return
}
// If it's a standard database, process it locally. Else send the query to our job queue backend
var cols []sqlite.Column
if !isLive {
// Get Minio bucket and object id for the SQLite file
bucket, id, _, err := com.MinioLocation(dbOwner, dbName, "", loggedInUser)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": err.Error(),
})
return
}
// Sanity check
if id == "" {
// The requested database wasn't found, or the user doesn't have permission to access it
c.JSON(http.StatusNotFound, gin.H{
"error": "Requested database not found",
})
return
}
// Retrieve the database from Minio, then open it
var sdb *sqlite.Conn
sdb, err = com.OpenSQLiteDatabase(bucket, id)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": err.Error(),
})
return
}
defer sdb.Close()
// Verify the requested table or view we're about to query does exist
tablesViews, err := com.TablesAndViews(sdb, dbName)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": err.Error(),
})
return
}
tableOrViewFound := false
for _, t := range tablesViews {
if t == table {
tableOrViewFound = true
}
}
if !tableOrViewFound {
c.JSON(http.StatusBadRequest, gin.H{
"error": "Provided table or view name doesn't exist in this database",
})
return
}
// Retrieve the list of columns for the table
cols, err = sdb.Columns("", table)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": err.Error(),
})
return
}
} else {
// Send the columns request to our job queue backend
cols, _, err = com.LiveColumns(liveNode, loggedInUser, dbOwner, dbName, table)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
})
log.Println(err)
return
}
}
// Transfer the column info into our own structure, for better json formatting
var jsonCols []APIJSONColumn
for _, j := range cols {
jsonCols = append(jsonCols, APIJSONColumn{
Cid: j.Cid,
Name: j.Name,
DataType: j.DataType,
NotNull: j.NotNull,
DfltValue: j.DfltValue,
Pk: j.Pk,
})
}
// Return the results
c.JSON(200, jsonCols)
}
// commitsHandler returns the details of all commits for a database
// This can be run from the command line using curl, like this:
//
// $ curl -F apikey="YOUR_API_KEY_HERE" -F dbowner="justinclift" -F dbname="Join Testing.sqlite" https://api.dbhub.io/v1/commits
// * "apikey" is one of your API keys. These can be generated from your Settings page once logged in
// * "dbowner" is the owner of the database
// * "dbname" is the name of the database
func commitsHandler(c *gin.Context) {
// Do auth check, grab request info
_, dbOwner, dbName, _, httpStatus, err := collectInfo(c)
if err != nil {
c.JSON(httpStatus, gin.H{
"error": err.Error(),
})
return
}
// If the database is a live database, we return an error message
isLive, _, err := database.CheckDBLive(dbOwner, dbName)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": err.Error(),
})
return
}
if isLive {
c.JSON(http.StatusBadRequest, gin.H{
"error": "That database is a live database. It doesn't have commits.",
})
return
}
// Retrieve the commits
commits, err := database.GetCommitList(dbOwner, dbName)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": err.Error(),
})
return
}
// Return the tags as JSON
c.JSON(200, commits)
}
// databasesHandler returns the list of databases in the requesting users account.
// If the new (optional) "live" boolean text field is set to true, then it will return the list of live
// databases. Otherwise, it will return the list of standard databases.
// This can be run from the command line using curl, like this:
//
// $ curl -F apikey="YOUR_API_KEY_HERE" -F live="true" https://api.dbhub.io/v1/databases
// * "apikey" is one of your API keys. These can be generated from your Settings page once logged in
// * "live" is whether to show Live databases, or standard ones
func databasesHandler(c *gin.Context) {
loggedInUser := c.MustGet("user").(string)
// Get "live" boolean value, if provided by the caller
live, err := com.GetFormLive(c.Request)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
})
return
}
// Retrieve the list of databases in the user account
var databases []database.DBInfo
if !live {
// Get the list of standard databases
databases, err = database.UserDBs(loggedInUser, database.DB_BOTH)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": err.Error(),
})
return
}
} else {
// Get the list of live databases
databases, err = com.LiveUserDBs(loggedInUser, database.DB_BOTH)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": err.Error(),
})
return
}
}
// Extract just the database names
var list []string
for _, j := range databases {
list = append(list, j.Database)
}
// Return the results
c.JSON(200, list)
}
// deleteHandler deletes a database from the requesting users account
// This can be run from the command line using curl, like this:
//
// $ curl -F apikey="YOUR_API_KEY_HERE" -F dbname="Join Testing.sqlite" https://api.dbhub.io/v1/delete
// * "apikey" is one of your API keys. These can be generated from your Settings page once logged in
// * "dbname" is the name of the database
func deleteHandler(c *gin.Context) {
loggedInUser := c.MustGet("user").(string)
// Validate the database name
dbName, err := com.GetDatabase(c.Request, false)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
})
return
}
dbOwner := loggedInUser
// Store database path for later logging
c.Set("owner", dbOwner)
c.Set("database", dbName)
// Check if the database exists
exists, err := database.CheckDBPermissions(loggedInUser, dbOwner, dbName, false)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": err.Error(),
})
return
}
if !exists {
c.JSON(http.StatusNotFound, gin.H{
"error": "Database does not exist, or user isn't authorised to access it",
})
return
}
// For a standard database, invalidate its memcache data
isLive, liveNode, err := database.CheckDBLive(dbOwner, dbName)
if err != nil {
c.JSON(http.StatusNotFound, gin.H{
"error": err.Error(),
})
return
}
if !isLive {
err = com.InvalidateCacheEntry(loggedInUser, dbOwner, dbName, "") // Empty string indicates "for all versions"
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": err.Error(),
})
return
}
}
// For a live database, delete it from both Minio and our job queue backend
var bucket, id string
if isLive {
// Get the Minio bucket and object names for this database
bucket, id, err = com.LiveGetMinioNames(loggedInUser, dbOwner, dbName)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": err.Error(),
})
return
}
// Delete the database from Minio
err = com.MinioDeleteDatabase("API server", dbOwner, dbName, bucket, id)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": err.Error(),
})
return
}
// Delete the database from our job queue backend
err = com.LiveDelete(liveNode, loggedInUser, dbOwner, dbName)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": err.Error(),
})
return
}
}
// Delete the database in PostgreSQL
err = database.DeleteDatabase(dbOwner, dbName)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": err.Error(),
})
return
}
// Return a "success" message
c.JSON(200, gin.H{
"status": "OK",
})
}
// diffHandler generates a diff between two databases or two versions of a database
// This can be run from the command line using curl, like this:
//
// $ curl -F apikey="YOUR_API_KEY_HERE" -F dbowner_a="justinclift" -F dbname_a="Join Testing.sqlite" -F commit_a="ea12..." -F commit_b="5a7c..." https://api.dbhub.io/v1/diff
// * "apikey" is one of your API keys. These can be generated from your Settings page once logged in
// * "dbowner_a" is the owner of the first database being diffed
// * "dbname_a" is the name of the first database being diffed
// * "dbowner_b" is the owner of the second database being diffed (optional, if not provided same as first owner)
// * "dbname_b" is the name of the second database being diffed (optional, if not provided same as first name)
// * "commit_a" is the first commit for diffing
// * "commit_b" is the second commit for diffing
// * "merge" specifies the merge strategy (possible values: "none", "preserve_pk", "new_pk"; optional, defaults to "none")
// * "include_data" can be set to "1" to include the full data of all changed rows instead of just the primary keys (optional, defaults to 0)
func diffHandler(c *gin.Context) {
loggedInUser := c.MustGet("user").(string)
// Get merge strategy and parse value. Default to "none"
merge := c.PostForm("merge")
mergeStrategy := com.NoMerge
if merge == "preserve_pk" {
mergeStrategy = com.PreservePkMerge
} else if merge == "new_pk" {
mergeStrategy = com.NewPkMerge
} else if merge != "" && merge != "none" {
c.JSON(http.StatusBadRequest, gin.H{
"error": "Invalid merge strategy",
})
return
}
// Get include data parameter
includeDataValue := c.PostForm("include_data")
includeData := false
if includeDataValue == "1" {
includeData = true
}
// Retrieve owner, name, and commit ids
oa := c.PostForm("dbowner_a")
na := c.PostForm("dbname_a")
ca := c.PostForm("commit_a")
ob := c.PostForm("dbowner_b")
nb := c.PostForm("dbname_b")
cb := c.PostForm("commit_b")
// If no primary database owner and name are given or if no commit ids are given, return
if oa == "" || na == "" || ca == "" || cb == "" {
c.JSON(http.StatusBadRequest, gin.H{
"error": "Incomplete database details provided",
})
return
}
// If no secondary database owner and name are provided, use the ones of the first database
if ob == "" || nb == "" {
ob = oa
nb = na
}
// Unescape, then validate the owner and database names and commit ids
dbOwnerA, err := url.QueryUnescape(oa)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
})
return
}
dbOwnerB, err := url.QueryUnescape(ob)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
})
return
}
dbNameA, err := url.QueryUnescape(na)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
})
return
}
dbNameB, err := url.QueryUnescape(nb)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
})
return
}
err = com.ValidateUser(dbOwnerA)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
})
return
}
err = com.ValidateUser(dbOwnerB)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
})
return
}
err = com.ValidateDB(dbNameA)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
})
return
}
err = com.ValidateDB(dbNameB)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
})
return
}
err = com.ValidateCommitID(ca)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
})
return
}
err = com.ValidateCommitID(cb)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
})
return
}
// Check permissions of the first database
allowed, err := database.CheckDBPermissions(loggedInUser, dbOwnerA, dbNameA, false)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": err.Error(),
})
return
}
if !allowed {
c.JSON(http.StatusNotFound, gin.H{
"error": "Database not found",
})
return
}
// Check permissions of the second database
allowed, err = database.CheckDBPermissions(loggedInUser, dbOwnerB, dbNameB, false)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": err.Error(),
})
return
}
if !allowed {
c.JSON(http.StatusNotFound, gin.H{
"error": "Database not found",
})
return
}
// If either database is a live database, we return an error message
isLive, _, err := database.CheckDBLive(dbOwnerA, dbNameA)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": err.Error(),
})
return
}
if isLive {
c.JSON(http.StatusBadRequest, gin.H{
"error": fmt.Sprintf("'%s/%s' is a live database. It doesn't support diffs.", dbOwnerA, dbNameA),
})
return
}
isLive, _, err = database.CheckDBLive(dbOwnerB, dbNameB)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": err.Error(),
})
return
}
if isLive {
c.JSON(http.StatusBadRequest, gin.H{
"error": fmt.Sprintf("'%s/%s' is a live database. It doesn't support diffs.", dbOwnerB, dbNameB),
})
return
}
// Perform diff
diffs, err := com.Diff(dbOwnerA, dbNameA, ca, dbOwnerB, dbNameB, cb, loggedInUser, mergeStrategy, includeData)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": err.Error(),
})
return
}
// Return the results
c.JSON(200, diffs)
}
// downloadHandler returns the requested SQLite database file.
// This can be run from the command line using curl, like this:
//
// $ curl -F apikey="YOUR_API_KEY_HERE" -F dbowner="justinclift" -F dbname="Join Testing.sqlite" -OJ https://api.dbhub.io/v1/download
// * "apikey" is one of your API keys. These can be generated from your Settings page once logged in
// * "dbowner" is the owner of the database
// * "dbname" is the name of the database
func downloadHandler(c *gin.Context) {
// Authenticate user and collect requested database details
loggedInUser, dbOwner, dbName, commitID, httpStatus, err := collectInfo(c)
if err != nil {
c.JSON(httpStatus, gin.H{
"error": err.Error(),
})
return
}
// Return the requested database to the user
_, err = com.DownloadDatabase(c.Writer, c.Request, dbOwner, dbName, commitID, loggedInUser, "api")
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": err.Error(),
})
return
}
}
// executeHandler executes a SQL query on a SQLite database. It's used for running SQL queries which don't
// return a result set, like `INSERT`, `UPDATE`, `DELETE`, and so forth.
// This can be run from the command line using curl, like this:
//
// $ curl -kD headers.out -F apikey="YOUR_API_KEY_HERE" -F dbowner="justinclift" -F dbname="Join Testing.sqlite" \
// -F sql="VVBEQVRFIHRhYmxlMSBTRVQgTmFtZSA9ICdUZXN0aW5nIDEnIFdIRVJFIGlkID0gMQ==" \
// https://api.dbhub.io/v1/execute
// * "apikey" is one of your API keys. These can be generated from your Settings page once logged in
// * "dbowner" is the owner of the database
// * "dbname" is the name of the database
// * "sql" is the SQL query to execute, base64 encoded
// NOTE that the above example (base64) encoded sql is: "UPDATE table1 SET Name = 'Testing 1' WHERE id = 1"
func executeHandler(c *gin.Context) {
// Note - This code is useful for very specific debugging of incoming POST data, so there's no need to leave it uncommented at all times
//if false {
// // Duplicate the request body in such a way that the existing functions don't need changing
// postData, err := io.ReadAll(r.Body)
// r.Body = io.NopCloser(bytes.NewBuffer(postData))
//
// // Write the post data into a file
// tmpFileName := "/tmp/postdata.log"
// tmpFile, err := os.OpenFile(tmpFileName, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
// if err != nil {
// log.Printf("Couldn't open temp file '%s' for writing POST data: %v", tmpFileName, err)
// } else {
// fmt.Fprintf(tmpFile, "URL: '%s'\n", r.URL.Path)
// fmt.Fprintf(tmpFile, "POST DATA: '%s'\n\n", postData)
// defer tmpFile.Close()
// }
//}
loggedInUser := c.MustGet("user").(string)
// Extract the database owner name, database name, and (optional) commit ID for the database from the request
dbOwner, dbName, _, err := com.GetFormODC(c.Request)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": err.Error(),
})
return
}
// Store database path for later logging
c.Set("owner", dbOwner)
c.Set("database", dbName)
// Grab the incoming SQLite query
rawInput := c.PostForm("sql")
sql, err := com.CheckUnicode(rawInput, true)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
})
return
}
// Check if the requested database exists
exists, err := database.CheckDBPermissions(loggedInUser, dbOwner, dbName, false)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": err.Error(),
})
return
}
if !exists {
c.JSON(http.StatusNotFound, gin.H{
"error": fmt.Sprintf("Database '%s/%s' doesn't exist", dbOwner, dbName),
})
return
}
// Check if the database is a live database, and get the node/queue to send the request to
isLive, liveNode, err := database.CheckDBLive(dbOwner, dbName)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": err.Error(),
})
return
}
// Reject attempts to run Execute() on non-live databases
if !isLive {
c.JSON(http.StatusInternalServerError, gin.H{
"error": "Execute() only runs on Live databases. This is not a live database.",
})
return
}
// If a live database has been uploaded but doesn't have a live node handling its requests, then error out as this
// should never happen
if isLive && liveNode == "" {
c.JSON(http.StatusInternalServerError, gin.H{
"error": "No job queue node available for request",
})
return
}
// Send the SQL execution request to our job queue backend
rowsChanged, err := com.LiveExecute(liveNode, loggedInUser, dbOwner, dbName, sql)
if err != nil {
log.Println(err)
c.JSON(http.StatusInternalServerError, gin.H{
"error": err.Error(),
})
return
}
// The Execute() succeeded, so pass along the # of rows changed
z := com.ExecuteResponseContainer{RowsChanged: rowsChanged, Status: "OK"}
c.JSON(200, z)
}
// indexesHandler returns the details of all indexes in a SQLite database
// This can be run from the command line using curl, like this:
//
// $ curl -F apikey="YOUR_API_KEY_HERE" -F dbowner="justinclift" -F dbname="Join Testing.sqlite" https://api.dbhub.io/v1/indexes
// * "apikey" is one of your API keys. These can be generated from your Settings page once logged in
// * "dbowner" is the owner of the database
// * "dbname" is the name of the database
func indexesHandler(c *gin.Context) {
// Do auth check, grab request info
loggedInUser, dbOwner, dbName, _, httpStatus, err := collectInfo(c)
if err != nil {
c.JSON(httpStatus, gin.H{
"error": err.Error(),
})
return
}
// Check if the database is a live database, and get the node/queue to send the request to
isLive, liveNode, err := database.CheckDBLive(dbOwner, dbName)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": err.Error(),
})
return
}
// If a live database has been uploaded but doesn't have a live node handling its requests, then error out as this
// should never happen
if isLive && liveNode == "" {
c.JSON(http.StatusInternalServerError, gin.H{
"error": "No job queue node available for request",
})
return
}
// If it's a standard database, process it locally. Else send the query to our job queue backend
var indexes []com.APIJSONIndex
if !isLive {
// Get Minio bucket and object id for the SQLite file
bucket, id, _, err := com.MinioLocation(dbOwner, dbName, "", loggedInUser)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": err.Error(),
})
return
}
// Sanity check
if id == "" {
// The requested database wasn't found, or the user doesn't have permission to access it
c.JSON(http.StatusNotFound, gin.H{
"error": "Requested database not found",
})
return
}
// Retrieve the database from Minio, then open it
var sdb *sqlite.Conn
sdb, err = com.OpenSQLiteDatabase(bucket, id)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": err.Error(),
})
return
}
defer sdb.Close()
// Retrieve the list of indexes
var idx map[string]string
idx, err = sdb.Indexes("")
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": err.Error(),
})
return
}
// Retrieve the details for each index
for nam, tab := range idx {
oneIndex := com.APIJSONIndex{
Name: nam,
Table: tab,
Columns: []com.APIJSONIndexColumn{},
}
cols, err := sdb.IndexColumns("", nam)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": err.Error(),
})
return
}
for _, k := range cols {
oneIndex.Columns = append(oneIndex.Columns, com.APIJSONIndexColumn{
CID: k.Cid,
Name: k.Name,
})
}
indexes = append(indexes, oneIndex)
}
} else {
// Send the indexes request to our job queue backend
indexes, err = com.LiveIndexes(liveNode, loggedInUser, dbOwner, dbName)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": err.Error(),
})
return
}
}
// Return the results
c.JSON(200, indexes)
}
// metadataHandler returns the commit, branch, release, tag and web page information for a database
// This can be run from the command line using curl, like this:
//
// $ curl -F apikey="YOUR_API_KEY_HERE" -F dbowner="justinclift" -F dbname="Join Testing.sqlite" https://api.dbhub.io/v1/metadata
// * "apikey" is one of your API keys. These can be generated from your Settings page once logged in
// * "dbowner" is the owner of the database
// * "dbname" is the name of the database
func metadataHandler(c *gin.Context) {
// Do auth check, grab request info
_, dbOwner, dbName, _, httpStatus, err := collectInfo(c)
if err != nil {
c.JSON(httpStatus, gin.H{
"error": err.Error(),
})
return
}
// If the database is a live database, we return an error message
isLive, _, err := database.CheckDBLive(dbOwner, dbName)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": err.Error(),
})
return
}
if isLive {
c.JSON(http.StatusBadRequest, gin.H{
"error": "That database is a live database. It doesn't support metadata.",
})
return
}
// Retrieve the metadata for the database
meta, err := com.MetadataResponse(dbOwner, dbName)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": err.Error(),
})
return
}
// Return the list as JSON
c.JSON(200, meta)
}
// queryHandler executes a SQL query on a SQLite database, returning the results to the caller
// This can be run from the command line using curl, like this:
//
// $ curl -kD headers.out -F apikey="YOUR_API_KEY_HERE" -F dbowner="justinclift" -F dbname="Join Testing.sqlite" \
// -F sql="U0VMRUNUIHRhYmxlMS5OYW1lLCB0YWJsZTIudmFsdWUKRlJPTSB0YWJsZTEgSk9JTiB0YWJsZTIKVVNJTkcgKGlkKQpPUkRFUiBCWSB0YWJsZTEuaWQ7" \
// https://api.dbhub.io/v1/query
// * "apikey" is one of your API keys. These can be generated from your Settings page once logged in
// * "dbowner" is the owner of the database
// * "dbname" is the name of the database
// * "sql" is the SQL query to run, base64 encoded
func queryHandler(c *gin.Context) {
loggedInUser := c.MustGet("user").(string)
// Extract the database owner name, database name, and (optional) commit ID for the database from the request
dbOwner, dbName, commitID, err := com.GetFormODC(c.Request)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": err.Error(),
})
return
}
// Store database path for later logging
c.Set("owner", dbOwner)
c.Set("database", dbName)
// Grab the incoming SQLite query
rawInput := c.PostForm("sql")
query, err := com.CheckUnicode(rawInput, true)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
})
return
}
// Check if the requested database exists
exists, err := database.CheckDBPermissions(loggedInUser, dbOwner, dbName, false)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": err.Error(),
})
return
}
if !exists {
c.JSON(http.StatusNotFound, gin.H{
"error": fmt.Sprintf("Database '%s/%s' doesn't exist", dbOwner, dbName),