マクロ

sqlc.arg

SQLクエリ内のパラメーターに名前を付けます。このマクロは、エンジン固有のパラメータープレースホルダーに展開されます。パラメーターの名前が記録され、コード生成時に使用されます。

-- name: GetAuthorByName :one
SELECT *
FROM authors
WHERE lower(name) = sqlc.arg(name);

-- >>> 以下に展開 >>>

-- name: GetAuthorByName :one
SELECT *
FROM authors
WHERE lower(name) = ?;

詳細な例については「パラメータの命名」を参照してください。

sqlc.embed

埋め込みにより、既存のモデル構造体をより多くのクエリで再利用でき、手動でのシリアル化作業を減らすことができます。まず、学生とテストスコアを持つ以下のスキーマを想像してください。

CREATE TABLE students (
  id   bigserial PRIMARY KEY,
  name text,
  age  integer
);

CREATE TABLE test_scores (
  student_id bigint,
  score integer,
  grade text
);

-- name: GetStudentAndScore :one
SELECT sqlc.embed(students), sqlc.embed(test_scores)
FROM students
JOIN test_scores ON test_scores.student_id = students.id
WHERE students.id = $1;

-- >>> 以下に展開 >>>

-- name: GetStudentAndScore :one
SELECT students.*, test_scores.*
FROM students
JOIN test_scores ON test_scores.student_id = students.id
WHERE students.id = $1;

Goメソッドは、各列が構造体に存在する代わりに、StudentのフィールドとテストTestScoreのフィールドを持つ構造体を返します。

type GetStudentAndScoreRow struct {
	Student   Student
	TestScore TestScore
}

func (q *Queries) GetStudentAndScore(ctx context.Context, id int64) (GetStudentAndScoreRow, error) {
    // ...
}

完全な例については「構造体の埋め込み」を参照してください。

sqlc.narg

sqlc.argと同じですが、常にパラメーターをnull許可としてマークします。

-- name: GetAuthorByName :one
SELECT *
FROM authors
WHERE lower(name) = sqlc.narg(name);

-- >>> 以下に展開 >>>

-- name: GetAuthorByName :one
SELECT *
FROM authors
WHERE LOWER(name) = ?;

詳細な例については「パラメータの命名」を参照してください。

sqlc.slice

IN演算子にスライスを渡すことをサポートしていないドライバーの場合、sqlc.sliceマクロは実行時に正しい数のパラメーターを持つ動的クエリを生成します。

/* name: SelectStudents :many */
SELECT * FROM students 
WHERE age IN (sqlc.slice("ages"))

-- >>> 以下に展開 >>>

/* name: SelectStudents :many */
SELECT id, name, age FROM authors 
WHERE age IN (/*SLICE:ages*/?)

/*SLICE:ages*/プレースホルダーはクエリごとに動的に置き換えられるため、このマクロはプリペアドステートメントと一緒に使用することはできません。

完全な例については「クエリにパラメータとしてスライスを渡す」を参照してください。


原文:https://docs.sqlc.dev/en/latest/reference/macros.html