mammoth icon indicating copy to clipboard operation
mammoth copied to clipboard

Option for `.as()` output to be wrapped in double-quotes?

Open echentw opened this issue 1 year ago • 2 comments

A use case is if we want to give an expression an alias that includes special characters, e.g.

db.columnName.as('?column?')

Right now, the generated SQL is column_name ?column?, which is invalid SQL. Desired output: column_name "?column?".

Maybe related: https://github.com/Ff00ff/mammoth/issues/243

If this seems reasonable, I'm happy to work on a PR. Maybe the usage could look like:

db.columnName.as('?column?', {quoted: true})

echentw avatar Apr 29 '23 01:04 echentw

Looks like Mammoth tries to automatically wrap in quotes, but its heuristic is off: https://github.com/Ff00ff/mammoth/blob/8122afe43425c135a1dd8f0cd22606fb0e0a994d/workspaces/mammoth/src/naming/index.ts#L4-L11

From the Postgres manual (link):

SQL identifiers and key words must begin with a letter (a-z, but also letters with diacritical marks and non-Latin letters) or an underscore (_). Subsequent characters in an identifier or key word can be letters, underscores, digits (0-9), or dollar signs ($). Note that dollar signs are not allowed in identifiers according to the letter of the SQL standard, so their use might render applications less portable. The SQL standard will not define a key word that contains digits or starts or ends with an underscore, so identifiers of this form are safe against possible conflict with future extensions of the standard.

So maybe we should replace the isCamelCase check with:

// More restrictive than strictly necessary, so we'll end up quoting some things that don't necessarily need quotes.
const isValidWithoutQuotes = /^[a-z_][A-Za-z0-9_$]*$/;

cakoose avatar May 01 '23 14:05 cakoose

Looks like Mammoth tries to automatically wrap in quotes, but its heuristic is off: https://github.com/Ff00ff/mammoth/blob/8122afe43425c135a1dd8f0cd22606fb0e0a994d/workspaces/mammoth/src/naming/index.ts#L4-L11

From the Postgres manual (link):

SQL identifiers and key words must begin with a letter (a-z, but also letters with diacritical marks and non-Latin letters) or an underscore (_). Subsequent characters in an identifier or key word can be letters, underscores, digits (0-9), or dollar signs ($). Note that dollar signs are not allowed in identifiers according to the letter of the SQL standard, so their use might render applications less portable. The SQL standard will not define a key word that contains digits or starts or ends with an underscore, so identifiers of this form are safe against possible conflict with future extensions of the standard.

So maybe we should replace the isCamelCase check with:

// More restrictive than strictly necessary, so we'll end up quoting some things that don't necessarily need quotes.
const isValidWithoutQuotes = /^[a-z_][A-Za-z0-9_$]*$/;

cakoose avatar May 01 '23 14:05 cakoose