diff --git a/internal/endtoend/testdata/embed_table/db/models.py b/internal/endtoend/testdata/embed_table/db/models.py new file mode 100644 index 0000000..795af68 --- /dev/null +++ b/internal/endtoend/testdata/embed_table/db/models.py @@ -0,0 +1,22 @@ +# Code generated by sqlc. DO NOT EDIT. +# versions: +# sqlc v1.28.0 +import dataclasses +import datetime +from typing import Optional + + +@dataclasses.dataclass() +class Author: + id: int + name: str + bio: Optional[str] + + +@dataclasses.dataclass() +class Book: + id: int + title: str + author_id: int + isbn: str + published: datetime.date diff --git a/internal/endtoend/testdata/embed_table/db/query.py b/internal/endtoend/testdata/embed_table/db/query.py new file mode 100644 index 0000000..f44da25 --- /dev/null +++ b/internal/endtoend/testdata/embed_table/db/query.py @@ -0,0 +1,202 @@ +# Code generated by sqlc. DO NOT EDIT. +# versions: +# sqlc v1.28.0 +# source: query.sql +import dataclasses +import datetime +from typing import AsyncIterator, Iterator, Optional + +import sqlalchemy +import sqlalchemy.ext.asyncio + +from db import models + + +CREATE_AUTHOR = """-- name: create_author \\:one +INSERT INTO authors ( + name, bio +) VALUES ( + :p1, :p2 +) +RETURNING id, name, bio +""" + + +CREATE_BOOK = """-- name: create_book \\:one +INSERT INTO books ( + title, author_id, isbn, published +) VALUES ( + :p1, :p2, :p3, :p4 +) +RETURNING id, title, author_id, isbn, published +""" + + +GET_BOOK_WITH_AUTHOR = """-- name: get_book_with_author \\:one +SELECT + b.id, b.title, b.author_id, b.isbn, b.published, + a.author, a.author, a.author AS author +FROM books b +JOIN authors a ON b.author_id = a.id +WHERE b.id = :p1 LIMIT 1 +""" + + +@dataclasses.dataclass() +class GetBookWithAuthorRow: + id: int + title: str + author_id: int + isbn: str + published: datetime.date + authors: models.Author + + +LIST_BOOKS_WITH_AUTHORS = """-- name: list_books_with_authors \\:many +SELECT + b.id, b.title, b.author_id, b.isbn, b.published, + a.author, a.author, a.author AS author +FROM books b +JOIN authors a ON b.author_id = a.id +ORDER BY b.title +""" + + +@dataclasses.dataclass() +class ListBooksWithAuthorsRow: + id: int + title: str + author_id: int + isbn: str + published: datetime.date + authors: models.Author + + +class Querier: + def __init__(self, conn: sqlalchemy.engine.Connection): + self._conn = conn + + def create_author(self, *, name: str, bio: Optional[str]) -> Optional[models.Author]: + row = self._conn.execute(sqlalchemy.text(CREATE_AUTHOR), {"p1": name, "p2": bio}).first() + if row is None: + return None + return models.Author( + id=row[0], + name=row[1], + bio=row[2], + ) + + def create_book(self, *, title: str, author_id: int, isbn: str, published: datetime.date) -> Optional[models.Book]: + row = self._conn.execute(sqlalchemy.text(CREATE_BOOK), { + "p1": title, + "p2": author_id, + "p3": isbn, + "p4": published, + }).first() + if row is None: + return None + return models.Book( + id=row[0], + title=row[1], + author_id=row[2], + isbn=row[3], + published=row[4], + ) + + def get_book_with_author(self, *, id: int) -> Optional[GetBookWithAuthorRow]: + row = self._conn.execute(sqlalchemy.text(GET_BOOK_WITH_AUTHOR), {"p1": id}).first() + if row is None: + return None + return GetBookWithAuthorRow( + id=row[0], + title=row[1], + author_id=row[2], + isbn=row[3], + published=row[4], + authors=models.Author( + id=row[5], + name=row[6], + bio=row[7], + ), + ) + + def list_books_with_authors(self) -> Iterator[ListBooksWithAuthorsRow]: + result = self._conn.execute(sqlalchemy.text(LIST_BOOKS_WITH_AUTHORS)) + for row in result: + yield ListBooksWithAuthorsRow( + id=row[0], + title=row[1], + author_id=row[2], + isbn=row[3], + published=row[4], + authors=models.Author( + id=row[5], + name=row[6], + bio=row[7], + ), + ) + + +class AsyncQuerier: + def __init__(self, conn: sqlalchemy.ext.asyncio.AsyncConnection): + self._conn = conn + + async def create_author(self, *, name: str, bio: Optional[str]) -> Optional[models.Author]: + row = (await self._conn.execute(sqlalchemy.text(CREATE_AUTHOR), {"p1": name, "p2": bio})).first() + if row is None: + return None + return models.Author( + id=row[0], + name=row[1], + bio=row[2], + ) + + async def create_book(self, *, title: str, author_id: int, isbn: str, published: datetime.date) -> Optional[models.Book]: + row = (await self._conn.execute(sqlalchemy.text(CREATE_BOOK), { + "p1": title, + "p2": author_id, + "p3": isbn, + "p4": published, + })).first() + if row is None: + return None + return models.Book( + id=row[0], + title=row[1], + author_id=row[2], + isbn=row[3], + published=row[4], + ) + + async def get_book_with_author(self, *, id: int) -> Optional[GetBookWithAuthorRow]: + row = (await self._conn.execute(sqlalchemy.text(GET_BOOK_WITH_AUTHOR), {"p1": id})).first() + if row is None: + return None + return GetBookWithAuthorRow( + id=row[0], + title=row[1], + author_id=row[2], + isbn=row[3], + published=row[4], + authors=models.Author( + id=row[5], + name=row[6], + bio=row[7], + ), + ) + + async def list_books_with_authors(self) -> AsyncIterator[ListBooksWithAuthorsRow]: + result = await self._conn.stream(sqlalchemy.text(LIST_BOOKS_WITH_AUTHORS)) + async for row in result: + yield ListBooksWithAuthorsRow( + id=row[0], + title=row[1], + author_id=row[2], + isbn=row[3], + published=row[4], + authors=models.Author( + id=row[5], + name=row[6], + bio=row[7], + ), + ) diff --git a/internal/endtoend/testdata/embed_table/query.sql b/internal/endtoend/testdata/embed_table/query.sql new file mode 100644 index 0000000..03bda07 --- /dev/null +++ b/internal/endtoend/testdata/embed_table/query.sql @@ -0,0 +1,31 @@ +-- name: GetBookWithAuthor :one +SELECT + b.*, + sqlc.embed(a) AS author +FROM books b +JOIN authors a ON b.author_id = a.id +WHERE b.id = $1 LIMIT 1; + +-- name: ListBooksWithAuthors :many +SELECT + b.*, + sqlc.embed(a) AS author +FROM books b +JOIN authors a ON b.author_id = a.id +ORDER BY b.title; + +-- name: CreateAuthor :one +INSERT INTO authors ( + name, bio +) VALUES ( + $1, $2 +) +RETURNING *; + +-- name: CreateBook :one +INSERT INTO books ( + title, author_id, isbn, published +) VALUES ( + $1, $2, $3, $4 +) +RETURNING *; diff --git a/internal/endtoend/testdata/embed_table/schema.sql b/internal/endtoend/testdata/embed_table/schema.sql new file mode 100644 index 0000000..3bf0f74 --- /dev/null +++ b/internal/endtoend/testdata/embed_table/schema.sql @@ -0,0 +1,13 @@ +CREATE TABLE authors ( + id BIGSERIAL PRIMARY KEY, + name TEXT NOT NULL, + bio TEXT +); + +CREATE TABLE books ( + id BIGSERIAL PRIMARY KEY, + title TEXT NOT NULL, + author_id BIGINT NOT NULL REFERENCES authors(id), + isbn TEXT NOT NULL, + published DATE NOT NULL +); diff --git a/internal/endtoend/testdata/embed_table/sqlc.yaml b/internal/endtoend/testdata/embed_table/sqlc.yaml new file mode 100644 index 0000000..ea6c47f --- /dev/null +++ b/internal/endtoend/testdata/embed_table/sqlc.yaml @@ -0,0 +1,17 @@ +version: '2' +plugins: +- name: py + wasm: + url: file://../../../../bin/sqlc-gen-python.wasm + sha256: "49a16426d49c060404cb1d63e3d6c668bf3992ea14cb933e546273b18948d295" +sql: +- schema: schema.sql + queries: query.sql + engine: postgresql + codegen: + - plugin: py + out: db + options: + package: db + emit_sync_querier: true + emit_async_querier: true diff --git a/internal/endtoend/testdata/emit_pydantic_models/sqlc.yaml b/internal/endtoend/testdata/emit_pydantic_models/sqlc.yaml index beae200..5a0c74a 100644 --- a/internal/endtoend/testdata/emit_pydantic_models/sqlc.yaml +++ b/internal/endtoend/testdata/emit_pydantic_models/sqlc.yaml @@ -3,7 +3,7 @@ plugins: - name: py wasm: url: file://../../../../bin/sqlc-gen-python.wasm - sha256: "d6846ffad948181e611e883cedd2d2be66e091edc1273a0abc6c9da18399e0ca" + sha256: "49a16426d49c060404cb1d63e3d6c668bf3992ea14cb933e546273b18948d295" sql: - schema: schema.sql queries: query.sql diff --git a/internal/endtoend/testdata/emit_str_enum/sqlc.yaml b/internal/endtoend/testdata/emit_str_enum/sqlc.yaml index 04e3feb..ba90729 100644 --- a/internal/endtoend/testdata/emit_str_enum/sqlc.yaml +++ b/internal/endtoend/testdata/emit_str_enum/sqlc.yaml @@ -3,7 +3,7 @@ plugins: - name: py wasm: url: file://../../../../bin/sqlc-gen-python.wasm - sha256: "d6846ffad948181e611e883cedd2d2be66e091edc1273a0abc6c9da18399e0ca" + sha256: "49a16426d49c060404cb1d63e3d6c668bf3992ea14cb933e546273b18948d295" sql: - schema: schema.sql queries: query.sql diff --git a/internal/endtoend/testdata/exec_result/sqlc.yaml b/internal/endtoend/testdata/exec_result/sqlc.yaml index ddffc83..70588f9 100644 --- a/internal/endtoend/testdata/exec_result/sqlc.yaml +++ b/internal/endtoend/testdata/exec_result/sqlc.yaml @@ -3,7 +3,7 @@ plugins: - name: py wasm: url: file://../../../../bin/sqlc-gen-python.wasm - sha256: "d6846ffad948181e611e883cedd2d2be66e091edc1273a0abc6c9da18399e0ca" + sha256: "49a16426d49c060404cb1d63e3d6c668bf3992ea14cb933e546273b18948d295" sql: - schema: schema.sql queries: query.sql diff --git a/internal/endtoend/testdata/exec_rows/sqlc.yaml b/internal/endtoend/testdata/exec_rows/sqlc.yaml index ddffc83..70588f9 100644 --- a/internal/endtoend/testdata/exec_rows/sqlc.yaml +++ b/internal/endtoend/testdata/exec_rows/sqlc.yaml @@ -3,7 +3,7 @@ plugins: - name: py wasm: url: file://../../../../bin/sqlc-gen-python.wasm - sha256: "d6846ffad948181e611e883cedd2d2be66e091edc1273a0abc6c9da18399e0ca" + sha256: "49a16426d49c060404cb1d63e3d6c668bf3992ea14cb933e546273b18948d295" sql: - schema: schema.sql queries: query.sql diff --git a/internal/endtoend/testdata/inflection_exclude_table_names/sqlc.yaml b/internal/endtoend/testdata/inflection_exclude_table_names/sqlc.yaml index efbb150..58418b7 100644 --- a/internal/endtoend/testdata/inflection_exclude_table_names/sqlc.yaml +++ b/internal/endtoend/testdata/inflection_exclude_table_names/sqlc.yaml @@ -3,7 +3,7 @@ plugins: - name: py wasm: url: file://../../../../bin/sqlc-gen-python.wasm - sha256: "d6846ffad948181e611e883cedd2d2be66e091edc1273a0abc6c9da18399e0ca" + sha256: "49a16426d49c060404cb1d63e3d6c668bf3992ea14cb933e546273b18948d295" sql: - schema: schema.sql queries: query.sql diff --git a/internal/endtoend/testdata/query_parameter_limit_two/sqlc.yaml b/internal/endtoend/testdata/query_parameter_limit_two/sqlc.yaml index 336bca7..6553c25 100644 --- a/internal/endtoend/testdata/query_parameter_limit_two/sqlc.yaml +++ b/internal/endtoend/testdata/query_parameter_limit_two/sqlc.yaml @@ -3,7 +3,7 @@ plugins: - name: py wasm: url: file://../../../../bin/sqlc-gen-python.wasm - sha256: "d6846ffad948181e611e883cedd2d2be66e091edc1273a0abc6c9da18399e0ca" + sha256: "49a16426d49c060404cb1d63e3d6c668bf3992ea14cb933e546273b18948d295" sql: - schema: schema.sql queries: query.sql diff --git a/internal/endtoend/testdata/query_parameter_limit_undefined/sqlc.yaml b/internal/endtoend/testdata/query_parameter_limit_undefined/sqlc.yaml index c20cd57..1c30721 100644 --- a/internal/endtoend/testdata/query_parameter_limit_undefined/sqlc.yaml +++ b/internal/endtoend/testdata/query_parameter_limit_undefined/sqlc.yaml @@ -3,7 +3,7 @@ plugins: - name: py wasm: url: file://../../../../bin/sqlc-gen-python.wasm - sha256: "d6846ffad948181e611e883cedd2d2be66e091edc1273a0abc6c9da18399e0ca" + sha256: "49a16426d49c060404cb1d63e3d6c668bf3992ea14cb933e546273b18948d295" sql: - schema: schema.sql queries: query.sql diff --git a/internal/endtoend/testdata/query_parameter_limit_zero/sqlc.yaml b/internal/endtoend/testdata/query_parameter_limit_zero/sqlc.yaml index 6e2cdeb..51d94e2 100644 --- a/internal/endtoend/testdata/query_parameter_limit_zero/sqlc.yaml +++ b/internal/endtoend/testdata/query_parameter_limit_zero/sqlc.yaml @@ -3,7 +3,7 @@ plugins: - name: py wasm: url: file://../../../../bin/sqlc-gen-python.wasm - sha256: "d6846ffad948181e611e883cedd2d2be66e091edc1273a0abc6c9da18399e0ca" + sha256: "49a16426d49c060404cb1d63e3d6c668bf3992ea14cb933e546273b18948d295" sql: - schema: schema.sql queries: query.sql diff --git a/internal/endtoend/testdata/query_parameter_no_limit/sqlc.yaml b/internal/endtoend/testdata/query_parameter_no_limit/sqlc.yaml index c432e4f..f67feb1 100644 --- a/internal/endtoend/testdata/query_parameter_no_limit/sqlc.yaml +++ b/internal/endtoend/testdata/query_parameter_no_limit/sqlc.yaml @@ -3,7 +3,7 @@ plugins: - name: py wasm: url: file://../../../../bin/sqlc-gen-python.wasm - sha256: "d6846ffad948181e611e883cedd2d2be66e091edc1273a0abc6c9da18399e0ca" + sha256: "49a16426d49c060404cb1d63e3d6c668bf3992ea14cb933e546273b18948d295" sql: - schema: schema.sql queries: query.sql diff --git a/internal/gen.go b/internal/gen.go index 6e50fae..9ce2590 100644 --- a/internal/gen.go +++ b/internal/gen.go @@ -53,6 +53,8 @@ type Field struct { Name string Type pyType Comment string + // EmbedFields contains the embedded fields that require scanning. + EmbedFields []Field } type Struct struct { @@ -105,14 +107,41 @@ func (v QueryValue) RowNode(rowVar string) *pyast.Node { call := &pyast.Call{ Func: v.Annotation(), } - for i, f := range v.Struct.Fields { - call.Keywords = append(call.Keywords, &pyast.Keyword{ - Arg: f.Name, - Value: subscriptNode( + rowIndex := 0 // We need to keep track of the index in the row variable. + for _, f := range v.Struct.Fields { + var valueNode *pyast.Node + // Check if we are using sqlc.embed, if so we need to create a new object. + if len(f.EmbedFields) > 0 { + // We keep this separate so we can easily add all arguments. + embed_call := &pyast.Call{Func: f.Type.Annotation()} + + // Now add all field Initializers for the embedded model that index into the original row. + for i, embedField := range f.EmbedFields { + embed_call.Keywords = append(embed_call.Keywords, &pyast.Keyword{ + Arg: embedField.Name, + Value: subscriptNode( + rowVar, + constantInt(rowIndex+i), + ), + }) + } + + valueNode = &pyast.Node{ + Node: &pyast.Node_Call{ + Call: embed_call, + }, + } + + rowIndex += len(f.EmbedFields) + } else { + valueNode = subscriptNode( rowVar, - constantInt(i), - ), - }) + constantInt(rowIndex), + ) + rowIndex++ + } + + call.Keywords = append(call.Keywords, &pyast.Keyword{Arg: f.Name, Value: valueNode}) } return &pyast.Node{ Node: &pyast.Node_Call{ @@ -319,6 +348,47 @@ func paramName(p *plugin.Parameter) string { type pyColumn struct { id int32 *plugin.Column + embed *pyEmbed +} + +type pyEmbed struct { + modelType string + modelName string + fields []Field +} + +// Taken from https://github.com/sqlc-dev/sqlc/blob/8c59fbb9938a0bad3d9971fc2c10ea1f83cc1d0b/internal/codegen/golang/result.go#L123-L126 +// look through all the structs and attempt to find a matching one to embed +// We need the name of the struct and its field names. +func newGoEmbed(embed *plugin.Identifier, structs []Struct, defaultSchema string) *pyEmbed { + if embed == nil { + return nil + } + + for _, s := range structs { + embedSchema := defaultSchema + if embed.Schema != "" { + embedSchema = embed.Schema + } + + // compare the other attributes + if embed.Catalog != s.Table.Catalog || embed.Name != s.Table.Name || embedSchema != s.Table.Schema { + continue + } + + fields := make([]Field, len(s.Fields)) + for i, f := range s.Fields { + fields[i] = f + } + + return &pyEmbed{ + modelType: s.Name, + modelName: s.Name, + fields: fields, + } + } + + return nil } func columnsToStruct(req *plugin.GenerateRequest, name string, columns []pyColumn) *Struct { @@ -342,10 +412,21 @@ func columnsToStruct(req *plugin.GenerateRequest, name string, columns []pyColum if suffix > 0 { fieldName = fmt.Sprintf("%s_%d", fieldName, suffix) } - gs.Fields = append(gs.Fields, Field{ + f := Field{ Name: fieldName, Type: makePyType(req, c.Column), - }) + } + + if c.embed != nil { + f.Type = pyType{ + InnerType: "models." + modelName(c.embed.modelType, req.Settings), + IsArray: false, + IsNull: false, + } + f.EmbedFields = c.embed.fields + } + + gs.Fields = append(gs.Fields, f) seen[colName]++ } return &gs @@ -401,6 +482,7 @@ func buildQueries(conf Config, req *plugin.GenerateRequest, structs []Struct) ([ cols = append(cols, pyColumn{ id: p.Number, Column: p.Column, + embed: newGoEmbed(p.Column.EmbedTable, structs, req.Catalog.DefaultSchema), }) } gq.Args = []QueryValue{{ @@ -459,6 +541,7 @@ func buildQueries(conf Config, req *plugin.GenerateRequest, structs []Struct) ([ columns = append(columns, pyColumn{ id: int32(i), Column: c, + embed: newGoEmbed(c.EmbedTable, structs, req.Catalog.DefaultSchema), }) } gs = columnsToStruct(req, query.Name+"Row", columns)