-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsql.lua
More file actions
79 lines (72 loc) · 2.45 KB
/
sql.lua
File metadata and controls
79 lines (72 loc) · 2.45 KB
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
------------------------------------------------------------------------------
-- Module for SQL generation
------------------------------------------------------------------------------
local _ = require 'underscore'
local string_ext = require 'string_ext'
local M = {}
------------------------------------------------------------------------------
-- Generate the sql for the given field def flags
------------------------------------------------------------------------------
local sqlForFieldFlags = function(fieldDef)
if fieldDef.flags ~= nil then
return _.join(fieldDef.flags, ' '):upper()
else
return ''
end
end
M.sqlForFieldFlags = sqlForFieldFlags
------------------------------------------------------------------------------
-- Generate a CREATE TABLE IF NOT EXISTS statement
-- for the given tablename and tablefield definitions
------------------------------------------------------------------------------
local generateCreateTable = function(tableName, tableFields)
local result = ''
result = 'CREATE TABLE IF NOT EXISTS ' .. tableName .. '('
for fieldName,fieldDef in pairs(tableFields) do
result = result .. string_ext.doubleQuote(fieldName) .. ' ' .. fieldDef.dataType:upper()
result = result .. ' ' .. M.sqlForFieldFlags(fieldDef)
result = result .. ','
end
result = string.sub( result, 1, result:len()-1 )
result = result .. ')'
return result
end
M.generateCreateTable = generateCreateTable
------------------------------------------------------------------------------
-- Generate a SELECT statement
--
-- Parameters:
-- tableName
-- columns
-- where
-- order
-- limit
------------------------------------------------------------------------------
local generateSelect = function(params)
local tableName = ''
if params.tableName == nil or params.tableName == '' then
return ''
else
tableName = params.tableName
end
local columns = ''
if params.columns == nil or params.columns == '' then
columns = '*'
else
columns = params.columns
end
local result = ''
result = 'SELECT ' .. columns .. ' FROM ' .. tableName
if params.where ~= nil and params.where ~= '' then
result = result .. ' WHERE ' .. params.where
end
if params.order ~= nil and params.order ~= '' then
result = result .. ' ORDER BY ' .. params.order
end
if params.limit ~= nil and params.limit ~= '' then
result = result .. ' LIMIT ' .. params.limit
end
return result
end
M.generateSelect = generateSelect
return M