1

I am trying to prepare some SQL query for Amazon Athena with dynamic 'WHERE' conditions in JavaScript. The query was saved on one variable in another file. How to add custom WHERE condition to it?

Pseudocode that I am trying to achieve,

file1.js

module.exports.queryFromFile1 = 'SELECT * Name FROM Contact WHERE Name = ?';

file2.js

const {queryFromFile1} = require('./file1.js');

const newQuery = queryFromFile1,['Jane']; 
console.log(newQuery); // 'SELECT * Name FROM Contact WHERE Name = 'Jane'

Can anyone suggest to me a proper method to do it. my current solution is posted below.

file1.js

module.exports.queryFromFile1 = 'SELECT * Name FROM Contact WHERE Name = {stringToReplace}';

file2.js

const {queryFromFile1} = require('./file1.js');

const newQuery = queryFromFile1.replace("{stringToReplace}", "'Jane"); 
console.log(newQuery); // 'SELECT * Name FROM Contact WHERE Name = 'Jane'
5
  • 1
    Please just use prepared statements. There is no need to open yourself to SQL injection by doing this by hand Commented Aug 1, 2021 at 10:11
  • @VLAZ Thanks for the comment. could you explain a bit more on prepared statements. the query that i am preparing is not for MYSQL/MSSQL it is for amazon Athena. Commented Aug 1, 2021 at 10:15
  • db.execute(queryFromFile1, ['Jane']) Commented Aug 1, 2021 at 10:23
  • hi, @LawrenceCherone, I' am trying to execute this query to Amazon Athena, so the mentioned method does not works for me. Commented Aug 1, 2021 at 10:27
  • I guess you meant SELECT * FROM Contact ? Commented Aug 1, 2021 at 11:50

2 Answers 2

3

I use a little helper function that let's you use straight es6 string interpolation in a round about way:

const template= (template, ctx) => {
   const script = new vm.Script('`' + template + '`')
   return script.runInNewContext(ctx)
}

const results = template('hello ${foo}', {foo:'jane'})

But, if you just need to do do a simple interpolation, why not just export the sql as a function?

const queryFromFile1 = str => (`SELECT * Name FROM Contact WHERE Name = ${str}`)

const query = queryFromFile1('Jane')
Sign up to request clarification or add additional context in comments.

Comments

1

As mentioned in the comments, you should not handle SQL statements with raw strings.

However, for a non-security critical parts of your code (for example, taking in a date format string from component props), this is how I prefer to do this:

const stringProducer = (insert) => `This was inserted: ${insert}`;

Then use like this:

const string = stringProducer("foo");

Comments

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.