Skip to content

generated code is not usable if a query contains backquotes #40

Open
@yshrsmz

Description

@yshrsmz

problem

Say I have MySQL database and users table below

CREATE TABLE users (
  `id` int UNSIGNED NOT NULL AUTO_INCREMENT,
  `comment` varchar(255) NOT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` datetime NOT NULL,
  PRIMARY KEY (`id`)
);

And this query.

-- name: FindAllUsers :many
SELECT
  `id`,
  `comment`
FROM
  users;

I wrap columns with backquotes as some are reserved words in MySQL (comment in this case).

And when I run sqlc, it generates the code below.

import mysql, { RowDataPacket } from "mysql2/promise";

type Client = mysql.Connection | mysql.Pool;

export const findAllUsersQuery = `-- name: FindAllUsers :many
SELECT
  `id`,
  `comment`
FROM
  users`;

export interface FindAllUsersRow {
    id: number;
    comment: string;
}

export async function findAllUsers(client: Client): Promise<FindAllUsersRow[]> {
    const [rows] = await client.query<RowDataPacket[]>({
        sql: findAllUsersQuery,
        values: [],
        rowsAsArray: true
    });
    return rows.map(row => {
        return {
            id: row[0],
            comment: row[1]
        };
    });
}

Apparently, it is broken as findAllUsersQuery contains unescaped backquotes, breaking its template literal.

solution

Escape the backquotes?

nodes.push(
queryDecl(
textName,
`-- name: ${query.name} ${query.cmd}
${query.text}`
)
);

Changing these lines could solve the problem, but these lines are common for all drivers, so I'm wondering if we can just escape it or we should abstract it.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions