Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add foreign key as part of set statement when reserved connection is needed #14696

Merged
merged 9 commits into from
Dec 6, 2023
28 changes: 28 additions & 0 deletions go/test/endtoend/vtgate/foreignkey/fk_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1207,3 +1207,31 @@ func TestReplaceWithFK(t *testing.T) {
utils.AssertMatches(t, conn, `select * from u_t1`, `[[INT64(1) INT64(1)] [INT64(2) INT64(2)]]`)
utils.AssertMatches(t, conn, `select * from u_t2`, `[[INT64(1) NULL] [INT64(2) NULL]]`)
}

// TestDDLFk tests that table is created with fk constraint when foreign_key_checks is off.
func TestDDLFk(t *testing.T) {
mcmp, closer := start(t)
defer closer()

utils.Exec(t, mcmp.VtConn, `use uks`)

createTableDDLTemp1 := `
create table temp1(id bigint auto_increment primary key, col varchar(20) not null,
foreign key (col) references temp2(col))
`
mcmp.Exec(`set foreign_key_checks = off`)
// should be able to create `temp1` table without a `temp2`
mcmp.Exec(createTableDDLTemp1)

createTableDDLTemp2 := `
create table temp2(id bigint auto_increment primary key, col varchar(20) not null, key (col))
`
// now create `temp2`
mcmp.Exec(createTableDDLTemp2)

// inserting some data with fk constraints on.
mcmp.Exec(`set foreign_key_checks = on`)
mcmp.Exec(`insert into temp2(col) values('a'), ('b'), ('c') `)
mcmp.Exec(`insert into temp1(col) values('a') `)
mcmp.ExecAllowAndCompareError(`insert into temp1(col) values('d') `)
}
23 changes: 23 additions & 0 deletions go/vt/vtgate/safe_session.go
Original file line number Diff line number Diff line change
Expand Up @@ -571,6 +571,22 @@ func (session *SafeSession) TimeZone() *time.Location {
loc, _ := datetime.ParseTimeZone(tz)
return loc
}
func (session *SafeSession) ForeignKeyChecks() *string {
session.mu.Lock()
fkVal, ok := session.SystemVariables["foreign_key_checks"]
session.mu.Unlock()

if !ok {
return nil
}
fkCheck := "0"
switch strings.ToLower(fkVal) {
case "off", "0":
return &fkCheck
}
fkCheck = "1"
GuptaManan100 marked this conversation as resolved.
Show resolved Hide resolved
return &fkCheck
}

// SetOptions sets the options
func (session *SafeSession) SetOptions(options *querypb.ExecuteOptions) {
Expand Down Expand Up @@ -610,6 +626,13 @@ func (session *SafeSession) SetPreQueries() []string {
sysVars[k] = v
})

fkVal := session.ForeignKeyChecks()
if fkVal != nil {
k := "foreign_key_checks"
keys = append(keys, k)
sysVars[k] = *fkVal
}

// if not system variables to set, return
if len(keys) == 0 {
return nil
Expand Down
Loading