This repository has been archived by the owner on Nov 9, 2021. It is now read-only.
/
squel.coffee
660 lines (511 loc) · 17.9 KB
/
squel.coffee
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
###
Copyright (c) 2012 Ramesh Nair (hiddentao.com)
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
###
# Extend given object's with other objects' properties, overriding existing ones if necessary
_extend = (dst, sources...) ->
if sources
for src in sources
if src
for own k,v of src
dst[k] = v
dst
# An SQL expression builder.
#
# SQL expressions are used in WHERE and ON clauses to filter data by various criteria.
#
# This builder works by building up the expression as a hierarchical tree of nodes. The toString() method then
# traverses this tree in order to build the final expression string.
#
# Expressions can be nested. Nested expression contains can themselves contain nested expressions.
# When rendered a nested expression will be fully contained within brackets.
#
# All the build methods in this object return the object instance for chained method calling purposes.
class Expression
# The expression tree.
tree: null
# The part of the expression tree we're currently working on.
current: null
# Initialise the expression.
constructor: ->
@tree =
parent: null
nodes: []
@current = @tree
# Begin a nested expression and combine it with the current expression using the given operator.
@_begin = (op) =>
new_tree =
type: op
parent: @current
nodes: []
@current.nodes.push new_tree
@current = @current.nodes[@current.nodes.length-1]
@
# Begin a nested expression and combine it with the current expression using the intersection operator (AND).
and_begin: =>
@_begin 'AND'
# Begin a nested expression and combine it with the current expression using the union operator (OR).
or_begin: =>
@_begin 'OR'
# End the current compound expression.
#
# This will throw an error if begin() hasn't been called yet.
end: =>
if not @current.parent
throw new Error "begin() needs to be called"
@current = @current.parent
@
# Combine the current expression with the given expression using the intersection operator (AND).
and: (expr) =>
if not expr or "string" isnt typeof expr
throw new Error "expr must be a string"
@current.nodes.push
type: 'AND'
expr: expr
@
# Combine the current expression with the given expression using the union operator (OR).
or: (expr) =>
if not expr or "string" isnt typeof expr
throw new Error "expr must be a string"
@current.nodes.push
type: 'OR'
expr: expr
@
# Get the final fully constructed expression string.
toString: =>
if null isnt @current.parent
throw new Error "end() needs to be called"
_toString @tree
# Get a string representation of the given expression tree node.
_toString = (node) ->
str = ""
for child in node.nodes
if child.expr?
nodeStr = child.expr
else
nodeStr = _toString(child)
# wrap nested expressions in brackets
if "" isnt nodeStr
nodeStr = "(" + nodeStr + ")"
if "" isnt nodeStr
# if this isn't first expression then add the operator
if "" isnt str then str += " " + child.type + " "
str += nodeStr
str
# Default builder options.
DefaultInsertBuilderOptions = DefaultUpdateBuilderOptions =
# If true then field values will not be rendered inside quotes so as to allow for field value placeholders (for
# parameterized querying).
usingValuePlaceholders: false
# Base class for all query builders
class QueryBuilder
# Get class name of given object.
_getObjectClassName: (obj) ->
if obj && obj.constructor && obj.constructor.toString
arr = obj.constructor.toString().match /function\s*(\w+)/;
if arr && arr.length is 2
return arr[1]
return undefined
# Sanitize the given condition.
_sanitizeCondition: (condition) ->
t = typeof condition
c = @_getObjectClassName(condition)
if 'Expression' isnt c and "string" isnt t
throw new Error "condition must be a string or Expression instance"
# If it's an expression builder instance then convert it to string form.
if 'Expression' is t or 'Expression' is c
condition = condition.toString()
condition
# Sanitize the given name.
# The 'type' parameter is used to construct a meaningful error message in case validation fails.
_sanitizeName: (value, type) ->
if "string" isnt typeof value
throw new Error "#{type} must be a string"
value
_sanitizeField: (item) -> @_sanitizeName item, "field name"
_sanitizeTable: (item) -> @_sanitizeName item, "table name"
_sanitizeAlias: (item) -> @_sanitizeName item, "alias"
# Sanitize the given limit/offset value.
_sanitizeLimitOffset: (value) ->
value = parseInt(value)
if 0 > value
throw new Error "limit/offset must be >=0"
value
# Santize the given field value
_sanitizeValue: (item) ->
t = typeof item
if null isnt item and "string" isnt t and "number" isnt t and "boolean" isnt t
throw new Error "field value must be a string, number, boolean or null"
item
# Format the given field value for inclusion into the query string
#
# options: see DefaultBuilderOptions
_formatValue: (value, options) ->
if null is value
value = "NULL"
else if "boolean" is typeof value
value = if value then "TRUE" else "FALSE"
else if "number" isnt typeof value
if not options or false is options.usingValuePlaceholders
value = "'#{value}'"
value
# Base class for query builders which support WHERE, ORDER and LIMIT clauses.
class WhereOrderLimit extends QueryBuilder
wheres: null
orders: null
limits: null
constructor: ->
super
@wheres = []
@orders = []
# Add a WHERE condition.
#
# When the final query is constructed all the WHERE conditions are combined using the intersection (AND) operator.
where: (condition) =>
condition = @_sanitizeCondition(condition)
if "" isnt condition
@wheres.push condition
@
# Add an ORDER BY transformation for the given field in the given order.
#
# To specify descending order pass false for the 'asc' parameter.
order: (field, asc = true) =>
field = @_sanitizeField(field)
@orders.push
field: field
dir: if asc then "ASC" else "DESC"
@
# Set the LIMIT transformation.
#
# Call this will override the previously set limit for this query. Also note that Passing 0 for 'max' will remove
# the limit.
limit: (max) =>
max = @_sanitizeLimitOffset(max)
@limits = max
@
# Get string representation of WHERE clause, if any
whereString: =>
if 0 < @wheres.length
" WHERE (" + @wheres.join(") AND (") + ")"
else
""
# Get string representation of ORDER BY clause, if any
orderString: =>
if 0 < @orders.length
orders = ""
for o in @orders
orders += ", " if "" isnt orders
orders += "#{o.field} #{o.dir}"
" ORDER BY #{orders}"
else
""
# Get string representation of LIMIT clause, if any
limitString: =>
if @limits
" LIMIT #{@limits}"
else
""
# Base class for query builders with JOIN clauses.
class JoinWhereOrderLimit extends WhereOrderLimit
joins: null
constructor: ->
super
# Add a JOIN with the given table.
#
# 'type' must be either one of inner, outer, left or right. Default is 'inner'.
#
# 'table' is the name of the table to join with.
#
# 'alias' is an optional alias for the table name.
#
# 'condition' is an optional condition (containing an SQL expression) for the JOIN. If this is an instance of
# an expression builder then it will only get evaluated during the final query string construction phase in
# toString().
@_join = (type, table, alias, condition) =>
table = @_sanitizeTable(table)
alias = @_sanitizeAlias(alias) if alias
condition = @_sanitizeCondition(condition) if condition
@joins.push
type: type
table: table
alias: alias
condition: condition
@
# Add an INNER JOIN with the given table.
join: (table, alias = null, condition = null) =>
@_join 'INNER', table, alias, condition
# Add a LEFT JOIN with the given table.
left_join: (table, alias = null, condition = null) =>
@_join 'LEFT', table, alias, condition
# Add a RIGHT JOIN with the given table.
right_join: (table, alias = null, condition = null) =>
@_join 'RIGHT', table, alias, condition
# Add an OUTER JOIN with the given table.
outer_join: (table, alias = null, condition = null) =>
@_join 'OUTER', table, alias, condition
# Get string representation of JOIN clauses, if any
joinString: =>
joins = ""
for j in (@joins or [])
joins += " #{j.type} JOIN #{j.table}"
joins += " `#{j.alias}`" if j.alias
joins += " ON (#{j.condition})" if j.condition
joins
# A SELECT query builder.
#
# Note that the query builder does not check the final query string for correctness.
#
# All the build methods in this object return the object instance for chained method calling purposes.
class Select extends JoinWhereOrderLimit
froms: null
fields: null
groups: null
offsets: null
useDistinct: false
constructor: ->
super
@froms = []
@fields = []
@joins = []
@groups = []
# Add the DISTINCT keyword to this query.
distinct: =>
@useDistinct = true
@
# Read data from the given table.
#
# An alias may also be specified for the table.
from: (table, alias = null) =>
table = @_sanitizeTable(table)
alias = @_sanitizeAlias(alias) if alias
@froms.push
name: table
alias: alias
@
# Add the given field to the final result set.
#
# The 'field' parameter does not necessarily have to be a fieldname. It can use database functions too,
# e.g. DATE_FORMAT(a.started, "%H")
#
# An alias may also be specified for this field.
field: (field, alias = null) =>
field = @_sanitizeField(field)
alias = @_sanitizeAlias(alias) if alias
@fields.push
field: field
alias: alias
@
# Add a GROUP BY transformation for the given field.
group: (field) =>
field = @_sanitizeField(field)
@groups.push field
@
# Set the OFFSET transformation.
#
# Call this will override the previously set offset for this query. Also note that Passing 0 for 'max' will remove
# the offset.
offset: (start) =>
start = @_sanitizeLimitOffset(start)
@offsets = start
@
# Get the final fully constructed query string.
toString: =>
# basic checks
if 0 >= @froms.length
throw new Error "from() needs to be called"
ret = "SELECT "
# distinct
ret += "DISTINCT " if @useDistinct
# fields
fields = ""
for field in @fields
fields += ", " if "" isnt fields
fields += field.field
fields += " AS \"#{field.alias}\"" if field.alias
ret += if "" is fields then "*" else fields
# tables
tables = ""
for table in @froms
tables += ", " if "" isnt tables
tables += table.name
tables += " `#{table.alias}`" if table.alias
ret += " FROM #{tables}"
# joins
ret += @joinString()
# where
ret += @whereString()
# group by
if 0 < @groups.length
groups = ""
for f in @groups
groups += ", " if "" isnt groups
groups += f
ret += " GROUP BY #{groups}"
# order by
ret += @orderString()
# limit
ret += @limitString()
# offset
ret += " OFFSET #{@offsets}" if @offsets
ret
# An UPDATE query builder.
#
# Note that the query builder does not check the final query string for correctness.
#
# All the build methods in this object return the object instance for chained method calling purposes.
class Update extends WhereOrderLimit
tables: null
fields: null
options: null
# options: see DefaultBuilderOptions
constructor: (options) ->
super
@tables = []
@fields = {}
@options = _extend {}, DefaultUpdateBuilderOptions, options
# Update the given table.
#
# An alias may also be specified for the table.
table: (table, alias = null) =>
table = @_sanitizeTable(table)
alias = @_sanitizeAlias(alias) if alias
@tables.push
name: table
alias: alias
@
# Update the given field with the given value.
# This will override any previously set value for the given field.
set: (field, value) =>
field = @_sanitizeField(field)
value = @_sanitizeValue(value)
@fields[field] = value
@
# Get the final fully constructed query string.
toString: =>
# basic checks
if 0 >= @tables.length then throw new Error "table() needs to be called"
fieldNames = (field for own field of @fields)
if 0 >= fieldNames.length then throw new Error "set() needs to be called"
ret = "UPDATE "
# tables
tables = ""
for table in @tables
tables += ", " if "" isnt tables
tables += table.name
tables += " AS `#{table.alias}`" if table.alias
ret += tables
# fields
fields = ""
for field in fieldNames
fields += ", " if "" isnt fields
fields += "#{field} = #{@_formatValue(@fields[field], @options)}"
ret += " SET #{fields}"
# where
ret += @whereString()
# order by
ret += @orderString()
# limit
ret += @limitString()
ret
# A DELETE query builder.
#
# Note that the query builder does not check the final query string for correctness.
#
# All the build methods in this object return the object instance for chained method calling purposes.
class Delete extends JoinWhereOrderLimit
table: null
# The table to delete from.
# Calling this will override any previously set value.
from: (table) =>
table = @_sanitizeTable(table)
@table = table
@
# Get the final fully constructed query string.
toString: =>
# basic checks
if not @table then throw new Error "from() needs to be called"
ret = "DELETE FROM #{@table}"
# joins
ret += @joinString()
# where
ret += @whereString()
# order by
ret += @orderString()
# limit
ret += @limitString()
ret
# An INSERT query builder.
#
# Note that the query builder does not check the final query string for correctness.
#
# All the build methods in this object return the object instance for chained method calling purposes.
class Insert extends QueryBuilder
table: null
fields: null
options: null
# options: see DefaultBuilderOptions
constructor: (options) ->
super
@fields = {}
@options = _extend {}, DefaultInsertBuilderOptions, options
# The table to insert into.
# This will override any previously set value.
into: (table) =>
table = @_sanitizeTable(table)
@table = table
@
# Set the given field to the given value.
# This will override any previously set value for the given field.
set: (field, value) =>
field = @_sanitizeField(field)
value = @_sanitizeValue(value)
@fields[field] = value
@
# Get the final fully constructed query string.
toString: =>
# basic checks
if not @table then throw new Error "into() needs to be called"
fieldNames = (name for own name of @fields)
if 0 >= fieldNames.length then throw new Error "set() needs to be called"
# fields
fields = ""
values = ""
for field in fieldNames
fields += ", " if "" isnt fields
fields += field
values += ", " if "" isnt values
values += @_formatValue(@fields[field], @options)
"INSERT INTO #{@table} (#{fields}) VALUES (#{values})"
# Export everything as easily usable methods.
_export = {
expr: -> new Expression
select: -> new Select
update: (options) -> new Update(options)
insert: (options) -> new Insert(options)
delete: -> new Delete
Expression
QueryBuilder
Select
Update
Insert
Delete
}
module?.exports = _export
window?.squel = _export