sqlx-ts icon indicating copy to clipboard operation
sqlx-ts copied to clipboard

Support for tagged template literal expressions

Open JulianCataldo opened this issue 1 year ago • 1 comments

Sorry, third issue in three days ☺️, don't wanna spam…

I would like to know if you are interested in adding support for template literal expression?

Use case is using the sql-template-tag package, alongside with mysql2 (but this is not important).

It's arguably more ergonomic to use string interpolations, in contrast to the traditional ? placeholder + a values array (which is outputted by this tag util. in the end, anyway).

  async function insertConfigSnapshot(options: {
    hash: string;
    probeConfigsString: string;
    probeId: number;
    uuid: UUID;
  }): Promise<void> {
    const insertConfigSnapshot = sql`
      INSERT INTO
        probe_config_history (configs_checksum_md5, configs, probe_id, uuid)
      VALUES
        (
          ${options.hash},
          ${options.probeConfigsString},
          ${options.probeId},
          ${options.uuid}
        )
    `;

    await execute(insertConfigSnapshot);
  }

With the ? and array of values, we lose in readability and code colocation, resulting in more potential human errors.

Actually, the parser is crashing. I know it can be tricky to parse template literal expression. Especially when they are nested. However, the most basic usage will not use nesting of SQL code (I didn't tried with sql-template-tag, I'm not sure it's even doable). Just primitive value interpolation cover the vast majority of use case, I think.

So maybe something like hard replacing \${(.*?)} with ? during the parsing phase should do the trick?

What's your thoughts?

Good bye

JulianCataldo avatar Jun 18 '24 19:06 JulianCataldo

hey, @JulianCataldo, thanks for this idea.

I'm not sure about supporting string replacement like in your example - I've been thinking about supporting named placeholders in a query.

named placeholder is a tricky one since no standard across ORMs or Databases follows one. Names placeholder as in

SELECT id
FROM items
WHERE id = :id

Let me think about it a bit more and come back on this

JasonShin avatar Jun 19 '24 05:06 JasonShin

Similar discussion & ideation is going on https://github.com/JasonShin/sqlx-ts/issues/193, will close this to reduce number of issues

JasonShin avatar Jan 05 '25 08:01 JasonShin