MCPcopy Index your code
hub / github.com/sqlc-dev/sqlc / onConflictClause

Function onConflictClause

internal/sql/validate/insert_stmt.go:52–121  ·  view source on GitHub ↗

onConflictClause validates an ON CONFLICT DO UPDATE clause against the target table. It checks: - ON CONFLICT (col, ...) conflict target columns exist - DO UPDATE SET col = ... assignment target columns exist - EXCLUDED.col references exist

(c *catalog.Catalog, fqn *ast.TableName, n *ast.InsertStmt)

Source from the content-addressed store, hash-verified

50// - DO UPDATE SET col = ... assignment target columns exist
51// - EXCLUDED.col references exist
52func onConflictClause(c *catalog.Catalog, fqn *ast.TableName, n *ast.InsertStmt) error {
53 if fqn == nil || n.OnConflictClause == nil || n.OnConflictClause.Action != ast.OnConflictActionUpdate {
54 return nil
55 }
56
57 table, err := c.GetTable(fqn)
58 if err != nil {
59 return err
60 }
61
62 // Build set of column names for existence checks.
63 colNames := make(map[string]struct{}, len(table.Columns))
64 for _, col := range table.Columns {
65 colNames[col.Name] = struct{}{}
66 }
67
68 // DO UPDATE requires a conflict target: ON CONFLICT (col) or ON CONFLICT ON CONSTRAINT name.
69 if n.OnConflictClause.Infer == nil {
70 return &sqlerr.Error{
71 Code: "42601",
72 Message: "ON CONFLICT DO UPDATE requires inference specification or constraint name",
73 }
74 }
75
76 // Validate ON CONFLICT (col, ...) conflict target columns.
77 if n.OnConflictClause.Infer.IndexElems != nil {
78 for _, item := range n.OnConflictClause.Infer.IndexElems.Items {
79 elem, ok := item.(*ast.IndexElem)
80 if !ok || elem.Name == nil {
81 continue
82 }
83
84 if _, exists := colNames[*elem.Name]; !exists {
85 e := sqlerr.ColumnNotFound(table.Rel.Name, *elem.Name)
86 e.Location = n.OnConflictClause.Infer.Location
87 return e
88 }
89 }
90 }
91
92 // Validate DO UPDATE SET col = ... assignment target columns and EXCLUDED.col references.
93 if n.OnConflictClause.TargetList == nil {
94 return nil
95 }
96
97 for _, item := range n.OnConflictClause.TargetList.Items {
98 target, ok := item.(*ast.ResTarget)
99 if !ok || target.Name == nil {
100 continue
101 }
102
103 if _, exists := colNames[*target.Name]; !exists {
104 e := sqlerr.ColumnNotFound(table.Rel.Name, *target.Name)
105 e.Location = target.Location
106 return e
107 }
108
109 if ref, ok := target.Val.(*ast.ColumnRef); ok {

Callers 1

InsertStmtFunction · 0.85

Calls 3

ColumnNotFoundFunction · 0.92
excludedColumnRefFunction · 0.85
GetTableMethod · 0.45

Tested by

no test coverage detected