memos/store/db/migration_history.go

84 lines
1.6 KiB
Go
Raw Normal View History

2022-05-21 19:59:22 +03:00
package db
import (
"context"
2022-07-01 20:06:28 +03:00
"strings"
2022-05-21 19:59:22 +03:00
)
type MigrationHistory struct {
Version string
2022-05-21 19:59:22 +03:00
CreatedTs int64
}
type MigrationHistoryUpsert struct {
Version string
2022-05-21 19:59:22 +03:00
}
2022-07-01 20:06:28 +03:00
type MigrationHistoryFind struct {
Version *string
2022-07-01 20:06:28 +03:00
}
2023-01-07 06:49:58 +03:00
func (db *DB) FindMigrationHistoryList(ctx context.Context, find *MigrationHistoryFind) ([]*MigrationHistory, error) {
where, args := []string{"1 = 1"}, []any{}
2022-07-01 20:06:28 +03:00
if v := find.Version; v != nil {
where, args = append(where, "version = ?"), append(args, *v)
}
2022-07-01 20:06:28 +03:00
query := `
2022-07-01 20:06:28 +03:00
SELECT
version,
created_ts
FROM
migration_history
WHERE ` + strings.Join(where, " AND ") + `
ORDER BY created_ts DESC
`
rows, err := db.DBInstance.QueryContext(ctx, query, args...)
2022-07-01 20:06:28 +03:00
if err != nil {
return nil, err
}
defer rows.Close()
list := make([]*MigrationHistory, 0)
2022-07-01 20:06:28 +03:00
for rows.Next() {
var migrationHistory MigrationHistory
if err := rows.Scan(
&migrationHistory.Version,
&migrationHistory.CreatedTs,
); err != nil {
return nil, err
}
list = append(list, &migrationHistory)
2022-07-01 20:06:28 +03:00
}
2022-08-24 16:53:12 +03:00
if err := rows.Err(); err != nil {
return nil, err
}
return list, nil
2022-07-01 20:06:28 +03:00
}
func (db *DB) UpsertMigrationHistory(ctx context.Context, upsert *MigrationHistoryUpsert) (*MigrationHistory, error) {
stmt := `
2022-05-21 19:59:22 +03:00
INSERT INTO migration_history (
version
2022-05-21 19:59:22 +03:00
)
VALUES (?)
2022-07-01 15:08:25 +03:00
ON CONFLICT(version) DO UPDATE
SET
version=EXCLUDED.version
RETURNING version, created_ts
`
var migrationHistory MigrationHistory
if err := db.DBInstance.QueryRowContext(ctx, stmt, upsert.Version).Scan(
2022-07-01 15:08:25 +03:00
&migrationHistory.Version,
&migrationHistory.CreatedTs,
); err != nil {
return nil, err
2022-05-21 19:59:22 +03:00
}
2022-07-01 15:08:25 +03:00
return &migrationHistory, nil
2022-05-21 19:59:22 +03:00
}