47 lines
1.8 KiB
Go
47 lines
1.8 KiB
Go
package store
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"errors"
|
|
)
|
|
|
|
// During a rolling upgrade an older world owner still inserts replacement lives.
|
|
// Enforce the account pointer at the database boundary as well as in new writers,
|
|
// so creating and losing a replacement on that owner cannot revive an older life.
|
|
func (d *DB) migrateLifeTrigger(ctx context.Context, tx *sql.Tx) error {
|
|
var version int
|
|
err := tx.QueryRowContext(ctx, `SELECT version FROM schema_migrations WHERE version=7`).Scan(&version)
|
|
if err == nil {
|
|
return nil
|
|
}
|
|
if !errors.Is(err, sql.ErrNoRows) {
|
|
return err
|
|
}
|
|
if d.postgres {
|
|
if _, e := tx.ExecContext(ctx, `CREATE OR REPLACE FUNCTION aeternalis_current_life() RETURNS trigger AS $$ BEGIN
|
|
INSERT INTO account_lives(account_id,character_id) VALUES(NEW.account_id,NEW.character_id)
|
|
ON CONFLICT(account_id) DO UPDATE SET character_id=EXCLUDED.character_id;
|
|
RETURN NEW;
|
|
END; $$ LANGUAGE plpgsql`); e != nil {
|
|
return e
|
|
}
|
|
if _, e := tx.ExecContext(ctx, `DROP TRIGGER IF EXISTS aeternalis_new_life ON character_records`); e != nil {
|
|
return e
|
|
}
|
|
if _, e := tx.ExecContext(ctx, `CREATE TRIGGER aeternalis_new_life AFTER INSERT ON character_records FOR EACH ROW WHEN (NEW.state IN ('alive','eligible','transit')) EXECUTE FUNCTION aeternalis_current_life()`); e != nil {
|
|
return e
|
|
}
|
|
} else {
|
|
_, e := tx.ExecContext(ctx, `CREATE TRIGGER IF NOT EXISTS aeternalis_new_life AFTER INSERT ON character_records WHEN NEW.state IN ('alive','eligible','transit') BEGIN
|
|
INSERT INTO account_lives(account_id,character_id) VALUES(NEW.account_id,NEW.character_id)
|
|
ON CONFLICT(account_id) DO UPDATE SET character_id=excluded.character_id;
|
|
END`)
|
|
if e != nil {
|
|
return e
|
|
}
|
|
}
|
|
_, err = tx.ExecContext(ctx, `INSERT INTO schema_migrations(version) VALUES(7)`)
|
|
return err
|
|
}
|