Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

208
Visualizações
How to generate raw sql query from knex migrations?

Question

For some reason, I can't use knex migrations in the production environment.

Can I generate raw SQL from knex migrations like knex select/insert/update operations?

For example:

I can get raw SQL from select sentences with:

Knex('t_example').select('id').toQuery()
// => select id from t_example

But I don't know how to generate raw SQL from the migration files:

import { Knex } from 'knex'

// how to get raw SQL like
//    "alter table `t_example` add `foo` int";
// from the "up" function
export async function up (knex: Knex): Promise<void> {
  return knex.schema.table('t_example', (table) => {
    table.integer('foo')
  })
}

export async function down (knex: Knex): Promise<void> {
  return knex.schema.table('t_example', (table) => {
    table.dropColumn('foo')
  })
}

My Attempts:

import the migration file and invoke the up function (from this github issue)

something like

const knex = require('knex')({...});
const {up, down} = require('./migrations/20200304140624_createUsersTable.js');

console.log(up(knex).toSQL().toNative());
console.log(down(knex).toSQL().toNative());

The above code snippet works fine for some migrations (createTable in my case), while not working for others (addColumn).

For example, with this migration file:

import { Knex } from 'knex'

export async function up (knex: Knex): Promise<void> {
  return knex.schema.table('t_example', (table) => {
    table.integer('foo')
  })
}

export async function down (knex: Knex): Promise<void> {
  return knex.schema.table('t_example', (table) => {
    table.dropColumn('foo')
  })
}

It throws error message: TypeError: up(...).toSql is not a function

and

UnhandledPromiseRejectionWarning: Error: ER_DUP_FIELDNAME: Duplicate column name 'foo'

run migration with DEBUG flag

Firstly, rollback the migrations with knex migrate:rollback

Then, run the migrations with DEBUG flag:

DEBUG=knex:query knex migrate:latest

It outputs SQL logs like

knex:query alter table `t_example` add `bar` int trx2 +8ms`

I can get SQL from these outputs now, but it requires some additional format tasks.

Is there a better solution?

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda