Skip to content

Instantly share code, notes, and snippets.

@honewatson
Forked from whodidthis/queries.sql
Created April 5, 2016 23:50
Show Gist options
  • Save honewatson/f2628ef142db188bf536ed28eb320b6b to your computer and use it in GitHub Desktop.
Save honewatson/f2628ef142db188bf536ed28eb320b6b to your computer and use it in GitHub Desktop.
YES for pgmoon too, because YeSQL
-- name: get_cools
SELECT *
FROM cools
-- name: insert_a_cool
INSERT INTO cools
(name, why)
VALUES
(?, ?)
RETURNING level
-- init_by_lua
local pgmoon = require "pgmoon"
yesql = require "yesql"
pg = pgmoon.new({database = "such"})
queries = yesql.loadqueries("/home/myuser/myproject/queries.sql")
-- such a serving of request
assert(pg:connect())
local query = yesql.fill(queries["insert_a_cool"], "kris", "he is such a cool jenkins")
local put = pg:query(query)
pg:keepalive()
ngx.say("kris on a level of: " .. put[1].level)
local function fill(sql, ...)
local i = 1
local arg = {...}
while i <= #arg do
local a = arg[i]
if type(a) == "string" then
a = "'" .. string.gsub(a, "'", "''") .. "'"
elseif type(a) == "number" then
a = tostring(a)
elseif type(a) == "boolean" then
a = a and "TRUE" or "FALSE"
end
sql = string.gsub(sql, "?", a, 1)
i = i + 1
end
return sql
end
local function loader(file)
local f = io.open(file, "rb")
assert(f, "file not found")
local c = f:read("*all")
f:close()
return c
end
local function splitter(text)
local pieces = {}
local i = 1
repeat
local f1s, f1e = string.find(text, "-- name:", i)
local f2s, f2e = string.find(text, "-- name:", f1e)
if f2s then
f2s = f2s - 1
end
local piece = string.sub(text, i, f2s)
local name, query = string.match(piece, "-- name:%s*([^%s]+)%s*\n%s*(.-)%s*$")
pieces[name] = query
i = f2s or #text
until i >= #text
return pieces
end
local function loadqueries(file)
local text = loader(file)
local pieces = splitter(text)
return pieces
end
return {fill = fill, loadqueries = loadqueries}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment