Skip to content

Commit

Permalink
Fix queryContext not being passed to raw queries (#3111)
Browse files Browse the repository at this point in the history
* Fix queryContext not being passed to raw queries

* Add unit case for transaction as well
  • Loading branch information
kibertoad committed Mar 18, 2019
1 parent 11fdc0c commit e7ed005
Show file tree
Hide file tree
Showing 2 changed files with 84 additions and 0 deletions.
6 changes: 6 additions & 0 deletions src/formatter.js
Expand Up @@ -138,6 +138,12 @@ export default class Formatter {
}
if (value instanceof Raw) {
value.client = this.client;
if (this.builder._queryContext) {
value.queryContext = () => {
return this.builder._queryContext;
};
}

query = value.toSQL();
if (query.bindings) {
this.bindings = this.bindings.concat(query.bindings);
Expand Down
78 changes: 78 additions & 0 deletions test/unit/knex.js
Expand Up @@ -185,6 +185,84 @@ describe('knex', () => {
).to.equal(null);
});

it('passes queryContext to wrapIdentifier in raw query', () => {
const knex = Knex(
Object.assign({}, sqliteConfig, {
wrapIdentifier: (str, origImpl, queryContext) => {
if (!queryContext) {
throw Error('We should have queryContext here right?');
}

if (str === 'iAmGoingToBeConvertedToId') {
str = 'id';
}
return origImpl(str);
},
})
);

return knex.schema
.queryContext({ someStuff: true })
.dropTableIfExists('test')
.then(() => {
return knex.schema
.queryContext({ someStuff: true })
.createTable('test', (table) => {
table.increments('id');
table.string('text');
});
})
.then(() => {
return knex('test')
.queryContext({ someStuff: true })
.select('id')
.whereRaw('id = ??', 'iAmGoingToBeConvertedToId');
})
.then(() => {
return knex.schema.queryContext({ someStuff: true }).dropTable('test');
});
});

it('passes queryContext to wrapIdentifier in raw query in transaction', () => {
const knex = Knex(
Object.assign({}, sqliteConfig, {
wrapIdentifier: (str, origImpl, queryContext) => {
if (!queryContext) {
throw Error('We should have queryContext here right?');
}

if (str === 'iAmGoingToBeConvertedToId') {
str = 'id';
}
return origImpl(str);
},
})
);

return knex.transaction((trx) => {
return trx.schema
.queryContext({ someStuff: true })
.dropTableIfExists('test')
.then(() => {
return trx.schema
.queryContext({ someStuff: true })
.createTable('test', (table) => {
table.increments('id');
table.string('text');
});
})
.then(() => {
return trx('test')
.queryContext({ someStuff: true })
.select('id')
.whereRaw('id = ??', 'iAmGoingToBeConvertedToId');
})
.then(() => {
return trx.schema.queryContext({ someStuff: true }).dropTable('test');
});
});
});

it('sets correct postProcessResponse for chained builders', () => {
const knex = Knex({
client: 'sqlite',
Expand Down

0 comments on commit e7ed005

Please sign in to comment.