use sqlx::PgExecutor;
#[cfg(feature = "event-store")]
use crate::error::PostgresEventStoreError;
#[cfg(feature = "event-store")]
pub const MIGRATION_1: &str = include_str!("../migrations/0001_event_log.sql");
#[cfg(feature = "event-store")]
pub const MIGRATION_3: &str = include_str!("../migrations/0003_write_group.sql");
#[cfg(feature = "event-store")]
pub const MIGRATION_4: &str = include_str!("../migrations/0004_removal_record.sql");
#[cfg(feature = "event-store")]
const EVENT_LOG: &str = concat!(
include_str!("../migrations/0001_event_log.sql"),
"\n",
include_str!("../migrations/0003_write_group.sql"),
"\n",
include_str!("../migrations/0004_removal_record.sql"),
);
#[cfg(all(test, feature = "event-store"))]
pub(crate) const WRITE_GROUP_LOG: &str = concat!(
include_str!("../migrations/0001_event_log.sql"),
"\n",
include_str!("../migrations/0003_write_group.sql"),
);
#[cfg(feature = "event-store")]
const WRITE_GROUP_SCHEMA_VERSION: u32 = 2;
#[cfg(feature = "event-store")]
pub const SCHEMA_VERSION: u32 = WRITE_GROUP_SCHEMA_VERSION + 1;
#[cfg(feature = "event-store")]
pub async fn apply<'e, E>(executor: E) -> Result<(), PostgresEventStoreError>
where
E: PgExecutor<'e>,
{
sqlx::raw_sql(EVENT_LOG).execute(executor).await?;
Ok(())
}
#[cfg(feature = "projection-store")]
pub const MIGRATION_2: &str = include_str!("../migrations/0002_projection_checkpoint.sql");
#[cfg(feature = "projection-store")]
pub const PROJECTION_SCHEMA_VERSION: u32 = 1;
#[cfg(feature = "projection-store")]
pub async fn apply_projection<'e, E>(
executor: E,
) -> Result<(), crate::error::PostgresProjectionStoreError>
where
E: PgExecutor<'e>,
{
sqlx::raw_sql(MIGRATION_2).execute(executor).await?;
Ok(())
}
#[cfg(test)]
mod tests {
#[cfg(feature = "event-store")]
use super::{MIGRATION_1, MIGRATION_4, SCHEMA_VERSION, WRITE_GROUP_SCHEMA_VERSION};
#[cfg(feature = "event-store")]
fn statements() -> String {
MIGRATION_1
.lines()
.map(|line| line.split_once("--").map_or(line, |(code, _)| code))
.collect::<Vec<_>>()
.join(
"
",
)
}
#[cfg(feature = "event-store")]
#[test]
fn the_comment_stripper_removes_prose_and_keeps_sql() {
let stripped = statements();
assert!(
!stripped.contains("ADR-0024"),
"prose survived the strip, so the guards below are scanning comments"
);
assert!(
stripped.contains("CREATE TABLE IF NOT EXISTS event"),
"the strip ate SQL, so the guards below are scanning nothing"
);
}
#[cfg(feature = "event-store")]
#[test]
fn migration_1_carries_the_visibility_mechanism_column() {
let statements = statements();
assert!(
statements.contains("xact_id"),
"the frontier mechanism's column is gone, but `head` and every read still filter on it"
);
assert!(
statements.contains("event_xact_idx"),
"the frontier predicate has lost its index, which turns every read into a sequential scan and charges the mechanism for the absence of an index rather than for what it costs"
);
}
#[cfg(feature = "event-store")]
#[test]
fn position_is_not_a_serial_column() {
let statements = statements();
for forbidden in ["bigserial", "serial", "AS IDENTITY"] {
assert!(
!statements.contains(forbidden),
"migration 1 contains `{forbidden}`: a sequence default on `position` \
is exactly the construction ES-10 forbids"
);
}
}
#[cfg(feature = "event-store")]
#[test]
fn the_schema_version_counts_the_write_group_migration() {
assert_eq!(WRITE_GROUP_SCHEMA_VERSION, 2);
}
#[cfg(feature = "event-store")]
#[test]
fn the_schema_version_counts_the_removal_record() {
assert_eq!(SCHEMA_VERSION, 3);
assert_eq!(SCHEMA_VERSION, WRITE_GROUP_SCHEMA_VERSION + 1);
}
#[cfg(feature = "event-store")]
fn migration_4_statements() -> String {
MIGRATION_4
.lines()
.map(|line| line.split_once("--").map_or(line, |(code, _)| code))
.collect::<Vec<_>>()
.join("\n")
}
#[cfg(feature = "event-store")]
#[test]
fn migration_4_creates_the_record_and_its_trigger_idempotently() {
let statements = migration_4_statements();
assert!(
!statements.contains("ADR-0110"),
"prose survived the strip, so the assertions below are scanning comments"
);
for expected in [
"CREATE TABLE IF NOT EXISTS event_removed (",
"origin_store bytea NOT NULL,",
"origin_position bigint NOT NULL,",
"PRIMARY KEY (origin_store, origin_position)",
"CREATE OR REPLACE FUNCTION event_record_removal() RETURNS trigger",
"LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp",
"REVOKE EXECUTE ON FUNCTION event_record_removal() FROM PUBLIC;",
"'INSERT INTO %I.event_removed (origin_store, origin_position) '",
"'VALUES ($1, $2) ON CONFLICT DO NOTHING',",
"TG_TABLE_SCHEMA",
"USING OLD.origin_store, OLD.origin_position;",
"RETURN OLD;",
"WHERE tgrelid = 'event'::regclass AND tgname = 'event_record_removal'",
"BEFORE DELETE ON event",
"FOR EACH ROW",
"WHEN (OLD.origin_store IS NOT NULL AND OLD.origin_position IS NOT NULL)",
"EXECUTE FUNCTION event_record_removal();",
] {
assert!(
statements.contains(expected),
"migration 4 has lost `{expected}`"
);
}
for forbidden in ["AFTER DELETE", "DROP TRIGGER", "TRUNCATE", "bigserial"] {
assert!(
!statements.contains(forbidden),
"migration 4 contains `{forbidden}`"
);
}
}
#[cfg(feature = "event-store")]
#[test]
fn apply_sends_migrations_1_and_3_then_migration_4() {
let batch = super::EVENT_LOG;
assert!(
batch.starts_with(super::WRITE_GROUP_LOG),
"migrations 1 and 3 go first, as a version-2 build sent them"
);
assert!(batch.ends_with(MIGRATION_4), "migration 4 goes last");
assert_eq!(
batch.len(),
super::WRITE_GROUP_LOG.len() + 1 + MIGRATION_4.len(),
"the batch is the three migrations and the lines between them, nothing else"
);
}
#[cfg(feature = "event-store")]
fn migration_3_statements() -> String {
super::MIGRATION_3
.lines()
.map(|line| line.split_once("--").map_or(line, |(code, _)| code))
.collect::<Vec<_>>()
.join("\n")
}
#[cfg(feature = "event-store")]
#[test]
fn migration_3_adds_the_write_group_columns_and_their_index() {
let statements = migration_3_statements();
assert!(
!statements.contains("#420"),
"prose survived the strip, so the assertions below are scanning comments"
);
for expected in [
"ALTER TABLE event ADD COLUMN IF NOT EXISTS write_group bigint",
"ALTER TABLE event ADD COLUMN IF NOT EXISTS group_guard bytea",
"CREATE INDEX IF NOT EXISTS event_write_group_idx",
"WHERE write_group IS NOT NULL",
] {
assert!(
statements.contains(expected),
"migration 3 has lost `{expected}`"
);
}
assert!(
!statements.contains("DEFAULT")
&& !statements.contains("bigint NOT NULL")
&& !statements.contains("bytea NOT NULL"),
"a default or a NOT NULL on a write-group column rewrites every row of an \
existing table, and the legacy rule needs NULL"
);
}
#[cfg(feature = "event-store")]
#[test]
fn migration_3_puts_no_sequence_default_on_position() {
let statements = migration_3_statements();
for forbidden in ["bigserial", "serial", "AS IDENTITY", "position"] {
assert!(
!statements.contains(forbidden),
"migration 3 mentions `{forbidden}`; it adds two columns and an index, \
and touches nothing migration 1 owns"
);
}
}
#[cfg(feature = "event-store")]
#[test]
fn apply_sends_migration_1_then_migration_3() {
let batch = super::WRITE_GROUP_LOG;
assert!(batch.starts_with(MIGRATION_1), "migration 1 goes first");
assert!(batch.ends_with(super::MIGRATION_3), "migration 3 goes last");
assert_eq!(
batch.len(),
MIGRATION_1.len() + 1 + super::MIGRATION_3.len(),
"the batch is the two migrations and the line between them, nothing else"
);
}
#[cfg(feature = "projection-store")]
#[test]
fn migration_2_stores_a_constrained_authority() {
let sql = super::MIGRATION_2;
assert!(
sql.contains(
"authority text NOT NULL CHECK (authority IN ('live', 'rebuilding'))"
),
"the authority column has lost its CHECK, so a row can record a state `Checkpoint` cannot represent and `checkpoint` will fail on read instead of the write failing where it happened"
);
}
#[cfg(feature = "projection-store")]
#[test]
fn no_migration_file_creates_the_probe_table() {
for sql in [
#[cfg(feature = "event-store")]
MIGRATION_1,
super::MIGRATION_2,
#[cfg(feature = "event-store")]
MIGRATION_4,
] {
assert!(
!sql.contains("projection_probe"),
"a migration file creates the conformance probe table, so applying this crate's schema would put the suite's read model in a consumer's database"
);
}
}
}