Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add execlastid implementation for mysql #13

Merged
merged 5 commits into from
Mar 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,4 @@ out.js: src/app.ts $(wildcard src/drivers/*.ts) src/gen/plugin/codegen_pb.ts
npx esbuild --bundle src/app.ts --tree-shaking=true --format=esm --target=es2020 --outfile=out.js

src/gen/plugin/codegen_pb.ts: buf.gen.yaml
buf generate --template buf.gen.yaml buf.build/sqlc/sqlc --path plugin/
buf generate --template buf.gen.yaml buf.build/sqlc/sqlc --path plugin/
11 changes: 9 additions & 2 deletions examples/authors/mysql/query.sql
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,14 @@ ORDER BY name;
INSERT INTO authors (
name, bio
) VALUES (
?, ?
?, ?
);

/* name: CreateAuthorReturnId :execlastid */
INSERT INTO authors (
name, bio
) VALUES (
?, ?
);

/* name: DeleteAuthor :exec */
Expand All @@ -19,4 +26,4 @@ WHERE id = ?;

/* name: Test :one */
SELECT * FROM node_mysql_types
LIMIT 1;
LIMIT 1;
24 changes: 22 additions & 2 deletions examples/bun-mysql2/src/db/query_sql.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// Code generated by sqlc. DO NOT EDIT.

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

type Client = mysql.Connection | mysql.Pool;

Expand Down Expand Up @@ -64,7 +64,7 @@ export const createAuthorQuery = `-- name: CreateAuthor :exec
INSERT INTO authors (
name, bio
) VALUES (
?, ?
?, ?
)`;

export interface CreateAuthorArgs {
Expand All @@ -79,6 +79,26 @@ export async function createAuthor(client: Client, args: CreateAuthorArgs): Prom
});
}

export const createAuthorReturnIdQuery = `-- name: CreateAuthorReturnId :execlastid
INSERT INTO authors (
name, bio
) VALUES (
?, ?
)`;

export interface CreateAuthorReturnIdArgs {
name: string;
bio: string | null;
}

export async function createAuthorReturnId(client: Client, args: CreateAuthorReturnIdArgs): Promise<number> {
const [result] = await client.query<ResultSetHeader>({
sql: createAuthorReturnIdQuery,
values: [args.name, args.bio]
});
return result?.insertId ?? 0;
}

export const deleteAuthorQuery = `-- name: DeleteAuthor :exec
DELETE FROM authors
WHERE id = ?`;
Expand Down
24 changes: 22 additions & 2 deletions examples/node-mysql2/src/db/query_sql.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// Code generated by sqlc. DO NOT EDIT.

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

type Client = mysql.Connection | mysql.Pool;

Expand Down Expand Up @@ -64,7 +64,7 @@ export const createAuthorQuery = `-- name: CreateAuthor :exec
INSERT INTO authors (
name, bio
) VALUES (
?, ?
?, ?
)`;

export interface CreateAuthorArgs {
Expand All @@ -79,6 +79,26 @@ export async function createAuthor(client: Client, args: CreateAuthorArgs): Prom
});
}

export const createAuthorReturnIdQuery = `-- name: CreateAuthorReturnId :execlastid
INSERT INTO authors (
name, bio
) VALUES (
?, ?
)`;

export interface CreateAuthorReturnIdArgs {
name: string;
bio: string | null;
}

export async function createAuthorReturnId(client: Client, args: CreateAuthorReturnIdArgs): Promise<number> {
const [result] = await client.query<ResultSetHeader>({
sql: createAuthorReturnIdQuery,
values: [args.name, args.bio]
});
return result?.insertId ?? 0;
}

export const deleteAuthorQuery = `-- name: DeleteAuthor :exec
DELETE FROM authors
WHERE id = ?`;
Expand Down
12 changes: 12 additions & 0 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,12 @@ interface Driver {
iface: string | undefined,
params: Parameter[]
) => Node;
execlastidDecl: (
name: string,
text: string,
iface: string | undefined,
params: Parameter[]
) => Node;
manyDecl: (
name: string,
text: string,
Expand Down Expand Up @@ -160,6 +166,12 @@ ${query.text}`
);
break;
}
case ":execlastid": {
nodes.push(
driver.execlastidDecl(lowerName, textName, argIface, query.params)
)
break;
}
case ":one": {
nodes.push(
driver.oneDecl(
Expand Down
12 changes: 11 additions & 1 deletion src/drivers/better-sqlite3.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { SyntaxKind, NodeFlags, Node, TypeNode, factory } from "typescript";
import { SyntaxKind, NodeFlags, Node, TypeNode, factory, FunctionDeclaration } from "typescript";

import { Parameter, Column, Query } from "../gen/plugin/codegen_pb";
import { argName } from "./utlis";
Expand Down Expand Up @@ -427,10 +427,20 @@ export function manyDecl(
);
}

export function execlastidDecl(
funcName: string,
queryName: string,
argIface: string | undefined,
params: Parameter[]
): FunctionDeclaration {
throw new Error('better-sqlite3 driver currently does not support :execlastid')
}

export default {
columnType,
execDecl,
manyDecl,
oneDecl,
preamble,
execlastidDecl,
};
118 changes: 116 additions & 2 deletions src/drivers/mysql2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { SyntaxKind, NodeFlags, TypeNode, factory } from "typescript";

// import { writeFileSync, STDIO } from "javy/fs";

import { Parameter, Column } from "../gen/plugin/codegen_pb";
import { Parameter, Column, Query } from "../gen/plugin/codegen_pb";
import { argName, colName } from "./utlis";

export function columnType(column?: Column): TypeNode {
Expand Down Expand Up @@ -165,7 +165,8 @@ export function columnType(column?: Column): TypeNode {
]);
}

export function preamble(queries: unknown) {
export function preamble(queries: Query[]) {
const hasExecLastIdCmd = queries.some((query) => query.cmd === ":execlastid");
return [
factory.createImportDeclaration(
undefined,
Expand All @@ -178,6 +179,15 @@ export function preamble(queries: unknown) {
undefined,
factory.createIdentifier("RowDataPacket")
),
...(hasExecLastIdCmd
? [
factory.createImportSpecifier(
false,
undefined,
factory.createIdentifier("ResultSetHeader")
),
]
: []),
])
),
factory.createStringLiteral("mysql2/promise"),
Expand Down Expand Up @@ -611,10 +621,114 @@ export function oneDecl(
);
}

export function execlastidDecl(
funcName: string,
queryName: string,
argIface: string | undefined,
params: Parameter[]
) {
const funcParams = funcParamsDecl(argIface, params);

return factory.createFunctionDeclaration(
[
factory.createToken(SyntaxKind.ExportKeyword),
factory.createToken(SyntaxKind.AsyncKeyword),
],
undefined,
factory.createIdentifier(funcName),
undefined,
funcParams,
factory.createTypeReferenceNode(factory.createIdentifier("Promise"), [
factory.createTypeReferenceNode("number", undefined),
]),
factory.createBlock(
[
factory.createVariableStatement(
undefined,
factory.createVariableDeclarationList(
[
factory.createVariableDeclaration(
factory.createArrayBindingPattern([
factory.createBindingElement(
undefined,
undefined,
factory.createIdentifier("result"),
undefined
),
]),
undefined,
undefined,
factory.createAwaitExpression(
factory.createCallExpression(
factory.createPropertyAccessExpression(
factory.createIdentifier("client"),
factory.createIdentifier("query")
),
[
factory.createTypeReferenceNode(
factory.createIdentifier("ResultSetHeader"),
undefined
),
],
[
factory.createObjectLiteralExpression(
[
factory.createPropertyAssignment(
factory.createIdentifier("sql"),
factory.createIdentifier(queryName)
),
factory.createPropertyAssignment(
factory.createIdentifier("values"),
factory.createArrayLiteralExpression(
params.map((param, i) =>
factory.createPropertyAccessExpression(
factory.createIdentifier("args"),
factory.createIdentifier(
argName(i, param.column)
)
)
),
false
)
),
],
true
),
]
)
)
),
],
NodeFlags.Const |
// NodeFlags.Constant |
NodeFlags.AwaitContext |
// NodeFlags.Constant |
NodeFlags.ContextFlags |
NodeFlags.TypeExcludesFlags
)
),
factory.createReturnStatement(
factory.createBinaryExpression(
factory.createPropertyAccessChain(
factory.createIdentifier("result"),
factory.createToken(SyntaxKind.QuestionDotToken),
factory.createIdentifier("insertId")
),
factory.createToken(SyntaxKind.QuestionQuestionToken),
factory.createNumericLiteral(0)
)
),
],
true
)
);
}

export default {
columnType,
preamble,
execDecl,
manyDecl,
oneDecl,
execlastidDecl,
};
12 changes: 11 additions & 1 deletion src/drivers/pg.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { SyntaxKind, NodeFlags, Node, TypeNode, factory } from "typescript";
import { SyntaxKind, NodeFlags, Node, TypeNode, factory, FunctionDeclaration } from "typescript";

import { Parameter, Column, Query } from "../gen/plugin/codegen_pb";
import { argName, colName } from "./utlis";
Expand Down Expand Up @@ -778,10 +778,20 @@ export function manyDecl(
);
}

export function execlastidDecl(
funcName: string,
queryName: string,
argIface: string | undefined,
params: Parameter[]
): FunctionDeclaration {
throw new Error('pg driver currently does not support :execlastid')
}

export default {
columnType,
execDecl,
manyDecl,
oneDecl,
preamble,
execlastidDecl,
};
12 changes: 11 additions & 1 deletion src/drivers/postgres.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { SyntaxKind, NodeFlags, TypeNode, factory } from "typescript";
import { SyntaxKind, NodeFlags, TypeNode, factory, FunctionDeclaration } from "typescript";

import { Parameter, Column } from "../gen/plugin/codegen_pb";
import { argName, colName } from "./utlis";
Expand Down Expand Up @@ -602,10 +602,20 @@ export function oneDecl(
);
}

export function execlastidDecl(
funcName: string,
queryName: string,
argIface: string | undefined,
params: Parameter[]
): FunctionDeclaration {
throw new Error('postgres driver currently does not support :execlastid')
}

export default {
columnType,
preamble,
execDecl,
manyDecl,
oneDecl,
execlastidDecl
};