Skip to content
Open
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
19 changes: 16 additions & 3 deletions src/formatter/formatter.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,33 @@ package formatter

import (
"fmt"
"strconv"
"strings"

"github.com/syucream/hakagi/src/constraint"
)

const (
baseSql = "ALTER TABLE %s ADD CONSTRAINT FOREIGN KEY (%s) REFERENCES %s(%s);"
baseSql = "ALTER TABLE %s ADD CONSTRAINT FOREIGN KEY (%s) REFERENCES %s(%s);"
customSql = "ALTER TABLE %s ADD CONSTRAINT %s FOREIGN KEY (%s) REFERENCES %s(%s);"
)

func FormatSql(constraints []constraint.Constraint) string {
var queries []string

for _, c := range constraints {
q := fmt.Sprintf(baseSql, c.Table, c.Column, c.ReferedTable, c.ReferedColumn)
for i, c := range constraints {
var q string

// If the table name is too long, the foreign key name will also be too long,
// and an error will occur if the foreign key name exceeds 64 characters.
// I think 4 digits is enough for numbering.
if len(c.Table) >= 56 {
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

64 characters - ( "_ibfk_"(6 characters) + number(1 or more characters) )
= 57 characters

Table name is allowed up to 57 characters, but considering the case where number is 2-digit, set it to 56 characters.

fk_name := c.Table[:56] + "_fk_" + strconv.Itoa(i)
q = fmt.Sprintf(customSql, c.Table, fk_name, c.Column, c.ReferedTable, c.ReferedColumn)
} else {
q = fmt.Sprintf(baseSql, c.Table, c.Column, c.ReferedTable, c.ReferedColumn)
}

queries = append(queries, q)
}

Expand Down