snapshot of https://github.com/sqlc-dev/sqlc.git (main, 2026-09-16; blobs > 131072B omitted)
Some checks failed
kotlin / test (push) Has been skipped
python / test (push) Has been skipped
typescript / test (push) Has been skipped
go / build darwin/amd64 (push) Has been cancelled
go / build linux/amd64 (push) Has been cancelled
go / build windows/amd64 (push) Has been cancelled
go / build darwin/arm64 (push) Has been cancelled
go / build linux/arm64 (push) Has been cancelled
go / build windows/arm64 (push) Has been cancelled
go / test (push) Has been cancelled
go / vuln_check (push) Has been cancelled
Some checks failed
kotlin / test (push) Has been skipped
python / test (push) Has been skipped
typescript / test (push) Has been skipped
go / build darwin/amd64 (push) Has been cancelled
go / build linux/amd64 (push) Has been cancelled
go / build windows/amd64 (push) Has been cancelled
go / build darwin/arm64 (push) Has been cancelled
go / build linux/arm64 (push) Has been cancelled
go / build windows/arm64 (push) Has been cancelled
go / test (push) Has been cancelled
go / vuln_check (push) Has been cancelled
This commit is contained in:
2936
docs/reference/changelog.md
Normal file
2936
docs/reference/changelog.md
Normal file
File diff suppressed because it is too large
Load Diff
29
docs/reference/cli.md
Normal file
29
docs/reference/cli.md
Normal file
@@ -0,0 +1,29 @@
|
||||
# CLI
|
||||
|
||||
```sh
|
||||
Usage:
|
||||
sqlc [command]
|
||||
|
||||
Available Commands:
|
||||
analyze Analyze a query against a schema and output the result columns and parameters
|
||||
compile Statically check SQL for syntax and type errors
|
||||
completion Generate the autocompletion script for the specified shell
|
||||
createdb Create an ephemeral database
|
||||
diff Compare the generated files to the existing files
|
||||
fmt Format SQL queries
|
||||
generate Generate source code from SQL
|
||||
help Help about any command
|
||||
init Create an empty sqlc.yaml settings file
|
||||
parse Parse SQL and output the AST as JSON
|
||||
push Push the schema, queries, and configuration for this project
|
||||
verify Verify schema, queries, and configuration for this project
|
||||
version Print the sqlc version number
|
||||
vet Vet examines queries
|
||||
|
||||
Flags:
|
||||
-f, --file string specify an alternate config file (default: sqlc.yaml)
|
||||
-h, --help help for sqlc
|
||||
--no-database disable database connections (default: false)
|
||||
|
||||
Use "sqlc [command] --help" for more information about a command.
|
||||
```
|
||||
501
docs/reference/config.md
Normal file
501
docs/reference/config.md
Normal file
@@ -0,0 +1,501 @@
|
||||
# Configuration
|
||||
|
||||
The `sqlc` tool is configured via a `sqlc.(yaml|yml)` or `sqlc.json` file. This
|
||||
file must be in the directory where the `sqlc` command is run.
|
||||
|
||||
## Version 2
|
||||
|
||||
```yaml
|
||||
version: "2"
|
||||
cloud:
|
||||
project: "<PROJECT_ID>"
|
||||
sql:
|
||||
- schema: "postgresql/schema.sql"
|
||||
queries: "postgresql/query.sql"
|
||||
engine: "postgresql"
|
||||
gen:
|
||||
go:
|
||||
package: "authors"
|
||||
out: "postgresql"
|
||||
database:
|
||||
managed: true
|
||||
rules:
|
||||
- sqlc/db-prepare
|
||||
- schema: "mysql/schema.sql"
|
||||
queries: "mysql/query.sql"
|
||||
engine: "mysql"
|
||||
gen:
|
||||
go:
|
||||
package: "authors"
|
||||
out: "mysql"
|
||||
```
|
||||
|
||||
### sql
|
||||
|
||||
Each mapping in the `sql` collection has the following keys:
|
||||
|
||||
- `name`:
|
||||
- An human-friendly identifier for this query set. Optional.
|
||||
- `engine`:
|
||||
- One of `postgresql`, `mysql` or `sqlite`.
|
||||
- `schema`:
|
||||
- Directory of SQL migrations or path to single SQL file; or a list of paths.
|
||||
- `queries`:
|
||||
- Directory of SQL queries or path to single SQL file; or a list of paths.
|
||||
- `codegen`:
|
||||
- A collection of mappings to configure code generators. See [codegen](#codegen) for the supported keys.
|
||||
- `gen`:
|
||||
- A mapping to configure built-in code generators. See [gen](#gen) for the supported keys.
|
||||
- `database`:
|
||||
- A mapping to configure database connections. See [database](#database) for the supported keys.
|
||||
- `rules`:
|
||||
- A collection of rule names to run via `sqlc vet`. See [rules](#rules) for configuration options.
|
||||
- `analyzer`:
|
||||
- A mapping to configure query analysis. See [analyzer](#analyzer) for the supported keys.
|
||||
- `strict_function_checks`
|
||||
- If true, return an error if a called SQL function does not exist. Defaults to `false`.
|
||||
- `strict_order_by`
|
||||
- If true, return an error if a order by column is ambiguous. Defaults to `true`.
|
||||
|
||||
### codegen
|
||||
|
||||
The `codegen` mapping supports the following keys:
|
||||
|
||||
- `out`:
|
||||
- Output directory for generated code.
|
||||
- `plugin`:
|
||||
- The name of the plugin. Must be defined in the `plugins` collection.
|
||||
- `options`:
|
||||
- A mapping of plugin-specific options.
|
||||
|
||||
```yaml
|
||||
version: '2'
|
||||
plugins:
|
||||
- name: py
|
||||
wasm:
|
||||
url: https://github.com/sqlc-dev/sqlc-gen-python/releases/download/v0.16.0-alpha/sqlc-gen-python.wasm
|
||||
sha256: 428476c7408fd4c032da4ec74e8a7344f4fa75e0f98a5a3302f238283b9b95f2
|
||||
sql:
|
||||
- schema: "schema.sql"
|
||||
queries: "query.sql"
|
||||
engine: postgresql
|
||||
codegen:
|
||||
- out: src/authors
|
||||
plugin: py
|
||||
options:
|
||||
package: authors
|
||||
emit_sync_querier: true
|
||||
emit_async_querier: true
|
||||
query_parameter_limit: 5
|
||||
```
|
||||
|
||||
### database
|
||||
|
||||
The `database` mapping supports the following keys:
|
||||
|
||||
- `managed`:
|
||||
- If true, connect to a [managed database](../howto/managed-databases.md). Defaults to `false`.
|
||||
- `uri`:
|
||||
- Database connection URI
|
||||
|
||||
The `uri` string can contain references to environment variables using the `${...}`
|
||||
syntax. In the following example, the connection string will have the value of
|
||||
the `PG_PASSWORD` environment variable set as its password.
|
||||
|
||||
```yaml
|
||||
version: '2'
|
||||
sql:
|
||||
- schema: schema.sql
|
||||
queries: query.sql
|
||||
engine: postgresql
|
||||
database:
|
||||
uri: postgresql://postgres:${PG_PASSWORD}@localhost:5432/authors
|
||||
gen:
|
||||
go:
|
||||
package: authors
|
||||
out: postgresql
|
||||
```
|
||||
|
||||
### analyzer
|
||||
|
||||
The `analyzer` mapping supports the following keys:
|
||||
|
||||
- `database`:
|
||||
- If false, do not use the configured database for query analysis. Defaults to `true`.
|
||||
|
||||
### gen
|
||||
|
||||
The `gen` mapping supports the following keys:
|
||||
|
||||
#### go
|
||||
|
||||
- `package`:
|
||||
- The package name to use for the generated code. Defaults to `out` basename.
|
||||
- `out`:
|
||||
- Output directory for generated code.
|
||||
- `sql_package`:
|
||||
- Either `pgx/v4`, `pgx/v5` or `database/sql`. Defaults to `database/sql`.
|
||||
- `sql_driver`:
|
||||
- Either `github.com/jackc/pgx/v4`, `github.com/jackc/pgx/v5`, `github.com/lib/pq` or `github.com/go-sql-driver/mysql`. No defaults. Required if query annotation `:copyfrom` is used.
|
||||
- `emit_db_tags`:
|
||||
- If true, add DB tags to generated structs. Defaults to `false`.
|
||||
- `emit_prepared_queries`:
|
||||
- If true, include support for prepared queries. Defaults to `false`.
|
||||
- `emit_interface`:
|
||||
- If true, output a `Querier` interface in the generated package. Defaults to `false`.
|
||||
- `emit_exact_table_names`:
|
||||
- If true, struct names will mirror table names. Otherwise, sqlc attempts to singularize plural table names. Defaults to `false`.
|
||||
- `emit_empty_slices`:
|
||||
- If true, slices returned by `:many` queries will be empty instead of `nil`. Defaults to `false`.
|
||||
- `emit_exported_queries`:
|
||||
- If true, autogenerated SQL statement can be exported to be accessed by another package.
|
||||
- `emit_json_tags`:
|
||||
- If true, add JSON tags to generated structs. Defaults to `false`.
|
||||
- `emit_result_struct_pointers`:
|
||||
- If true, query results are returned as pointers to structs. Queries returning multiple results are returned as slices of pointers. Defaults to `false`.
|
||||
- `emit_params_struct_pointers`:
|
||||
- If true, parameters are passed as pointers to structs. Defaults to `false`.
|
||||
- `emit_methods_with_db_argument`:
|
||||
- If true, generated methods will accept a DBTX argument instead of storing a DBTX on the `*Queries` struct. Defaults to `false`.
|
||||
- `emit_pointers_for_null_types`:
|
||||
- If true, generated types for nullable columns are emitted as pointers (ie. `*string`) instead of `database/sql` null types (ie. `NullString`). Currently only supported for PostgreSQL if `sql_package` is `pgx/v4` or `pgx/v5`, and for SQLite. Defaults to `false`. Nullable enum columns also follow this setting unless `emit_pointers_for_null_enum_types` is set.
|
||||
- `emit_pointers_for_null_enum_types`:
|
||||
- Overrides `emit_pointers_for_null_types` for nullable enum columns only. When `true`, nullable enum columns are emitted as pointers (ie. `*UserRole`). When `false`, nullable enum columns use the generated `NullUserRole` wrapper struct even if `emit_pointers_for_null_types` is true. Set this to `false` to keep the pre-v1.31 behavior when upgrading. Only applies to PostgreSQL with `sql_package` `pgx/v4` or `pgx/v5`.
|
||||
- `emit_enum_valid_method`:
|
||||
- If true, generate a Valid method on enum types,
|
||||
indicating whether a string is a valid enum value.
|
||||
- `emit_all_enum_values`:
|
||||
- If true, emit a function per enum type
|
||||
that returns all valid enum values.
|
||||
- `emit_sql_as_comment`:
|
||||
- If true, emits the SQL statement as a code-block comment above the generated function, appending to any existing comments. Defaults to `false`.
|
||||
- `build_tags`:
|
||||
- If set, add a `//go:build <build_tags>` directive at the beginning of each generated Go file.
|
||||
- `initialisms`:
|
||||
- An array of [initialisms](https://google.github.io/styleguide/go/decisions.html#initialisms) to upper-case. For example, `app_id` becomes `AppID`. Defaults to `["id"]`.
|
||||
- `json_tags_id_uppercase`:
|
||||
- If true, "Id" in json tags will be uppercase. If false, will be camelcase. Defaults to `false`
|
||||
- `json_tags_case_style`:
|
||||
- `camel` for camelCase, `pascal` for PascalCase, `snake` for snake_case or `none` to use the column name in the DB. Defaults to `none`.
|
||||
- `omit_unused_structs`:
|
||||
- If `true`, sqlc won't generate table and enum structs that aren't used in queries for a given package. Defaults to `false`.
|
||||
- `output_batch_file_name`:
|
||||
- Customize the name of the batch file. Defaults to `batch.go`.
|
||||
- `output_db_file_name`:
|
||||
- Customize the name of the db file. Defaults to `db.go`.
|
||||
- `output_models_file_name`:
|
||||
- Customize the name of the models file. Defaults to `models.go`.
|
||||
- `output_querier_file_name`:
|
||||
- Customize the name of the querier file. Defaults to `querier.go`.
|
||||
- `output_copyfrom_file_name`:
|
||||
- Customize the name of the copyfrom file. Defaults to `copyfrom.go`.
|
||||
- `output_files_suffix`:
|
||||
- If specified the suffix will be added to the name of the generated files.
|
||||
- `query_parameter_limit`:
|
||||
- The number of positional arguments that will be generated for Go functions. To always emit a parameter struct, set this to `0`. Defaults to `1`.
|
||||
- `rename`:
|
||||
- Customize the name of generated struct fields. See [Renaming fields](../howto/rename.md) for usage information.
|
||||
- `overrides`:
|
||||
- A collection of configurations to override sqlc's default Go type choices. See [Overriding types](../howto/overrides.md) for usage information.
|
||||
|
||||
##### overrides
|
||||
|
||||
See [Overriding types](../howto/overrides.md) for an in-depth guide to using type overrides.
|
||||
|
||||
#### kotlin
|
||||
|
||||
> Removed in v1.17.0 and replaced by the [sqlc-gen-kotlin](https://github.com/sqlc-dev/sqlc-gen-kotlin) plugin. Follow the [migration guide](../guides/migrating-to-sqlc-gen-kotlin.md) to switch.
|
||||
|
||||
- `package`:
|
||||
- The package name to use for the generated code.
|
||||
- `out`:
|
||||
- Output directory for generated code.
|
||||
- `emit_exact_table_names`:
|
||||
- If true, use the exact table name for generated models. Otherwise, guess a singular form. Defaults to `false`.
|
||||
|
||||
#### python
|
||||
|
||||
> Removed in v1.17.0 and replaced by the [sqlc-gen-python](https://github.com/sqlc-dev/sqlc-gen-python) plugin. Follow the [migration guide](../guides/migrating-to-sqlc-gen-python.md) to switch.
|
||||
|
||||
- `package`:
|
||||
- The package name to use for the generated code.
|
||||
- `out`:
|
||||
- Output directory for generated code.
|
||||
- `emit_exact_table_names`:
|
||||
- If true, use the exact table name for generated models. Otherwise, guess a singular form. Defaults to `false`.
|
||||
- `emit_sync_querier`:
|
||||
- If true, generate a class with synchronous methods. Defaults to `false`.
|
||||
- `emit_async_querier`:
|
||||
- If true, generate a class with asynchronous methods. Defaults to `false`.
|
||||
- `emit_pydantic_models`:
|
||||
- If true, generate classes that inherit from `pydantic.BaseModel`. Otherwise, define classes using the `dataclass` decorator. Defaults to `false`.
|
||||
|
||||
#### json
|
||||
|
||||
- `out`:
|
||||
- Output directory for the generated JSON.
|
||||
- `filename`:
|
||||
- Filename for the generated JSON document. Defaults to `codegen_request.json`.
|
||||
- `indent`:
|
||||
- Indent string to use in the JSON document. Defaults to ` `.
|
||||
|
||||
### plugins
|
||||
|
||||
Each mapping in the `plugins` collection has the following keys:
|
||||
|
||||
- `name`:
|
||||
- The name of this plugin. Required
|
||||
- `env`
|
||||
- A list of environment variables to pass to the plugin. By default, no environment variables are passed.
|
||||
- `process`: A mapping with a single `cmd` key
|
||||
- `cmd`:
|
||||
- The executable to call when using this plugin
|
||||
- `format`:
|
||||
- The format expected. Supports `json` and `protobuf` formats. Defaults to `protobuf`.
|
||||
- `wasm`: A mapping with a two keys `url` and `sha256`
|
||||
- `url`:
|
||||
- The URL to fetch the WASM file. Supports the `https://` or `file://` schemes.
|
||||
- `sha256`
|
||||
- The SHA256 checksum for the downloaded file.
|
||||
|
||||
```yaml
|
||||
version: "2"
|
||||
plugins:
|
||||
- name: "py"
|
||||
wasm:
|
||||
url: "https://github.com/sqlc-dev/sqlc-gen-python/releases/download/v0.16.0-alpha/sqlc-gen-python.wasm"
|
||||
sha256: "428476c7408fd4c032da4ec74e8a7344f4fa75e0f98a5a3302f238283b9b95f2"
|
||||
- name: "js"
|
||||
env:
|
||||
- PATH
|
||||
process:
|
||||
cmd: "sqlc-gen-json"
|
||||
```
|
||||
|
||||
### rules
|
||||
|
||||
Each mapping in the `rules` collection has the following keys:
|
||||
|
||||
- `name`:
|
||||
- The name of this rule. Required
|
||||
- `rule`:
|
||||
- A [Common Expression Language (CEL)](https://github.com/google/cel-spec) expression. Required.
|
||||
- `message`:
|
||||
- An optional message shown when this rule evaluates to `true`.
|
||||
|
||||
See the [vet](../howto/vet.md) documentation for a list of built-in rules and
|
||||
help writing custom rules.
|
||||
|
||||
```yaml
|
||||
version: "2"
|
||||
sql:
|
||||
- schema: "query.sql"
|
||||
queries: "query.sql"
|
||||
engine: "postgresql"
|
||||
gen:
|
||||
go:
|
||||
package: "authors"
|
||||
out: "db"
|
||||
rules:
|
||||
- no-pg
|
||||
- no-delete
|
||||
- only-one-param
|
||||
- no-exec
|
||||
rules:
|
||||
- name: no-pg
|
||||
message: "invalid engine: postgresql"
|
||||
rule: |
|
||||
config.engine == "postgresql"
|
||||
- name: no-delete
|
||||
message: "don't use delete statements"
|
||||
rule: |
|
||||
query.sql.contains("DELETE")
|
||||
- name: only-one-param
|
||||
message: "too many parameters"
|
||||
rule: |
|
||||
query.params.size() > 1
|
||||
- name: no-exec
|
||||
message: "don't use exec"
|
||||
rule: |
|
||||
query.cmd == "exec"
|
||||
```
|
||||
|
||||
### Global overrides
|
||||
|
||||
Sometimes, the same configuration must be done across various specifications of
|
||||
code generation. Then a global definition for type overriding and field
|
||||
renaming can be done using the `overrides` mapping the following manner:
|
||||
|
||||
```yaml
|
||||
version: "2"
|
||||
overrides:
|
||||
go:
|
||||
rename:
|
||||
id: "Identifier"
|
||||
overrides:
|
||||
- db_type: "pg_catalog.timestamptz"
|
||||
nullable: true
|
||||
engine: "postgresql"
|
||||
go_type:
|
||||
import: "gopkg.in/guregu/null.v4"
|
||||
package: "null"
|
||||
type: "Time"
|
||||
sql:
|
||||
- schema: "postgresql/schema.sql"
|
||||
queries: "postgresql/query.sql"
|
||||
engine: "postgresql"
|
||||
gen:
|
||||
go:
|
||||
package: "authors"
|
||||
out: "postgresql"
|
||||
- schema: "mysql/schema.sql"
|
||||
queries: "mysql/query.sql"
|
||||
engine: "mysql"
|
||||
gen:
|
||||
go:
|
||||
package: "authors"
|
||||
out: "mysql"
|
||||
```
|
||||
|
||||
With the previous configuration, whenever a struct field is generated from a
|
||||
table column that is called `id`, it will generated as `Identifier`.
|
||||
|
||||
Also, whenever there is a nullable `timestamp with time zone` column in a
|
||||
Postgres table, it will be generated as `null.Time`. Note that the mapping for
|
||||
global type overrides has a field called `engine` that is absent in the regular
|
||||
type overrides. This field is only used when there are multiple definitions
|
||||
using multiple engines. Otherwise, the value of the `engine` key
|
||||
defaults to the engine that is currently being used.
|
||||
|
||||
Currently, type overrides and field renaming, both global and regular, are only
|
||||
fully supported in Go.
|
||||
|
||||
## Version 1
|
||||
|
||||
```yaml
|
||||
version: "1"
|
||||
packages:
|
||||
- name: "db"
|
||||
path: "internal/db"
|
||||
queries: "./sql/query/"
|
||||
schema: "./sql/schema/"
|
||||
engine: "postgresql"
|
||||
emit_db_tags: false
|
||||
emit_prepared_queries: true
|
||||
emit_interface: false
|
||||
emit_exact_table_names: false
|
||||
emit_empty_slices: false
|
||||
emit_exported_queries: false
|
||||
emit_json_tags: true
|
||||
emit_result_struct_pointers: false
|
||||
emit_params_struct_pointers: false
|
||||
emit_methods_with_db_argument: false
|
||||
emit_pointers_for_null_types: false
|
||||
emit_enum_valid_method: false
|
||||
emit_all_enum_values: false
|
||||
build_tags: "some_tag"
|
||||
json_tags_case_style: "camel"
|
||||
omit_unused_structs: false
|
||||
output_batch_file_name: "batch.go"
|
||||
output_db_file_name: "db.go"
|
||||
output_models_file_name: "models.go"
|
||||
output_querier_file_name: "querier.go"
|
||||
output_copyfrom_file_name: "copyfrom.go"
|
||||
query_parameter_limit: 1
|
||||
```
|
||||
|
||||
### packages
|
||||
|
||||
Each mapping in the `packages` collection has the following keys:
|
||||
|
||||
- `name`:
|
||||
- The package name to use for the generated code. Defaults to `path` basename.
|
||||
- `path`:
|
||||
- Output directory for generated code.
|
||||
- `queries`:
|
||||
- Directory of SQL queries or path to single SQL file; or a list of paths.
|
||||
- `schema`:
|
||||
- Directory of SQL migrations or path to single SQL file; or a list of paths.
|
||||
- `engine`:
|
||||
- Either `postgresql` or `mysql`. Defaults to `postgresql`.
|
||||
- `sql_package`:
|
||||
- Either `pgx/v4`, `pgx/v5` or `database/sql`. Defaults to `database/sql`.
|
||||
- `overrides`:
|
||||
- A list of type override configurations. See the [Overriding types](../howto/overrides.md) guide for details.
|
||||
- `emit_db_tags`:
|
||||
- If true, add DB tags to generated structs. Defaults to `false`.
|
||||
- `emit_prepared_queries`:
|
||||
- If true, include support for prepared queries. Defaults to `false`.
|
||||
- `emit_interface`:
|
||||
- If true, output a `Querier` interface in the generated package. Defaults to `false`.
|
||||
- `emit_exact_table_names`:
|
||||
- If true, struct names will mirror table names. Otherwise, sqlc attempts to singularize plural table names. Defaults to `false`.
|
||||
- `emit_empty_slices`:
|
||||
- If true, slices returned by `:many` queries will be empty instead of `nil`. Defaults to `false`.
|
||||
- `emit_exported_queries`:
|
||||
- If true, autogenerated SQL statement can be exported to be accessed by another package.
|
||||
- `emit_json_tags`:
|
||||
- If true, add JSON tags to generated structs. Defaults to `false`.
|
||||
- `emit_result_struct_pointers`:
|
||||
- If true, query results are returned as pointers to structs. Queries returning multiple results are returned as slices of pointers. Defaults to `false`.
|
||||
- `emit_params_struct_pointers`:
|
||||
- If true, parameters are passed as pointers to structs. Defaults to `false`.
|
||||
- `emit_methods_with_db_argument`:
|
||||
- If true, generated methods will accept a DBTX argument instead of storing a DBTX on the `*Queries` struct. Defaults to `false`.
|
||||
- `emit_pointers_for_null_types`:
|
||||
- If true and `sql_package` is set to `pgx/v4` or `pgx/v5`, generated types for nullable columns are emitted as pointers (ie. `*string`) instead of `database/sql` null types (ie. `NullString`). Defaults to `false`. Nullable enum columns also follow this setting unless `emit_pointers_for_null_enum_types` is set.
|
||||
- `emit_pointers_for_null_enum_types`:
|
||||
- Overrides `emit_pointers_for_null_types` for nullable enum columns only. When `true`, nullable enum columns are emitted as pointers (ie. `*UserRole`). When `false`, nullable enum columns use the generated `NullUserRole` wrapper struct even if `emit_pointers_for_null_types` is true. Set this to `false` to keep the pre-v1.31 behavior when upgrading. Only applies to PostgreSQL with `sql_package` `pgx/v4` or `pgx/v5`.
|
||||
- `emit_enum_valid_method`:
|
||||
- If true, generate a Valid method on enum types,
|
||||
indicating whether a string is a valid enum value.
|
||||
- `emit_all_enum_values`:
|
||||
- If true, emit a function per enum type
|
||||
that returns all valid enum values.
|
||||
- `build_tags`:
|
||||
- If set, add a `//go:build <build_tags>` directive at the beginning of each generated Go file.
|
||||
- `json_tags_case_style`:
|
||||
- `camel` for camelCase, `pascal` for PascalCase, `snake` for snake_case or `none` to use the column name in the DB. Defaults to `none`.
|
||||
- `omit_unused_structs`:
|
||||
- If `true`, sqlc won't generate table and enum structs that aren't used in queries for a given package. Defaults to `false`.
|
||||
- `output_batch_file_name`:
|
||||
- Customize the name of the batch file. Defaults to `batch.go`.
|
||||
- `output_db_file_name`:
|
||||
- Customize the name of the db file. Defaults to `db.go`.
|
||||
- `output_models_file_name`:
|
||||
- Customize the name of the models file. Defaults to `models.go`.
|
||||
- `output_querier_file_name`:
|
||||
- Customize the name of the querier file. Defaults to `querier.go`.
|
||||
- `output_copyfrom_file_name`:
|
||||
- Customize the name of the copyfrom file. Defaults to `copyfrom.go`.
|
||||
- `output_files_suffix`:
|
||||
- If specified the suffix will be added to the name of the generated files.
|
||||
- `query_parameter_limit`:
|
||||
- Positional arguments that will be generated in Go functions (`>= 0`). To always emit a parameter struct, you would need to set it to `0`. Defaults to `1`.
|
||||
|
||||
### overrides
|
||||
|
||||
See the version 1 configuration section of the [Overriding types](../howto/overrides.md#version-1-configuration) guide for details.
|
||||
|
||||
### rename
|
||||
|
||||
Struct field names are generated from column names using a simple algorithm:
|
||||
split the column name on underscores and capitalize the first letter of each
|
||||
part.
|
||||
|
||||
```
|
||||
account -> Account
|
||||
spotify_url -> SpotifyUrl
|
||||
app_id -> AppID
|
||||
```
|
||||
|
||||
If you're not happy with a field's generated name, use the `rename` mapping
|
||||
to pick a new name. The keys are column names and the values are the struct
|
||||
field name to use.
|
||||
|
||||
```yaml
|
||||
version: "1"
|
||||
packages: [...]
|
||||
rename:
|
||||
spotify_url: "SpotifyURL"
|
||||
```
|
||||
388
docs/reference/datatypes.md
Normal file
388
docs/reference/datatypes.md
Normal file
@@ -0,0 +1,388 @@
|
||||
# Datatypes
|
||||
|
||||
`sqlc` attempts to make reasonable default choices when mapping internal
|
||||
database types to Go types. Choices for more complex types are described below.
|
||||
|
||||
If you're unsatisfied with the default, you can override any type using the
|
||||
[overrides list](config.md#overrides) in your `sqlc` config file.
|
||||
|
||||
## Arrays
|
||||
|
||||
PostgreSQL [arrays](https://www.postgresql.org/docs/current/arrays.html) are
|
||||
materialized as Go slices.
|
||||
|
||||
```sql
|
||||
CREATE TABLE places (
|
||||
name text not null,
|
||||
tags text[]
|
||||
);
|
||||
```
|
||||
|
||||
```go
|
||||
package db
|
||||
|
||||
type Place struct {
|
||||
Name string
|
||||
Tags []string
|
||||
}
|
||||
```
|
||||
|
||||
## Dates and times
|
||||
|
||||
All date and time types are returned as `time.Time` structs. For
|
||||
null time or date values, the `NullTime` type from `database/sql` is used.
|
||||
|
||||
The `pgx/v5` sql package uses the appropriate pgx types.
|
||||
|
||||
For MySQL users relying on `github.com/go-sql-driver/mysql`, ensure that
|
||||
`parseTime=true` is added to your database connection string.
|
||||
|
||||
```sql
|
||||
CREATE TABLE authors (
|
||||
id SERIAL PRIMARY KEY,
|
||||
created_at timestamp NOT NULL DEFAULT NOW(),
|
||||
updated_at timestamp
|
||||
);
|
||||
```
|
||||
|
||||
```go
|
||||
package db
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Author struct {
|
||||
ID int
|
||||
CreatedAt time.Time
|
||||
UpdatedAt sql.NullTime
|
||||
}
|
||||
```
|
||||
|
||||
## Enums
|
||||
|
||||
PostgreSQL [enums](https://www.postgresql.org/docs/current/datatype-enum.html) are
|
||||
mapped to an aliased string type.
|
||||
|
||||
```sql
|
||||
CREATE TYPE status AS ENUM (
|
||||
'open',
|
||||
'closed'
|
||||
);
|
||||
|
||||
CREATE TABLE stores (
|
||||
name text PRIMARY KEY,
|
||||
status status NOT NULL
|
||||
);
|
||||
```
|
||||
|
||||
```go
|
||||
package db
|
||||
|
||||
type Status string
|
||||
|
||||
const (
|
||||
StatusOpen Status = "open"
|
||||
StatusClosed Status = "closed"
|
||||
)
|
||||
|
||||
type Store struct {
|
||||
Name string
|
||||
Status Status
|
||||
}
|
||||
```
|
||||
|
||||
## Null
|
||||
|
||||
For structs, null values are represented using the appropriate type from the
|
||||
`database/sql` or `pgx` package.
|
||||
|
||||
```sql
|
||||
CREATE TABLE authors (
|
||||
id SERIAL PRIMARY KEY,
|
||||
name text NOT NULL,
|
||||
bio text
|
||||
);
|
||||
```
|
||||
|
||||
```go
|
||||
package db
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
)
|
||||
|
||||
type Author struct {
|
||||
ID int
|
||||
Name string
|
||||
Bio sql.NullString
|
||||
}
|
||||
```
|
||||
|
||||
## UUIDs
|
||||
|
||||
For UUID support, sqlc uses the `github.com/google/uuid` package by default.
|
||||
The pgx/v5 sql package uses `pgtype.UUID`.
|
||||
|
||||
```sql
|
||||
CREATE TABLE records (
|
||||
id uuid PRIMARY KEY
|
||||
);
|
||||
```
|
||||
|
||||
```go
|
||||
package db
|
||||
|
||||
import (
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type Author struct {
|
||||
ID uuid.UUID
|
||||
}
|
||||
```
|
||||
|
||||
### Using the standard library uuid package
|
||||
|
||||
Go 1.27 added a [`uuid`](https://pkg.go.dev/uuid) package to the standard
|
||||
library. sqlc will use this package by default in a future release. Until
|
||||
then, use it today with type overrides
|
||||
(see [Overriding types](../howto/overrides.md) for details).
|
||||
|
||||
Two overrides are required: one for non-nullable columns and one for nullable
|
||||
columns. The standard library does not include a `NullUUID` type, so nullable
|
||||
columns map to `*uuid.UUID` instead.
|
||||
|
||||
```yaml
|
||||
version: "2"
|
||||
sql:
|
||||
- engine: "postgresql"
|
||||
schema: "schema.sql"
|
||||
queries: "query.sql"
|
||||
gen:
|
||||
go:
|
||||
package: "db"
|
||||
out: "db"
|
||||
sql_package: "pgx/v5"
|
||||
overrides:
|
||||
- db_type: "uuid"
|
||||
go_type: "uuid.UUID"
|
||||
- db_type: "uuid"
|
||||
nullable: true
|
||||
go_type:
|
||||
import: "uuid"
|
||||
type: "UUID"
|
||||
pointer: true
|
||||
```
|
||||
|
||||
With this configuration, a table with both nullable and non-nullable `uuid`
|
||||
columns:
|
||||
|
||||
```sql
|
||||
CREATE TABLE records (
|
||||
id uuid PRIMARY KEY,
|
||||
external_id uuid
|
||||
);
|
||||
```
|
||||
|
||||
generates:
|
||||
|
||||
```go
|
||||
package db
|
||||
|
||||
import (
|
||||
"uuid"
|
||||
)
|
||||
|
||||
type Record struct {
|
||||
ID uuid.UUID
|
||||
ExternalID *uuid.UUID
|
||||
}
|
||||
```
|
||||
|
||||
These overrides work with both the `pgx/v5` and `database/sql` sql packages.
|
||||
pgx supports any type whose underlying type is `[16]byte`, and as of Go 1.27
|
||||
`database/sql` converts `uuid.UUID` values in both directions: parameters are
|
||||
bound via `driver.DefaultParameterConverter` and results are scanned into
|
||||
`uuid.UUID` and `*uuid.UUID` destinations, with `nil` representing `NULL`.
|
||||
|
||||
For MySQL, there is no native `uuid` data type. When using `UUID_TO_BIN` to store a `UUID()`, the underlying field type is `BINARY(16)` which by default sqlc would map to `sql.NullString`. To have sqlc automatically convert these fields to a `uuid.UUID` type, use an overide on the column storing the `uuid`
|
||||
(see [Overriding types](../howto/overrides.md) for details).
|
||||
|
||||
```json
|
||||
{
|
||||
"overrides": [
|
||||
{
|
||||
"column": "*.uuid",
|
||||
"go_type": "github.com/google/uuid.UUID"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## JSON
|
||||
|
||||
By default, sqlc will generate the `[]byte`, `pgtype.JSON` or `json.RawMessage` for JSON column type.
|
||||
But if you use the `pgx/v5` sql package then you can specify a struct instead of the default type
|
||||
(see [Overriding types](../howto/overrides.md) for details).
|
||||
The `pgx` implementation will marshal/unmarshal the struct automatically.
|
||||
|
||||
```go
|
||||
package dto
|
||||
|
||||
type BookData struct {
|
||||
Genres []string `json:"genres"`
|
||||
Title string `json:"title"`
|
||||
Published bool `json:"published"`
|
||||
}
|
||||
```
|
||||
|
||||
```sql
|
||||
CREATE TABLE books (
|
||||
data jsonb
|
||||
);
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"overrides": [
|
||||
{
|
||||
"column": "books.data",
|
||||
"go_type": {
|
||||
"import":"example.com/db",
|
||||
"package": "dto",
|
||||
"type":"BookData",
|
||||
"pointer": true
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
```go
|
||||
package db
|
||||
|
||||
import (
|
||||
"example.com/db/dto"
|
||||
)
|
||||
|
||||
type Book struct {
|
||||
Data *dto.BookData
|
||||
}
|
||||
```
|
||||
|
||||
## TEXT
|
||||
|
||||
In PostgreSQL, when you have a column with the TEXT type, sqlc will map it to a Go string by default. This default mapping applies to `TEXT` columns that are not nullable. However, for nullable `TEXT` columns, sqlc maps them to `pgtype.Text` when using the pgx/v5 driver. This distinction is crucial for developers looking to handle null values appropriately in their Go applications.
|
||||
|
||||
To accommodate nullable strings and map them to `*string` in Go, you can use the `emit_pointers_for_null_types` option in your sqlc configuration. This option ensures that nullable SQL columns are represented as pointer types in Go, allowing for a clear distinction between null and non-null values. Another way to do this is by passing the option `pointer: true` when you are overriding the `TEXT` datatype in your sqlc config file (see [Overriding types](../howto/overrides.md) for details).
|
||||
|
||||
## Geometry
|
||||
|
||||
### PostGIS
|
||||
|
||||
#### Using `github.com/twpayne/go-geos` (pgx/v5 only)
|
||||
|
||||
sqlc can be configured to use the [geos](https://github.com/twpayne/go-geos)
|
||||
package for working with PostGIS geometry types in [GEOS](https://libgeos.org/).
|
||||
|
||||
There are three steps:
|
||||
|
||||
1. Configure sqlc to use `*github.com/twpayne/go-geos.Geom` for geometry types (see [Overriding types](../howto/overrides.md) for details).
|
||||
2. Call `github.com/twpayne/pgx-geos.Register` on each
|
||||
`*github.com/jackc/pgx/v5.Conn`.
|
||||
3. Annotate your SQL with `::geometry` typecasts, if needed.
|
||||
|
||||
```sql
|
||||
-- Multipolygons in British National Grid (epsg:27700)
|
||||
create table shapes(
|
||||
id serial,
|
||||
name varchar,
|
||||
geom geometry(Multipolygon, 27700)
|
||||
);
|
||||
|
||||
-- name: GetCentroids :many
|
||||
SELECT id, name, ST_Centroid(geom)::geometry FROM shapes;
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"version": 2,
|
||||
"gen": {
|
||||
"go": {
|
||||
"overrides": [
|
||||
{
|
||||
"db_type": "geometry",
|
||||
"go_type": {
|
||||
"import": "github.com/twpayne/go-geos",
|
||||
"package": "geos",
|
||||
"pointer": true,
|
||||
"type": "Geom"
|
||||
},
|
||||
"nullable": true
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```go
|
||||
import (
|
||||
"github.com/twpayne/go-geos"
|
||||
pgxgeos "github.com/twpayne/pgx-geos"
|
||||
)
|
||||
|
||||
// ...
|
||||
|
||||
config.AfterConnect = func(ctx context.Context, conn *pgx.Conn) error {
|
||||
if err := pgxgeos.Register(ctx, conn, geos.NewContext()); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
#### Using `github.com/twpayne/go-geom`
|
||||
|
||||
sqlc can be configured to use the [geom](https://github.com/twpayne/go-geom)
|
||||
package for working with PostGIS geometry types. See [Overriding types](../howto/overrides.md) for more information.
|
||||
|
||||
```sql
|
||||
-- Multipolygons in British National Grid (epsg:27700)
|
||||
create table shapes(
|
||||
id serial,
|
||||
name varchar,
|
||||
geom geometry(Multipolygon, 27700)
|
||||
);
|
||||
|
||||
-- name: GetShapes :many
|
||||
SELECT * FROM shapes;
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"version": "1",
|
||||
"packages": [
|
||||
{
|
||||
"path": "db",
|
||||
"engine": "postgresql",
|
||||
"schema": "query.sql",
|
||||
"queries": "query.sql"
|
||||
}
|
||||
],
|
||||
"overrides": [
|
||||
{
|
||||
"db_type": "geometry",
|
||||
"go_type": "github.com/twpayne/go-geom.MultiPolygon"
|
||||
},
|
||||
{
|
||||
"db_type": "geometry",
|
||||
"go_type": "github.com/twpayne/go-geom.MultiPolygon",
|
||||
"nullable": true
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
190
docs/reference/environment-variables.md
Normal file
190
docs/reference/environment-variables.md
Normal file
@@ -0,0 +1,190 @@
|
||||
# Environment variables
|
||||
|
||||
## SQLCEXPERIMENT
|
||||
|
||||
The `SQLCEXPERIMENT` variable controls experimental features within sqlc. It is
|
||||
a comma-separated list of experiment names. This is modeled after Go's
|
||||
[GOEXPERIMENT](https://pkg.go.dev/internal/goexperiment) environment variable.
|
||||
|
||||
Experiment names can be prefixed with `no` to explicitly disable them.
|
||||
|
||||
```
|
||||
SQLCEXPERIMENT=foo,bar # enable foo and bar experiments
|
||||
SQLCEXPERIMENT=nofoo # explicitly disable foo experiment
|
||||
SQLCEXPERIMENT=foo,nobar # enable foo, disable bar
|
||||
```
|
||||
|
||||
The following experiments are defined:
|
||||
|
||||
### coreanalyzer
|
||||
|
||||
Routes `sqlc generate` through the core catalog and analyzer instead of each
|
||||
engine's own analysis path. This is the same analysis used by `sqlc analyze`,
|
||||
and the only analysis path for the ClickHouse and GoogleSQL engines.
|
||||
|
||||
```
|
||||
SQLCEXPERIMENT=coreanalyzer
|
||||
```
|
||||
|
||||
## SQLCCACHE
|
||||
|
||||
The `SQLCCACHE` environment variable dictates where `sqlc` will store cached
|
||||
data. By default `sqlc` follows the [XDG Base Directory
|
||||
Specification](https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html).
|
||||
|
||||
The cache is designed after Bazel's local disk cache and has three parts:
|
||||
|
||||
- `cas/` — a content-addressable store holding blobs (query analysis
|
||||
results, WASM plugin binaries, compiled WASM machine code) keyed by the
|
||||
SHA-256 hash of their contents. A remotely fetched plugin's address is
|
||||
exactly the checksum declared in the configuration file, so it is loaded
|
||||
directly by that address.
|
||||
- `ac/` — an action cache mapping the digest of a unit of cacheable work and
|
||||
its inputs (analyzing a query against a schema, compiling a WASM module to
|
||||
machine code) to the CAS digests of its outputs.
|
||||
- `exec/` — per-action directories where cached output trees are
|
||||
materialized for tools that read them from disk, such as the
|
||||
[wazero](https://wazero.io) runtime's compilation cache.
|
||||
|
||||
The entire directory is safe to delete at any time; sqlc will rebuild it as
|
||||
needed.
|
||||
|
||||
## SQLCDEBUG
|
||||
|
||||
The `SQLCDEBUG` variable controls debugging variables within the runtime. It is
|
||||
a comma-separated list of name=val pairs settings.
|
||||
|
||||
### dumpast
|
||||
|
||||
The `dumpast` command shows the SQL AST that was generated by the parser. Note
|
||||
that this is the generic SQL AST, not the engine-specific SQL AST.
|
||||
|
||||
```
|
||||
SQLCDEBUG=dumpast=1
|
||||
```
|
||||
|
||||
```
|
||||
([]interface {}) (len=1 cap=1) {
|
||||
(*catalog.Catalog)(0xc0004f48c0)({
|
||||
Comment: (string) "",
|
||||
DefaultSchema: (string) (len=6) "public",
|
||||
Name: (string) "",
|
||||
Schemas: ([]*catalog.Schema) (len=3 cap=4) {
|
||||
(*catalog.Schema)(0xc0004f4930)({
|
||||
Name: (string) (len=6) "public",
|
||||
Tables: ([]*catalog.Table) (len=1 cap=1) {
|
||||
(*catalog.Table)(0xc00052ff20)({
|
||||
Rel: (*ast.TableName)(0xc00052fda0)({
|
||||
Catalog: (string) "",
|
||||
Schema: (string) "",
|
||||
Name: (string) (len=7) "authors"
|
||||
}),
|
||||
```
|
||||
|
||||
### dumpcatalog
|
||||
|
||||
The `dumpcatalog` command outputs the entire catalog. If you're using MySQL or
|
||||
PostgreSQL, this can be a bit overwhelming. Expect this output to change in
|
||||
future versions.
|
||||
|
||||
```
|
||||
SQLCDEBUG=dumpcatalog=1
|
||||
```
|
||||
|
||||
```
|
||||
([]interface {}) (len=1 cap=1) {
|
||||
(*catalog.Catalog)(0xc00050d1f0)({
|
||||
Comment: (string) "",
|
||||
DefaultSchema: (string) (len=6) "public",
|
||||
Name: (string) "",
|
||||
Schemas: ([]*catalog.Schema) (len=3 cap=4) {
|
||||
(*catalog.Schema)(0xc00050d260)({
|
||||
Name: (string) (len=6) "public",
|
||||
Tables: ([]*catalog.Table) (len=1 cap=1) {
|
||||
(*catalog.Table)(0xc0000c0840)({
|
||||
Rel: (*ast.TableName)(0xc0000c06c0)({
|
||||
Catalog: (string) "",
|
||||
Schema: (string) "",
|
||||
Name: (string) (len=7) "authors"
|
||||
}),
|
||||
```
|
||||
|
||||
### trace
|
||||
|
||||
The `trace` command is helpful for tracking down performance issues.
|
||||
|
||||
`SQLCDEBUG=trace=1`
|
||||
|
||||
By default, the trace output is written to `trace.out` in the current working
|
||||
directory. You can configure a different path if needed.
|
||||
|
||||
`SQLCDEBUG=trace=name.out`
|
||||
|
||||
View the execution trace using the Go `trace` tool.
|
||||
|
||||
```
|
||||
go tool trace trace.out
|
||||
```
|
||||
|
||||
There's a ton of different views for the trace output, but here's an example
|
||||
log showing the execution time for each package.
|
||||
|
||||
```
|
||||
0.000043897 . 1 task sqlc (id 1, parent 0) created
|
||||
0.000144923 . 101026 1 region generate started (duration: 47.619781ms)
|
||||
0.001048975 . 904052 1 region package started (duration: 14.588456ms)
|
||||
0.001054616 . 5641 1 name=authors dir=/Users/kyle/projects/sqlc/examples/python language=python
|
||||
0.001071257 . 16641 1 region parse started (duration: 7.966549ms)
|
||||
0.009043960 . 7972703 1 region codegen started (duration: 6.587086ms)
|
||||
0.009171704 . 127744 1 new goroutine 35: text/template/parse.lex·dwrap·1
|
||||
0.010361654 . 1189950 1 new goroutine 36: text/template/parse.lex·dwrap·1
|
||||
0.015641815 . 5280161 1 region package started (duration: 10.904938ms)
|
||||
0.015644943 . 3128 1 name=booktest dir=/Users/kyle/projects/sqlc/examples/python language=python
|
||||
0.015647431 . 2488 1 region parse started (duration: 4.207749ms)
|
||||
0.019860308 . 4212877 1 region codegen started (duration: 6.681624ms)
|
||||
0.020028488 . 168180 1 new goroutine 37: text/template/parse.lex·dwrap·1
|
||||
0.021020310 . 991822 1 new goroutine 8: text/template/parse.lex·dwrap·1
|
||||
0.026551163 . 5530853 1 region package started (duration: 9.217294ms)
|
||||
0.026554368 . 3205 1 name=jets dir=/Users/kyle/projects/sqlc/examples/python language=python
|
||||
0.026556804 . 2436 1 region parse started (duration: 3.491005ms)
|
||||
0.030051911 . 3495107 1 region codegen started (duration: 5.711931ms)
|
||||
0.030213937 . 162026 1 new goroutine 20: text/template/parse.lex·dwrap·1
|
||||
0.031099938 . 886001 1 new goroutine 38: text/template/parse.lex·dwrap·1
|
||||
0.035772637 . 4672699 1 region package started (duration: 10.267039ms)
|
||||
0.035775688 . 3051 1 name=ondeck dir=/Users/kyle/projects/sqlc/examples/python language=python
|
||||
0.035778150 . 2462 1 region parse started (duration: 4.094518ms)
|
||||
0.039877181 . 4099031 1 region codegen started (duration: 6.156341ms)
|
||||
0.040010771 . 133590 1 new goroutine 39: text/template/parse.lex·dwrap·1
|
||||
0.040894567 . 883796 1 new goroutine 40: text/template/parse.lex·dwrap·1
|
||||
0.046042779 . 5148212 1 region writefiles started (duration: 1.718259ms)
|
||||
0.047767781 . 1725002 1 task end
|
||||
```
|
||||
|
||||
### processplugins
|
||||
|
||||
Setting this value to `0` disables process-based plugins. If a process-based
|
||||
plugin is declared in the configuration file, running any `sqlc` command will
|
||||
return an error.
|
||||
|
||||
`SQLCDEBUG=processplugins=0`
|
||||
|
||||
### dumpvetenv
|
||||
|
||||
The `dumpvetenv` command prints the variables available to a `sqlc vet` rule
|
||||
during evaluation.
|
||||
|
||||
`SQLCDEBUG=dumpvetenv=1`
|
||||
|
||||
### dumpexplain
|
||||
|
||||
The `dumpexplain` command prints the JSON-formatted result from running
|
||||
`EXPLAIN ...` on a query when a `sqlc vet` rule evaluation requires its output.
|
||||
|
||||
`SQLCDEBUG=dumpexplain=1`
|
||||
|
||||
## SQLCTMPDIR
|
||||
|
||||
If specified, use the given directory as the base for temporary folders. Only
|
||||
applies when using WASM-based codegen plugins. When not specified, this
|
||||
defaults to passing an empty string to
|
||||
[`os.MkdirTemp`](https://pkg.go.dev/os#MkdirTemp).
|
||||
34
docs/reference/language-support.md
Normal file
34
docs/reference/language-support.md
Normal file
@@ -0,0 +1,34 @@
|
||||
# Database and language support
|
||||
|
||||
| Language | Plugin | MySQL | PostgreSQL | SQLite |
|
||||
| ---------- | ---------------------------------------------------------------------- | ------ | ---------- | --------------- |
|
||||
| Go | (built-in) | Stable | Stable | Beta |
|
||||
| Go | [sqlc-gen-go](https://github.com/sqlc-dev/sqlc-gen-go) | Stable | Stable | Beta |
|
||||
| Kotlin | [sqlc-gen-kotlin](https://github.com/sqlc-dev/sqlc-gen-kotlin) | Beta | Beta | Not implemented |
|
||||
| Python | [sqlc-gen-python](https://github.com/sqlc-dev/sqlc-gen-python) | Beta | Beta | Not implemented |
|
||||
| TypeScript | [sqlc-gen-typescript](https://github.com/sqlc-dev/sqlc-gen-typescript) | Beta | Beta | Not implemented |
|
||||
|
||||
## Community language support
|
||||
|
||||
New languages can be added via [plugins](../guides/plugins.md).
|
||||
|
||||
| Language | Plugin | MySQL | PostgreSQL | SQLite |
|
||||
| -------- | ------------------------------------------------------------------------------------- | ------ | ---------- | ------ |
|
||||
| C# | [DaredevilOSS/sqlc-gen-csharp](https://github.com/DaredevilOSS/sqlc-gen-csharp) | Stable | Stable | Stable |
|
||||
| F# | [kaashyapan/sqlc-gen-fsharp](https://github.com/kaashyapan/sqlc-gen-fsharp) | N/A | Beta | Beta |
|
||||
| Java | [tandemdude/sqlc-gen-java](https://github.com/tandemdude/sqlc-gen-java) | Beta | Beta | N/A |
|
||||
| PHP | [lcarilla/sqlc-plugin-php-dbal](https://github.com/lcarilla/sqlc-plugin-php-dbal) | Beta | N/A | N/A |
|
||||
| Ruby | [DaredevilOSS/sqlc-gen-ruby](https://github.com/DaredevilOSS/sqlc-gen-ruby) | Beta | Beta | Beta |
|
||||
| Zig | [tinyzimmer/sqlc-gen-zig](https://github.com/tinyzimmer/sqlc-gen-zig) | N/A | Beta | Beta |
|
||||
| Python | [rayakame/sqlc-gen-better-python](https://github.com/rayakame/sqlc-gen-better-python) | Beta | Stable | Stable |
|
||||
| Rust | [mathematic-inc/sqlc-gen-sqlx](https://github.com/mathematic-inc/sqlc-gen-sqlx) | N/A | Beta | N/A |
|
||||
| \[Any\] | [fdietze/sqlc-gen-from-template](https://github.com/fdietze/sqlc-gen-from-template) | Stable | Stable | Stable |
|
||||
|
||||
Plugins developed by our Community can also be found using our
|
||||
[github topic](https://github.com/topics/sqlc-plugin).
|
||||
|
||||
## Community projects
|
||||
|
||||
| Language | Project | MySQL | PostgreSQL | SQLite |
|
||||
| -------- | ----------------------------------------------------------------- | ------ | ---------- | ------ |
|
||||
| Gleam | [daniellionel01/parrot](https://github.com/daniellionel01/parrot) | Stable | Stable | Stable |
|
||||
119
docs/reference/macros.md
Normal file
119
docs/reference/macros.md
Normal file
@@ -0,0 +1,119 @@
|
||||
# Macros
|
||||
|
||||
## `sqlc.arg`
|
||||
|
||||
Attach a name to a parameter in a SQL query. This macro expands to an
|
||||
engine-specific parameter placeholder. The name of the parameter is noted and
|
||||
used during code generation.
|
||||
|
||||
```sql
|
||||
-- name: GetAuthorByName :one
|
||||
SELECT *
|
||||
FROM authors
|
||||
WHERE lower(name) = sqlc.arg(name);
|
||||
|
||||
-- >>> EXPANDS TO >>>
|
||||
|
||||
-- name: GetAuthorByName :one
|
||||
SELECT *
|
||||
FROM authors
|
||||
WHERE lower(name) = ?;
|
||||
```
|
||||
|
||||
See more examples in [Naming parameters](../howto/named_parameters.md).
|
||||
|
||||
## `sqlc.embed`
|
||||
|
||||
Embedding allows you to reuse existing model structs in more queries, resulting
|
||||
in less manual serialization work. First, imagine we have the following schema
|
||||
with students and test scores.
|
||||
|
||||
```sql
|
||||
CREATE TABLE students (
|
||||
id bigserial PRIMARY KEY,
|
||||
name text,
|
||||
age integer
|
||||
);
|
||||
|
||||
CREATE TABLE test_scores (
|
||||
student_id bigint,
|
||||
score integer,
|
||||
grade text
|
||||
);
|
||||
```
|
||||
|
||||
```sql
|
||||
-- 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;
|
||||
|
||||
-- >>> EXPANDS TO >>>
|
||||
|
||||
-- name: GetStudentAndScore :one
|
||||
SELECT students.*, test_scores.*
|
||||
FROM students
|
||||
JOIN test_scores ON test_scores.student_id = students.id
|
||||
WHERE students.id = $1;
|
||||
```
|
||||
|
||||
The Go method will return a struct with a field for the `Student` and field for
|
||||
the test `TestScore` instead of each column existing on the struct.
|
||||
|
||||
```go
|
||||
type GetStudentAndScoreRow struct {
|
||||
Student Student
|
||||
TestScore TestScore
|
||||
}
|
||||
|
||||
func (q *Queries) GetStudentAndScore(ctx context.Context, id int64) (GetStudentAndScoreRow, error) {
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
See a full example in [Embedding structs](../howto/embedding.md).
|
||||
|
||||
## `sqlc.narg`
|
||||
|
||||
The same as `sqlc.arg`, but always marks the parameter as nullable.
|
||||
|
||||
```sql
|
||||
-- name: GetAuthorByName :one
|
||||
SELECT *
|
||||
FROM authors
|
||||
WHERE lower(name) = sqlc.narg(name);
|
||||
|
||||
-- >>> EXPANDS TO >>>
|
||||
|
||||
-- name: GetAuthorByName :one
|
||||
SELECT *
|
||||
FROM authors
|
||||
WHERE LOWER(name) = ?;
|
||||
```
|
||||
|
||||
See more examples in [Naming parameters](../howto/named_parameters.md).
|
||||
|
||||
## `sqlc.slice`
|
||||
|
||||
For drivers that do not support passing slices to the IN operator, the
|
||||
`sqlc.slice` macro generates a dynamic query at runtime with the correct
|
||||
number of parameters.
|
||||
|
||||
```sql
|
||||
/* name: SelectStudents :many */
|
||||
SELECT * FROM students
|
||||
WHERE age IN (sqlc.slice("ages"))
|
||||
|
||||
-- >>> EXPANDS TO >>>
|
||||
|
||||
/* name: SelectStudents :many */
|
||||
SELECT id, name, age FROM authors
|
||||
WHERE age IN (/*SLICE:ages*/?)
|
||||
```
|
||||
|
||||
Since the `/*SLICE:ages*/` placeholder is dynamically replaced on a per-query
|
||||
basis, this macro can't be used with prepared statements.
|
||||
|
||||
See a full example in [Passing a slice as a parameter to a
|
||||
query](../howto/select.md#mysql-and-sqlite).
|
||||
230
docs/reference/query-annotations.md
Normal file
230
docs/reference/query-annotations.md
Normal file
@@ -0,0 +1,230 @@
|
||||
# Query annotations
|
||||
|
||||
sqlc requires each query to have a small comment indicating the name and
|
||||
command. The format of this comment is as follows:
|
||||
|
||||
```sql
|
||||
-- name: <name> <command>
|
||||
```
|
||||
|
||||
## `:exec`
|
||||
|
||||
The generated method will return the error from
|
||||
[ExecContext](https://golang.org/pkg/database/sql/#DB.ExecContext).
|
||||
|
||||
```sql
|
||||
-- name: DeleteAuthor :exec
|
||||
DELETE FROM authors
|
||||
WHERE id = $1;
|
||||
```
|
||||
|
||||
```go
|
||||
func (q *Queries) DeleteAuthor(ctx context.Context, id int64) error {
|
||||
_, err := q.db.ExecContext(ctx, deleteAuthor, id)
|
||||
return err
|
||||
}
|
||||
```
|
||||
|
||||
## `:execresult`
|
||||
|
||||
The generated method will return the [sql.Result](https://golang.org/pkg/database/sql/#Result) returned by
|
||||
[ExecContext](https://golang.org/pkg/database/sql/#DB.ExecContext).
|
||||
|
||||
```sql
|
||||
-- name: DeleteAllAuthors :execresult
|
||||
DELETE FROM authors;
|
||||
```
|
||||
|
||||
```go
|
||||
func (q *Queries) DeleteAllAuthors(ctx context.Context) (sql.Result, error) {
|
||||
return q.db.ExecContext(ctx, deleteAllAuthors)
|
||||
}
|
||||
```
|
||||
|
||||
## `:execrows`
|
||||
|
||||
The generated method will return the number of affected rows from the
|
||||
[result](https://golang.org/pkg/database/sql/#Result) returned by
|
||||
[ExecContext](https://golang.org/pkg/database/sql/#DB.ExecContext).
|
||||
|
||||
```sql
|
||||
-- name: DeleteAllAuthors :execrows
|
||||
DELETE FROM authors;
|
||||
```
|
||||
|
||||
```go
|
||||
func (q *Queries) DeleteAllAuthors(ctx context.Context) (int64, error) {
|
||||
_, err := q.db.ExecContext(ctx, deleteAllAuthors)
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
## `:execlastid`
|
||||
|
||||
The generated method will return the number generated by the database from the
|
||||
[result](https://golang.org/pkg/database/sql/#Result) returned by
|
||||
[ExecContext](https://golang.org/pkg/database/sql/#DB.ExecContext).
|
||||
|
||||
```sql
|
||||
-- name: InsertAuthor :execlastid
|
||||
INSERT INTO authors (name) VALUES (?);
|
||||
```
|
||||
|
||||
```go
|
||||
func (q *Queries) InsertAuthor(ctx context.Context, name string) (int64, error) {
|
||||
_, err := q.db.ExecContext(ctx, insertAuthor, name)
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
## `:many`
|
||||
|
||||
The generated method will return a slice of records via
|
||||
[QueryContext](https://golang.org/pkg/database/sql/#DB.QueryContext).
|
||||
|
||||
```sql
|
||||
-- name: ListAuthors :many
|
||||
SELECT * FROM authors
|
||||
ORDER BY name;
|
||||
```
|
||||
|
||||
```go
|
||||
func (q *Queries) ListAuthors(ctx context.Context) ([]Author, error) {
|
||||
rows, err := q.db.QueryContext(ctx, listAuthors)
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
## `:one`
|
||||
|
||||
The generated method will return a single record via
|
||||
[QueryRowContext](https://golang.org/pkg/database/sql/#DB.QueryRowContext).
|
||||
|
||||
```sql
|
||||
-- name: GetAuthor :one
|
||||
SELECT * FROM authors
|
||||
WHERE id = $1 LIMIT 1;
|
||||
```
|
||||
|
||||
```go
|
||||
func (q *Queries) GetAuthor(ctx context.Context, id int64) (Author, error) {
|
||||
row := q.db.QueryRowContext(ctx, getAuthor, id)
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
## `:batchexec`
|
||||
|
||||
__NOTE: This command only works with PostgreSQL using the `pgx/v4` and `pgx/v5` drivers and outputting Go code.__
|
||||
|
||||
The generated method will return a batch object. The batch object will have
|
||||
the following methods:
|
||||
- `Exec`, that takes a `func(int, error)` parameter,
|
||||
- `Close`, to close the batch operation early.
|
||||
|
||||
```sql
|
||||
-- name: DeleteBook :batchexec
|
||||
DELETE FROM books
|
||||
WHERE book_id = $1;
|
||||
```
|
||||
|
||||
```go
|
||||
type DeleteBookBatchResults struct {
|
||||
br pgx.BatchResults
|
||||
ind int
|
||||
}
|
||||
|
||||
func (q *Queries) DeleteBook(ctx context.Context, bookID []int32) *DeleteBookBatchResults {
|
||||
//...
|
||||
}
|
||||
func (b *DeleteBookBatchResults) Exec(f func(int, error)) {
|
||||
//...
|
||||
}
|
||||
func (b *DeleteBookBatchResults) Close() error {
|
||||
//...
|
||||
}
|
||||
```
|
||||
|
||||
## `:batchmany`
|
||||
|
||||
__NOTE: This command only works with PostgreSQL using the `pgx/v4` and `pgx/v5` drivers and outputting Go code.__
|
||||
|
||||
The generated method will return a batch object. The batch object will have
|
||||
the following methods:
|
||||
- `Query`, that takes a `func(int, []T, error)` parameter, where `T` is your query's return type
|
||||
- `Close`, to close the batch operation early.
|
||||
|
||||
```sql
|
||||
-- name: BooksByTitleYear :batchmany
|
||||
SELECT * FROM books
|
||||
WHERE title = $1 AND year = $2;
|
||||
```
|
||||
|
||||
```go
|
||||
type BooksByTitleYearBatchResults struct {
|
||||
br pgx.BatchResults
|
||||
ind int
|
||||
}
|
||||
type BooksByTitleYearParams struct {
|
||||
Title string `json:"title"`
|
||||
Year int32 `json:"year"`
|
||||
}
|
||||
|
||||
func (q *Queries) BooksByTitleYear(ctx context.Context, arg []BooksByTitleYearParams) *BooksByTitleYearBatchResults {
|
||||
//...
|
||||
}
|
||||
func (b *BooksByTitleYearBatchResults) Query(f func(int, []Book, error)) {
|
||||
//...
|
||||
}
|
||||
func (b *BooksByTitleYearBatchResults) Close() error {
|
||||
//...
|
||||
}
|
||||
```
|
||||
|
||||
## `:batchone`
|
||||
|
||||
__NOTE: This command only works with PostgreSQL using the `pgx/v4` and `pgx/v5` drivers and outputting Go code.__
|
||||
|
||||
The generated method will return a batch object. The batch object will have
|
||||
the following methods:
|
||||
- `QueryRow`, that takes a `func(int, T, error)` parameter, where `T` is your query's return type
|
||||
- `Close`, to close the batch operation early.
|
||||
|
||||
```sql
|
||||
-- name: CreateBook :batchone
|
||||
INSERT INTO books (
|
||||
author_id,
|
||||
isbn
|
||||
) VALUES (
|
||||
$1,
|
||||
$2
|
||||
)
|
||||
RETURNING book_id, author_id, isbn
|
||||
```
|
||||
|
||||
```go
|
||||
type CreateBookBatchResults struct {
|
||||
br pgx.BatchResults
|
||||
ind int
|
||||
}
|
||||
type CreateBookParams struct {
|
||||
AuthorID int32 `json:"author_id"`
|
||||
Isbn string `json:"isbn"`
|
||||
}
|
||||
|
||||
func (q *Queries) CreateBook(ctx context.Context, arg []CreateBookParams) *CreateBookBatchResults {
|
||||
//...
|
||||
}
|
||||
func (b *CreateBookBatchResults) QueryRow(f func(int, Book, error)) {
|
||||
//...
|
||||
}
|
||||
func (b *CreateBookBatchResults) Close() error {
|
||||
//...
|
||||
}
|
||||
```
|
||||
|
||||
## `:copyfrom`
|
||||
|
||||
__NOTE: This command is driver and package specific, see [how to insert](../howto/insert.md#using-copyfrom)
|
||||
|
||||
This command is used to insert rows a lot faster than sequential inserts.
|
||||
Reference in New Issue
Block a user