Skip to content

Commit

Permalink
Add sorter for SQLStatements
Browse files Browse the repository at this point in the history
  • Loading branch information
qbart committed Nov 30, 2021
1 parent 589cd29 commit 888c707
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 13 deletions.
21 changes: 21 additions & 0 deletions krab/sql_statement.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package krab
import (
"io"
"strings"

"github.com/hashicorp/hcl/v2"
)

// ToSQL converts DSL struct to SQL.
Expand All @@ -16,9 +18,28 @@ type SQLStatement string
// SQLStatements represents list of raw SQL statements.
type SQLStatements []SQLStatement

// SQLStatementsSorter sorts SQLStatement by the order how they are defined in a file.
type SQLStatementsSorter struct {
Statements SQLStatements
Bytes []int
}

// Append adds new SQL statement to the list from object that satisfies ToSQL interface.
func (s *SQLStatements) Append(sql ToSQL) {
sb := &strings.Builder{}
sql.ToSQL(sb)
*s = append(*s, SQLStatement(sb.String()))
}

// Insert ToSQL at given range.
func (s *SQLStatementsSorter) Insert(r hcl.Range, sql ToSQL) {
s.Statements.Append(sql)
s.Bytes = append(s.Bytes, r.Start.Byte)
}

// Sort sorts statements by byte range.
func (s *SQLStatementsSorter) Sort() SQLStatements {
ret := make(SQLStatements, len(s.Statements))
copy(ret, s.Statements) // TODO: replace with actual sort
return ret
}
20 changes: 7 additions & 13 deletions krab/type_migration.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,30 +78,24 @@ func (m *MigrationUpOrDown) ToSQL(w io.StringWriter) {

// ToSQLStatements returns list of SQL statements to executre during the migration.
func (m *MigrationUpOrDown) ToSQLStatements() SQLStatements {
sqls := SQLStatements{}

toSort := map[int]ToSQL{}
sorter := SQLStatementsSorter{Statements: SQLStatements{}, Bytes: []int{}}

if m.SQL != "" {
toSort[m.AttrDefRanges["sql"].Start.Byte] = m
sorter.Insert(m.AttrDefRanges["sql"], m)
}

for _, t := range m.CreateTables {
toSort[t.DefRange.Start.Byte] = t
sorter.Insert(t.DefRange, t)
}
for _, t := range m.CreateIndices {
toSort[t.DefRange.Start.Byte] = t
sorter.Insert(t.DefRange, t)
}
for _, t := range m.DropIndices {
toSort[t.DefRange.Start.Byte] = t
sorter.Insert(t.DefRange, t)
}
for _, t := range m.DropTables {
toSort[t.DefRange.Start.Byte] = t
}

for _, sql := range toSort {
sqls.Append(sql)
sorter.Insert(t.DefRange, t)
}

return sqls
return sorter.Sort()
}

0 comments on commit 888c707

Please sign in to comment.