Be the first user to complete this post
|
Add to List |
Writing multiline sql queries in javascript using knex
knex('users').where({
id: userId
});
knex.raw('select * from users, orders on users.id = orders.user_id');
var query = multiline.stripIndent(function () {/*
select
t.id, t.tag_text, count(t.id)
from user_links ul,
user_link_tags ult,
tags t
where ul.content_link_id = ?
and ult.user_link_id = ul.id
and t.id = ult.tag_id
group by t.id,t.tag_text
*/});
query = query.replace(/\n/g, '').replace(/\t/g, ' ');
return knex.raw(query, [+contentLinkId])
select users.id, orders.id, items.id, item.name
from users,
orders,
items
where users.id = 1
and order.user_id = users.id
and items.order_id = order.id;
knex("select users.id, orders.id, items.id, item.name from users, orders, items where users.id = 1 and order.user_id = users.id and items.order_id = order.id");
Code that cannot be easily read should not be written.
The reason is simple. We are all human beings, not machines.
Well, I had to find a better way to do this. Luckily I stumbled across an npm package called multiline that really did the job for me.
Here's what you'd do.
npm install multiline --save
var query = multiline.stripIndent(function () {/*
select users.id, orders.id, items.id, item.name
from users,
orders,
items
where users.id = ?
and order.user_id = users.id
and items.order_id = order.id
*/});
?
in the query so that I can pass the user id as an argument to the query. We will use this later.
The only problem is that now you have all these extra newline characters and tab characters in your query string as a side effect of having a query on multiple lines. Thats much easier to handle.
query = query.replace(/\n/g, '').replace(/\t/g, ' ');
var userId = 1;
return knex.raw(query, [userId])
.then(function (response) {
return resp.rows;
});
Also Read:
- Disable eslint no-unused-vars warning on global functions
- Use es6 and es6+ in eslint with babel
- Sublime Text plugins to boost your productivity
- Reinitialize addthis after loading ajax content
- Dynamic module loading with require