|
| 1 | +// Copyright 2024 The Gitea Authors. All rights reserved. |
| 2 | +// SPDX-License-Identifier: MIT |
| 3 | + |
| 4 | +package unittest |
| 5 | + |
| 6 | +import ( |
| 7 | + "database/sql" |
| 8 | + "encoding/hex" |
| 9 | + "fmt" |
| 10 | + "os" |
| 11 | + "path/filepath" |
| 12 | + "slices" |
| 13 | + "strings" |
| 14 | + |
| 15 | + "gopkg.in/yaml.v3" |
| 16 | + "xorm.io/xorm" |
| 17 | + "xorm.io/xorm/schemas" |
| 18 | +) |
| 19 | + |
| 20 | +type fixtureItem struct { |
| 21 | + tableName string |
| 22 | + tableNameQuoted string |
| 23 | + sqlInserts []string |
| 24 | + sqlInsertArgs [][]any |
| 25 | + |
| 26 | + mssqlHasIdentityColumn bool |
| 27 | +} |
| 28 | + |
| 29 | +type fixturesLoaderInternal struct { |
| 30 | + db *sql.DB |
| 31 | + dbType schemas.DBType |
| 32 | + files []string |
| 33 | + fixtures map[string]*fixtureItem |
| 34 | + quoteObject func(string) string |
| 35 | + paramPlaceholder func(idx int) string |
| 36 | +} |
| 37 | + |
| 38 | +func (f *fixturesLoaderInternal) mssqlTableHasIdentityColumn(db *sql.DB, tableName string) (bool, error) { |
| 39 | + row := db.QueryRow(`SELECT COUNT(*) FROM sys.identity_columns WHERE OBJECT_ID = OBJECT_ID(?)`, tableName) |
| 40 | + var count int |
| 41 | + if err := row.Scan(&count); err != nil { |
| 42 | + return false, err |
| 43 | + } |
| 44 | + return count > 0, nil |
| 45 | +} |
| 46 | + |
| 47 | +func (f *fixturesLoaderInternal) preprocessFixtureRow(row []map[string]any) (err error) { |
| 48 | + for _, m := range row { |
| 49 | + for k, v := range m { |
| 50 | + if s, ok := v.(string); ok { |
| 51 | + if strings.HasPrefix(s, "0x") { |
| 52 | + if m[k], err = hex.DecodeString(s[2:]); err != nil { |
| 53 | + return err |
| 54 | + } |
| 55 | + } |
| 56 | + } |
| 57 | + } |
| 58 | + } |
| 59 | + return nil |
| 60 | +} |
| 61 | + |
| 62 | +func (f *fixturesLoaderInternal) prepareFixtureItem(file string) (_ *fixtureItem, err error) { |
| 63 | + fixture := &fixtureItem{} |
| 64 | + fixture.tableName, _, _ = strings.Cut(filepath.Base(file), ".") |
| 65 | + fixture.tableNameQuoted = f.quoteObject(fixture.tableName) |
| 66 | + |
| 67 | + if f.dbType == schemas.MSSQL { |
| 68 | + fixture.mssqlHasIdentityColumn, err = f.mssqlTableHasIdentityColumn(f.db, fixture.tableName) |
| 69 | + if err != nil { |
| 70 | + return nil, err |
| 71 | + } |
| 72 | + } |
| 73 | + |
| 74 | + data, err := os.ReadFile(file) |
| 75 | + if err != nil { |
| 76 | + return nil, fmt.Errorf("failed to read file %q: %w", file, err) |
| 77 | + } |
| 78 | + |
| 79 | + var rows []map[string]any |
| 80 | + if err = yaml.Unmarshal(data, &rows); err != nil { |
| 81 | + return nil, fmt.Errorf("failed to unmarshal yaml data from %q: %w", file, err) |
| 82 | + } |
| 83 | + if err = f.preprocessFixtureRow(rows); err != nil { |
| 84 | + return nil, fmt.Errorf("failed to preprocess fixture rows from %q: %w", file, err) |
| 85 | + } |
| 86 | + |
| 87 | + var sqlBuf []byte |
| 88 | + var sqlArguments []any |
| 89 | + for _, row := range rows { |
| 90 | + sqlBuf = append(sqlBuf, fmt.Sprintf("INSERT INTO %s (", fixture.tableNameQuoted)...) |
| 91 | + for k, v := range row { |
| 92 | + sqlBuf = append(sqlBuf, f.quoteObject(k)...) |
| 93 | + sqlBuf = append(sqlBuf, ","...) |
| 94 | + sqlArguments = append(sqlArguments, v) |
| 95 | + } |
| 96 | + sqlBuf = sqlBuf[:len(sqlBuf)-1] |
| 97 | + sqlBuf = append(sqlBuf, ") VALUES ("...) |
| 98 | + paramIdx := 1 |
| 99 | + for range row { |
| 100 | + sqlBuf = append(sqlBuf, f.paramPlaceholder(paramIdx)...) |
| 101 | + sqlBuf = append(sqlBuf, ',') |
| 102 | + paramIdx++ |
| 103 | + } |
| 104 | + sqlBuf[len(sqlBuf)-1] = ')' |
| 105 | + fixture.sqlInserts = append(fixture.sqlInserts, string(sqlBuf)) |
| 106 | + fixture.sqlInsertArgs = append(fixture.sqlInsertArgs, slices.Clone(sqlArguments)) |
| 107 | + sqlBuf = sqlBuf[:0] |
| 108 | + sqlArguments = sqlArguments[:0] |
| 109 | + } |
| 110 | + return fixture, nil |
| 111 | +} |
| 112 | + |
| 113 | +func (f *fixturesLoaderInternal) loadFixtures(tx *sql.Tx, file string) (err error) { |
| 114 | + fixture := f.fixtures[file] |
| 115 | + if fixture == nil { |
| 116 | + if fixture, err = f.prepareFixtureItem(file); err != nil { |
| 117 | + return err |
| 118 | + } |
| 119 | + f.fixtures[file] = fixture |
| 120 | + } |
| 121 | + |
| 122 | + _, err = tx.Exec(fmt.Sprintf("DELETE FROM %s", fixture.tableNameQuoted)) // sqlite3 doesn't support truncate |
| 123 | + if err != nil { |
| 124 | + return err |
| 125 | + } |
| 126 | + |
| 127 | + if fixture.mssqlHasIdentityColumn { |
| 128 | + _, err = tx.Exec(fmt.Sprintf("SET IDENTITY_INSERT %s ON", fixture.tableNameQuoted)) |
| 129 | + if err != nil { |
| 130 | + return err |
| 131 | + } |
| 132 | + defer func() { _, err = tx.Exec(fmt.Sprintf("SET IDENTITY_INSERT %s OFF", fixture.tableNameQuoted)) }() |
| 133 | + } |
| 134 | + for i := range fixture.sqlInserts { |
| 135 | + _, err = tx.Exec(fixture.sqlInserts[i], fixture.sqlInsertArgs[i]...) |
| 136 | + } |
| 137 | + if err != nil { |
| 138 | + return err |
| 139 | + } |
| 140 | + return nil |
| 141 | +} |
| 142 | + |
| 143 | +func (f *fixturesLoaderInternal) Load() error { |
| 144 | + tx, err := f.db.Begin() |
| 145 | + if err != nil { |
| 146 | + return err |
| 147 | + } |
| 148 | + defer func() { _ = tx.Rollback() }() |
| 149 | + |
| 150 | + for _, file := range f.files { |
| 151 | + if err := f.loadFixtures(tx, file); err != nil { |
| 152 | + return fmt.Errorf("failed to load fixtures from %s: %w", file, err) |
| 153 | + } |
| 154 | + } |
| 155 | + return tx.Commit() |
| 156 | +} |
| 157 | + |
| 158 | +func FixturesFileFullPaths(dir string, files []string) ([]string, error) { |
| 159 | + if files != nil && len(files) == 0 { |
| 160 | + return nil, nil // load nothing |
| 161 | + } |
| 162 | + files = slices.Clone(files) |
| 163 | + if len(files) == 0 { |
| 164 | + entries, err := os.ReadDir(dir) |
| 165 | + if err != nil { |
| 166 | + return nil, err |
| 167 | + } |
| 168 | + for _, e := range entries { |
| 169 | + files = append(files, e.Name()) |
| 170 | + } |
| 171 | + } |
| 172 | + for i, file := range files { |
| 173 | + if !filepath.IsAbs(file) { |
| 174 | + files[i] = filepath.Join(dir, file) |
| 175 | + } |
| 176 | + } |
| 177 | + return files, nil |
| 178 | +} |
| 179 | + |
| 180 | +func NewFixturesLoader(x *xorm.Engine, opts FixturesOptions) (FixturesLoader, error) { |
| 181 | + files, err := FixturesFileFullPaths(opts.Dir, opts.Files) |
| 182 | + if err != nil { |
| 183 | + return nil, fmt.Errorf("failed to get fixtures files: %w", err) |
| 184 | + } |
| 185 | + f := &fixturesLoaderInternal{db: x.DB().DB, dbType: x.Dialect().URI().DBType, files: files, fixtures: map[string]*fixtureItem{}} |
| 186 | + switch f.dbType { |
| 187 | + case schemas.SQLITE: |
| 188 | + f.quoteObject = func(s string) string { return fmt.Sprintf(`"%s"`, s) } |
| 189 | + f.paramPlaceholder = func(idx int) string { return "?" } |
| 190 | + case schemas.POSTGRES: |
| 191 | + f.quoteObject = func(s string) string { return fmt.Sprintf(`"%s"`, s) } |
| 192 | + f.paramPlaceholder = func(idx int) string { return fmt.Sprintf(`$%d`, idx) } |
| 193 | + case schemas.MYSQL: |
| 194 | + f.quoteObject = func(s string) string { return fmt.Sprintf("`%s`", s) } |
| 195 | + f.paramPlaceholder = func(idx int) string { return "?" } |
| 196 | + case schemas.MSSQL: |
| 197 | + f.quoteObject = func(s string) string { return fmt.Sprintf("[%s]", s) } |
| 198 | + f.paramPlaceholder = func(idx int) string { return "?" } |
| 199 | + } |
| 200 | + return f, nil |
| 201 | +} |
0 commit comments