Hello everyone, I am here with yet another SQL issue.
The editor that I am currently using is "Sublime Editor". It highlights the function "sql.TableExists" but as I have learned "sql.(some sql function)" is used for SQLite. I am using MySQLoo v9. What is the best way of checking if a specific table exists in the database?
This is what I made, but it only works for SQLite, and I am using mysqloo 9
function CheckDBTables()
if( sql.TableExists( "leeroys_table" ) ) then -- this checks if the table exists. It allways returns true, and this function is for SQLite.
text( "Table(s) exists!", 0 )
else
-- create table
dbObject:at_query( "CREATE TABLE leeroys_table ( uuid bigint, money int, level int, xp int );" )--custom function that I made, it was getting annoying with queries
if( sql.TableExists( "leeroys_table" ) ) then
text( "Table was successfully created!", 0 ) -- also a custom fucntion just ignore
else
text( "Something went wrong when creating table...", 1 )
text( sql.LastError( result ), 1 )
end
end
end
My question is, is there any way I could do this in mysqloo? I haven't seen any function in the documentation.
This how garry's mod checks for tables in SQL Lite.
https://github.com/Facepunch/garrysmod/blob/a2918191191fb54c3f5ee91cfdfea4535a32ccda/garrysmod/lua/includes/util/sql.lua#L33
I'm not too familiar with MySql or MySqlOO however, something like this should work..
--[[
@brief Checks if database contains table matching exact name
@param db - Database
@param name - Exact name of table to search for
@param cb - Callback matching signature function(err, has_table)
]]
function mysqloo.TableExists(db, name, cb)
local query = db:prepare([[
SELECT
COUNT(*)
FROM information_schema.tables
WHERE
name = ?
]])
function query:onSuccess(data)
return cb(nil, #data > 0 and data[0] > 0)
end
function query:onError(err)
return cb(err)
end
query:setString(name)
query:start()
end
If it was SQL Server I could tell you with 100% certainty that `COUNT(1)` would work as well.
If you're just using the check to determine if the table should be created, why not use "CREATE TABLE IF NOT EXISTS" in the query and leave the if check out.
Also MySQLOO won't have built in shorthand functions like the SQLite provided, it provides you the ability to run queries on your MySQL instance, the rest would be up to you.
Sorry, you need to Log In to post a reply to this thread.