We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Verify if table exist

Hi,

It's possible to verify if the table exist before execute any request ?

to avoid putting a catch everywhere.

For exemple, in the onConstruct method.

Yes, there is method tableExists in in db service.



4.2k

Have you an exemple or link for doc ? I don't find anythink...



145.0k
Accepted
answer
edited Oct '19

https://github.com/phalcon/cphalcon/blob/3.4.x/phalcon/db/adapter.zep#L689

Just do:

$tableExists = $this->getDI()->get('db')->tableExists($tableName, $schemaName);


4.2k
edited Oct '19

Can I do this on my models ?

public function initialize()
    {
        if (!$this->getDI()->get('db')->tableExist('signup'))
        {
            $logger = \Phalcon\DI::getDefault()->get('logger');
            $logger->error("La table Signup n'éxiste pas");
            throw new Phalcon\Mvc\Dispatcher\Exception();
        }
    }

What's your purpose for checking if a table exists? The code you wrote should work, but I don't think you should need to have that code.



4.2k
edited Oct '19

I need this code, because when our provider deploys the application, it can forget to initialize the database. It's only for that....

Thanks for your help.

I would suggest, then, that you tie in some table-checking code into deployment or a one-time task. Checking the table's existence on every model initialization is adding a lot of unnecessary, repeated overhead.



4.2k

I'm agree. But it's not me who deploy and if i do a update they can forgot to update the database. I'm just the developper, the deployment script is not develop by me...

Why not put it on composer script maybe or something like this? Not sure how update is made.



4.2k

The app is use by 11 companies, with different design, the same "core" but different design. Our provider have created different git repositories. They have 1 script for generate the docker and the app with only variable for the configuration.

Maybe compos is better, but I do not have the knowledge on the subject, I'm not a web developer and I do not have the time to train on it. The fun of work world.

Ok, how about tying something into your index.php or bootstrap.php file. A script that checks the existence of all tables once per session, rather than checking for multiple tables each page load.



4.2k

I have only 3 tables, and they are call only in 1 or 2 actions, the rest of the data is in a WebService. Maybe my code is good for my app ?

Because, now i have only 3 tables, but in the future i don't know, so if i need to check all, i can forgot one.