What's the usage of double colon in sql using sequelize? - node.js

I saw this in a node.js project.
sequelize.query("select * from user where user.age=::age",
{replacements:{age:20}});
Why does he use double colon rather than single colon?

Looking at the docs it seems you need a single colon. Replacements can be named using a colon or anonymous using a question mark. e.g.
sequelize.query("select * from user where user.age=:age", {replacements:{age:20}});
or
sequelize.query("select * from user where user.age=?", {replacements:[20]});

Oh,I guess I got it. #chriskelly you're right. one more colon will also match the RegEx,and two more colon will also work. i.e. ::::age is accepted, too.
SqlString.formatNamedParameters = function(sql, values, timeZone, dialect) {
return sql.replace(/\:+(?!\d)(\w+)/g, function(value, key) {
if ('postgres' === dialect && '::' === value.slice(0, 2)) {
return value;
}
if (values.hasOwnProperty(key)) {
return SqlString.escape(values[key], false, timeZone, dialect);
} else {
throw new Error('Named parameter "' + value + '" has no value in the given object.');
}
});
};

Related

Passing a JSON array to fulfillmentText

I have an array of JSON objects that looks like this...
JSONarray =
[ { name: 'Steven' },
{ name: 'Clark' },
{ name: 'Kensington' } ]
With respect to dialogflow and google assistant I would need to send a webhook response that looks something like this...
"fulfillmentText": JSONarray}),
"fulfillmentMessages" : [
{
"text":
{"text": [JSONarray]
}
}
]}
The issue I have is this piece "fulfillmentText": JSONarray. 'fulfillmentText' is the part that Google Assistant reads back and ideally I want to have it read back each of the three names but if I just pass the array it fails. Is there away I can build the JSON that will let this happen?
First, a minor semantic point. That is not a "JSON Array". It is an array of JavaScript Objects. JSON refers to the string representation of those objects (JavaScript Object Notation).
This is important because "fulfillmentText" expects a string. You can turn JavaScript objects into a string by using the JSON.stringify() method, so you'd do something like
const text = JSON.stringify( JSONarray );
However, this probably isn't what you want, since the Assistant would read this out as something like
Open bracket open brace quote name quote colon quote Steven quote close bracket, ...
and so forth.
Instead, you probably should write a function that takes the array and turns it into a string. Simplistically, you could call join() on just the values of the names. Something like this:
const names = JSONarray.map( o => o.name ); // Gets just an array of the names
const namesString = names.join(', '); // Joins them into a single string, separated by commas
const text = `The names are: ${namesString}`;
This is better, and what would be read out is something like
The names are Steven, Clark, Kensington
But this isn't how people actually read (or listen to) names. We expect it to be something more like
The names are Steven, Clark, and Kensington
This is so common that multivocal includes a template function to do this based on a list of strings. So your template would just be something like:
"The names are: {{Oxford names}}"
If you're not using multivocal, something like this would work:
/**
* Similar to Array.join(), but using rules for the Oxford comma.
* #param values The array to return joined values for
* #param sep1 The normal separator for each element (defaults to ", ")
* #param sep2 The separator before the final element (defaults to "and ")
* #returns {*}
*/
function oxford( values, sep1=", ", sep2="and " ){
if( !Array.isArray( values ) ){
return values;
} else if( values.length === 0 ){
return '';
} else if( values.length === 1 ){
return values[0];
} else if( values.length === 2 ){
return values[0]+' '+sep2+values[1];
}
var ret = '';
for( var co=0; co<values.length-1; co++ ){
ret += values[co]+sep1;
}
ret += sep2;
ret += values[values.length-1];
return ret;
};
const namesString = oxford( names );
const text = `The names are: ${namesString}`;

node.js - Error: SQLITE_ERROR: near "users": syntax error

I'm trying to put a JSON object "Synced" (Which you will see in the code)
This is the code for a function "addServer(userid, serverid)"
The function is being required from another javascript file
db.all(`SELECT * FROM Users WHERE Tag = ? LIMIT 1`, userid, async(error,element) => {
if(element[0].Synced === '') {
var sJSON = {
users:{
[userid]:4,
},
servers:[`${serverid}`]
}
var serverJSON = JSON.stringify(sJSON)
console.log(serverJSON)
} else {
//Else statement not done yet
}
db.run(`UPDATE Users SET Synced = "${serverJSON}" WHERE Tag = "${userid}"`)
})
Solved. Needed to change quoting.
As Dave Newton said, I had to check my quoting. What I did was change my double quotes to single quotes which solved the problem.

not equal to not working in postgresql query

if (req.body.positionDetails && req.body.positionDetails.length > 0) {
let total = req.body.positionDetails.length;
for (let i = 0; i < total; i++) {
db.query('SELECT * FROM position WHERE position <> $1',[req.body.positionDetails[i].position],function(err,p) {
console.log(p.rows)
});
}
}
It is selecting all the values from the database without checking the condition. How to solve this??
data is like
"positionDetails":[{"position":"manager"},{"position":"developer"}] and it is from postman.
Your prepared statement looks off to me. Try using ? as a placeholder for the position in your query.
db.query(
'SELECT * FROM position WHERE position <> ?', [req.body.positionDetails[i].position],
function(err, p) {
console.log(p.rows)
});
If this fixes the problem, then I suggest that you were comparing the position against the literal string $1, and every comparison failed resulting in every record appearing in the result set.

named parameter binding with sql-wildcard not working

I'm using the node-sqlite3 package to access my db.
I'm trying to get rows from a Clients table with this code:
var st = db.prepare("SELECT * FROM Clients where name LIKE '%$name%'");
st.all({ $name: "test" }, function (err, rows) {
console.log("this: " + JSON.stringify(this));
if (err)
console.log(err);
else {
console.log("found: " + JSON.stringify(rows));
}
});
Output of err is this:
{ [Error: SQLITE_RANGE: bind or column index out of range] errno: 25, code: 'SQLITE_RANGE' }
The query works and doesn't throw errors when I change the sql to SELECT * FROM Clients where name LIKE '%$name%'. So I guess the problem is, that node-sqlite3 tries to find a variable called $name% or something like that in the object passed as first parameter to Statement#all.
I've searched the API doc for more hints about this, but couldn't find any.
Do I need to escape something? How do I get my query to work with named binding and the sql wildcards %?
This is not the way bindings work.
You can have
SELECT * FROM Clients where name LIKE $name
and
var name = "%"+"test"+"%";
..
{ $name: name }
bound variables are negociated with the backend database as a "whole" variable and you should not confuse this with variable replacement.
you should also be able to use the concatenate function of sqlite (not tested) :
SELECT * FROM Clients where name LIKE '%'||$name||'%'
..
{ $name: test }

Sharepoint > Which characters are *not* allowed in a list?

I've tried looking this up and haven't come up with the answer I'm looking for; I've found what cannot be included in filenames, folder names, and site names... but nothing on actual fields in a list.
I noticed that the percent symbol (%) is one that's not allowed in files/sites/folders. But it also doesn't populate when I try to pro grammatically add the fields to the list. I am doing this by using a small C# application that sends the data via Sharepoint 2010's built-in web services. I can manually enter the character, but it messes up each field in the row if I try it through code.
I've tried some of the escape characters that I've found via Google (_x26), but these don't seem to work either. Has anyone else had an issue with this? If these characters are allowed, how can I escape them when sending the data through a web service call?
Thanks in advance!
Justin
Any characters that aren't allowed when you enter a field name get encoded in the internal name. The format is a little different to what you show - try "_x0026_".
I usually avoid issues with weird internal names by creating the field with no spaces or special characters in the name, then renaming it. When you rename a field, only the display name changes and you keep the simple internal name.
Characters not allowed in SharePoint file name:
~, #, %, & , *, {, }, \, :, <, >, ?, /, |, "
Pasted from http://chrisbarba.com/2011/01/27/sharepoint-filename-special-characters-not-allowed/
Am I saying something weird when I state that there usually is a reason for certain characters not being allowed. I don't know which or why, but there probably is a reason.
Since you control which fields need to be there you can also dictate their (internal) names. I'd say follow best practice and name your fields using Camel case. And because you created them, you can just map the fields to the according fields in your data source.
As a follow on to #Elisa's answer, here's some JavaScript / TypeScript code that helps to prevent users from uploading files into SharePoint with invalid characters in the file name implemented on Nintex forms.
Here's the gist of the JavaScript version (note you'll have to obviously adapt for your own needs since this was designed for Nintex) :
//------------------------------------------------------------------------
//JavaScript Version:
//Code from http://cc.davelozinski.com/tips-techniques/nintex-form-tips-techniques/javascript-typescript-for-nintex-forms-to-validate-file-names
//------------------------------------------------------------------------
function validateAttachmentNames(eventObject) {
var textbox$ = NWF$(this);
var attachrowid = this.id.substring(10, 47);
var fileUploadid = attachrowid;
var index = attachrowid.substring(36);
//console.log('index:' + index);
//console.log('attachrowid:' + attachrowid);
//console.log('fileUploadid:' + fileUploadid);
if (index == '') {
attachrowid += '0';
}
var fileName = NWF.FormFiller.Attachments.TrimWhiteSpaces(textbox$.val().replace(/^.*[\\\/]/, ''));
var match = (new RegExp('[~#%\&{}+\|]|\\.\\.|^\\.|\\.$')).test(fileName);
if (match) {
isValid = false;
setTimeout(function () {
NWF$("tr[id^='attachRow']").each(function () {
var arrParts = (NWF$(this).find(".ms-addnew")[0]).href.split('"');
var fileName = arrParts[5];
var attachRow = arrParts[1];
var fileUpload = arrParts[3];
var match = (new RegExp('[~#%\&{}+\|]|\\.\\.|^\\.|\\.$')).test(fileName);
if (match) {
console.log(fileName);
NWF.FormFiller.Attachments.RemoveLocal(attachRow, fileUpload, fileName);
alert('Invalid file: ' + fileName + ' You cannot attach files with the following characters ~ # % & * { } \ : < > ? / + | \n\nThe file has been removed.');
}
});
}, 500);
}
}

Resources