Skip to content

Immutable queries? #71

Open
Open

Description

@cassiozen

Currently query.append mutates the original query, which makes cumbersome to reuse a base query in multiple places.

For example, this will not work - Every time the route handler gets called, a new WHERE segment will be appended to the original baseQuery:

const baseQuery = SQL`SELECT * FROM books`;

app.get("/", (req, res) => {
  const query = baseQuery.append(SQL` WHERE id = ${req.params.id}`);
  // Some response
});

Is there any immutable way of appending?

Activity

  1. felixfbecker commented on Jan 10, 2018

    @felixfbecker
    Owner

    No, the idea was to always use queries inline for readability.

  2. cassiozen commented on Jan 10, 2018

    @cassiozen
    Author

    Would you consider adding such a feature, under a different method name? (PR #72)

  3. slavik-m commented on Mar 18, 2018

    @slavik-m

    @cassiozen +1
    I need it!

  4. migueloller commented on Jul 29, 2018

    @migueloller

    No, the idea was to always use queries inline for readability.

    That seems like a very bad excuse. When building a data access layer it is very common to share queries, especially CTEs. Adding something like #72 also doesn't remove the ability to use queries inline.

  5. samholmes commented on Apr 8, 2019

    @samholmes

    I suggest .concat() as a method name.

  6. olsonpm commented on Jun 30, 2026

    @olsonpm

    Anyone looking for an immutable approach can check out my solution at sql-tagged-templates

    It uses nesting to solve this problem e.g.

    const author = 'Kurt Vonnegut'
    
    // before
    import sts from 'sql-template-strings'
    
    const query = sts`select * from books`
    query.append(sts`where author = ${author}`)
    
    // after
    import stt from 'sql-tagged-templates/mysql2'
    
    const where = stt`where author = ${author}`
    const query = `select * from books ${where}`
  7. RagedPanda commented on Nov 13, 2026

    @RagedPanda

    Another option for sharing a base query: in named-sql-tag fragments are frozen and there is no append. You compose by nesting one fragment in another (sql`${baseQuery} WHERE id = ${id}`), and the values get renumbered for the outer query, so a shared base query never grows between requests.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions