SQLC

SQLC 設定せってい使用しようリファレンス。

YAML 設定

version: "2"
sql:
  - engine: "sqlite"
    queries: "db/query.sql"
    schema: "db/schema.sql"
    gen:
      go:
        # 基本設定
        package: "sqlite"
        out: "db/sqlite"

        # コード生成オプション
        emit_interface: true                     # Querier インターフェースを生成
        emit_json_tags: true                     # JSON タグを生成
        emit_prepared_queries: true              # プリペアドステートメントを使用
        emit_exact_table_names: false            # テーブル名をそのまま使用
        emit_empty_slices: true                  # 空の結果は空のスライスを返す
        emit_exported_queries: true              # SQL クエリをエクスポート
        emit_result_struct_pointers: false       # 結果をポインタとして返す
        emit_params_struct_pointers: false       # パラメータをポインタとして渡す

        # 列挙型関連
        emit_enum_valid_method: true             # 列挙型検証メソッドを生成
        emit_all_enum_values: true               # すべての列挙値リストを生成

        # フィールド命名
        emit_pointers_for_null_types: true       # NULL 値にポインタを使用

        # コメント生成
        emit_file_header_comments: true          # ファイルヘッダーコメント
        emit_doc_comments: true                  # ドキュメントコメントを生成

        # フレームワーク統合
        emit_db_tags: true                       # db タグを生成

設定せっていオプションの説明せつめい

emit_interface

Querier interface を生成せいせい依存いぞんせい注入ちゅうにゅうとテストに役立やくだつ。

type Querier interface {
    GetBook(ctx context.Context, id int64) (Book, error)
    ListBooks(ctx context.Context) ([]Book, error)
}

emit_json_tags

struct に json タグを追加ついか、シリアライズ/デシリアライズに便利べんり

type Book struct {
    ID    int64  `json:"id"`
    Title string `json:"title"`
}

emit_prepared_queries

プリペアドステートメントを生成せいせい、パフォーマンスを向上こうじょう、SQL インジェクションを防止ぼうし

emit_exact_table_names

あたい効果こうか
false (推奨すいしょう)type Book struct {}
truetype Books struct {}

emit_empty_slices

クエリ結果けっかがない場合ばあい、nil ではなくからのスライスをかえす。

// true: books = []Book{}
// false: books = nil
var books []Book

emit_exported_queries

SQL クエリを定数ていすうとしてエクスポート、実際じっさい実行じっこうされる SQL を確認かくにんしやすい。

const getBookSQL = `SELECT * FROM books WHERE id = $1`

emit_result_struct_pointers

あたい効果こうか
falsefunc GetBook() (Book, error)
truefunc GetBook() (*Book, error)

emit_params_struct_pointers

true に設定せっていすると、生成せいせいされたクエリメソッドはポインタ引数ひきすう使用しよう

func (q *Queries) GetUserByID(ctx context.Context, arg *GetUserByIDParams) (*User, error)
func (q *Queries) CreateUser(ctx context.Context, arg *CreateUserParams) (*User, error)

emit_enum_valid_method

列挙型れっきょがたValid() メソッドを自動じどう生成せいせい

func (e UserStatus) Valid() bool {
    switch e {
    case UserStatusActive, UserStatusInactive, UserStatusSuspended:
        return true
    }
    return false
}

emit_all_enum_values

すべての列挙れっきょあたいふくむスライスを生成せいせい

var AllSubscriptionTier = []SubscriptionTier{
    SubscriptionTierFree,
    SubscriptionTierBasic,
    SubscriptionTierPremium,
    SubscriptionTierEnterprise,
}

Annotations

Annotation説明せつめい
:one単一たんいつ結果けっかかえす、WHERE しゅキークエリでよく使用しよう
:many複数ふくすう結果けっかかえす、スライスかたかえ
:exec変更へんこう操作そうさ実行じっこう結果けっかかえさない
:execresultsql.Result をかえす(LastInsertId, RowsAffected)
:execrows影響えいきょうけた行数ぎょうすうかえ
:execlastidINSERT を実行じっこう自動じどう増分ぞうぶん ID をかえ
:batchexecバッチ DML を実行じっこう
:batchoneバッチで単一たんいつクエリ
:batchmanyバッチで複数ふくすうクエリ

データベースサポート

AnnotationPostgreSQLSQLiteMySQL
:one
:many
:exec
:execresult
:execrows
:execlastid
:batchexec
:batchmany
:batchone
  • batch* シリーズは PostgreSQL + pgx/v4、pgx/v5 ドライバのみサポート
  • SQLite の :execresult、:execrows 機能きのうは SQLite 自体じたい制限せいげんける
  • すべての annotation で生成せいせいされるコードには context.Context パラメータがふくまれる