fix: upsert migration history

This commit is contained in:
boojack 2022-07-01 20:08:25 +08:00
parent 0945b14deb
commit 87e6277977
2 changed files with 27 additions and 51 deletions

View File

@ -142,26 +142,23 @@ func (db *DB) compareMigrationHistory() error {
return err return err
} }
if table == nil { if table == nil {
createTable(db, ` if err := createTable(db, `
CREATE TABLE migration_history ( CREATE TABLE migration_history (
version TEXT NOT NULL PRIMARY KEY, version TEXT NOT NULL PRIMARY KEY,
created_ts BIGINT NOT NULL DEFAULT (strftime('%s', 'now')) created_ts BIGINT NOT NULL DEFAULT (strftime('%s', 'now'))
); );
`) `); err != nil {
return err
}
} }
migrationHistoryList, err := findMigrationHistoryList(db) currentVersion := common.Version
migrationHistory, err := upsertMigrationHistory(db.Db, currentVersion)
if err != nil { if err != nil {
return err return err
} }
if migrationHistory == nil {
if len(migrationHistoryList) == 0 { return fmt.Errorf("failed to upsert migration history")
createMigrationHistory(db, common.Version)
} else {
migrationHistory := migrationHistoryList[0]
if migrationHistory.Version != common.Version {
createMigrationHistory(db, common.Version)
}
} }
return nil return nil

View File

@ -1,7 +1,7 @@
package db package db
import ( import (
"fmt" "database/sql"
) )
type MigrationHistory struct { type MigrationHistory struct {
@ -9,53 +9,32 @@ type MigrationHistory struct {
Version string Version string
} }
func findMigrationHistoryList(db *DB) ([]*MigrationHistory, error) { func upsertMigrationHistory(db *sql.DB, version string) (*MigrationHistory, error) {
rows, err := db.Db.Query(` row, err := db.Query(`
SELECT INSERT INTO migration_history (
version
)
VALUES (?)
ON CONFLICT(version) DO UPDATE
SET
version=EXCLUDED.version
RETURNING version, created_ts
`,
version, version,
created_ts )
FROM
migration_history
ORDER BY created_ts DESC
`)
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer rows.Close() defer row.Close()
migrationHistoryList := make([]*MigrationHistory, 0) row.Next()
for rows.Next() { migrationHistory := MigrationHistory{}
var migrationHistory MigrationHistory if err := row.Scan(
if err := rows.Scan(
&migrationHistory.Version, &migrationHistory.Version,
&migrationHistory.CreatedTs, &migrationHistory.CreatedTs,
); err != nil { ); err != nil {
return nil, err return nil, err
} }
migrationHistoryList = append(migrationHistoryList, &migrationHistory) return &migrationHistory, nil
}
return migrationHistoryList, nil
}
func createMigrationHistory(db *DB, version string) error {
result, err := db.Db.Exec(`
INSERT INTO migration_history (
version
)
VALUES (?)
`,
version,
)
if err != nil {
return err
}
rows, _ := result.RowsAffected()
if rows == 0 {
return fmt.Errorf("failed to create migration history with %s", version)
}
return nil
} }