Skip to content

Allow fn(), cast(), col(), etc… to be used in literal() #14299

Closed

Description

@ephys

Literals are things we see the community try to avoid at all costs. Unfortunately, The Sequelize team is not able to implement each and every feature request due to time constraints.

This goal of this RFC is to propose new literal-based APIs to improve their Developer Experience.

More RFCs to improve literals:

Examples below are written in postgres, so columns are quoted with "double quotes"

The sql tag function

I propose to add a new way to define literals using a template literal tag function.

This tag is a more ergonomic, but equivalent, alternative to using Sequelize.literal:
Writing:

import { sql }  from  'sequelize';

User.findAll({
  where:  sql`LOWER(first_name) = $name`,
  bind: { name },
});

Is equivalent to writing

import { literal }  from  'sequelize';

User.findAll({
  where: literal(`LOWER(first_name) = $name`),
  bind: { name },
});

Where this becomes interesting is that we can exploit the power of tag functions to improve these literals, by adding support for inlined bind parameters, for col(), attr(), fn, cast, where:

bind parameters & replacements

Simply put, any simple value added by interpolation will be added to the query as either a bind parameter or a replacement.

That excludes values with special meaning like col(), cast(), etc…

Whether a bind parameter or replacement is used will follow the bindParam option (true by default in INSERT, and UPDATE, false by default in SELECT)

import { sql }  from  'sequelize';

const name = 'zoe';

User.findAll({
  where:  sql`first_name = ${name}`,
});

// ... WHERE first_name = 'zoe'

User.update({ /* values */ }, {
  where:  sql`first_name = ${name}`,
});

// ... WHERE first_name = $sequelize_bind_param_1

User.update({ /* values */ }, {
  where:  sql`first_name = ${name}`,
  bindParam: false,
});

// ... WHERE first_name = 'zoe'

col

Col can be used to escape any column name in the raw SQL. Making it safe to use variables as identifiers.

import { sql, col }  from  'sequelize';

sql`LOWER(${col('first_name')}) = $name`
// produces:
// LOWER("first_name") = $name

attr

attr attr() is a proposed replacement to col. It escapes an attribute and follows the same rules as the keys in a POJO where object. If attr works as expected, col will be deprecated.

This means that attr() will map your attribute name to your column name:

import { sql, Model, attr }  from  'sequelize';

class User extends Model {}
User.init({
  firstName: {
    field: 'first_name',
  },
})

User.findAll({
  where:  sql`LOWER(${attr('firstName')}) = $name`,
  bind: { name },
});

// ... WHERE LOWER("first_name") = $name

That attr() supports the JSON syntax:

import { sql, Model, DataTypes, attr }  from  'sequelize';

class User extends Model {}
User.init({
  jsonField: DataTypes.JSON,
})

User.findAll({
  where:  sql`LOWER(${attr('jsonField.property')}) = $name`,
  bind: { name },
});

// ... WHERE LOWER("jsonField"->'property') = $name

And can reference includes:

import { sql, attr }  from  'sequelize';

User.findAll({
  include: [User.associations.projects]
  where:  sql`${attr('$project.archived$')} IS false`,
  bind: { name },
});

// ... WHERE "project"."archived" IS false

identifier

We have col and attr for escaping column names. Neither can be used to escape any identifier because col follows some special column syntax (col('a.b') becomes "a"."b") and attr maps attribute names to column names.

identifier() is meant to be used as a general purpose identifier escaper. It doesn't modify its input at all.

This makes it useful for escaping table names and other non-column identifiers.

const myTable = 'users';
sequelize.query(sql`SELECT * FROM ${identifier(myTable)}`);

produces

SELECT * FROM "users";

We can also add custom behavior for non-strings, such as for escaping table names:

class User extends Model {}
User.init({}, { schema: 'schema1', tableName: 'users' })

// using a model
sequelize.query(sql`SELECT * FROM ${identifier(User)}`);

// using a TableName object
sequelize.query(sql`SELECT * FROM ${identifier({ tableName: 'projects', schema: 'public' })}`);

produces, respectively

-- model
SELECT * FROM "schema1"."users";

-- TableName
SELECT * FROM "public"."projects";

where

where lets you go back to using the POJO syntax, inside your literal:

import { sql, where, Op }  from  'sequelize';

User.findAll({
  where:  sql`first_name IS NOT NULL AND ${where('firstName', { [Op.eq]: 'Zoe' })}`,
});

// ... WHERE first_name IS NOT NULL AND "first_name" = 'Zoe'

fn

Arguably not as useful as the other ones, it's often going to be more readable to write this in raw SQL, but it is still supported for symmetry:

import { sql, fn, attr }  from  'sequelize';

User.findAll({
  where:  sql`${fn('LOWER', attr('firstName'))} = $name`,
  bind: { name },
});

// ... WHERE LOWER("first_name") = $name

cast

Arguably not as useful as the other ones, it's often going to be more readable to write this in raw SQL, but it is still supported for symmetry:

import { sql, cast, attr }  from  'sequelize';

User.findAll({
  where:  sql`${cast(attr('firstName'), 'CITEXT')} = $name`,
  bind: { name },
});

// ... WHERE CAST("first_name" as CITEXT) = $name

unsafeReplacement

There are cases where sequelize will not treat your input as a replacement or a bind parameter, because that would be unsafe (or simply impossible), such as when it's added in a comment, in an identifier, or in a string:

For instance, the following will throw an error because name would be escaped inside of a string, which would result in an SQL injection vulnerability if name itself is a string.

import { sql }  from  'sequelize';

User.findAll({
  where:  sql`first_name = '${name}'`,
});

There are cases where this is safe enough, assuming the user knows what they're doing. For instance, the following query is safe AS LONG AS dateFormat never includes the $$ characters.

It would throw without unsafeReplacement because the user must do extra sanitation, but with an explicit opt-in, the user could be allowed to write this:

const dateFormat = 'yyyy-MM-dd';

await sequelize.query(sql`
  SELECT * FROM CROSSTAB ($$
    SELECT TO_CHAR("start_date", ${unsafeReplacement(dateFormat)})  FROM "calendar"
  $$)
`);

More Examples

This feature would solve a large number of use cases, reducing the need for Sequelize to natively support new SQL features if the raw SQL version is clearer. Here are a few examples:

If add an overload to where(), which accepts only one parameter:

import { sql, where } from 'sequelize';

User.findAll({
  attributes: [
    sql`COUNT(*) FILTER (WHERE ${where({ id: 1 })})`,
  ],
});

would generate the following SQL:

-- postgres
SELECT COUNT(*) FILTER (WHERE "id" = 1) FROM users;

Issues this feature resolves

Activity

  1. added
    RFC
    on Mar 30, 2022
  2. self-assigned this
    on Mar 30, 2022
  3. github-actions commented on Apr 14, 2022

    @github-actions
    Contributor

    This issue has been automatically marked as stale because it has been open for 14 days without activity. It will be closed if no further activity occurs within the next 14 days. If this is still an issue, just leave a comment or remove the "stale" label. 🙂

  4. added
    type: feature
    and removed
    RFC
    on Dec 2, 2022
  5. changed the title [-][RFC] Allow `fn()`, `cast()`, `col()`, etc… to be used in `literal()`[/-] [+]Allow `fn()`, `cast()`, `col()`, etc… to be used in `literal()`[/+] on Dec 2, 2022
  6. ephys commented on May 27, 2023

    @ephys
    MemberAuthor

    This is actually released in v7

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

type: feature

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions