|
9 | 9 | "github.com/sqlc-dev/sqlc/internal/sql/astutils" |
10 | 10 | "github.com/sqlc-dev/sqlc/internal/sql/catalog" |
11 | 11 | "github.com/sqlc-dev/sqlc/internal/sql/lang" |
| 12 | + "github.com/sqlc-dev/sqlc/internal/sql/preprocess" |
12 | 13 | "github.com/sqlc-dev/sqlc/internal/sql/sqlerr" |
13 | 14 | ) |
14 | 15 |
|
@@ -53,6 +54,8 @@ func hasStarRef(cf *ast.ColumnRef) bool { |
53 | 54 | // Return an error if column references are ambiguous |
54 | 55 | // Return an error if column references don't exist |
55 | 56 | func (c *Compiler) outputColumns(qc *QueryCatalog, node ast.Node) ([]*Column, error) { |
| 57 | + var embedErr error |
| 58 | + |
56 | 59 | tables, err := c.sourceTables(qc, node) |
57 | 60 | if err != nil { |
58 | 61 | return nil, err |
@@ -267,6 +270,11 @@ func (c *Compiler) outputColumns(qc *QueryCatalog, node ast.Node) ([]*Column, er |
267 | 270 |
|
268 | 271 | // add a column with a reference to an embedded table |
269 | 272 | if embed, ok := qc.embeds.Find(n.Location, res.Location); ok { |
| 273 | + // Keep the column and report the error with the rest, so an |
| 274 | + // analyzer that discards inference errors still sees the embed. |
| 275 | + if err := checkEmbedRequired(node, embed, res.Location); err != nil && embedErr == nil { |
| 276 | + embedErr = err |
| 277 | + } |
270 | 278 | cols = append(cols, &Column{ |
271 | 279 | Name: embed.Table.Name, |
272 | 280 | EmbedTable: embed.Table, |
@@ -416,7 +424,7 @@ func (c *Compiler) outputColumns(qc *QueryCatalog, node ast.Node) ([]*Column, er |
416 | 424 | } |
417 | 425 | } |
418 | 426 |
|
419 | | - return cols, nil |
| 427 | + return cols, embedErr |
420 | 428 | } |
421 | 429 |
|
422 | 430 | const ( |
@@ -467,6 +475,31 @@ func isTableRequired(n ast.Node, col *Column, prior int) int { |
467 | 475 | return tableNotFound |
468 | 476 | } |
469 | 477 |
|
| 478 | +// An embedded struct is the model of its table, whose columns may not be |
| 479 | +// nullable, so it cannot hold the NULLs the optional side of an outer join |
| 480 | +// produces. |
| 481 | +func checkEmbedRequired(node ast.Node, embed *preprocess.Embed, location int) error { |
| 482 | + n, ok := node.(*ast.SelectStmt) |
| 483 | + if !ok { |
| 484 | + return nil |
| 485 | + } |
| 486 | + col := &Column{Table: embed.Table, TableAlias: embed.Param()} |
| 487 | + for _, f := range n.FromClause.Items { |
| 488 | + res := isTableRequired(f, col, tableRequired) |
| 489 | + if res != tableNotFound { |
| 490 | + if res == tableOptional { |
| 491 | + return &sqlerr.Error{ |
| 492 | + Code: "0A000", |
| 493 | + Message: fmt.Sprintf("sqlc.embed(%s) on the nullable side of an outer join is not supported", embed.Param()), |
| 494 | + Location: location, |
| 495 | + } |
| 496 | + } |
| 497 | + break |
| 498 | + } |
| 499 | + } |
| 500 | + return nil |
| 501 | +} |
| 502 | + |
470 | 503 | type tableVisitor struct { |
471 | 504 | list ast.List |
472 | 505 | } |
|
0 commit comments