Nested sql tags accross modules
petrzjunior opened this issue · 0 comments
petrzjunior commented
I have a library which constructs SQL filters and I want to consume it in my main project.
Example
In library
:
export const filter = sql`WHERE year = 2018`;
In the main project:
const {filter} = require('library');
sql`SELECT * FROM books ${filterThisYear ? filter : undefined}`
Expected behavior
I expect nested sql
tags to merge and append the filter.
Actual behavior
Due to the object weirdness in JavaScript, class instances are compared by their prototype chain which depends on the way the class was imported. In this case, instanceof returns false
. The SqlContainer
class is the same, but imported from a different place. Finally this cause sql
not to detect nested tag and treats is as an object parameter instead.
- https://stackoverflow.com/questions/18261788/nodejs-require-instanceof-behaviour
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof#instanceof_and_multiple_contexts_e.g._frames_or_windows
Suggested fix
I created a fork which adds a tag method to allow comparison across modules. This is not the cleanest code ever, but is successfully used in Moment.js for instance.