-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbazaar_db.lua
More file actions
222 lines (168 loc) · 6.99 KB
/
bazaar_db.lua
File metadata and controls
222 lines (168 loc) · 6.99 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
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
local BazaarDB = { _version = '1.0', author = 'Derple', }
BazaarDB.__index = BazaarDB
local mq = require('mq')
local sqlite = require('lsqlite3')
local function dump(o)
if type(o) == 'table' then
local s = '{ '
for k, v in pairs(o) do
if type(k) ~= 'number' then k = '"' .. k .. '"' end
s = s .. '[\ay' .. k .. '\ax] = \am' .. dump(v) .. '\ax,'
end
return s .. '} '
else
return tostring(o)
end
end
---@param t any
---@return table
function BazaarDB.new(t)
local newBazaarDB = setmetatable(
{ itemPriceCache = {}, itemListedTimeCache = {}, historicalSales = {}, historicalItem = nil, DB = sqlite.open(t), },
BazaarDB)
return newBazaarDB
end
function BazaarDB:dbStartTransaction()
if not self["DB"] then return end
local res = 0
repeat
res = self["DB"]:exec("BEGIN IMMEDIATE TRANSACTION;")
if res == sqlite.BUSY then
mq.delay(1000)
print("\ayWaiting for DB Lock...")
end
until res ~= sqlite.BUSY
print("\agStarting DB Transaction")
end
function BazaarDB:dbCompleteTransaction()
if not self["DB"] then return end
self["DB"]:exec("COMMIT;")
print("\agCommitted DB Transaction")
end
function BazaarDB:setupDB()
if not self["DB"] then return end
self["DB"]:exec("PRAGMA journal_mode=WAL;")
assert(self["DB"]:exec "CREATE TABLE IF NOT EXISTS items (item_id INTEGER PRIMARY KEY AUTOINCREMENT, server_name TEXT NOT NULL, item_name TEXT NOT NULL);")
assert(self["DB"]:exec "CREATE TABLE IF NOT EXISTS item_prices (price_id INTEGER PRIMARY KEY AUTOINCREMENT, item_id INTEGER NOT NULL, seller_name TEXT NOT NULL, price INTEGER NOT NULL, seen_date INTEGER NOT NULL);")
assert(self["DB"]:exec "CREATE TABLE IF NOT EXISTS item_listed (listed_id INTEGER PRIMARY KEY AUTOINCREMENT, item_id INTEGER NOT NULL, price INTEGER NOT NULL, listed_date INTEGER NOT NULL);")
end
function BazaarDB:queryItemDBId(itemName)
local query_item_stmt = assert(self["DB"]:prepare "SELECT * FROM items WHERE server_name=? AND item_name=?;")
query_item_stmt:bind(1, mq.TLO.MacroQuest.Server())
query_item_stmt:bind(2, itemName)
for row in query_item_stmt:nrows() do
query_item_stmt:finalize()
return tonumber(row.item_id)
end
print(string.format("\arItem not found: %s on %s", itemName, mq.TLO.MacroQuest.Server()))
query_item_stmt:finalize()
return nil
end
function BazaarDB:insertItem(itemName)
local insert_item_stmt = assert(self["DB"]:prepare "INSERT INTO items VALUES (NULL, :server, :item);")
insert_item_stmt:bind_names { server = mq.TLO.MacroQuest.Server(), item = itemName, }
insert_item_stmt:step()
insert_item_stmt:finalize()
return self:queryItemDBId(itemName)
end
function BazaarDB:getItemDBId(itemName)
local dbid = self:queryItemDBId(itemName)
if dbid then return dbid end
-- Not in DB Add it.
self:dbStartTransaction()
dbid = self:insertItem(itemName)
self:dbCompleteTransaction()
printf("\ayCreated item in DB \at%s \ay(\am%d\ay)", itemName, dbid)
return dbid
end
function BazaarDB:insertPrice(values)
local insert_item_stmt = assert(self["DB"]:prepare "INSERT INTO item_prices VALUES (NULL, :item_id, :seller, :price, :date);")
insert_item_stmt:bind_names(values)
insert_item_stmt:step()
local result = insert_item_stmt:finalize()
print(string.format("Insert Price %s Result: \ay%d", dump(values), result))
end
function BazaarDB:cacheItemPrice(dbid, seller, price)
table.insert(self["itemPriceCache"], { item_id = dbid, seller = seller, price = price, date = os.time(), })
end
function BazaarDB:writeItemPriceCache()
if #self["itemPriceCache"] == 0 then return end
self:dbStartTransaction()
for k, v in ipairs(self["itemPriceCache"]) do
self:insertPrice(v)
end
self:dbCompleteTransaction()
self["itemPriceCache"] = {}
end
function BazaarDB:getItemListedTime(dbid)
local query_item_stmt = assert(self["DB"]:prepare "SELECT listed_date FROM item_listed WHERE item_id=? ORDER BY listed_date ASC;")
query_item_stmt:bind(1, dbid)
local last_date = nil
for date in query_item_stmt:urows() do
--print(string.format("Found listed time: \ay%s\ax for \at%s", date, itemName))
last_date = date
end
query_item_stmt:finalize()
--print(string.format("\arItem list not found: %s", itemName))
return last_date
end
function BazaarDB:getAllItems()
local query_item_stmt = assert(self["DB"]:prepare "SELECT item_id, item_name FROM items WHERE server_name=? ORDER BY item_name ASC;")
query_item_stmt:bind(1, mq.TLO.MacroQuest.Server())
local res = {}
for item_id, item_name in query_item_stmt:urows() do
--print(string.format("Found listed time: \ay%s\ax for \at%s", date, itemName))
table.insert(res, { Name = item_name, ID = item_id, })
end
query_item_stmt:finalize()
--print(string.format("\arItem list not found: %s", itemName))
return res
end
function BazaarDB:insertItemListedTime(values)
local insert_item_stmt = assert(self["DB"]:prepare "INSERT INTO item_listed VALUES (NULL, :item_id, :price, :listed_date);")
insert_item_stmt:bind_names(values)
insert_item_stmt:step()
local result = insert_item_stmt:finalize()
print(string.format("Insert Listed Time %s Result: \ay%d", dump(values), result))
return true
end
function BazaarDB:writeItemListedCache()
if #self["itemListedTimeCache"] == 0 then return end
self:dbStartTransaction()
for k, v in ipairs(self["itemListedTimeCache"]) do
self:insertItemListedTime(v)
end
self:dbCompleteTransaction()
self["itemListedTimeCache"] = {}
end
function BazaarDB:cacheItemListedTime(dbid, price, date)
table.insert(self["itemListedTimeCache"], { item_id = dbid, price = price, listed_date = date, })
end
function BazaarDB:clearHistoricalData()
self["historicalSales"] = {}
self["historicalItem"] = nil
end
function BazaarDB:loadHistoricalData(itemName, dbid)
local query_item_stmt = assert(self["DB"]:prepare "SELECT seller_name, price, seen_date FROM item_prices WHERE item_id=?;")
query_item_stmt:bind(1, dbid)
printf("\ayLoading \at%s \ay(\am%d\ay)", itemName, dbid)
self["historicalItem"] = itemName
self["historicalSales"] = {}
for trader, price, date in query_item_stmt:urows() do
table.insert(self["historicalSales"], { Trader = trader, Price = price, Date = date, })
end
query_item_stmt:finalize()
return true
end
function BazaarDB:getHistoricalData()
return self["historicalItem"], self["historicalSales"]
end
function BazaarDB:GiveTime()
self:writeItemListedCache()
self:writeItemPriceCache()
end
function BazaarDB:Shutdown()
self["DB"]:close()
self["DB"] = nil
end
return BazaarDB