Skip to content

Instantly share code, notes, and snippets.

@Python1320
Last active August 29, 2015 14:05
Show Gist options
  • Save Python1320/eec8cdc84828a8261b00 to your computer and use it in GitHub Desktop.
Save Python1320/eec8cdc84828a8261b00 to your computer and use it in GitHub Desktop.
print(date('now','start of year','+9 months','weekday 2'))
-- http://www.sqlite.org/lang_corefunc.html#last_insert_rowid
function sql.LastRowID()
local ret = sql.Query("SELECT last_insert_rowid() as x")[1].x
return ret
end
-- http://www.tutorialspoint.com/sqlite/sqlite_date_time.htm
local escape=sql.SQLStr
local function gen_datefunc(fname)
local beginning = "SELECT "..fname.."("
local function func(...)
local mods = {...}
for k,v in next,mods do
mods[k]=isnumber(v) and v or escape(v)
end
local q=beginning..table.concat(mods,",")..") as x;"
local ret = sql.Query(q)
ret = ret and ret[1]
ret = ret and ret.x
ret = ret and ret~="NULL" and ret
return ret
end
sql[fname]=func
_G[fname]=func
end
gen_datefunc'date'
gen_datefunc'time'
gen_datefunc'datetime'
gen_datefunc'julianday'
gen_datefunc'strftime'
print(date('now','start of year','+9 months','weekday 2'))
print(julianday('now'))
print(time('12:00', 'localtime'))
print(time('12:00', 'utc'))
-- Example command: sql .tables
-- Return serverside data by calling with: cmd sql .tables
local commands={
tables="SELECT name FROM sqlite_master WHERE type='table'"
}
concommand.Add("sql",function(pl,_,_,line)
if SERVER and pl:IsValid() and not pl:IsSuperAdmin() then return end
local function out(...)
if SERVER and pl and pl:IsValid() then
pl:ChatPrint(table.concat({"SQL>",...}," "))
else
Msg"[SQL] " print(...)
end
end
local cmd,arg = line:match'^%.(%w+) (.*)$'
if not arg then
cmd = line:match'^%.(%w+)$'
end
if cmd then
cmd=commands[cmd]
if not cmd then out"Unknown command" return end
if isfunction(cmd) then
cmd=cmd(arg,line)
if not cmd then return end
end
line=cmd
end
local ret = sql.Query(line..';')
if ret == false then
out("Error: "..tostring(sql.LastError()))
elseif ret==nil then
out"Command executed succesfully"
elseif not istable(ret) then
out("Unhandled value: "..tostring(ret))
elseif not next(ret) then
out"Empty result set returne"
else
out ("Query results: "..table.Count(ret))
for k,v in next,ret do
if k>50 then
out"--- truncated ---"
break
end
local t={}
for kk,vv in next,v do
t[#t+1] = string.format("%s = %s",kk,isstring(vv) and tonumber(vv) and vv or ("%q"):format(vv) or tostring(vv))
end
out(table.concat(t," "))
end
end
end)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment