Skip to content

Commit

Permalink
Add support for custom quote types (#516)
Browse files Browse the repository at this point in the history
  • Loading branch information
nene authored Nov 5, 2022
2 parents 039f655 + a0aca28 commit 15de546
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 5 deletions.
8 changes: 4 additions & 4 deletions src/lexer/TokenizerOptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,13 @@ export interface PrefixedQuoteType {
requirePrefix?: boolean; // True when prefix is required
}

export type QuoteType = PlainQuoteType | PrefixedQuoteType;

export interface VariableRegex {
export interface RegexPattern {
regex: string;
}

export type VariableType = VariableRegex | PrefixedQuoteType;
export type QuoteType = PlainQuoteType | PrefixedQuoteType | RegexPattern;

export type VariableType = RegexPattern | PrefixedQuoteType;

export interface ParamTypes {
// True to allow for positional "?" parameter placeholders
Expand Down
2 changes: 2 additions & 0 deletions src/lexer/regexFactory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,8 @@ export const quotePatterns = {
const singleQuotePattern = (quoteTypes: QuoteType): string => {
if (typeof quoteTypes === 'string') {
return quotePatterns[quoteTypes];
} else if ('regex' in quoteTypes) {
return quoteTypes.regex;
} else {
return prefixesPattern(quoteTypes) + quotePatterns[quoteTypes.quote];
}
Expand Down
25 changes: 24 additions & 1 deletion test/sqlFormatter.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import dedent from 'dedent-js';

import { format, formatDialect, SqlLanguage, sqlite } from '../src/index.js';
import { format, formatDialect, SqlLanguage, sqlite, DialectOptions } from '../src/index.js';

describe('sqlFormatter', () => {
it('throws error when unsupported language parameter specified', () => {
Expand Down Expand Up @@ -63,5 +63,28 @@ describe('sqlFormatter', () => {
\`bar\`;
`);
});

it('allows use of regex-based custom string type', () => {
// Extend SQLite dialect with additional string type
const sqliteWithTemplates: DialectOptions = {
tokenizerOptions: {
...sqlite.tokenizerOptions,
stringTypes: [...sqlite.tokenizerOptions.stringTypes, { regex: String.raw`\{\{.*?\}\}` }],
},
formatOptions: sqlite.formatOptions,
};

expect(
formatDialect(`SELECT {{template item}}, 'normal string' FROM {{tbl}};`, {
dialect: sqliteWithTemplates,
})
).toBe(dedent`
SELECT
{{template item}},
'normal string'
FROM
{{tbl}};
`);
});
});
});

0 comments on commit 15de546

Please sign in to comment.