yburon
yburon

Reputation: 151

Drupal : How can I know if the db is mysql or postgres

I have a complicated query and since I need that my module work on both mysql and postgres, I need to write two version of it.

Unfortunately, I don't know how I can check if the db I use is mysql or postgres, to know which query use. Do you know if a function can return this value?

Upvotes: 3

Views: 3735

Answers (2)

felipsmartins
felipsmartins

Reputation: 13559

As long as the abstract DatabaseConnection class extends PDO class, you can invoking pdo methods in order to know the current database driver.

For instance:

$conn = Database::getConnection();
print $conn->getAttribute($conn::ATTR_DRIVER_NAME); #returns mysql, pgsql...

There is a second way to do it using DatabaseConnection::driver():

print $conn->driver();

or DatabaseConnection::databaseType();

print $conn->databaseType();

Note that DatabaseConnection::driver() and DatabaseConnection::databaseType() are similar functions but not equals! The return value from DatabaseConnection::driver() method depends on the implementation and other factors. in the Drupal Database API page:

database.inc abstract public DatabaseConnection::driver()

This is not necessarily the same as the type of the database itself. For instance, there could be two MySQL drivers, mysql and mysql_mock. This function would return different values for each, but both would return "mysql" for databaseType().

In the most cases you just gonna want to use only $conn->getAttribute($conn::ATTR_DRIVER_NAME) or $conn->databaseType()

If you want get more specific properties, you should take advantage the PHP ReflectionClass features:

$conn = Database::getConnection();
$ref = new ReflectionClass($conn);
#ref->getProperties, ref->getConstants $ref->isAbstract...

Reference:
PDO::getAttribute
PDO::ATTR_DRIVER_NAME
Drupal Database API
Drupal Base Database API class

Upvotes: 3

Craig Ringer
Craig Ringer

Reputation: 325051

As @kordirko says, one option is to query the server version: SELECT version(); will work on both MySQL and PostgreSQL, though not most other database engines.

Parsing version strings is always a bit fragile though, and MySQL returns just a version number like 5.5.32 wheras PostgreSQL returns something like PostgreSQL 9.4devel on x86_64-unknown-linux-gnu, compiled by gcc (GCC) 4.7.2 20121109 (Red Hat 4.7.2-8), 64-bit. What do you do if you're connecting to a PostgreSQL-compatible database like EnterpriseDB Postgres Plus, or a MySQL-compatible database?

It's much safer to use the Drupal function for the purpose, DatabaseConnection::databaseType. This avoids a query round-trip to the DB, will work on databases that won't understand/accept SELECT version(), and will avoid the need to parse version strings.

You'll find this bug report useful; it suggests that the correct usage is Database::getConnection()->databaseType().

(I've never even used Drupal, I just searched for this).

Upvotes: 7

Related Questions