Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added Foreign & Composite Primary Key support to mysqloo driver #27

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 35 additions & 5 deletions lua/sqlier/drivers/mysqloo.lua
Original file line number Diff line number Diff line change
Expand Up @@ -52,11 +52,13 @@ function db:initialize(options)
self.Dataflow:degreeOfParallelism(1)
end

self.MaxRetries = options.maxRetries or 3
self.Connection:connect()
end

function db:validateSchema(schema)
schema.NormalizedColumnsCache = {}
schema.ForeignKeysCache = {}

for key in pairs(schema.Columns) do
schema.NormalizedColumnsCache[string.lower(key)] = true
Expand All @@ -80,14 +82,16 @@ function db:validateSchema(schema)

query = query .. type

if name == schema.Identity then
query = query .. " PRIMARY KEY"
if schema.Identity and isstring(schema.Identity) then
if schema.Identity == name then
query = query .. " PRIMARY KEY"
end
end

if options.AutoIncrement then
query = query .. " AUTO_INCREMENT"
end

if type == sqlier.Type.Timestamp and name == "CreateTimestamp" then
query = query .. " DEFAULT CURRENT_TIMESTAMP"
elseif type == sqlier.Type.Timestamp and name == "UpdateTimestamp" then
Expand All @@ -97,6 +101,28 @@ function db:validateSchema(schema)
end

query = query .. ", "

if options.Relation then
local Table = options.Relation.Table
local Column = options.Relation.Column

if (!Column || !Table) then continue end

table.insert(schema.ForeignKeysCache, { Name = name, Table = Table, Column = Column })
end
end

if istable(schema.Identity) and #schema.Identity > 0 then
print("Primary Keys Cache", schema.Identity)
PrintTable(schema.Identity)
query = query .. "PRIMARY KEY (`" .. table.concat(schema.Identity, "`, `") .. "`), "
end

if #schema.ForeignKeysCache > 0 then
for _, foreignKey in ipairs(schema.ForeignKeysCache) do
query = query .. "FOREIGN KEY (`" .. foreignKey.Name .. "`) REFERENCES `" .. foreignKey.Table .. "`(`" .. foreignKey.Column .. "`)"
query = query .. ", "
end
end

query = query:sub(1, -3) .. ")"
Expand Down Expand Up @@ -132,9 +158,13 @@ function db:query(query, callback)
end
end

self:logError("Query Failed: " .. err .. "(" .. usedQuery .. ")")
if usedQuery then
self:logError("Query failed: " .. err .. "(" .. usedQuery .. ")")
else
self:logError(err)
end

if tries < 3 then
if tries < self.MaxRetries then
tries = tries + 1
q:start()
end
Expand Down