WeSee
WeSee

Reputation: 3772

Yii2/PHP: Check connection to MySQL and PostgreSQL

When starting my Yii2/PHP application, how can I check if / wait until the database is up?

Currently with MySQL I use:

$time = time();
$ok = false;
do {
  try {
    $pdo = new PDO($dsn,$username,$password);
    if ($pdo->query("SELECT 1 FROM INFORMATION_SCHEMA.SCHEMATA")) 
        $ok=true;
  } catch (\Exception $e) {
    sleep(1);
  }
} while (!$ok && time()<$time+30); 

Now I want make my application running with MySQL and PostgreSQL.

But SELECT 1 FROM INFORMATION_SCHEMA.SCHEMATA does not work in PostgreSQL.

Is there a SQL-statement (using PDO database connectivity) that works on both database systems to check if the database is up and running?

Upvotes: 2

Views: 3060

Answers (2)

Alejandro
Alejandro

Reputation: 866

Yii2 has a property to verify if a connection exists or not, it is really not necessary to create a script for this, since this framework has an abstraction implemented for the databases it supports ($isActive property).

$isActive public read-only property Whether the DB connection is established

public boolean getIsActive ( )

You can do the check in your default controller in the following way:

<?php

class DefaultController extends Controller 
{
    public function init()
    {
        if (!Yii::$app->db->isActive) {
            // The connection does not exist.
        }

        parent::init();
    }
}

It is not good practice to force waiting for a connection to a database unless there are very specific requirements. The availability of a connection to the database must be a mandatory requirement for an application to start and the application should not "wait" for the database to be available.

There are ways to run containers in docker in an orderly manner or with a specific requirement, this link could give you a better option instead of delegating this to the application.

Upvotes: 5

danblack
danblack

Reputation: 14711

You could use SELECT 1 which is standard SQL.

You can use dbfiddle to test against various servers.

The server could go away an any time so checking the error response with every query is a much better approach.

Upvotes: 3

Related Questions