Question

I searched for similar questions but all I got is "CREATE TABLE IF NOT EXISTS".

That's not what I want at all! I only want to check whether the 5 needed tables exist or not, creating them is an entirely different thing.

Meaning I just want the "IF NOT EXISTS" part, without the "CREATE TABLE". Is there anyway to do it with Idiorm?

P/S: if possible, please write the entire code line (for example ORM::raw_execute('query') or something). I have almost no experience working with database queries :( )

Was it helpful?

Solution

After spending hours into this, the problem came to: "how do I run execute a sql query in paris/idiorm and get the query result?"

Ididorm's raw_execute() doesn't return the query result but instead return true if the query was executed successfully and false otherwise.

In the end, I solved the problem with:

ORM::for_table('')->raw_query("SQL query to check for existence of the table")->find_one();

Instead of giving a table name as parameter for for_table(), I gave it an empty string then call a raw_query(), which is equivalent to just calling a raw query directly. It worked in my case. I also had to reset Idiorm's db connection and clear the cache for it to work when switching between different dbs.

OTHER TIPS

On MySql you can query an information_schema.tables view

SELECT n.table_name,
       case when x.table_name is null
            then 'Does not exist'
            else 'Exists'
       end as chk
FROM (
    select 'mytable' as table_name union all
    select 'table1' union all
    select 'tbl1' union all
    select 'another_table' union all
    select 'fifth_table'
) n
LEFT JOIN information_schema.tables x
ON ( x.table_schema = 'test' AND x.table_name = n.table_name );



+ --------------- + -------------- +
| table_name      | chk            |
+ --------------- + -------------- +
| mytable         | Exists         |
| tbl1            | Exists         |
| table1          | Does not exist |
| another_table   | Does not exist |
| fifth_table     | Does not exist |
+ --------------- + -------------- +
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top