Skip to content

Commit

Permalink
opt: add outbound FK checks for upsert
Browse files Browse the repository at this point in the history
This is a re-implementation of Justin's change 3d1dd0f, except that we now
perform the insertion check for all new rows instead of just the inserted rows.
We do this by utilizing the same column that would be used for a RETURNING
clause, which in some cases is of the form
`CASE WHEN canary IS NULL col1 ELSE col2`.

Release note: None
  • Loading branch information
RaduBerinde committed Feb 27, 2020
1 parent 93cfa03 commit edb8a53
Show file tree
Hide file tree
Showing 3 changed files with 1,204 additions and 3 deletions.
13 changes: 10 additions & 3 deletions pkg/sql/opt/optbuilder/mutation_builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -1013,15 +1013,22 @@ func (mb *mutationBuilder) buildFKChecksForUpdate() {
}

func (mb *mutationBuilder) buildFKChecksForUpsert() {
if mb.tab.OutboundForeignKeyCount() == 0 && mb.tab.InboundForeignKeyCount() == 0 {
numOutbound := mb.tab.OutboundForeignKeyCount()
numInbound := mb.tab.InboundForeignKeyCount()

if numOutbound == 0 && numInbound == 0 {
return
}
if !mb.b.evalCtx.SessionData.OptimizerFKs {
mb.fkFallback = true
return
}
// TODO(justin): not implemented yet.
mb.fkFallback = true

mb.withID = mb.b.factory.Memo().NextWithID()

for i := 0; i < numOutbound; i++ {
mb.addInsertionCheck(i)
}
}

// addInsertionCheck adds a FK check for rows which are added to a table.
Expand Down
38 changes: 38 additions & 0 deletions pkg/sql/opt/optbuilder/testdata/fk-checks-insert
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,44 @@ insert child
└── filters
└── column2:5 = parent.p:6

build
INSERT INTO child VALUES (100, 1), (200, 1) ON CONFLICT DO NOTHING
----
insert child
├── columns: <none>
├── insert-mapping:
│ ├── column1:3 => c:1
│ └── column2:4 => child.p:2
├── input binding: &1
├── project
│ ├── columns: column1:3!null column2:4!null
│ └── select
│ ├── columns: column1:3!null column2:4!null c:5 child.p:6
│ ├── left-join (hash)
│ │ ├── columns: column1:3!null column2:4!null c:5 child.p:6
│ │ ├── values
│ │ │ ├── columns: column1:3!null column2:4!null
│ │ │ ├── (100, 1)
│ │ │ └── (200, 1)
│ │ ├── scan child
│ │ │ └── columns: c:5!null child.p:6!null
│ │ └── filters
│ │ └── column1:3 = c:5
│ └── filters
│ └── c:5 IS NULL
└── f-k-checks
└── f-k-checks-item: child(p) -> parent(p)
└── anti-join (hash)
├── columns: column2:7!null
├── with-scan &1
│ ├── columns: column2:7!null
│ └── mapping:
│ └── column2:4 => column2:7
├── scan parent
│ └── columns: parent.p:8!null
└── filters
└── column2:7 = parent.p:8

# Use a non-constant input.
exec-ddl
CREATE TABLE xy (x INT, y INT)
Expand Down
Loading

0 comments on commit edb8a53

Please sign in to comment.