Search code examples
javascripttypescriptknex.js

Knex tries to use sqlite3 when already using mysql2


I'm trying to run some operations on a Node Typescript project with knex. It is already configured and when using knex-cli to create or run migrations (just as an example) it works perfectly fine. The problem comes when I try to execute a normal operation e.g. insert, when I try to run, it throws an error:

Knex: run\n$ npm install sqlite3 --save\nCannot find module 'sqlite3'\

And that's pretty weird because the knexfile.ts is already configured.

Here I show the files:

knexfile.ts

import type { Knex } from "knex";

const config: { [key: string]: Knex.Config } = {
  development: {
    client: 'mysql2',
        connection: {
            host: 'localhost',
            database:  'test',
            user: 'root',
            password: 'root',
            port: 6033,
        },
        migrations: {
            directory: './src/infrastructure/repositories/mysql/migrations',
        },
        seeds: {
            directory: './src/infrastructure/repositories/mysql/seeds',
        }
  },
};

module.exports = config;

The part that is not working:

root.ts

import { FastifyPluginAsync } from 'fastify'
import knex from 'knex'


const root: FastifyPluginAsync = async (fastify, opts): Promise<void> => {
  
  fastify.post('/create', async(request, reply) => {

    // const knexapp = knex({
    //   client: 'mysql2',
    //       connection: {
    //           host: 'localhost',
    //           database:  'test',
    //           user: 'root',
    //           password: 'root',
    //           port: 6033,
    //       },
    //       migrations: {
    //           directory: './src/infrastructure/repositories/mysql/migrations',
    //       },
    //       seeds: {
    //           directory: './src/infrastructure/repositories/mysql/seeds',
    //       }
    // })

    await knex('users').insert(request.body)    
    return {message: request.body}
  })
}

export default root;

The code commented is because of another answer I got here that stated using a knex local variable would work and indeed it worked, but I don't think that should be the best idea to solve this.


Solution

  • Please ensure that you are initializing knex with the config before using it to query.

    import { FastifyPluginAsync } from 'fastify'
    import knex from 'knex';
    import {config} from 'knexfile';
    
    const db = knex(config);
    
    const root: FastifyPluginAsync = async (fastify, opts): Promise<void> => {
      
      fastify.post('/create', async(request, reply) => {
    
        await db('users').insert(request.body)    
        return {message: request.body}
      })
    }
    
    export default root;