Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jamesperi/6a6e92f36e3b3fd2b226b1463df27276 to your computer and use it in GitHub Desktop.
Save jamesperi/6a6e92f36e3b3fd2b226b1463df27276 to your computer and use it in GitHub Desktop.
parser for an SQL REPLACE INTO string

parser for an SQL REPLACE INTO string

Needed to get keys and values into a pair of arrays for some sanitation of row data.

A Pen by Jim on CodePen.

License.

const sampleReplaceString = "REPLACE INTO `Users` (`id`, `firstname`, `lastname`, `email`, `telephone`, `cellphone`, `active` `location`, `joined`, `last_online`) VALUES (15,'Smith','Steve','[email protected]','+1 2223331212',NULL,1,'Idaho Falls,ID','2014-10-09 14:59:56','2016-04-25 06:10:40');"
let isInteger = _.isInteger
let asInt = _.parseInt
const getKeys = str => {
const newKeys = []
for(let p of str.split(',')) {
newKeys.push(p.split('`')[1])
}
return newKeys
}
const getValues = (values, keys) => {
const cleanStringStart = str => {
if (str.startsWith("'")) {
// string to string
str = str.slice(1, str.length);
}
if (str.startsWith(",")) {
str = str.slice(1, str.length);
}
return str;
};
const getNewEnd = str => {
let end = str.indexOf(",");
if (str.startsWith("'")) {
// its a string
end = str.indexOf("',") + 1;
}
return end > -1 ? end : str.length;
};
let items = [];
let str = values;
for (let i = 0; i < keys.length; i++) {
str = cleanStringStart(str);
let newEnd = getNewEnd(str);
items.push(str.substr(0, newEnd));
str = str.slice(newEnd, str.length);
}
let cleanedValues = [];
for (let value of items) {
value = value.trim()
if (isInteger(asInt(value)) && value.toString().includes('.')) {
// floating point "x.xx" leave as string
cleanedValues.push(value)
} else if (isInteger(asInt(value)) ) {
cleanedValues.push(asInt(value))
} else if (value === "NULL") {
cleanedValues.push(value)
} else if (value.startsWith("'") && value.endsWith("'")) {
cleanedValues.push(value.slice(1, value.length -1).trim());
} else {
// something other than a string
cleanedValues.push(value)
}
}
return cleanedValues;
};
const parseSqlReplace = (str) => {
const template = "REPLACE INTO `${ tableName }` (${ keys }) VALUES (${ values });"
const regex = /REPLACE INTO `(.*)` \((.+)\) VALUES \((.+)\);/
const parts = regex.exec(JSON.stringify(str))
let tableName = parts[1]
let keys = getKeys(parts[2])
let values = getValues(parts[3], keys)
return {
keys: keys,
values: values,
template: template
}
}
const cleaned = parseSqlReplace(sampleReplaceString)
console.log(cleaned)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment