diff --git a/krab/sql_statement.go b/krab/sql_statement.go index f6fc780..05291b8 100644 --- a/krab/sql_statement.go +++ b/krab/sql_statement.go @@ -3,6 +3,8 @@ package krab import ( "io" "strings" + + "github.com/hashicorp/hcl/v2" ) // ToSQL converts DSL struct to SQL. @@ -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 +} diff --git a/krab/type_migration.go b/krab/type_migration.go index 7bc3835..c6408ef 100644 --- a/krab/type_migration.go +++ b/krab/type_migration.go @@ -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() }