1 | criterion = require 'criterion'
|
2 |
|
3 | actions = require './actions'
|
4 |
|
5 | rawPrototype =
|
6 | sql: -> @_sql
|
7 | params: -> @_params
|
8 |
|
9 | module.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: (sql = '*', params...) ->
|
53 | @fluent '_action', actions.select sql, params
|
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 |
|
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 | sql: ->
|
93 | throw new Error 'sql() requires call to table() before it' unless @_table?
|
94 | @_action.sql @
|
95 |
|
96 | params: ->
|
97 | @_action.params @
|