Repository navigation
Expand file tree
/
Copy pathexample-keyvalue.lua
More file actions
69 lines (55 loc) · 1.69 KB
/
Copy pathexample-keyvalue.lua
File metadata and controls
69 lines (55 loc) · 1.69 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
--[[
This is a simple example of using SQLite for key-value storage.
Make sure your require paths are correct and that you have an sqlite library.
Usage:
local Database = require('./example-keyvalue') -- path to this file
local db = Database('test') -- open a database file by name (or create a new one)
local tbl = db:getTable('table') -- get a table by name (or create a new one)
tbl:set('foo', 'bar') -- set values
local foo = tbl:get('foo') -- get values
tbl:set('foo', nil) -- use nil to delete values
tbl:set(42, '1234') -- numbers work, too
]]
local sql = require('./sqlite3')
local f = string.format
local Database = {}
Database.__index = Database
local Table = {}
Table.__index = Table
setmetatable(Database, {__call = function(self, name)
return setmetatable({
conn = sql.open(name .. '.db'),
name = name,
}, self)
end})
function Database:getTable(name)
self.conn:exec(f("CREATE TABLE IF NOT EXISTS %q (key PRIMARY KEY, value);", name))
return Table(name, self)
end
setmetatable(Table, {__call = function(self, name, database)
local conn = database.conn
return setmetatable({
stmts = {
get = conn:prepare(f("SELECT value FROM %q WHERE key == ?;", name)),
set = conn:prepare(f("INSERT OR REPLACE INTO %q VALUES (?, ?);", name)),
delete = conn:prepare(f("DELETE FROM %q WHERE key == ?;", name)),
},
name = name,
database = database,
}, self)
end})
function Table:get(k)
local stmt = self.stmts.get
local res = stmt:reset():bind(k):step()
return res and res[1]
end
function Table:set(k, v)
if v == nil then
local stmt = self.stmts.delete
return stmt:reset():bind(k):step()
else
local stmt = self.stmts.set
return stmt:reset():bind(k, v):step()
end
end
return Database