0
# Utilities
1
2
Helper functions for expanding SQL syntax patterns and handling configuration validation.
3
4
## Capabilities
5
6
### Expand Phrases
7
8
Utility function for expanding SQL syntax patterns with optional and alternative elements.
9
10
```typescript { .api }
11
/**
12
* Performs expandSinglePhrase() on array of phrases
13
* @param phrases - Array of syntax description strings
14
* @returns Array of all possible combinations
15
*/
16
function expandPhrases(phrases: string[]): string[];
17
18
/**
19
* Expands a single syntax description into all possible combinations
20
* @param phrase - Syntax description with optional [] and alternative {} elements
21
* @returns Array of all possible phrase combinations
22
*/
23
function expandSinglePhrase(phrase: string): string[];
24
```
25
26
This function is used internally by dialect definitions to expand syntax patterns like `"CREATE [OR REPLACE] [TEMP|TEMPORARY] TABLE"` into all possible combinations.
27
28
**Syntax Pattern Rules:**
29
30
- `[OPTIONAL]` - Optional elements (can be present or absent)
31
- `{REQUIRED|ALTERNATIVE}` - Required choice between alternatives
32
- `[OPTIONAL {CHOICE1|CHOICE2}]` - Nested patterns supported
33
- Elements can be nested to any depth
34
35
**Usage Examples:**
36
37
```typescript
38
import { expandPhrases } from "sql-formatter";
39
40
// Simple optional element
41
const result1 = expandPhrases(["CREATE [TEMPORARY] TABLE"]);
42
// Result: ["CREATE TABLE", "CREATE TEMPORARY TABLE"]
43
44
// Required alternatives
45
const result2 = expandPhrases(["DROP {TABLE|VIEW}"]);
46
// Result: ["DROP TABLE", "DROP VIEW"]
47
48
// Complex nested pattern
49
const result3 = expandPhrases([
50
"CREATE [OR REPLACE] [TEMP|TEMPORARY] TABLE"
51
]);
52
// Result: [
53
// "CREATE TABLE",
54
// "CREATE TEMP TABLE",
55
// "CREATE TEMPORARY TABLE",
56
// "CREATE OR REPLACE TABLE",
57
// "CREATE OR REPLACE TEMP TABLE",
58
// "CREATE OR REPLACE TEMPORARY TABLE"
59
// ]
60
61
// Multiple patterns
62
const result4 = expandPhrases([
63
"SELECT [ALL | DISTINCT]",
64
"INSERT [IGNORE] [INTO]"
65
]);
66
// Result: [
67
// "SELECT", "SELECT ALL", "SELECT DISTINCT",
68
// "INSERT", "INSERT IGNORE", "INSERT INTO", "INSERT IGNORE INTO"
69
// ]
70
```
71
72
**Advanced Pattern Examples:**
73
74
```typescript
75
import { expandPhrases } from "sql-formatter";
76
77
// Nested optional with alternatives
78
const patterns = expandPhrases([
79
"FOR [OF {UNIQUE | MANDATORY} TABLES]"
80
]);
81
// Result: [
82
// "FOR",
83
// "FOR OF UNIQUE TABLES",
84
// "FOR OF MANDATORY TABLES"
85
// ]
86
87
// Complex MySQL-style patterns
88
const mysqlPatterns = expandPhrases([
89
"UPDATE [LOW_PRIORITY] [IGNORE]",
90
"DELETE [LOW_PRIORITY] [QUICK] [IGNORE] FROM"
91
]);
92
```
93
94
### Configuration Error
95
96
Error class for configuration validation failures.
97
98
```typescript { .api }
99
class ConfigError extends Error {
100
constructor(message: string);
101
}
102
```
103
104
This error is thrown when invalid configuration options are provided to formatting functions.
105
106
**Common Configuration Errors:**
107
108
- Unsupported SQL dialect
109
- Invalid expressionWidth (must be positive)
110
- Deprecated configuration options
111
- Invalid parameter configuration
112
113
**Usage Examples:**
114
115
```typescript
116
import { format, ConfigError } from "sql-formatter";
117
118
try {
119
const result = format("SELECT * FROM users", {
120
language: "invalid-dialect"
121
});
122
} catch (error) {
123
if (error instanceof ConfigError) {
124
console.error("Configuration error:", error.message);
125
// Output: "Configuration error: Unsupported SQL dialect: invalid-dialect"
126
}
127
}
128
129
try {
130
const result = format("SELECT * FROM users", {
131
expressionWidth: -10
132
});
133
} catch (error) {
134
if (error instanceof ConfigError) {
135
console.error("Invalid expression width:", error.message);
136
}
137
}
138
```
139
140
### Configuration Validation
141
142
Internal validation function for format options.
143
144
```typescript { .api }
145
/**
146
* Validates and normalizes configuration options
147
* @param cfg - Configuration object to validate
148
* @returns Validated configuration object
149
* @throws ConfigError for invalid configuration
150
*/
151
function validateConfig(cfg: FormatOptions): FormatOptions;
152
```
153
154
This function is used internally but can be useful for validating configuration before formatting.
155
156
**Validation Rules:**
157
158
- `expressionWidth` must be a positive number
159
- Parameter values should be strings (shows warning if not)
160
- Custom parameter regex cannot be empty
161
- Removed options trigger ConfigError
162
163
**Usage Examples:**
164
165
```typescript
166
import { validateConfig, ConfigError } from "sql-formatter";
167
168
try {
169
const validatedConfig = validateConfig({
170
tabWidth: 4,
171
keywordCase: "upper",
172
expressionWidth: 80
173
});
174
console.log("Configuration is valid");
175
} catch (error) {
176
if (error instanceof ConfigError) {
177
console.error("Invalid configuration:", error.message);
178
}
179
}
180
181
// Check for deprecated options
182
try {
183
const config = validateConfig({
184
tabWidth: 2,
185
multilineLists: true // Deprecated option
186
});
187
} catch (error) {
188
if (error instanceof ConfigError) {
189
console.error("Deprecated option:", error.message);
190
// Output: "multilineLists config is no more supported."
191
}
192
}
193
```
194
195
## Internal Utility Types
196
197
These types are used internally but exported for advanced usage:
198
199
```typescript { .api }
200
interface IdentChars {
201
/** Additional characters for first character of identifier */
202
first?: string;
203
/** Additional characters after first character */
204
rest?: string;
205
/** Allow single dashes inside identifiers */
206
dashes?: boolean;
207
/** Allow identifier to begin with number */
208
allowFirstCharNumber?: boolean;
209
}
210
211
type PlainQuoteType = keyof typeof quotePatterns;
212
213
interface PrefixedQuoteType {
214
quote: PlainQuoteType;
215
prefixes: string[];
216
requirePrefix?: boolean;
217
}
218
219
interface RegexPattern {
220
regex: string;
221
}
222
223
type QuoteType = PlainQuoteType | PrefixedQuoteType | RegexPattern;
224
type VariableType = RegexPattern | PrefixedQuoteType;
225
```
226
227
These types are primarily used in dialect definitions and tokenizer configuration.