-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathxrowset_sql.lua
276 lines (232 loc) · 7.61 KB
/
xrowset_sql.lua
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
--[[
SQL rowsets.
Written by Cosmin Apreutesei. Public Domain.
What must be specified manually:
- select : select without where clause.
- where_all : where clause for all rows (without the word "where").
- order_by : order-by clause.
- pk : 'foo bar ...', required as it can't be inferred reliably.
- db : optional, connection alias to query on.
More complex cases can specify:
- select_all : instead of select + where_all.
- where_row : where clause for single row: 'tbl.pk1 = :as_pk1 and ...'.
- select_row : instead of select + where_row.
- select_none : instead of select_row or (select + 'where 1 = 0').
If all else fails, you can always implement the rowset's S/U/I/D methods
yourself. Just make sure to wrap multiple update queries in atomic().
Inferred field attributes:
name : column alias.
type : field type.
min, max : numeric range (integers).
decimals : number of decimals (integers and decimals).
max_char_w : max length in characters in the current result set.
Additionally, for fields that can be traced back to their origin table:
enum_values : enum values.
default : default value.
not_null : not-null flag.
maxlen : max length in characters.
min, max : numeric range (decimals).
ref_table : reference table (foreign key).
ref_col : column name in reference table (single-column fk).
Fields without an origin table (SQL expressions) are made readonly.
Auto-increment fields are made readonly.
How to use rowset param values in queries:
- in where_all:
- `:param:filter`
- `tbl.pk in (:param:filter)`, if the rowset's pk is a single column.
- `$filter(foo = :foo and bar = :bar, :param:filter)` for composite pks.
- `:param:lang` : current language.
- `:param:default_lang` : default language.
- in insert and update queries:
- `:COL` : the column's new or changed value.
- in update and delete where clause:
- `:COL:old` : the column's old value.
Field methods to implement:
to_lua(v) : convert value for select result sets.
to_sql(v) : convert value for update queries (SQL statements).
to_bin(v) : convert value for update queries (prepared statements).
]]
require'xrowset'
require'webb_query'
local glue = require'glue'
local format = string.format
local concat = table.concat
local add = table.insert
local outdent = glue.outdent
local names = glue.names
local noop = glue.noop
local index = glue.index
local assertf = glue.assert
local repl = glue.repl
local memoize = glue.memoize
local sortedpairs = glue.sortedpairs
--usage in sql:
-- single-key: foo in (:param:filter)
-- multi-key : $filter(foo <=> :foo and bar <=> :bar, :param:filter)
function qmacro.filter(expr, filter)
local t = {}
for i,vals in ipairs(filter) do
t[i] = sqlparams(expr, vals)
end
return concat(t, ' or ')
end
local rowset_type = {
bool = 'bool',
tinyint = 'number',
smallint = 'number',
mediumint = 'number',
int = 'number',
bigint = 'number',
float = 'number',
double = 'number',
decimal = 'number',
year = 'number',
enum = 'enum',
timestamp = 'datetime',
datetime = 'datetime',
date = 'date',
time = 'time',
blob = 'file',
tinyblob = 'file',
mediumblob = 'file',
longblob = 'file',
}
local function guess_name_col(tdef)
if tdef.name_col then return tdef.name_col end
if tdef.fields.name then return 'name' end
end
local function lookup_rowset(tbl)
local rs = 'lookup_'..tbl
if not rowset[rs] then
local tdef = table_def(tbl)
local name_col = guess_name_col(tdef)
local t = glue.extend({name_col}, tdef.pk)
local cols = concat(glue.imap(t, sqlname), ', ')
rowset[rs] = sql_rowset{
select = format('select %s from %s', cols, tbl),
pk = concat(tdef.pk, ' '),
name_col = name_col,
}
end
return rs, rs.name_col
end
function sql_rowset(...)
return virtual_rowset(function(rs, sql, ...)
if type(sql) == 'string' then
rs.select = sql
else
update(rs, sql, ...)
end
rs.delay_init_fields = true
--the rowset's pk cannot be reliably inferred so it must be user-supplied.
rs.pk = names(rs.pk)
assert(rs.pk and #rs.pk > 0, 'pk missing')
table.sort(rs.pk)
--static query generation (just stitching together user-supplied parts).
if not rs.select_all and rs.select then
rs.select_all = outdent(rs.select)
.. (rs.where_all and '\nwhere '..rs.where_all or '')
.. (rs.order_by and '\norder by '..rs.order_by or '')
end
if not rs.select_row and rs.select and rs.where_row then
rs.select_row = outdent(rs.select) .. '\nwhere ' .. rs.where_row
end
if not rs.select_none and rs.select then
rs.select_none = rs.select .. '\nwhere 1 = 0'
end
--query wrappers.
local function query(...)
return db(rs.db):query(...)
end
--see if we can make a static load_row().
if not rs.load_row and rs.select_row then
function rs:load_row(vals)
local rows = query(rs.select_row, vals)
assert(#rows < 2, 'loaded back multiple rows for one inserted row')
return rows[1]
end
end
--dynamic generation of update queries based on the mapping of the
--selected columns to their origin tables obtained from running the
--select query the first time. if any of the update methods are called
--before the select is run, it runs the select_none query once to get
--the column mappings.
local configure
local load_opt = {
compact = true,
null_value = null,
get_table_defs = true,
field_attrs = rs.field_attrs,
}
if not rs.load_rows then
assert(rs.select_all, 'select_all missing')
function rs:load_rows(res, param_vals)
local rows, fields, params = query(load_opt, rs.select_all, param_vals)
if configure then
configure(fields)
rs.params = params
end
res.rows = rows
end
end
local user_methods = {}
assert(rs.select_none, 'select_none missing')
local apply_changes = rs.apply_changes
function rs:apply_changes(changes)
if configure then
local _, fields = query(rs.select_none)
configure(fields)
end
return apply_changes(self, changes)
end
--[[local]] function configure(fields)
configure = nil --one-shot.
rs.fields = fields
for i,f in ipairs(fields) do
f.sqltype = f.type
f.type = rowset_type[f.type]
if f.sqltype == 'tinyint' and f.digits == 1 then --only for origin columns!
f.type = 'bool'
end
if not f.col or f.auto_increment then
f.readonly = true
end
if f.ref_table then
f.lookup_rowset_name, f.display_col = lookup_rowset(f.ref_table)
f.lookup_col = f.ref_col
end
end
rs:init_fields()
local function where_row_sql()
local t = {}
for i, as_col in ipairs(rs.pk) do
local f = fields[as_col]
local tbl = f.db..'.'..f.table
local where_col = (f.table_alias or tbl)..'.'..f.col
if i > 1 then add(t, ' and ') end
add(t, where_col..' = :'..as_col)
end
return concat(t)
end
if not rs.load_row then
assert(rs.select, 'select missing to create load_row()')
local where_row = where_row_sql()
function rs:load_row(vals)
local sql = outdent(rs.select) .. (where_all
and format('\nwhere (%s) and (%s)', where_all, where_row)
or format('\nwhere %s', where_row))
return first_row(load_opt, sql, vals)
end
end
end
local function make_atomic(f)
if not f then return end
return function(...)
return atomic(f, ...)
end
end
make_atomic(rs.insert_row)
make_atomic(rs.update_row)
make_atomic(rs.delete_row)
end, ...)
end