File size: 1,150 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package migratetest

import (
	"slices"
	"sort"
	"strings"
)

// TableSnapshot is a snapshot of a table's data.
type TableSnapshot struct {
	// Name is the name of the table.
	Name    string
	Columns []string
	Rows    [][]string
}

func (t TableSnapshot) EntityName() string { return t.Name }

type columnSort TableSnapshot

func (data *columnSort) Len() int { return len(data.Columns) }
func (data *columnSort) Less(i, j int) bool {
	// sort by column name, but prefer "id" as the first column
	if data.Columns[i] == "id" {
		return true
	}
	if data.Columns[j] == "id" {
		return false
	}

	return data.Columns[i] < data.Columns[j]
}
func (data *columnSort) Swap(i, j int) {
	data.Columns[i], data.Columns[j] = data.Columns[j], data.Columns[i]
	for _, row := range data.Rows {
		row[i], row[j] = row[j], row[i]
	}
}

// Sort sorts the columns and rows of the snapshot.
func (data *TableSnapshot) Sort() {
	sort.Sort((*columnSort)(data))

	// sort rows by first column, then second, etc.
	slices.SortFunc(data.Rows, func(a, b []string) int {
		for i := range a {
			if a[i] != b[i] {
				return strings.Compare(a[i], b[i])
			}
		}

		return 0
	})
}