diff --git a/docs/paramTypes.md b/docs/paramTypes.md index b615cd3486..184e027bec 100644 --- a/docs/paramTypes.md +++ b/docs/paramTypes.md @@ -70,6 +70,8 @@ An object with the following following optional fields: For example in MySQL using `paramTypes: {quoted: [':']}` would allow you to use `` :`name` `` syntax, while in Transact-SQL `:"name"` and `:[name]` would work instead. See [identifier syntax wiki page][] for information about differences in support quoted identifiers. +- **`custom`**: `Array<{ regex: string, key?: (text: string) => string }>`. + An option to implement custom syntax for parameter placeholders. See below for details. Note that using this config will override the by default supported placeholders types. For example PL/SQL supports numbered (`:1`) and named (`:name`) placeholders by default. @@ -89,5 +91,53 @@ The result will be: This config option can be used together with [params][] to substitute the placeholders with actual values. +## Custom parameter syntax + +Say, you'd like to support the `{name}` parameter placeholders in this SQL: + +```sql +SELECT id, fname, age FROM person WHERE lname = {lname} AND age > {age}; +``` + +You can define a regex pattern to match the custom parameters: + +```js +paramTypes: { + custom: [{ regex: '\\{[a-zA-Z0-9_]+\\}' }]; +} +``` + +Note the double backslashes. You can get around the double-escaping problem by using `String.raw`: + +```js +paramTypes: { + custom: [{ regex: String.raw`\{[a-zA-Z0-9_]+\}` }]; +} +``` + +You can also use the [params][] option to substitute values of these parameters. +However by default the parameter names contain the whole string that is matched by the regex: + +```js +params: { '{lname}': 'Doe', '{age}': '25' }, +``` + +To get around this, you can also specify the `key` function to extract the name of the parameter: + +```js +paramTypes: { + custom: [{ + regex: String.raw`\{[a-zA-Z0-9_]+\}` + key: (text) => text.slice(1, -1), // discard first and last char + }] +} +``` + +Now you can refer to the parameters by their actual name: + +```js +params: { 'lname': 'Doe', 'age': '25' }, +``` + [params]: ./params.md [identifier syntax wiki page]: https://github.com/sql-formatter-org/sql-formatter/wiki/identifiers