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

fix: Add backticks to src table names, columns and sequences #923

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 81 additions & 1 deletion conversion/store_files.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import (

"github.com/GoogleCloudPlatform/spanner-migration-tool/common/utils"
"github.com/GoogleCloudPlatform/spanner-migration-tool/internal"
"github.com/GoogleCloudPlatform/spanner-migration-tool/schema"
"github.com/GoogleCloudPlatform/spanner-migration-tool/spanner/ddl"
"github.com/GoogleCloudPlatform/spanner-migration-tool/spanner/writer"
)
Expand Down Expand Up @@ -93,18 +94,62 @@ func WriteSessionFile(conv *internal.Conv, name string, out *os.File) {
}
// Session file will basically contain 'conv' struct in JSON format.
// It contains all the information for schema and data conversion state.
convJSON, err := json.MarshalIndent(conv, "", " ")

// add backticks from names for table, sequences, columns, etc
convCopy := addBackticksToNames(conv, out)
convJSON, err := json.MarshalIndent(convCopy, "", " ")
if err != nil {
fmt.Fprintf(out, "Can't encode session state to JSON: %v\n", err)
return
}

if _, err := f.Write(convJSON); err != nil {
fmt.Fprintf(out, "Can't write out session file: %v\n", err)
return
}
fmt.Fprintf(out, "Wrote session to file '%s'.\n", name)
}

func addBackticksToNames(conv *internal.Conv, out *os.File) *internal.Conv {
convJSON, err := json.MarshalIndent(conv, "", " ")
if err != nil {
fmt.Fprintf(out, "Can't encode session state to JSON: %v\n", err)
return conv
}
// Creating copy of conv object to modify it before write
convCopy := &internal.Conv{}
err = json.Unmarshal(convJSON, convCopy)
if err != nil {
fmt.Fprintf(out, "Can't encode session state to JSON: %v\n", err)
return conv
}

srcSchemaCopy := make(map[string]schema.Table)
for tableName, table := range convCopy.SrcSchema {
// Add backticks to table Name
table.Name = "`" + table.Name + "`"

// Add backticks to each ColName
for colName, column := range table.ColDefs {
column.Name = "`" + column.Name + "`"
table.ColDefs[colName] = column
}

srcSchemaCopy[tableName] = table
}

convCopy.SrcSchema = srcSchemaCopy

srcSequenceCopy := make(map[string]ddl.Sequence)
for sequenceName, sequence := range convCopy.SrcSequences {
// Add backticks to Sequence Name
sequence.Name = "`" + sequence.Name + "`"
srcSequenceCopy[sequenceName] = sequence
}
convCopy.SrcSequences = srcSequenceCopy
return convCopy
}

// WriteConvGeneratedFiles creates a directory labeled downloads with the current timestamp
// where it writes the sessionfile, report summary and DDLs then returns the directory where it writes.
func WriteConvGeneratedFiles(conv *internal.Conv, dbName string, driver string, BytesRead int64, out *os.File) (string, error) {
Expand Down Expand Up @@ -136,9 +181,44 @@ func ReadSessionFile(conv *internal.Conv, sessionJSON string) error {
if err != nil {
return err
}

// remove backticks from names for table, sequences, columns, etc
removeBackticks(conv)
return nil
}

func removeBackticks(conv *internal.Conv) {
processString := func(s *string) string {
if len(*s) >= 2 && (*s)[0] == '`' && (*s)[len(*s)-1] == '`' {
*s = (*s)[1 : len(*s)-1]
}
return *s
}

// Remove backticks from SrcSchema
for tableName, table := range conv.SrcSchema {
// Remove backticks from table Name
processString(&table.Name)

// Remove backticks from each ColDef
for colName, col := range table.ColDefs {
col.Name = processString(&col.Name)
table.ColDefs[colName] = col
}

conv.SrcSchema[tableName] = table
}

// Remove backticks from SrcSequences
for sequenceName, sequence := range conv.SrcSequences {
// Remove backticks from Sequence Name
sequence.Name = processString(&sequence.Name)
conv.SrcSequences[sequenceName] = sequence

conv.SrcSequences[sequenceName] = sequence
}
}

// WriteBadData prints summary stats about bad rows and writes detailed info
// to file 'name'.
func WriteBadData(bw *writer.BatchWriter, conv *internal.Conv, banner, name string, out *os.File) {
Expand Down
156 changes: 156 additions & 0 deletions conversion/store_files_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,14 @@
package conversion

import (
"bytes"
"crypto/sha256"
"io"
"os"
"path/filepath"
"testing"

"github.com/GoogleCloudPlatform/spanner-migration-tool/common/utils"
"github.com/GoogleCloudPlatform/spanner-migration-tool/internal"
"github.com/GoogleCloudPlatform/spanner-migration-tool/schema"
"github.com/GoogleCloudPlatform/spanner-migration-tool/spanner/ddl"
Expand Down Expand Up @@ -107,6 +112,13 @@ func TestReadSessionFile(t *testing.T) {
SequenceKind: "BIT REVERSED POSITIVE",
},
}
expectedConvWithSequences.SrcSequences = map[string]ddl.Sequence{
"s1": {
Name: "Seq",
Id: "s1",
SequenceKind: "BIT REVERSED POSITIVE",
},
}
testCases := []struct {
name string
filePath string
Expand All @@ -133,3 +145,147 @@ func TestReadSessionFile(t *testing.T) {
assert.Equal(t, &tc.expectedConv, &conv, tc.name)
}
}

func TestWriteSessionFile(t *testing.T) {
createConv := func() *internal.Conv {
conv := internal.MakeConv()
conv.SpSchema = map[string]ddl.CreateTable{
"t1": {
Name: "numbers",
ColIds: []string{"c1", "c2"},
ShardIdColumn: "c1",
ColDefs: map[string]ddl.ColumnDef{
"c1": {
Name: "id",
NotNull: true,
Comment: "From: id int(10)",
Id: "c2",
},
"c2": {
Name: "value",
NotNull: false,
Id: "c2",
},
},
PrimaryKeys: []ddl.IndexKey{
{
ColId: "c1",
Order: 1,
},
},
Comment: "Spanner schema for source table numbers",
Id: "t1",
},
}
conv.SrcSchema = map[string]schema.Table{
"t1": {
Name: "numbers",
Schema: "default",
ColIds: []string{"c1", "c2"},
ColDefs: map[string]schema.Column{
"c1": {
Name: "id",
Type: schema.Type{
Name: "int",
Mods: []int64{10},
},
NotNull: true,
Id: "c1",
},
"c2": {
Name: "value",
Type: schema.Type{
Name: "int",
Mods: []int64{10},
},
NotNull: true,
Id: "c2",
},
},
PrimaryKeys: []schema.Key{
{
ColId: "c1",
Desc: false,
Order: 1,
},
},
Id: "t1",
},
}
conv.SchemaIssues = map[string]internal.TableIssues{
"t1": {
ColumnLevelIssues: map[string][]internal.SchemaIssue{
"c1": {14},
},
},
}
conv.SpSequences = map[string]ddl.Sequence{
"s1": {
Name: "Seq",
Id: "s1",
SequenceKind: "BIT REVERSED POSITIVE",
},
}
conv.SrcSequences = map[string]ddl.Sequence{
"s1": {
Name: "Seq",
Id: "s1",
SequenceKind: "BIT REVERSED POSITIVE",
},
}
return conv
}
conv := createConv()
testCases := []struct {
name string
expectedFilePath string
conv *internal.Conv
expectError bool
}{
{
name: "test basic session file",
expectedFilePath: filepath.Join("..", "test_data", "basic_session_file_test.json"),
conv: conv,
expectError: false,
},
}
for _, tc := range testCases {
ioHelper := &utils.IOStreams{Out: os.Stdout}
WriteSessionFile(tc.conv, "session_file", ioHelper.Out)

equal, err := compareFiles("session_file", tc.expectedFilePath)
assert.NoError(t, err, "error comparing files")
assert.True(t, equal, "session_file does not match expected file")

err = os.Remove("session_file")
assert.NoError(t, err, "error deleting session_file")
}
}

// compareFiles function (using hashing)
func compareFiles(file1, file2 string) (bool, error) {
hash1, err := hashFile(file1)
if err != nil {
return false, err
}
hash2, err := hashFile(file2)
if err != nil {
return false, err
}
return bytes.Equal(hash1, hash2), nil
}

func hashFile(filePath string) ([]byte, error) {
f, err := os.Open(filePath)
if err != nil {
return nil, err
}
defer f.Close()

h := sha256.New()
if _, err := io.Copy(h, f); err != nil {
return nil, err
}
return h.Sum(nil),
nil
}
35 changes: 28 additions & 7 deletions test_data/basic_session_file_test.json
Original file line number Diff line number Diff line change
Expand Up @@ -48,23 +48,26 @@
],
"ForeignKeys": null,
"Indexes": null,
"ParentTable": {"Id":"","OnDelete":""},
"ParentTable": {
"Id": "",
"OnDelete": ""
},
"Comment": "Spanner schema for source table numbers",
"Id": "t1"
}
},
"SyntheticPKeys": {},
"SrcSchema": {
"t1": {
"Name": "numbers",
"Name": "`numbers`",
"Schema": "default",
"ColIds": [
"c1",
"c2"
],
"ColDefs": {
"c1": {
"Name": "id",
"Name": "`id`",
"Type": {
"Name": "int",
"Mods": [
Expand All @@ -81,10 +84,14 @@
"ForeignKey": false,
"AutoIncrement": false
},
"Id": "c1"
"Id": "c1",
"AutoGen": {
"Name": "",
"GenerationType": ""
}
},
"c2": {
"Name": "value",
"Name": "`value`",
"Type": {
"Name": "int",
"Mods": [
Expand All @@ -101,7 +108,11 @@
"ForeignKey": false,
"AutoIncrement": false
},
"Id": "c2"
"Id": "c2",
"AutoGen": {
"Name": "",
"GenerationType": ""
}
}
},
"PrimaryKeys": [
Expand Down Expand Up @@ -146,5 +157,15 @@
"ColumnsUsingSeq": null
}
},
"SrcSequences": {}
"SrcSequences": {
"s1": {
"Id": "s1",
"Name": "`Seq`",
"SequenceKind": "BIT REVERSED POSITIVE",
"SkipRangeMin": "",
"SkipRangeMax": "",
"StartWithCounter": "",
"ColumnsUsingSeq": null
}
}
}
6 changes: 3 additions & 3 deletions test_data/basic_sessions_file_wo_sequences_test.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,15 +56,15 @@
"SyntheticPKeys": {},
"SrcSchema": {
"t1": {
"Name": "numbers",
"Name": "`numbers`",
"Schema": "default",
"ColIds": [
"c1",
"c2"
],
"ColDefs": {
"c1": {
"Name": "id",
"Name": "`id`",
"Type": {
"Name": "int",
"Mods": [
Expand All @@ -84,7 +84,7 @@
"Id": "c1"
},
"c2": {
"Name": "value",
"Name": "`value`",
"Type": {
"Name": "int",
"Mods": [
Expand Down
Loading