sqlc-gen-python

repository·main·Indexed 43 days ago

https://github.com/sqlc-dev/sqlc-gen-python

A plugin for sqlc that generates type-safe Python code from SQL queries. It supports generating Pythonic structures such as dataclasses, Pydantic models, and Enums, and can be configured via sqlc.yaml to emit sync and async queriers.

Tokens
636
Snippets
4
Records
4
Agent score
6%

What's inside sqlc-gen-python

  1. Configure sqlc-gen-python in sqlc.yaml

    main

    To use the Python generator, add it to the plugins section of your sqlc.yaml configuration file. You must specify the wasm URL and the sha256 checksum for the plugin. In the codegen section, set the plugin name to py and define your options such as package, emit_sync_querier, and emit_async_querier.

    version: "2"
    plugins:
      - name: py
        wasm:
          url: https://downloads.sqlc.dev/plugin/sqlc-gen-python_1.3.0.wasm
          sha256: fbedae96b5ecae2380a70fb5b925fd4bff58a6cfb1f3140375d098fbab7b3a3c
    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
  2. Use enum.StrEnum for Enums

    main

    By default, the generator emits enums as (str, enum.Enum). If you are using Python 3.11+ and prefer the enum.StrEnum subclass (which allows direct string comparisons and better serialization), enable the emit_str_enum option in your sqlc.yaml codegen configuration.

    # Inside codegen options
    options:
      emit_str_enum: true
  3. Emit Pydantic models instead of dataclasses

    main

    By default, sqlc-gen-python generates Python dataclasses. If you want to use pydantic models for your generated code, enable the emit_pydantic_models option in your sqlc.yaml codegen configuration.

    # Inside codegen options
    options:
      emit_pydantic_models: true
  4. Run the sqlc-gen-python plugin

    main

    The sqlc-gen-python plugin is a WASM-based plugin for sqlc. It is invoked by the sqlc engine, which calls the plugin's entrypoint. The plugin uses the plugin-sdk-go to bridge the sqlc codegen process with the Python generation logic defined in the python.Generate function.

    // The plugin entrypoint executes the generation logic via the SDK
    func main() {
    	codegen.Run(python.Generate)
    }