Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add DuckDB Dialect Support #738

Open
wants to merge 24 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/dialect.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ The following dialects can be imported from `"sql-formatter"` module:
- `bigquery` - [GCP BigQuery][]
- `db2` - [IBM DB2][]
- `db2i` - [IBM DB2i][] (experimental)
- `duckdb` - [duckdb][]
- `hive` - [Apache Hive][]
- `mariadb` - [MariaDB][]
- `mysql` - [MySQL][]
Expand Down Expand Up @@ -78,6 +79,7 @@ You likely only want to use this if your other alternative is to fork SQL Format
[mysql]: https://www.mysql.com/
[tidb]: https://github.com/pingcap/tidb/
[couchbase n1ql]: http://www.couchbase.com/n1ql
[duckdb]: https://duckdb.org/
[oracle pl/sql]: http://www.oracle.com/technetwork/database/features/plsql/index.html
[postgresql]: https://www.postgresql.org/
[presto]: https://prestodb.io/docs/current/
Expand Down
2 changes: 2 additions & 0 deletions docs/language.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ const result = format('SELECT * FROM tbl', { dialect: 'sqlite' });
- `"bigquery"` - [GCP BigQuery][]
- `"db2"` - [IBM DB2][]
- `"db2i"` - [IBM DB2i][] (experimental)
- `"duckdb"` - [duckdb][]
- `"hive"` - [Apache Hive][]
- `"mariadb"` - [MariaDB][]
- `"mysql"` - [MySQL][]
Expand Down Expand Up @@ -55,6 +56,7 @@ See docs for [dialect][] option.
[mysql]: https://www.mysql.com/
[tidb]: https://github.com/pingcap/tidb/
[couchbase n1ql]: http://www.couchbase.com/n1ql
[duckdb]: https://duckdb.org/
[oracle pl/sql]: http://www.oracle.com/technetwork/database/features/plsql/index.html
[postgresql]: https://www.postgresql.org/
[presto]: https://prestodb.io/docs/current/
Expand Down
1 change: 1 addition & 0 deletions src/allDialects.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
export { bigquery } from './languages/bigquery/bigquery.formatter.js';
export { db2 } from './languages/db2/db2.formatter.js';
export { db2i } from './languages/db2i/db2i.formatter.js';
export { duckdb } from './languages/duckdb/duckdb.formatter.js';
export { hive } from './languages/hive/hive.formatter.js';
export { mariadb } from './languages/mariadb/mariadb.formatter.js';
export { mysql } from './languages/mysql/mysql.formatter.js';
Expand Down
178 changes: 178 additions & 0 deletions src/languages/duckdb/duckdb.formatter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
import { DialectOptions } from '../../dialect.js';
import { expandPhrases } from '../../expandPhrases.js';
import { functions } from './duckdb.functions.js';
import { dataTypes, keywords } from './duckdb.keywords.js';

const reservedSelect = expandPhrases(['SELECT [ALL | DISTINCT] [EXCLUDE | REPLACE]']);

const reservedClauses = expandPhrases([
// queries
'WITH [RECURSIVE]',
'FROM',
'WHERE',
'GROUP BY [ALL | DISTINCT]',
'HAVING',
'QUALIFY',
'WINDOW',
'PARTITION BY',
'ORDER BY',
'LIMIT',
'OFFSET',
// Data manipulation
// - insert:
'INSERT INTO',
'VALUES',
'DEFAULT VALUES',
'BY [POSITION | NAME]',
// - update:
'SET',
// other
'RETURNING',
]);

const standardOnelineClauses = expandPhrases([
'CREATE [OR REPLACE] [TEMP | TEMPORARY] TABLE',
]);

const tabularOnelineClauses = expandPhrases([
// - create
'CREATE [OR REPLACE] [TEMP | TEMPORARY] VIEW',
// - update:
'UPDATE',
// - insert:
'ON CONFLICT',
// - delete:
'DELETE FROM',
// - drop table:
'DROP TABLE [IF EXISTS]',
// - alter table:
'ALTER TABLE [IF EXISTS]',
'ALTER TABLE ALL IN TABLESPACE',
'RENAME [COLUMN]',
'RENAME TO',
'ADD [COLUMN] [IF NOT EXISTS]',
'DROP [COLUMN] [IF EXISTS]',
'DROP [PERSISTENT] SECRET',
'DROP [SEQUENCE | MACRO | FUNCTION | INDEX | TYPE | SCHEMA] [IF EXISTS]',
'DROP [VIEW] [IF EXISTS]',
'ALTER [COLUMN]',
'SET DATA TYPE', // for alter column
'{SET | DROP} DEFAULT', // for alter column
'{SET | DROP} NOT NULL', // for alter column
// - truncate:
'TRUNCATE [TABLE]',
// other
'ABORT',
'ALTER VIEW',
'ANALYZE',
'BEGIN',
'CALL',
'CHECKPOINT',
'COMMIT',
'COPY',
'CREATE FUNCTION',
'CREATE INDEX',
'CREATE MACRO',
'CREATE SCHEMA',
'CREATE SECRET',
'CREATE SEQUENCE',
'CREATE TYPE',
'DEALLOCATE',
'DECLARE',
'EXECUTE',
'EXPLAIN',
'INSTALL',
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks like INSTALL is the only name added to this list compared to PostgreSQL. I would suspect there are more differences by the statements supported by PostgreSQL and DuckDB.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @nene - you're correct. DuckDB uses the PostgreSQL parser. That's why DuckDB’s SQL dialect closely follows the conventions of the PostgreSQL dialect with only a few exceptions as listed here.

Many features are unsupported so I've removed unsupported elements in the formatter.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @nene - let me know if it's OK to resolve this conversation.

I've also added some specific DuckDB features below.

'LOAD',
'PREPARE',
'INSERT INTO',
'SHOW',
'BEGIN TRANSACTION',
'UNLISTEN',
'VACUUM [ANALYZE | FULL]',
]);

const reservedSetOperations = expandPhrases([
'UNION [ALL] BY NAME',
'EXCEPT [ALL]',
'INTERSECT [ALL]',
]);

const reservedJoins = expandPhrases([
hughcameron marked this conversation as resolved.
Show resolved Hide resolved
'ASOF {LEFT} JOIN',
'JOIN',
'NATURAL [INNER] JOIN',
'NATURAL [LEFT] {ANTI | SEMI} JOIN',
'NATURAL {LEFT | RIGHT | FULL} [OUTER] JOIN',
'POSITIONAL JOIN',
'[LEFT] {ANTI | SEMI} JOIN',
'{INNER | CROSS} JOIN',
'{LEFT | RIGHT | FULL} [OUTER] JOIN',
]);

const reservedPhrases = expandPhrases([
'PRIMARY KEY',
'GENERATED ALWAYS',
'ON {UPDATE | DELETE} [SET NULL | SET DEFAULT]',
'{ROWS | RANGE | GROUPS} BETWEEN',
'[TIMESTAMP | TIME] {WITH | WITHOUT} TIME ZONE',
// comparison operator
'IS [NOT] DISTINCT FROM',
]);

export const duckdb: DialectOptions = {
name: 'duckdb',
tokenizerOptions: {
reservedSelect,
reservedClauses: [...reservedClauses, ...standardOnelineClauses, ...tabularOnelineClauses],
reservedSetOperations,
reservedJoins,
reservedPhrases,
reservedKeywords: keywords,
reservedDataTypes: dataTypes,
reservedFunctionNames: functions,
nestedBlockComments: true,
extraParens: ['[]'],
stringTypes: [
'$$',
{ quote: "''-qq", prefixes: ['U&'] },
{ quote: "''-qq-bs", prefixes: ['E'], requirePrefix: true },
{ quote: "''-raw", prefixes: ['B', 'X'], requirePrefix: true },
],
identTypes: [{ quote: '""-qq', prefixes: ['U&'] }],
identChars: { rest: '$' },
paramTypes: { numbered: ['$'] },
operators: [
// Arithmetic
'%',
'^',
'@',
// Assignment
':=',
// Bitwise
'&',
'|',
'~',
'<<',
'>>',
// JSON
'->',
'->>',
// Pattern matching
'~~',
'~~*',
'!~~',
'!~~*',
'~',
'!~',
// String concatenation
'||',
// Text search
'^@',
],
},
formatOptions: {
alwaysDenseOperators: ['::', ':'],
onelineClauses: [...standardOnelineClauses, ...tabularOnelineClauses],
tabularOnelineClauses,
},
};
Loading