Skip to content

Commit

Permalink
fix(export): escape MySQL column names (#8961)
Browse files Browse the repository at this point in the history
This change wraps all the column names with backticks so
that MySQL won't complain when a table has columns that 
are also reserved keywords in MySQL.
  • Loading branch information
andres-lowrie authored and mangalaman93 committed Nov 27, 2023
1 parent a22e248 commit 4ee6462
Showing 1 changed file with 17 additions and 2 deletions.
19 changes: 17 additions & 2 deletions dgraph/cmd/migrate/dump.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,17 @@ type sqlRow struct {
tableInfo *sqlTable
}

// escapeColumnNames wraps columnNames with backticks in order to avoid creating
// invalid sql queries in cases where a table uses a reserved keyword as a
// column name
func escapeColumnNames(columnNames []string) []string {
var escapedColNames []string
for _, c := range columnNames {
escapedColNames = append(escapedColNames, fmt.Sprintf("`"+"%s"+"`", c))
}
return escapedColNames
}

// dumpSchema generates the Dgraph schema based on m.tableGuides
// and sends the schema to m.schemaWriter
func (m *dumpMeta) dumpSchema() error {
Expand Down Expand Up @@ -91,7 +102,9 @@ func (m *dumpMeta) dumpTable(table string) error {
tableGuide := m.tableGuides[table]
tableInfo := m.tableInfos[table]

query := fmt.Sprintf(`select %s from %s`, strings.Join(tableInfo.columnNames, ","), table)
escapedColNames := escapeColumnNames(tableInfo.columnNames)

query := fmt.Sprintf(`select %s from %s`, strings.Join(escapedColNames, ","), table)
rows, err := m.sqlPool.Query(query)
if err != nil {
return err
Expand Down Expand Up @@ -135,7 +148,9 @@ func (m *dumpMeta) dumpTableConstraints(table string) error {
tableGuide := m.tableGuides[table]
tableInfo := m.tableInfos[table]

query := fmt.Sprintf(`select %s from %s`, strings.Join(tableInfo.columnNames, ","), table)
escapedColNames := escapeColumnNames(tableInfo.columnNames)

query := fmt.Sprintf(`select %s from %s`, strings.Join(escapedColNames, ","), table)
rows, err := m.sqlPool.Query(query)
if err != nil {
return err
Expand Down

0 comments on commit 4ee6462

Please sign in to comment.