Search code examples
mysqlnode.jstypescriptpostgresqlknex.js

Get connection type with knex


I'm writing an application that supports MySQL and Postgres at the same time, using Knex.

For certain features the query builder doesn't cut it, and I need to write a MySQL or Postgres specific query.

What I'm looking for is a syntax such as this:

switch(knex.type) {

  case 'mysql' :
    knex.raw('...');
    break;
  case 'pg' :
    knex.raw('...');
    break;

}

I can't seem to find if there's a way to do this. Not in the documentation or in the types (so far). Is this possible?


Solution

  • I saw this while checking around, and while I was originally going to use the same environment variable I was using in the switch statement, the below seems to work fine.

    const getSqlStatement = (knex: Knex) => {
      const database = knex.client.dialect;
    
      switch (database) {
        case "mssql":
          return mssql statement;
        ... other cases
        default:
          // do nothing or throw an error or ?
      }
    };
    

    The important part was that knex.client.dialect should take care of it.