0

I'm facing an issue when trying to deploy a Node.js API that uses Knex, Express, and the SQLite database on Vercel. Since Vercel doesn't support SQLite, I'm seeking guidance on how to transform my project from using SQLite to PostgreSQL, which is supported by Vercel.

I'm following the Vercel guide for PostgreSQL: Vercel PostgreSQL Quickstart.

Here's my current knexfile.js file, which configures Knex to use SQLite:

const path = require('path');

module.exports = {
  development: {
    client: 'sqlite3',
    connection: {
      filename: path.resolve(__dirname, 'src', 'database', 'database.db'),
    },
    pool: {
      afterCreate: (conn, cb) => conn.run('PRAGMA foreign_keys = ON', cb),
    },
    migrations: {
      directory: path.resolve(
        __dirname,
        'src',
        'database',
        'knex',
        'migrations'
      ),
    },
    useNullAsDefault: true,
  },
};

I've already tried to change it to:

const path = require('path');

module.exports = {
  development: {
    client: 'pg',
    connection: {
      host: process.env.POSTGRES_HOST,
      user: process.env.POSTGRES_USER,
      password: process.env.POSTGRES_PASSWORD,
      database: process.env.POSTGRES_DATABASE,
      ssl: { rejectUnauthorized: false },
    },
    pool: {
      afterCreate: (conn, cb) => conn.run('PRAGMA foreign_keys = ON', cb),
    },
    migrations: {
      directory: path.resolve(
        __dirname,
        'src',
        'database',
        'knex',
        'migrations'
      ),
    },
    useNullAsDefault: true,
  },
};

But I only get errors, such as TypeError: conn.run is not a function at afterCreate (/var/task/knexfile.js:14:39).

3
  • 1) This 'PRAGMA foreign_keys = ON' will not work with Postgres. 2) I don't use Knex. I did find this example afterCreate for Postgres, that differs from what you show. I'm guessing conn.run is not something the pg driver supports. Commented Dec 27, 2023 at 16:12
  • It basically triggers a cascade reaction when deleting a record; those records with foreign keys are also deleted. An example is a 'users' table and an 'orders' table: when a user is deleted, their orders are also deleted. Is it possible to enable this in PostgreSQL? Commented Dec 27, 2023 at 21:22
  • I know what it does, but its a SQLite specific feature. It is there because at one time SQLite did not enforce FK constraints. The default is to still not to enforce them, which is why you have to invoke 'PRAGMA foreign_keys = ON'. In Postgres: a) There is no PRAGMA command. b) FK's are enforced by default. Commented Dec 27, 2023 at 22:17

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.