summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorPixel <pixel@nobis-crew.org>2008-10-06 16:18:09 -0700
committerPixel <pixel@nobis-crew.org>2008-10-06 16:18:09 -0700
commit372a85a4b0f850abe0f3457eaefb0951102d54ff (patch)
treee6153ecd6ab7a9fa85fac09bf0718a516249d645
parent8d1517ed8c7f253a6efc4d153836159138ed9fac (diff)
Adding some early foreign key system.
-rw-r--r--lib/dblib.lua48
1 files changed, 40 insertions, 8 deletions
diff --git a/lib/dblib.lua b/lib/dblib.lua
index 0c07edd..ffd93e6 100644
--- a/lib/dblib.lua
+++ b/lib/dblib.lua
@@ -459,7 +459,7 @@ _luadb = {
return t._.db._.conn:NumAffectedRows()
end,
- iselect = function(t, fields, bypass)
+ iselect = function(bypass, t, fields, foreign, options)
local stmt = "SELECT "
local first = true
local k, v
@@ -468,7 +468,16 @@ _luadb = {
stmt = stmt .. "*"
else
for k, v in pairs(fields) do
- if not bypass and not t._.ddl[v] then
+ local is_foreign = false
+ if foreign then
+ local _, f
+ for _, f in pairs(foreign) do
+ if f._.ddl[v] then
+ is_foreign = true
+ end
+ end
+ end
+ if not bypass and not is_foreign and not t._.ddl[v] then
error("Trying to select a field which doesn't exist: " .. k .. " - inside of table " .. t._.tablename)
end
if not first then
@@ -484,7 +493,30 @@ _luadb = {
end
end
- stmt = stmt .. " FROM " .. t._.tname .. " WHERE " .. t._.conditions
+ if foreign then
+ local foreign_conds = "1"
+ stmt = stmt .. " FROM " .. t._.tname
+ local found_table, fname, f
+ for k, v in foreign do
+ stmt = stmt .. ", " .. v._.tname
+ found_table = false
+ for fname, f in pairs(t._.ddl) do
+ if f.foreign and f.foreign.tablename == v._.tablename then
+ if not v._.ddl[f.foreign.fieldname] then
+ error("Foreign key points to an unknown field in table: " .. f.foreign.tablename .. "." .. f.foreign.fieldname)
+ end
+ foreign_conds = foreign_conds .. " AND " .. t._.tname .. ".`" .. fname .. "`=" .. v._.tname .. ".`" .. f.foreign.fieldname .. "`"
+ found_table = true
+ end
+ end
+ if not found_table then
+ error("Foreign table " .. v._.tablename .. " specified in request didn't match any of the foreign key of table " .. t._.tablename)
+ end
+ end
+ stmt = stmt .. " WHERE (" .. t._.conditions .. ") AND (" .. foreign_conds .. ")"
+ else
+ stmt = stmt .. " FROM " .. t._.tname .. " WHERE " .. t._.conditions
+ end
if t._.db:SafeQuery(stmt) ~= 0 then
error("Error selecting row(s) inside table " .. t._.tablename .. ": " .. t._.db:Error())
@@ -499,8 +531,8 @@ _luadb = {
end
end,
- select = function(t, fields)
- return _luadb.iselect(t, fields)
+ select = function(...)
+ return _luadb.iselect(false, ...)
end,
numrows = function(t)
@@ -512,12 +544,12 @@ _luadb = {
end,
count = function(t)
- _luadb.iselect(t, {"COUNT(*) AS count"}, true)
+ _luadb.iselect(true, t, {"COUNT(*) AS count"})
return t:nextrow().count
end,
- gselect = function(t, fields)
- _luadb.iselect(t, fields)
+ gselect = function(t, ...)
+ _luadb.iselect(false, t, ...)
return t.nextrow, t
end,