-
Notifications
You must be signed in to change notification settings - Fork 0
/
ep3sql.go
3012 lines (2877 loc) · 111 KB
/
ep3sql.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 eprinttools
//
// ep3sql.go provides crosswalk methods to/from SQL
//
import (
"database/sql"
"fmt"
"log"
"strings"
"time"
// Caltech Packages
"github.com/caltechlibrary/eprinttools/cleaner"
"github.com/caltechlibrary/pairtree"
_ "github.com/go-sql-driver/mysql"
)
const (
// timestamp holds the Format of a MySQL time field
timestamp = `2006-01-02 15:04:05`
datestamp = `2006-01-02`
)
//
// DB SQL functions.
//
// OpenConnections
func OpenConnections(config *Config) error {
if config.Connections == nil {
config.Connections = map[string]*sql.DB{}
}
for repoID, dataSource := range config.Repositories {
dataSourceName := dataSource.DSN
// Setup DB connection for target repository
db, err := sql.Open("mysql", dataSourceName)
if err != nil {
return fmt.Errorf("could not open MySQL connection for %s, %s", repoID, err)
}
config.Connections[repoID] = db
dataSource.TableMap, err = eprintTablesAndColumns(db, repoID)
if err != nil {
return fmt.Errorf("failed to map table and columns for %q, %s", repoID, err)
}
}
return nil
}
// CloseConnections
func CloseConnections(config *Config) error {
var (
errors []string
)
if config.Connections == nil {
config.Connections = map[string]*sql.DB{}
return fmt.Errorf("no connections defined")
}
for name, db := range config.Connections {
if err := db.Close(); err != nil {
errors = append(errors, fmt.Sprintf("Failed to close %s, %s", name, err))
}
}
if len(errors) > 0 {
return fmt.Errorf("%s", strings.Join(errors, "\n"))
}
return nil
}
// sqlQueryInts takes a repostory ID, a SQL statement and returns
// intergers retrieved.
func sqlQueryInts(config *Config, repoID string, stmt string) ([]int, error) {
if db, ok := config.Connections[repoID]; ok {
rows, err := db.Query(stmt)
if err != nil {
return nil, fmt.Errorf("ERROR: query error (%q), %s", repoID, err)
}
defer rows.Close()
value := 0
values := []int{}
for rows.Next() {
err := rows.Scan(&value)
if err == nil {
values = append(values, value)
} else {
return nil, fmt.Errorf("ERROR: scan error (%q), %s", repoID, err)
}
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("ERROR: rows error (%q), %s", repoID, err)
}
return values, nil
}
return nil, fmt.Errorf("bad request")
}
// sqlQueryIntIDs takes a repostory ID, a SQL statement and applies
// the args returning a list of integer id or error.
func sqlQueryIntIDs(config *Config, repoID string, stmt string, args ...interface{}) ([]int, error) {
if db, ok := config.Connections[repoID]; ok {
rows, err := db.Query(stmt, args...)
if err != nil {
return nil, fmt.Errorf("ERROR: query error (%q), %s", repoID, err)
}
defer rows.Close()
value := 0
values := []int{}
for rows.Next() {
err := rows.Scan(&value)
if (err == nil) && (value > 0) {
values = append(values, value)
} else {
return nil, fmt.Errorf("ERROR: scan error (%q), %s", repoID, err)
}
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("ERROR: rows error (%q), %s", repoID, err)
}
if err != nil {
return nil, fmt.Errorf("ERROR: query error (%q), %s", repoID, err)
}
return values, nil
}
return nil, fmt.Errorf("bad request")
}
// sqlQueryStringIDs takes a repostory ID, a SQL statement and applies
// the args returning a list of string type id or error.
func sqlQueryStringIDs(config *Config, repoID string, stmt string, args ...interface{}) ([]string, error) {
if db, ok := config.Connections[repoID]; ok {
rows, err := db.Query(stmt, args...)
if err != nil {
return nil, fmt.Errorf("ERROR: query error (%q), %s", repoID, err)
}
defer rows.Close()
value := ``
values := []string{}
for rows.Next() {
err := rows.Scan(&value)
if err == nil {
values = append(values, value)
} else {
return nil, fmt.Errorf("ERROR: scan error (%q), %q, %s", repoID, stmt, err)
}
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("ERROR: rows error (%q), %s", repoID, err)
}
if err != nil {
return nil, fmt.Errorf("ERROR: query error (%q), %s", repoID, err)
}
return values, nil
}
return nil, fmt.Errorf("bad request")
}
// IsPublic takes an EPrintID and returns true if public, false otherwise
//
// Check if an EPrint record "is public"
func IsPublic(config *Config, repoID string, eprintid int) (bool, error) {
if db, ok := config.Connections[repoID]; ok {
stmt := `SELECT IFNULL(eprint_status, '') AS status, IFNULL(metadata_visibility, '') AS visibility FROM eprint WHERE eprintid = ? LIMIT 1`
rows, err := db.Query(stmt, eprintid)
if err != nil {
return false, fmt.Errorf("ERROR: query error (%q), %s", repoID, err)
}
defer rows.Close()
var (
status, visibility string
)
for rows.Next() {
err := rows.Scan(&status, &visibility)
if err != nil {
return false, fmt.Errorf("ERROR: scan error (%q), %q, %s", repoID, stmt, err)
}
}
if err := rows.Err(); err != nil {
return false, fmt.Errorf("ERROR: rows error (%q), %s", repoID, err)
}
if err != nil {
return false, fmt.Errorf("ERROR: query error (%q), %s", repoID, err)
}
return ((status == "archive") && (visibility == "show")), nil
}
return false, fmt.Errorf("bad request")
}
//
// Expose EPrint meta data structure
//
func GetTablesAndColumns(config *Config, repoID string) (map[string][]string, error) {
if config.Connections == nil {
return nil, fmt.Errorf(`database access not configured`)
}
if db, ok := config.Connections[repoID]; ok == true {
return eprintTablesAndColumns(db, repoID)
}
return nil, fmt.Errorf(`database connections not defined for %s`, repoID)
}
//
// EPrint User Info
//
// GetUsernames returns a list of all usernames in a repository
func GetUsernames(config *Config, repoID string, userids ...int) ([]string, error) {
stmt := `SELECT username FROM user ORDER BY userid`
return sqlQueryStringIDs(config, repoID, stmt)
}
// GetUserID takes a username and returns a list of userid
func GetUserID(config *Config, repoID string, username string) ([]int, error) {
stmt := `SELECT userid FROM user WHERE username = ?`
return sqlQueryIntIDs(config, repoID, stmt, username)
}
// GetUserBy takes a field name (e.g. userid, username) and value
// and returns an EPrintUser object.
func GetUserBy(config *Config, repoID string, queryField string, queryValue interface{}) (*EPrintUser, error) {
var (
year, month, day, hour, minute, second int
hideEMail string
)
if db, ok := config.Connections[repoID]; ok {
stmt := fmt.Sprintf(`SELECT userid, username, usertype, IFNULL(name_honourific, '') AS honourific, IFNULL(name_family, '') AS family, IFNULL(name_given, '') AS given, IFNULL(name_lineage, '') AS lineage, IFNULL(email, '') AS email, IFNULL(hideemail, '') AS hideemail, IFNULL(dept, '') AS dept, IFNULL(org, '') AS org, IFNULL(address, '') AS address, IFNULL(country, '') AS country, IFNULL(joined_year, 0) AS joined_year, IFNULL(joined_month, 0) AS joined_month, IFNULL(joined_day, 0) AS joined_day, IFNULL(joined_hour, 0) AS joined_hour, IFNULL(joined_minute, 0) AS joined_minute, IFNULL(joined_second, 0) AS joined_second FROM user WHERE %s = ? LIMIT 1`, queryField)
rows, err := db.Query(stmt, queryValue)
if err != nil {
return nil, fmt.Errorf("ERROR: query error (%q), %s", repoID, err)
}
defer rows.Close()
// Map values back into our object.
user := new(EPrintUser)
user.Name = new(Name)
for rows.Next() {
err := rows.Scan(&user.UserID, &user.Username, &user.Type,
&user.Name.Honourific, &user.Name.Family,
&user.Name.Given, &user.Name.Lineage,
&user.EMail, &hideEMail,
&user.Dept, &user.Org,
&user.Address, &user.Country,
&year, &month, &day, &hour, &minute, &second)
if err != nil {
return nil, fmt.Errorf("ERROR: scan error (%q), %q, %s", repoID, stmt, err)
}
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("ERROR: rows error (%q), %s", repoID, err)
}
if err != nil {
return nil, fmt.Errorf("ERROR: query error (%q), %s", repoID, err)
}
user.Joined = fmt.Sprintf(`%04d-%02d-%02d %02d:%02d:%02d`, year, month, day, hour, minute, second)
if strings.ToLower(hideEMail) == "true" {
user.HideEMail = true
} else {
user.HideEMail = false
}
return user, nil
}
return nil, fmt.Errorf(`bad request`)
}
func SQLCreateUser(config *Config, repoID string, user *EPrintUser) (int, error) {
var (
year, month, day, hour, minute, second int
)
now := time.Now()
if user.Name == nil {
user.Name = &Name{
Honourific: ``,
Family: ``,
Given: ``,
Lineage: ``,
}
}
if user.Joined == "" {
user.Joined = now.Format(timestamp)
year = now.Year()
month = int(now.Month())
day = now.Day()
hour = now.Hour()
minute = now.Minute()
second = now.Second()
} else {
if dt, err := time.Parse(timestamp, user.Joined); err == nil {
year = dt.Year()
month = int(dt.Month())
day = dt.Day()
hour = dt.Hour()
minute = dt.Minute()
second = dt.Second()
}
}
hideEMail := "FALSE"
if user.HideEMail {
hideEMail = "TRUE"
}
if db, ok := config.Connections[repoID]; ok {
// First generate new row for user.
stmt := `INSERT INTO user (userid) (SELECT (IFNULL((SELECT userid FROM user ORDER BY userid DESC LIMIT 1), 0) + 1) AS userid)`
_, err := db.Exec(stmt)
if err != nil {
return 0, fmt.Errorf(`SQL error, %q, %s`, stmt, err)
}
stmt = `SELECT userid FROM user ORDER BY userid DESC LIMIT 1`
rows, err := db.Query(stmt)
if err != nil {
return 0, fmt.Errorf(`SQL error, %q, %s`, stmt, err)
}
id := 0
for rows.Next() {
if err := rows.Scan(&id); err != nil {
return 0, fmt.Errorf(`could not calculate the new userid value, %s`, err)
}
}
rows.Close()
if err != nil {
return 0, fmt.Errorf(`SQL failed to get insert id, %s`, err)
}
// Update user
user.UserID = id
stmt = `REPLACE INTO user (userid, username, usertype, name_honourific, name_family, name_given, name_lineage, email, hideemail, dept, org, address, country, joined_year, joined_month, joined_day, joined_hour, joined_minute, joined_second) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
_, err = db.Exec(stmt, user.UserID, user.Username, user.Type, user.Name.Honourific, user.Name.Family, user.Name.Given, user.Name.Lineage, user.EMail, hideEMail, user.Dept, user.Org, user.Address, user.Country, year, month, day, hour, minute, second)
if err != nil {
return 0, fmt.Errorf(`SQL error, %q, %s`, stmt, err)
}
return user.UserID, nil
}
return 0, fmt.Errorf(`bad request`)
}
func SQLUpdateUser(config *Config, repoID string, user *EPrintUser) error {
if db, ok := config.Connections[repoID]; ok {
hideEMail := "FALSE"
if user.HideEMail {
hideEMail = "TRUE"
}
stmt := `UPDATE user SET username = ?, usertype = ?, name_honourific = ?, name_family = ?, name_given = ?, name_lineage = ?, email = ?, hideemail = ?, dept = ?, org = ?, address = ?, country = ? WHERE userid = ?`
_, err := db.Exec(stmt, user.Username, user.Type, user.Name.Honourific, user.Name.Family, user.Name.Given, user.Name.Lineage, user.EMail, hideEMail, user.Dept, user.Org, user.Address, user.Country, user.UserID)
if err != nil {
return fmt.Errorf(`SQL error, %q, %s`, stmt, err)
}
return nil
}
return fmt.Errorf(`bad request`)
}
func SQLReadUser(config *Config, repoID string, userid int) (*EPrintUser, error) {
return GetUserBy(config, repoID, `userid`, userid)
}
//
// EPrint ID Lists
//
// GetAllEPrintIDs return a list of all eprint ids in repository or error
func GetAllEPrintIDs(config *Config, repoID string) ([]int, error) {
return sqlQueryIntIDs(config, repoID, `SELECT eprintid FROM eprint
ORDER BY date_year DESC, date_month DESC, date_day DESC`)
}
// GetAllEPrintIDsWithStatus return a list of all eprint ids in a repository with a given status or return error
func GetAllEPrintIDsWithStatus(config *Config, repoID string, status string) ([]int, error) {
return sqlQueryIntIDs(config, repoID, `SELECT eprintid FROM eprint WHERE (eprint_status = ?) ORDER BY date_year DESC, date_month DESC, date_day DESC`, status)
}
// GetEPrintIDsInTimestampRange return a list of EPrintIDs in created timestamp range
// or return error. field maybe either "datestamp" (for created date), "lastmod" (for last modified date)
func GetEPrintIDsInTimestampRange(config *Config, repoID string, field string, start string, end string) ([]int, error) {
stmt := fmt.Sprintf(`SELECT eprintid FROM eprint WHERE
(CONCAT(%s_year, "-",
LPAD(IFNULL(%s_month, 1), 2, "0"), "-",
LPAD(IFNULL(%s_day, 1), 2, "0"), " ",
LPAD(IFNULL(%s_hour, 0), 2, "0"), ":",
LPAD(IFNULL(%s_minute, 0), 2, "0"), ":",
LPAD(IFNULL(%s_second, 0), 2, "0")) >= ?) AND
(CONCAT(%s_year, "-",
LPAD(IFNULL(%s_month, 12), 2, "0"), "-",
LPAD(IFNULL(%s_day, 28), 2, "0"), " ",
LPAD(IFNULL(%s_hour, 23), 2, "0"), ":",
LPAD(IFNULL(%s_minute, 59), 2, "0"), ":",
LPAD(IFNULL(%s_second, 59), 2, "0")) <= ?)
ORDER BY %s_year DESC, %s_month DESC, %s_day DESC, %s_hour DESC, %s_minute DESC, %s_second DESC`,
field, field, field, field, field, field, field, field, field, field, field, field,
field, field, field, field, field, field)
return sqlQueryIntIDs(config, repoID, stmt, start, end)
}
// GetEPrintIDsWithStatusInTimestampRange return a list of EPrintIDs with eprint_status in field timestamp range
// or return error. field maybe either "datestamp" (for created date), "lastmod" (for last modified date)
func GetEPrintIDsWithStatusInTimestampRange(config *Config, repoID string, status string, field string, start string, end string) ([]int, error) {
stmt := fmt.Sprintf(`SELECT eprintid FROM eprint WHERE
(eprint_status = ?) AND
(CONCAT(%s_year, "-",
LPAD(IFNULL(%s_month, 1), 2, "0"), "-",
LPAD(IFNULL(%s_day, 1), 2, "0"), " ",
LPAD(IFNULL(%s_hour, 0), 2, "0"), ":",
LPAD(IFNULL(%s_minute, 0), 2, "0"), ":",
LPAD(IFNULL(%s_second, 0), 2, "0")) >= ?) AND
(CONCAT(%s_year, "-",
LPAD(IFNULL(%s_month, 12), 2, "0"), "-",
LPAD(IFNULL(%s_day, 28), 2, "0"), " ",
LPAD(IFNULL(%s_hour, 23), 2, "0"), ":",
LPAD(IFNULL(%s_minute, 59), 2, "0"), ":",
LPAD(IFNULL(%s_second, 59), 2, "0")) <= ?)
ORDER BY %s_year DESC, %s_month DESC, %s_day DESC, %s_hour DESC, %s_minute DESC, %s_second DESC`,
field, field, field, field, field, field,
field, field, field, field, field, field,
field, field, field, field, field, field)
return sqlQueryIntIDs(config, repoID, stmt, status, start, end)
}
// GetEPrintIDsWithStatus returns a list of eprints in a timestmap range for
// a given status or returns an error
func GetEPrintIDsWithStatus(config *Config, repoID string, status string, start string, end string) ([]int, error) {
stmt := `SELECT eprintid FROM eprint WHERE (eprint_status = ?) AND
(CONCAT(lastmod_year, "-",
LPAD(IFNULL(lastmod_month, 1), 2, "0"), "-",
LPAD(IFNULL(lastmod_day, 1), 2, "0"), " ",
LPAD(IFNULL(lastmod_hour, 0), 2, "0"), ":",
LPAD(IFNULL(lastmod_minute, 0), 2, "0"), ":",
LPAD(IFNULL(lastmod_second, 0), 2, "0")) >= ?) AND
(CONCAT(lastmod_year, "-",
LPAD(IFNULL(lastmod_month, 12), 2, "0"), "-",
LPAD(IFNULL(lastmod_day, 28), 2, "0"), " ",
LPAD(IFNULL(lastmod_hour, 23), 2, "0"), ":",
LPAD(IFNULL(lastmod_minute, 59), 2, "0"), ":",
LPAD(IFNULL(lastmod_second, 59), 2, "0")) <= ?)
ORDER BY lastmod_year DESC, lastmod_month DESC, lastmod_day DESC,
lastmod_hour DESC, lastmod_minute DESC, lastmod_minute DESC`
return sqlQueryIntIDs(config, repoID, stmt, status, start, end)
}
// GetEPrintIDsForDateType returns list of eprints in date range
// or returns an error
func GetEPrintIDsForDateType(config *Config, repoID string, dateType string, start string, end string) ([]int, error) {
stmt := fmt.Sprintf(`SELECT eprintid FROM eprint
WHERE ((date_type) = ?) AND
(CONCAT(date_year, "-",
LPAD(IFNULL(date_month, 1), 2, "0"), "-",
LPAD(IFNULL(date_day, 1), 2, "0")) >= ?) AND
(CONCAT(date_year, "-",
LPAD(IFNULL(date_month, 12), 2, "0"), "-",
LPAD(IFNULL(date_day, 28), 2, "0")) <= ?)
ORDER BY date_year DESC, date_month DESC, date_day DESC
`)
return sqlQueryIntIDs(config, repoID, stmt, dateType, start, end)
}
// GetEPrintIDsWithStatusForDateType returns list of eprints in
// date range for a given status or returns an error
func GetEPrintIDsWithStatusForDateType(config *Config, repoID string, status string, dateType string, start string, end string) ([]int, error) {
stmt := fmt.Sprintf(`SELECT eprintid FROM eprint
WHERE (eprint_status = ? ) AND (date_type = ?) AND
(CONCAT(date_year, "-",
LPAD(IFNULL(date_month, 1), 2, "0"), "-",
LPAD(IFNULL(date_day, 1), 2, "0")) >= ?) AND
(CONCAT(date_year, "-",
LPAD(IFNULL(date_month, 12), 2, "0"), "-",
LPAD(IFNULL(date_day, 28), 2, "0")) <= ?)
ORDER BY date_year DESC, date_month DESC, date_day DESC
`)
return sqlQueryIntIDs(config, repoID, stmt, status, dateType, start, end)
}
// GetAllUniqueID return a list of unique id values in repository
func GetAllUniqueID(config *Config, repoID string, field string) ([]string, error) {
stmt := fmt.Sprintf(`SELECT %s
FROM eprint
WHERE %s IS NOT NULL
GROUP BY %s ORDER BY %s`,
field, field, field, field)
return sqlQueryStringIDs(config, repoID, stmt)
}
// GetEPrintIDsForUniqueID return list of eprints for DOI
func GetEPrintIDsForUniqueID(config *Config, repoID string, field string, value string) ([]int, error) {
// NOTE: There should only be one eprint per DOI but we have dirty data because the field is not contrained as Unique
stmt := fmt.Sprintf(`SELECT eprintid FROM eprint WHERE LOWER(%s) = LOWER(?)`, field)
return sqlQueryIntIDs(config, repoID, stmt, value)
}
// GetAllPersonOrOrgIDs return a list of creator ids or error
func GetAllPersonOrOrgIDs(config *Config, repoID string, field string) ([]string, error) {
stmt := fmt.Sprintf(`SELECT %s_id FROM eprint_%s_id
WHERE %s_id IS NOT NULL
GROUP BY %s_id ORDER BY %s_id`, field, field, field, field, field)
return sqlQueryStringIDs(config, repoID, stmt)
}
// GetEPrintIDForPersonOrOrgID return a list of eprint ids associated with the person or organization id
func GetEPrintIDsForPersonOrOrgID(config *Config, repoID string, personOrOrgType string, personOrOrgID string) ([]int, error) {
stmt := fmt.Sprintf(`SELECT eprint_%s_id.eprintid AS eprintid
FROM eprint_%s_id JOIN eprint ON (eprint_%s_id.eprintid = eprint.eprintid)
WHERE eprint_%s_id.%s_id = ?
ORDER BY date_year DESC, date_month DESC, date_day DESC`,
personOrOrgType, personOrOrgType, personOrOrgType, personOrOrgType, personOrOrgType)
return sqlQueryIntIDs(config, repoID, stmt, personOrOrgID)
}
// GetAllORCIDs return a list of all ORCID in repository
func GetAllORCIDs(config *Config, repoID string) ([]string, error) {
values, err := sqlQueryStringIDs(config, repoID, `SELECT creators_orcid
FROM eprint_creators_orcid
WHERE creators_orcid IS NOT NULL
GROUP BY creators_orcid ORDER BY creators_orcid`)
return values, err
}
// GetEPrintIDsForORCID return a list of eprint ids associated with the ORCID
func GetEPrintIDsForORCID(config *Config, repoID string, orcid string) ([]int, error) {
return sqlQueryIntIDs(config, repoID, `SELECT eprint.eprintid AS eprintid
FROM eprint_creators_orcid JOIN eprint ON (eprint_creators_orcid.eprintid = eprint.eprintid)
WHERE creators_orcid = ?
ORDER BY date_year DESC, date_month DESC, date_day DESC
`, orcid)
}
// GetAllItems returns a list of simple items (e.g. local_group)
func GetAllItems(config *Config, repoID string, field string) ([]string, error) {
stmt := fmt.Sprintf(`SELECT %s
FROM eprint_%s
WHERE eprint_%s.%s IS NOT NULL
GROUP BY eprint_%s.%s ORDER BY eprint_%s.%s`,
field, field, field, field, field, field, field, field)
return sqlQueryStringIDs(config, repoID, stmt)
}
// GetEPrintIDsForItem
func GetEPrintIDsForItem(config *Config, repoID string, field string, value string) ([]int, error) {
stmt := fmt.Sprintf(`SELECT eprint.eprintid AS eprintid
FROM eprint_%s JOIN eprint ON (eprint_%s.eprintid = eprint.eprintid)
WHERE eprint_%s.%s = ?
ORDER BY eprint.date_year DESC, eprint.date_month DESC, eprint.date_day DESC`, field, field, field, field)
return sqlQueryIntIDs(config, repoID, stmt, value)
}
// GetAllPersonNames return a list of person names in repository
func GetAllPersonNames(config *Config, repoID string, field string) ([]string, error) {
stmt := fmt.Sprintf(`SELECT CONCAT(%s_family, "/", %s_given) AS %s
FROM eprint_%s
WHERE (%s_family IS NOT NULL) OR (%s_given IS NOT NULL)
GROUP BY %s_family, %s_given ORDER BY %s_family, %s_given`,
field, field, field,
field, field, field, field, field, field, field)
return sqlQueryStringIDs(config, repoID, stmt)
}
// GetEPrintIDsForPersonName return a list of eprint id for a person's name (family, given)
func GetEPrintIDsForPersonName(config *Config, repoID, field string, family string, given string) ([]int, error) {
conditions := []string{}
if strings.Contains(family, "*") || strings.Contains(given, "%") {
conditions = append(conditions, fmt.Sprintf(`%s_family LIKE ?`, field))
} else if family != "" {
conditions = append(conditions, fmt.Sprintf(`%s_family = ?`, field))
}
if strings.Contains(given, "*") || strings.Contains(given, "%") {
conditions = append(conditions, fmt.Sprintf(`%s_given LIKE ?`, field))
} else if given != "" {
conditions = append(conditions, fmt.Sprintf(`%s_given = ?`, field))
}
stmt := fmt.Sprintf(`SELECT eprint.eprintid AS eprintid
FROM eprint_%s JOIN eprint ON (eprint_%s.eprintid = eprint.eprintid)
WHERE %s
ORDER BY %s_family ASC, %s_given ASC, eprint.date_year DESC, eprint.date_month DESC, eprint.date_day DESC`,
field, field, strings.Join(conditions, " AND "), field, field)
return sqlQueryIntIDs(config, repoID, stmt, family, given)
}
// GetAllYears returns the publication years found in a repository
func GetAllYears(config *Config, repoID string) ([]int, error) {
stmt := fmt.Sprintf(`SELECT date_year FROM eprint WHERE date_type = "published" AND date_year IS NOT NULL GROUP BY date_year ORDER BY date_year DESC`)
return sqlQueryInts(config, repoID, stmt)
}
// GetEPrintsIDsForYear returns a list of published eprint IDs for a given
// year.
func GetEPrintIDsForYear(config *Config, repoID string, year int) ([]int, error) {
stmt := fmt.Sprintf(`SELECT eprintid FROM eprint WHERE date_type = "published" AND date_year = ? ORDER BY date_year DESC, date_month DESC, date_day DESC`)
return sqlQueryIntIDs(config, repoID, stmt, year)
}
//
// EPrints Metadata Structure
//
// eprintTablesAndColumns takes a DB connection and repoID then builds a map[string][]string{}
// structure representing the tables and their columns available in a EPrints Repository
func eprintTablesAndColumns(db *sql.DB, repoID string) (map[string][]string, error) {
data := map[string][]string{}
stmt := `SHOW TABLES LIKE "eprint%"`
rows, err := db.Query(stmt)
if err != nil {
return nil, fmt.Errorf("SQL(%q), %s", repoID, err)
}
tables := []string{}
for rows.Next() {
tableName := ""
if err := rows.Scan(&tableName); err == nil {
if !strings.Contains(tableName, "__") {
tables = append(tables, tableName)
}
}
}
rows.Close()
for _, tableName := range tables {
data[tableName] = []string{}
stmt := fmt.Sprintf(`SHOW COLUMNS IN %s`, tableName)
cRows, err := db.Query(stmt)
if err != nil {
return nil, fmt.Errorf("SQL(%q), %s", repoID, err)
}
columns := []string{}
var (
colName, f1, f2, f3, f5 string
f4 interface{}
)
for cRows.Next() {
//colName, f1, f2, f3, f4, f5 = &"", &"", &"", &"", nil, &""
if err := cRows.Scan(&colName, &f1, &f2, &f3, &f4, &f5); err != nil {
return nil, fmt.Errorf("cRows.Scan() error: %s", err)
} else {
columns = append(columns, colName)
}
}
data[tableName] = columns
cRows.Close()
}
// We need to add the document set of tables too.
stmt = `SHOW TABLES LIKE "document%"`
rows, err = db.Query(stmt)
if err != nil {
return nil, fmt.Errorf("SQL(%q), %s", repoID, err)
}
tables = []string{}
for rows.Next() {
tableName := ""
if err := rows.Scan(&tableName); err == nil {
if !strings.Contains(tableName, "__") {
tables = append(tables, tableName)
}
}
}
rows.Close()
for _, tableName := range tables {
data[tableName] = []string{}
stmt := fmt.Sprintf(`SHOW COLUMNS IN %s`, tableName)
cRows, err := db.Query(stmt)
if err != nil {
return nil, fmt.Errorf("SQL(%q), %s", repoID, err)
}
columns := []string{}
var (
colName, f1, f2, f3, f5 string
f4 interface{}
)
for cRows.Next() {
//colName, f1, f2, f3, f4, f5 = &"", &"", &"", &"", nil, &""
if err := cRows.Scan(&colName, &f1, &f2, &f3, &f4, &f5); err != nil {
return nil, fmt.Errorf("cRows.Scan() error: %s", err)
} else {
columns = append(columns, colName)
}
}
data[tableName] = columns
cRows.Close()
}
// We need to add the files set of tables too.
stmt = `SHOW TABLES LIKE "file%"`
rows, err = db.Query(stmt)
if err != nil {
return nil, fmt.Errorf("SQL(%q), %s", repoID, err)
}
tables = []string{}
for rows.Next() {
tableName := ""
if err := rows.Scan(&tableName); err == nil {
if !strings.Contains(tableName, "__") {
tables = append(tables, tableName)
}
}
}
rows.Close()
for _, tableName := range tables {
data[tableName] = []string{}
stmt := fmt.Sprintf(`SHOW COLUMNS IN %s`, tableName)
cRows, err := db.Query(stmt)
if err != nil {
return nil, fmt.Errorf("SQL(%q), %s", repoID, err)
}
columns := []string{}
var (
colName, f1, f2, f3, f5 string
f4 interface{}
)
for cRows.Next() {
//colName, f1, f2, f3, f4, f5 = &"", &"", &"", &"", nil, &""
if err := cRows.Scan(&colName, &f1, &f2, &f3, &f4, &f5); err != nil {
return nil, fmt.Errorf("cRows.Scan() error: %s", err)
} else {
columns = append(columns, colName)
}
}
data[tableName] = columns
cRows.Close()
}
return data, nil
}
/*
* Column mapping for tables.
*/
// colExpr takes a column name, ifNull bool and default value.
// If the "ifNull" bool is true then the form expressed is
// `IFNULL(%s, %s) AS %s` otherwise just the column name
// is returned.
func colExpr(name string, ifNull bool, value string) string {
if ifNull {
return fmt.Sprintf(`IFNULL(%s, %s) AS %s`, name, value, name)
}
return name
}
// eprintToColumnsAndValues for a given EPrints struct generate a
// list of column names to query along with a recieving values array.
// Return a list of column names (with null handle and aliases) and values.
//
// The bool ifNull will control the type of expression of the column.
func eprintToColumnsAndValues(eprint *EPrint, columnsIn []string, ifNull bool) ([]string, []interface{}) {
columnsOut := []string{}
values := []interface{}{}
for i, key := range columnsIn {
switch key {
case "eprintid":
values = append(values, &eprint.EPrintID)
columnsOut = append(columnsOut, key)
case "rev_number":
values = append(values, &eprint.RevNumber)
columnsOut = append(columnsOut, colExpr(key, ifNull, `0`))
case "eprint_status":
values = append(values, &eprint.EPrintStatus)
columnsOut = append(columnsOut, colExpr(key, ifNull, `""`))
case "userid":
values = append(values, &eprint.UserID)
columnsOut = append(columnsOut, colExpr(key, ifNull, `0`))
case "dir":
values = append(values, &eprint.Dir)
columnsOut = append(columnsOut, colExpr(key, ifNull, `""`))
case "datestamp_year":
values = append(values, &eprint.DatestampYear)
columnsOut = append(columnsOut, colExpr(key, ifNull, `0`))
case "datestamp_month":
values = append(values, &eprint.DatestampMonth)
columnsOut = append(columnsOut, colExpr(key, ifNull, `0`))
case "datestamp_day":
values = append(values, &eprint.DatestampDay)
columnsOut = append(columnsOut, colExpr(key, ifNull, `0`))
case "datestamp_hour":
values = append(values, &eprint.DatestampHour)
columnsOut = append(columnsOut, colExpr(key, ifNull, `0`))
case "datestamp_minute":
values = append(values, &eprint.DatestampMinute)
columnsOut = append(columnsOut, colExpr(key, ifNull, `0`))
case "datestamp_second":
values = append(values, &eprint.DatestampSecond)
columnsOut = append(columnsOut, colExpr(key, ifNull, `0`))
case "lastmod_year":
values = append(values, &eprint.LastModifiedYear)
columnsOut = append(columnsOut, colExpr(key, ifNull, `0`))
case "lastmod_month":
values = append(values, &eprint.LastModifiedMonth)
columnsOut = append(columnsOut, colExpr(key, ifNull, `0`))
case "lastmod_day":
values = append(values, &eprint.LastModifiedDay)
columnsOut = append(columnsOut, colExpr(key, ifNull, `0`))
case "lastmod_hour":
values = append(values, &eprint.LastModifiedHour)
columnsOut = append(columnsOut, colExpr(key, ifNull, `0`))
case "lastmod_minute":
values = append(values, &eprint.LastModifiedMinute)
columnsOut = append(columnsOut, colExpr(key, ifNull, `0`))
case "lastmod_second":
values = append(values, &eprint.LastModifiedSecond)
columnsOut = append(columnsOut, colExpr(key, ifNull, `0`))
case "status_changed_year":
values = append(values, &eprint.StatusChangedYear)
columnsOut = append(columnsOut, colExpr(key, ifNull, `0`))
case "status_changed_month":
values = append(values, &eprint.StatusChangedMonth)
columnsOut = append(columnsOut, colExpr(key, ifNull, `0`))
case "status_changed_day":
values = append(values, &eprint.StatusChangedDay)
columnsOut = append(columnsOut, colExpr(key, ifNull, `0`))
case "status_changed_hour":
values = append(values, &eprint.StatusChangedHour)
columnsOut = append(columnsOut, colExpr(key, ifNull, `0`))
case "status_changed_minute":
values = append(values, &eprint.StatusChangedMinute)
columnsOut = append(columnsOut, colExpr(key, ifNull, `0`))
case "status_changed_second":
values = append(values, &eprint.StatusChangedSecond)
columnsOut = append(columnsOut, colExpr(key, ifNull, `0`))
case "type":
values = append(values, &eprint.Type)
columnsOut = append(columnsOut, colExpr(key, ifNull, `""`))
case "metadata_visibility":
values = append(values, &eprint.MetadataVisibility)
columnsOut = append(columnsOut, colExpr(key, ifNull, `""`))
case "title":
values = append(values, &eprint.Title)
columnsOut = append(columnsOut, colExpr(key, ifNull, `""`))
case "ispublished":
values = append(values, &eprint.IsPublished)
columnsOut = append(columnsOut, colExpr(key, ifNull, `""`))
case "full_text_status":
values = append(values, &eprint.FullTextStatus)
columnsOut = append(columnsOut, colExpr(key, ifNull, `""`))
case "keywords":
values = append(values, &eprint.Keywords)
columnsOut = append(columnsOut, colExpr(key, ifNull, `""`))
case "note":
values = append(values, &eprint.Note)
columnsOut = append(columnsOut, colExpr(key, ifNull, `""`))
case "abstract":
values = append(values, &eprint.Abstract)
columnsOut = append(columnsOut, colExpr(key, ifNull, `""`))
case "date_year":
values = append(values, &eprint.DateYear)
columnsOut = append(columnsOut, colExpr(key, ifNull, `0`))
case "date_month":
values = append(values, &eprint.DateMonth)
columnsOut = append(columnsOut, colExpr(key, ifNull, `0`))
case "date_day":
values = append(values, &eprint.DateDay)
columnsOut = append(columnsOut, colExpr(key, ifNull, `0`))
case "date_type":
values = append(values, &eprint.DateType)
columnsOut = append(columnsOut, colExpr(key, ifNull, `0`))
case "series":
values = append(values, &eprint.Series)
columnsOut = append(columnsOut, colExpr(key, ifNull, `""`))
case "volume":
values = append(values, &eprint.Volume)
columnsOut = append(columnsOut, colExpr(key, ifNull, `""`))
case "number":
values = append(values, &eprint.Number)
columnsOut = append(columnsOut, colExpr(key, ifNull, `""`))
case "publication":
values = append(values, &eprint.Publication)
columnsOut = append(columnsOut, colExpr(key, ifNull, `""`))
case "publisher":
values = append(values, &eprint.Publisher)
columnsOut = append(columnsOut, colExpr(key, ifNull, `""`))
case "place_of_pub":
values = append(values, &eprint.PlaceOfPub)
columnsOut = append(columnsOut, colExpr(key, ifNull, `""`))
case "edition":
values = append(values, &eprint.Edition)
columnsOut = append(columnsOut, colExpr(key, ifNull, `""`))
case "pagerange":
values = append(values, &eprint.PageRange)
columnsOut = append(columnsOut, colExpr(key, ifNull, `""`))
case "pages":
values = append(values, &eprint.Pages)
columnsOut = append(columnsOut, colExpr(key, ifNull, `0`))
case "event_type":
values = append(values, &eprint.EventType)
columnsOut = append(columnsOut, colExpr(key, ifNull, `""`))
case "event_title":
values = append(values, &eprint.EventTitle)
columnsOut = append(columnsOut, colExpr(key, ifNull, `""`))
case "event_location":
values = append(values, &eprint.EventLocation)
columnsOut = append(columnsOut, colExpr(key, ifNull, `""`))
case "event_dates":
values = append(values, &eprint.EventDates)
columnsOut = append(columnsOut, colExpr(key, ifNull, `""`))
case "id_number":
values = append(values, &eprint.IDNumber)
columnsOut = append(columnsOut, colExpr(key, ifNull, `""`))
case "refereed":
values = append(values, &eprint.Refereed)
columnsOut = append(columnsOut, colExpr(key, ifNull, `""`))
case "isbn":
values = append(values, &eprint.ISBN)
columnsOut = append(columnsOut, colExpr(key, ifNull, `""`))
case "issn":
values = append(values, &eprint.ISSN)
columnsOut = append(columnsOut, colExpr(key, ifNull, `""`))
case "book_title":
values = append(values, &eprint.BookTitle)
columnsOut = append(columnsOut, colExpr(key, ifNull, `""`))
case "official_url":
values = append(values, &eprint.OfficialURL)
columnsOut = append(columnsOut, colExpr(key, ifNull, `""`))
case "alt_url":
values = append(values, &eprint.AltURL)
columnsOut = append(columnsOut, colExpr(key, ifNull, `""`))
case "rights":
values = append(values, &eprint.Rights)
columnsOut = append(columnsOut, colExpr(key, ifNull, `""`))
case "collection":
values = append(values, &eprint.Collection)
columnsOut = append(columnsOut, colExpr(key, ifNull, `""`))
case "reviewer":
values = append(values, &eprint.Reviewer)
columnsOut = append(columnsOut, colExpr(key, ifNull, `""`))
case "official_cit":
values = append(values, &eprint.OfficialCitation)
columnsOut = append(columnsOut, colExpr(key, ifNull, `""`))
case "monograph_type":
values = append(values, &eprint.MonographType)
columnsOut = append(columnsOut, colExpr(key, ifNull, `""`))
case "suggestions":
values = append(values, &eprint.Suggestions)
columnsOut = append(columnsOut, colExpr(key, ifNull, `""`))
case "pres_type":
values = append(values, &eprint.PresType)
columnsOut = append(columnsOut, colExpr(key, ifNull, `""`))
case "succeeds":
values = append(values, &eprint.Succeeds)
columnsOut = append(columnsOut, colExpr(key, ifNull, `0`))
case "commentary":
values = append(values, &eprint.Commentary)
columnsOut = append(columnsOut, colExpr(key, ifNull, `0`))
case "contact_email":
values = append(values, &eprint.ContactEMail)
columnsOut = append(columnsOut, colExpr(key, ifNull, `""`))
case "fileinfo":
values = append(values, &eprint.FileInfo)
columnsOut = append(columnsOut, colExpr(key, ifNull, `""`))
case "latitude":
values = append(values, &eprint.Latitude)
columnsOut = append(columnsOut, colExpr(key, ifNull, `0.0`))
case "longitude":
values = append(values, &eprint.Longitude)
columnsOut = append(columnsOut, colExpr(key, ifNull, `0.0`))
case "department":
values = append(values, &eprint.Department)
columnsOut = append(columnsOut, colExpr(key, ifNull, `""`))
case "output_media":
values = append(values, &eprint.OutputMedia)
columnsOut = append(columnsOut, colExpr(key, ifNull, `""`))
case "num_pieces":
values = append(values, &eprint.NumPieces)
columnsOut = append(columnsOut, colExpr(key, ifNull, `0`))
case "composition_type":
values = append(values, &eprint.CompositionType)
columnsOut = append(columnsOut, colExpr(key, ifNull, `""`))
case "data_type":
values = append(values, &eprint.DataType)
columnsOut = append(columnsOut, colExpr(key, ifNull, `""`))
case "pedagogic_type":
values = append(values, new(string))
columnsOut = append(columnsOut, colExpr(key, ifNull, `""`))
case "learning_level":
values = append(values, &eprint.LearningLevelText)
columnsOut = append(columnsOut, colExpr(key, ifNull, `""`))
case "completion_time":
values = append(values, &eprint.CompletionTime)
columnsOut = append(columnsOut, colExpr(key, ifNull, `""`))
case "task_purpose":
values = append(values, &eprint.TaskPurpose)
columnsOut = append(columnsOut, colExpr(key, ifNull, `""`))
case "doi":
values = append(values, &eprint.DOI)
columnsOut = append(columnsOut, colExpr(key, ifNull, `""`))
case "pmc_id":
values = append(values, &eprint.PMCID)
columnsOut = append(columnsOut, colExpr(key, ifNull, `""`))
case "pmid":
values = append(values, &eprint.PMID)
columnsOut = append(columnsOut, colExpr(key, ifNull, `""`))
case "parent_url":
values = append(values, &eprint.ParentURL)
columnsOut = append(columnsOut, colExpr(key, ifNull, `""`))
case "toc":
values = append(values, &eprint.TOC)
columnsOut = append(columnsOut, colExpr(key, ifNull, `""`))
case "interviewer":
values = append(values, &eprint.Interviewer)
columnsOut = append(columnsOut, colExpr(key, ifNull, `""`))
case "interviewdate":
values = append(values, &eprint.InterviewDate)
columnsOut = append(columnsOut, colExpr(key, ifNull, `""`))
case "nonsubj_keywords":
values = append(values, &eprint.NonSubjKeywords)
columnsOut = append(columnsOut, colExpr(key, ifNull, `""`))
case "season":
values = append(values, &eprint.Season)
columnsOut = append(columnsOut, colExpr(key, ifNull, `""`))
case "classification_code":
values = append(values, &eprint.ClassificationCode)
columnsOut = append(columnsOut, colExpr(key, ifNull, `""`))