Skip to content

Commit

Permalink
option to use regex with replace (#366)
Browse files Browse the repository at this point in the history
  • Loading branch information
nshiab authored Mar 27, 2024
1 parent 0645f22 commit 1e05d7b
Show file tree
Hide file tree
Showing 3 changed files with 439 additions and 2 deletions.
12 changes: 11 additions & 1 deletion src/class/SimpleDB.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1125,14 +1125,17 @@ export default class SimpleDB {
*
* // Replaces only if matching entire string.
* await sdb.replaceStrings("tableA", "column1", {"kilograms": "kg", liters: "l" }, {entireString: true})
*
* // Replaces using a regular expression. Any sequence of one or more digits would be replaced by a hyphen.
* await sdb.replaceStrings("tableA", "column1", {"\d+": "-" }, {regex: true})
* ```
*
* @param table - The name of the table in which strings will be replaced.
* @param columns - Either a string or an array of strings specifying the columns where string replacements will occur.
* @param strings - An object mapping old strings to new strings.
* @param options - An optional object with configuration options:
* @param options.entireString - A boolean indicating whether the entire string must match for replacement. Defaults to false.
*
* @param options.regex - A boolean indicating the use of regular expressions for a global replace. See the [RE2 docs](https://github.com/google/re2/wiki/Syntax) for the syntax. Defaults to false.
* @category Updating data
*/
async replaceStrings(
Expand All @@ -1141,9 +1144,16 @@ export default class SimpleDB {
strings: { [key: string]: string },
options: {
entireString?: boolean
regex?: boolean
} = {}
) {
options.entireString = options.entireString ?? false
options.regex = options.regex ?? false
if (options.entireString === true && options.regex === true) {
throw new Error(
"You can't have entireString to true and regex to true at the same time. Pick one."
)
}
await queryDB(
this,
replaceStringsQuery(
Expand Down
4 changes: 3 additions & 1 deletion src/methods/replaceStringsQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ export default function replaceStringsQuery(
columns: string[],
oldTexts: string[],
newTexts: string[],
options: { entireString?: boolean } = {}
options: { entireString?: boolean; regex?: boolean } = {}
) {
let query = ""

Expand All @@ -18,6 +18,8 @@ export default function replaceStringsQuery(
WHEN "${column}" = '${oldTexts[i]}' THEN '${newTexts[i]}'
ELSE "${column}"
END;\n`
} else if (options.regex) {
query += `UPDATE ${table} SET "${column}" = REGEXP_REPLACE("${column}", '${oldTexts[i]}', '${newTexts[i]}', 'g');\n`
} else {
query += `UPDATE ${table} SET "${column}" = REPLACE("${column}", '${oldTexts[i]}', '${newTexts[i]}');\n`
}
Expand Down
Loading

0 comments on commit 1e05d7b

Please sign in to comment.