@@ -11,6 +11,77 @@ const isLite = knex => {
11
11
12
12
module . exports = knex => {
13
13
14
+ const dateParse = exp => {
15
+ return isLite ( knex )
16
+ ? knex . raw ( `strftime('%Y-%m-%dT%H:%M:%fZ', ${ exp } )` )
17
+ : knex . raw ( exp )
18
+ }
19
+
20
+ const dateFormat = date => {
21
+ const iso = moment ( date ) . toDate ( ) . toISOString ( )
22
+ return dateParse ( `'${ iso } '` )
23
+ }
24
+
25
+ const columnOrDateFormat = colOrDate => {
26
+ const lite = isLite ( knex )
27
+
28
+ if ( colOrDate . sql ) {
29
+ return colOrDate . sql
30
+ }
31
+
32
+ if ( typeof colOrDate === 'string' ) {
33
+ return lite ? dateParse ( colOrDate ) : `"${ colOrDate } "`
34
+ }
35
+
36
+ return dateFormat ( colOrDate )
37
+ }
38
+
39
+ return {
40
+ isLite : ( ) => isLite ( knex ) ,
41
+
42
+ // knex's createTableIfNotExists doesn't work with postgres
43
+ // https://github.com/tgriesser/knex/issues/1303
44
+ createTableIfNotExists : ( tableName , cb ) => {
45
+ return knex . schema . hasTable ( tableName )
46
+ . then ( exists => {
47
+ if ( exists ) return
48
+ return knex . schema . createTableIfNotExists ( tableName , cb )
49
+ } )
50
+ } ,
51
+
52
+ date : {
53
+ format : dateFormat ,
54
+
55
+ now : ( ) => isLite ( knex ) ? knex . raw ( "strftime('%Y-%m-%dT%H:%M:%fZ', 'now')" ) : knex . raw ( 'now()' ) ,
56
+
57
+ isBefore : ( d1 , d2 ) => {
58
+ d1 = columnOrDateFormat ( d1 )
59
+ d2 = columnOrDateFormat ( d2 )
60
+
61
+ return knex . raw ( d1 + ' < ' + d2 )
62
+ } ,
63
+
64
+ isAfter : ( d1 , d2 ) => {
65
+ d1 = columnOrDateFormat ( d1 )
66
+ d2 = columnOrDateFormat ( d2 )
67
+
68
+ return knex . raw ( d1 + ' > ' + d2 )
69
+ } ,
70
+
71
+ isBetween : ( d1 , d2 , d3 ) => {
72
+ d1 = columnOrDateFormat ( d1 )
73
+ d2 = columnOrDateFormat ( d2 )
74
+
75
+ return knex . raw ( `${ d1 } BETWEEN ${ d2 } AND ${ d3 } ` )
76
+ } ,
77
+
78
+ isSameDay : ( d1 , d2 ) => {
79
+ d1 = columnOrDateFormat ( d1 )
80
+ d2 = columnOrDateFormat ( d2 )
81
+
82
+ return knex . raw ( `date(${ d1 } ) = date(${ d2 } )` )
83
+ }
84
+ }
14
85
15
86
}
16
87
}
0 commit comments