I am using Firebase Firestore in my Angular project and lately there is a project called fireSQL to use SQL sentence query in Firestore, it's working great, but when I try to select something where my value has a single quote it just sends an error. I try to escape using all the JavaScript techniques, but nothing happens.
The error msg:
ERROR
Object { message: "Expected \"!=\", \"%\", \"*\", \"+\", \"-\", \"/\", \"<\", \"<=\", \"<>\", \"=\", \">\", \">=\", \"AND\", \"GROUP\", \"LIMIT\", \"OR\", \"ORDER\", \"UNION\", WHITE_SPACE, or end of input but \"s\" found.", expected: (29) […], found: "s", location: {…}, name: "SyntaxError", stack: "" }
and the query is:
getBrandfromSub(brand, sub) {
const fireSQL = new FireSQL(firebase.firestore());
return fireSQL.rxQuery(`SELECT * FROM products WHERE brand = '${brand}' AND subcategory = '${sub}'`);
}
You need to escape the single quotes in the strings you are sending as SQL queries. The FireSQL source indicates that \\'
is the escape sequence for '
. So your code could do the following. (If you need to escape other special characters you'll need to add them to the escapeSingleQuotes()
method.)
getBrandfromSub(brand, sub) {
const fireSQL = new FireSQL(firebase.firestore());
return fireSQL.rxQuery(`SELECT * FROM products WHERE brand = '${this.escapeSingleQuotes(brand)}' AND subcategory = '${this.escapeSingleQuotes(sub)}'`);
}
escapeSingleQuotes(s: string) {
return s.replace("'", "\\'");
}