UNPKG

2.73 kBtext/coffeescriptView Raw
1criterion = require 'criterion'
2
3actions = require './actions'
4
5rawPrototype =
6 sql: -> @_sql
7 params: -> @_params
8
9module.exports =
10 raw: (sql, params...) ->
11 object = Object.create rawPrototype
12 object._sql = sql
13 object._params = params
14 object
15
16 fluent: (key, value) ->
17 object = Object.create @
18 object[key] = value
19 object
20
21 _escape: (string) -> string
22 _action: actions.select '*'
23 _joins: []
24
25 insert: (data) ->
26 unless 'object' is typeof data
27 throw new Error 'data argument must be an object'
28
29 @fluent '_action', actions.insert data
30
31 insertMany: (array) ->
32 unless Array.isArray array
33 throw new Error 'array argument must be an array'
34
35 throw new Error 'array argument is empty - no records to insert' if array.length is 0
36
37 msg = 'all records in the argument array must have the same keys.'
38 keysOfFirstRecord = Object.keys array[0]
39 array.forEach (data) ->
40 keys = Object.keys data
41
42 throw new Error msg if keys.length isnt keysOfFirstRecord.length
43
44 keysOfFirstRecord.forEach (key) ->
45 throw new Error msg unless data[key]?
46
47 @fluent '_action', actions.insertMany array
48
49 escape: (arg) ->
50 @fluent '_escape', arg
51
52 select: ->
53 @fluent '_action', actions.select.apply null, arguments
54
55 delete: ->
56 @fluent '_action', actions.delete()
57
58 update: (updates) ->
59 @fluent '_action', actions.update updates
60
61 join: (sql, criterionArgs...) ->
62 join = {sql: sql}
63 join.criterion = criterion criterionArgs... if criterionArgs.length isnt 0
64
65 object = Object.create @
66 # slice without arguments clones an array
67 object._joins = @_joins.slice()
68 object._joins.push join
69
70 object
71
72 with: (arg) ->
73 unless ('object' is typeof arg) and Object.keys(arg).length isnt 0
74 throw new Error 'with must be called with an object that has at least one property'
75 @fluent '_with', arg
76 group: (arg) ->
77 @fluent '_group', arg
78 order: (arg) ->
79 @fluent '_order', arg
80 limit: (arg) ->
81 @fluent '_limit', parseInt(arg, 10)
82 offset: (arg) ->
83 @fluent '_offset', parseInt(arg, 10)
84
85 table: (table) ->
86 @fluent '_table', table
87
88 where: (args...) ->
89 where = criterion args...
90 @fluent '_where', if @_where? then @_where.and(where) else where
91
92 having: (args...) ->
93 having = criterion args...
94 @fluent '_having', if @_having? then @_having.and(having) else having
95
96 sql: ->
97 @_action.sql @
98
99 params: ->
100 @_action.params @