Unable to insert single quotes in SQL Server 2016 - node.js

I am trying to insert data in my SQL Server and I am using loopback framework in the backend.
But at the time of inserting a string with single quotes, I get an error
RequestError: Unclosed quotation mark after the character string ',8272)
SELECT id AS insertId from #insertedIds
and the string which I am trying to insert is like this
An open-ended equity fund investing in stocks which are currently undervalued to their future earning potential and carry medium risk profile to provide 'Capital Appreciation',
I tried to resolve this issue by replacing single quotes but afterward, when I am selecting data from the database again this error is happening.
Code is something like this
let mutualFundRecord = {
fundObjective: An open-ended equity fund investing in stocks which are currently undervalued to their future earning potential and carry medium risk profile to provide 'Capital Appreciation'
}
function updateRecordData(mutualFundRecord, callback) {
const promise = new Promise(function (resolve, reject) {
let promiseP1;
if (!mutualFundRecord.instrument || !mutualFundRecord.instrument.id) {
promiseP1 = app.models.Instrument.create(mutualFundRecord)
.then(function (newlyCreatedInstrument) {
mutualFundRecord.mutualFundDetails.instrumentId = newlyCreatedInstrument.id;
return app.models.MutualFundDetails.create(mutualFundRecord.mutualFundDetails);
});
}
}

If you try to assign the string with a single quote(s) in it to the variable, you would get the same error as you mentioned in your question:
declare #text nvarchar(100) = 'That's all folks'
Error: Unclosed quotation mark after the character string ''.
What you need to do is to replace each single quote character in the string with two single quote characters - that's called "escaping" the character.
Following code is a small demo and it will show you that although in the code you see two quote character, only one quote will be written into the database:
declare #text nvarchar(100) = 'That''s all folks'
select #text as Txt
into #t
select Txt from #t
That's all folks

Related

How to avoid google translate to translate :parameters

I'm using a library nikaia/translation-sheet who basically pulls all the translations from the Laravel site into a google spreadsheet making it "easily" translatable with =GOOGLETRANSLATE(A1)
The problem comes with the parameters:
:price
:amount
:etc
So I've got the idea to substitute ":" with #nonmakingsenseworblablaprice so Google couldn't translate example:
=SUBSTITUTE(GOOGLETRANSLATE(SUBSTITUTE(B2;":";"#nonmakingsenseworblabla");"ES";"EU");"#nonmakingsenseworblabla";":")
Well, not sure why Google eats some letters and puts new ones:
:amount de saldo -> #nonmakingseseworblatamount of saldo
So I decided to do something like detect the parameter and change :amount to :a_m_o_u_n_t and that is apparently working and not being weirdly parsed converted or translated.
I was looking for a solution and found a similar idea but having problems migrating it to spreadsheets script plus is not detecting the parameter
Any one knows how to detect all :parameters in a sentence and put a symbol, slash, dash etc between the characters or letters? Example:
The amount :amount for this order number :order_id is :price
I've also tried regex but not been lucky so far
=REGEXREPLACE(GOOGLETRANSLATE(REGEXREPLACE(B22; ":(\w)([\w]+)"; "{%$1_$2%}"); "ES"; $C$1); "{%(\w)_([^_]+)%}"; ":$1$2")
There's a regex to select the spaces between letters, but good luck making that in excel or spreadsheets. Demo
Finally I've created a script to avoid parameters translation:
function translate(cell, lang) {
const content = cell.toString();
const keys = [];
const enc = content.replace(/:([\w_]+)/ig, function(m, param) {
const n = `[§${keys.length}]`;
keys.push(param);
return n;
});
return LanguageApp.translate(enc, "es", lang).replace(/\[§(\d+)\]/ig, function(m, param) {
return `:${keys[param]}`;
});

Why postgres is returning additional backslash in a simple query

So in my node code postgres query is returning double quotes when it's returning its values.
As opposed to the query at pgAdmin.
I already tried to solve it using regex but this attempt was innefective. So if anyone had a problem like this and could help me, I would be glad.
Thanks in advance
There are neither quotes nor extra back slashes in the string. They are part of the string representation as literal.
Try console.log(value) - or even directly console.log('/\\w/g') - and you'll see the output is /\w/g as expected.
To answer my own question, after a lot of reading and researching, I managed to discover that because a backslash character is a special character it will create some problems around its implementation in regex, because it is not permitted to have a lone backslash stored in a variable for example.
This would never work stored inside a variable because the backslash have to be escaped.
/\w+/ig
Javascript will transform it automatically to be able to perform.
/\w+/ig
When reading
RegExp - Javascript documentation, I came across an interesting statement, the RegExp function will recognize and use a double slash regex, thankfully!
So I just adapted my regex to split it's statement from it's flags and mount it again using RegExp.
Below is the code that I used to solve this problem
// Getting values from postgres
const values = (await pgConn.admRead.query(clientQuery)).rows[0].value || [];
// Splitting regex ( values: /\w/g )
const valuesSplit = values.split('/'); // RESULT -> ['', w, g]
// Removing first array item when it's empty
if (valuesSplit[0].length === 0) {
valuesSplit.shift();
}
// Creating regex from splitted array
const regexOperation = new RegExp(valuesSplit[0], valuesSplit[1]);
// Executing replace function
const messageMasked = message.replace(regexOperation, '*');
return messageMasked;

How to fix 'Unclosed quotation mark after the character string \')\'.' error

I'm generating a dynamic sql query based on some user input. Here is the code that prepares the query:
var preparedParamValues = paramValues.map(paramValue => `'${paramValue}'`).join(',');
var sql = `INSERT INTO [DB] (${paramNames}) VALUES (${preparedParamValues})`;
When I send the following string to the DB it throws the below error:
'They're forced to drive stupid cars.'
I get an error :
'Unclosed quotation mark after the character string \')\'.'
I'm trying to find a way to escape all those characters but I don't understand the error or at least the last part of it with all the symbols.
You have to use two single quotes when a single quote appears in the string:
'They''re forced to drive stupid cars.'

nodejs skipping single quote from json key in output

I see a very weird problem when json when used in nodejs, it is skipping single quote from revision key . I want to pass this json as input to node request module and since single quote is missing from 'revision' key so it is not taking as valid json input. Could someone help how to retain it so that I can use it. I have tried multiple attempts but not able to get it correct.
What did I try ?
console.log(jsondata)
jsondata = {
'splits': {
'os-name': 'ubuntu',
'platform-version': 'os',
'traffic-percent': 100,
'revision': 'master'
}
}
Expected :-
{ splits:
{ 'os-name': 'ubuntu',
'platform-version': 'os',
'traffic-percent': 100,
'revision': 'master'
}
}
But in actual output single quote is missing from revision key :-
{ splits:
{ 'os-name': 'ubuntu',
'platform-version': 'os',
'traffic-percent': 100,
revision: 'master'
}
}
Run 2 :- Tried below code this also produce same thing.
data = JSON.stringify(jsondata)
result = JSON.parse(data)
console.log(result)
Run 3:- Used another way to achieve it
jsondata = {}
temp = {}
splits = []
temp['revision'] = 'master',
temp['os-name'] = 'ubuntu'
temp['platform-version'] = 'os'
temp['traffic-percent'] = 100
splits.push(temp)
jsondata['splits'] = splits
console.log(jsondata)
Run 4: tries replacing single quotes to double quotes
Run 5 : Change the order of revision line
This is what is supposed to happen. The quotes are kept only if the object key it’s not a valid JavaScript identifier. In your example, the 'splits' & 'revision' don't have a dash in their name, so they are the only ones with the quotes removed.
You shouldn't receive any error using this object - if you do, update this post mentioning the scenario and the error.
You should note that JSON and JavaScript are not the same things.
JSON is a format where all keys and values are surrounded by double quotes ("key" and "value"). A JSON string is produced by JSON.stringify, and is required by JSON.parse.
A JavaScript object has very similar syntax to the JSON file format, but is more flexible - the values can be surrounded by double quotes or single quotes, and the keys can have no quotes at all as long as they are valid JavaScript identifiers. If the keys have spaces, dashes, or other non-valid characters, then they need to be surrounded by single quotes or double quotes.
If you need your string to be valid JSON, generate it with JSON.stringify. If it's OK for it to be just valid JavaScript, then it's already fine - it does not matter whether the quotes are there or not.
If, for some reason, you need some imaginary third option (perhaps you are interacting with an API where someone has written their own custom string parser, and they are demanding that all keys are surrounded by single quotes?) you will probably need to write your own little string generator.

Escaping single quotes and double quotes in a string in dart

I am creating a basic chat application in flutter. It involves a Text Field where the user can enter any text and click on the send button.
The application works fine for any string you enter in the text box except for the string containing quotes. I get a Database exception when trying to add that string to the sql database as the quotes are not escaped.
Doing replaceAll("'", "\'").replaceAll('"', "\'") on a string works as i'm using double quotes in sql queries, but all the double quotes are now single quotes.
Thanks for the help.
Does the database support bind parameters? If not, does the package you are using to talk to the database have a string escape function?
Those will work better than doing it manually, especially since there can be very unsafe stuff in the user input beyond quotes. If you are manually putting together a query string and sending it to the DB it will be open to SQL attacks.
For your immediate question, you are replacing with single quotes in both places. Assuming you can escape quotes by prefixing with a slash it should look like .replaceAll('"', '\\"').
Please look for a more secure way to sanitize user input.
The best and safest way to run queries SQL in Dart is to use the bind parameters.
For example, if you are using sqflite you'll need to pass parameters in a List in this way using the ? as wildcard in the query:
INSERT
int id2 = await txn.rawInsert(
'INSERT INTO Test(name, value, num) VALUES(?, ?, ?)',
['another name', 12345678, 3.1416]);
UPDATE
int count = await database.rawUpdate(
'UPDATE Test SET name = ?, value = ? WHERE name = ?',
['updated name', '9876', 'some name']);
DELETE
count = await database
.rawDelete('DELETE FROM Test WHERE name = ?', ['another name']);

Resources