Skip to content

Commit

Permalink
Document custom paramTypes syntax
Browse files Browse the repository at this point in the history
  • Loading branch information
nene committed Mar 22, 2023
1 parent e8b8f7b commit 0a3d401
Showing 1 changed file with 50 additions and 0 deletions.
50 changes: 50 additions & 0 deletions docs/paramTypes.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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

0 comments on commit 0a3d401

Please sign in to comment.