This question already has answers here:
node-postgres: how to execute "WHERE col IN (<dynamic value list>)" query?
(7 answers)
Closed 2 years ago.
I have to use an SQL query like the one below in a Node.js app.
SELECT * FROM my_table
WHERE my_column IN ['name1','name2']
The array ['name1', 'name2'] is inputted by the user. And it may contain more than 2 names sometimes. How do I format this query using the pg-format package to avoid SQL injection?
Aren't the IN clause arguments supposed to be wrapped using parentheses?
Anyway, here's an example on formatting using pg-format,
var format = require('pg-format');
var sql = format("SELECT * FROM my_table WHERE my_column IN (%L, %L)", 'Alice', 'Bob'); // name1, name2
console.log(sql);
Edit 1:
With dynamic names using an array,
var format = require('pg-format');
var names = ['Alice', 'Bob', 'Charlie'];
var inCaluseStr = '(' + Array(names.length).fill('%L').join(',') + ')';
var sql = format.withArray("SELECT * FROM my_table WHERE my_column IN " + inCaluseStr, names);
console.log(sql);
I hope this helps.
Related
I have a dynamic string that is generated like one of the following:
var q = "FROM Table SELECT avg(1), avg(2), avg(3) where x='y'
var q = "SELECT avg(1), avg(2), avg(3) FROM Table where z='x' since x days ago
The values after the select are also dynamic where there could be 1 select option, or 10. I'm trying to create some logic to always pluck whatever is selected into an array, but having trouble dealing with the dynamic nature (string being constructed dynamically AND the # of selects being dynamic).
Basically, end result something like this:
['avg(1)', 'avg(2)', 'avg(3)']
Currently I'm doing something like the following, but it always expects the string to be formatted in a certain order (always starting with SELECT and where after the fields to pluck):
let splitQ = q.match(".*SELECT(.*)where");
let selects = splitQ[1].trim().split(",");
Here is a working solution.
It makes these assumptions about the query (after lowercased).
the values come after the first instance of the word 'select '
if the query starts with 'from', values end before the first instance of ' where'
if the query starts with 'select', values end before the first instance of ' from'
const test1 = "FROM Table SELECT avg(1), avg(2), avg(3) where x='y'";
const test2 = "SELECT avg(1), avg(2), avg(3) FROM Table where z='x' since x days ago";
function extractValues(query) {
// in both scenarios, the values always come directly after 'select '
const valuesComeAfterMe = 'select ';
query = query.toLowerCase();
let valuesEndBeforeMe;
// conditionally handle both query syntaxes
if (query.startsWith('from')) {
valuesEndBeforeMe = ' where';
} else if (query.startsWith('select')) {
valuesEndBeforeMe = ' from';
} else {
throw Error('query not handled');
}
// remove start
query = query.slice(query.indexOf(valuesComeAfterMe) + valuesComeAfterMe.length);
// remove end
query = query.slice(0, query.indexOf(valuesEndBeforeMe));
// split values and trim whitespace
return query.split(',').map(item => item.trim());
}
console.log(extractValues(test1));
console.log(extractValues(test2));
This question already has answers here:
Javascript Regexp - Match Characters after a certain phrase
(5 answers)
Closed 2 years ago.
I have a string lets say,
const message = 'This is a relationship: Salary = 73010 - 58.9 * Potential'
What I am trying to achieve here is get everything after relationship: and put it in a seperate variable using Regex. After storing the new string in a seperate variable I want the old variable containing the whole string to be replaced with just
message = 'This is a relationship'
So far, I have managed to do this:
const equation = new RegExp(/relationship:.*$/); // this gets everything removed starting from the relationship:
const tooltip = message.split(equation);
const tip = message.replace(equation, '');
Apologies for my noob code. I just started understanding Regex!
Is the pattern always everything after :? If so this is quite simple, you don't even need an explicit regex:
let message = 'This is a relationship : Salary = 73010 - 58.9 * Potential';
const array = message.split(":");
message = array[0].trim(); // Overwrite the original message (you asked for this)
const tooltip = array[1].trim();
console.log(`message: "${ message }"`);
console.log(`tooltip: "${ tooltip }"`);
.as-console-wrapper { min-height: 100%!important; top: 0; }
This returns:
message: "This is a relationship"
tooltip: "Salary = 73010 - 58.9 * Potential"
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I am trying to build a SQL string dynamically, for example:
"SELECT * FROM TABLE WHERE A = B AND C = D AND E = F AND"
How can I better build this SQL query without an extra AND in the end?
My code:
let where = "";
if (_conditions.length > 0) {
where = "WHERE ";
for (let i = 0; i < _conditions.length; i++) {
let curr_cond = _conditions[i];
let keys = Object.keys(curr_cond);
where += keys[0] + " = '" + curr_cond[keys[0]] + "' AND ";
}}
I assume you're building up the WHERE clause using a loop.
It would be more elegant to use some kind of a String join.
In most languages, there's a way to join together a bunch of string values with a "separator".
For example in Java:
List<String> conditions = List.of("A = B","C = D","E = F");
String whereClause = String.join(" AND ",conditions);
Or in Python:
conditions = ['A = B', 'C = D', 'E = F']
whereclause = ' AND '.join(conditions)
Or in Javascript:
var _conditions = ["A = B", "C = D", "E = F"];
var whereClause = _conditions.join(" AND ");
You probably don't even need to check the length of the list; an empty list or a list of one item won't include the separator.
I have a lot of tables with the same _ips endings. Example:
first-domain.com_ips
secons-domain.com_ips
...
I'm trying to get UNION result table which will contains all rows from all _ips tables. For this I use:
SELECT id, expirationDate FROM `first-domain.com_ips` WHERE isBlocked = 1
UNION
SELECT id, expirationDate FROM `secons-domain.com_ips` WHERE isBlocked = 1
...;
I have an array which consists of domain names. So I'm looking for a way to use this domain array in SQL query. Maybe something like we use with SELECT. Example:
const ids = [3, 4, 6, 8];
const query = 'SELECT * FROM table WHERE id IN (' + ids.join() + ')';
Is there a way to use array for tables names in SQL? Thank you in advance!
You can do this by using dynamic queries and regexps:
This dynamic query does what you want :
SELECT
GROUP_CONCAT(
CONCAT(
'SELECT * FROM `',
TABLE_NAME,
'`') SEPARATOR ' UNION ALL ')
FROM
`INFORMATION_SCHEMA`.`TABLES`
WHERE
`TABLE_NAME` REGEXP '_ips$'
INTO #sql;
SELECT #sql;
PREPARE stmt FROM #sql;
EXECUTE stmt;
This query gives two outputs, first is the final SQL query string which looks like :
SELECT * FROM `first-domain.com_ips` UNION ALL SELECT * FROM `second-domain.com_ips`
and the other output is the actual data from all tables, if you want only the final data, you can remove this statement:
SELECT #sql;
This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
Get query string values in JavaScript
Use the get paramater of the url in javascript
I have a long list of URLs where in one part of the URL I've got a command such as 'KEY=123'. I would like to find all those keys.
For Example: /somecommand?ACTION=UPDATE&DATATYPE=1&KEY=462&NUMBER=123.5263&SOMEID=845&IDTYPE=1
How could this be accomplished? My idea was just to search all the 'KEY' words and look for the number next to it - but I guess there is something much quicker for this.
The language of preference would be Javascript.
EDIT:
The URLs are cluttered and can't be extrapolated out of the text easily. a small example of the text:
2011-07-29 01:17:55.965/somecommand?ACTION=UPDATE&DATATYPE=1&KEY=462&NUMBER=123.5263&SOMEID=845&IDTYPE=1 200 685ms 157cpu_ms 87api_cpu_ms 0kb ABCABC/2.0 CFNetwork/485.12.7 Darwin/10.4.0 Paros/3.2.13`
2011-07-29 01:05:19.566 /somecommand?ACTION=UPDATE&DATATYPE=1&KEY=462&NUMBER=123.5263&SOMEID=845&IDTYPE=1 200 29ms 23cpu_ms 0kb ABCABC/2.0 CFNetwork/485.12.7 Darwin/10.4.0 Paros/3.2.13
2011-07-29 01:04:41.231 /somecommand?ACTION=UPDATE&DATATYPE=1&KEY=462&NUMBER=123.5263&SOMEID=845&IDTYPE=1 200 972ms 78cpu_ms 8api_cpu_ms 0kb ABCABC/2.0 CFNetwork/485.12.7 Darwin/10.4.0 Paros/3.2.13
The Javascript you'd need would be something like -
var text = 'ACTION=UPDATE&DATATYPE=1&KEY=462&NUMBER=123.5263&SOMEID=845&IDTYPE=1&key=678';
var matches = text.match(/KEY=\d*|key=\d*/g);
for (i=0; i<matches.length; i++) {
alert(matches[i]);
}
If you wanted just the number, you could do something like -
var text = 'ACTION=UPDATE&DATATYPE=1&KEY=462&NUMBER=123.5263&SOMEID=845&IDTYPE=1&key=678';
var matches = text.match(/KEY=\d*|key=\d*/g);
for (i=0; i<matches.length; i++) {
alert(matches[i].toLowerCase().replace('key=',''));
}
If you are interested only in the KEY value:
var regex = new RegExp("KEY=(\d+)");
var result = regex.exec(window.location.href);
result would be "123" in your case. If you have multiple lines, then:
var regex = new RegExp("KEY=(\d+)", "gm");
var results = regex.exec(window.location.href);
in this case results is an array.
a = "/somecommand?ACTION=UPDATE&DATATYPE=1&KEY=462&NUMBER=123.5263&SOMEID=845&IDTYPE=1";
a.match(/KEY\=(\d+)/gi)