diff --git a/core/crates/core/src/unsupported_feature.rs b/core/crates/core/src/unsupported_feature.rs index c6a9d43c71..12ceae5799 100644 --- a/core/crates/core/src/unsupported_feature.rs +++ b/core/crates/core/src/unsupported_feature.rs @@ -12,8 +12,8 @@ pub enum UnsupportedFeature { NetworkConnection, /// A save that turns foreign key checks off and verifies them after. ForeignKeySuspension, - /// The engine's client library is older than the driver needs, such - /// as `SQLite 3.37.0`. + /// The engine's client library or server is older than the driver + /// needs, such as `SQLite 3.43.0` or `PostgreSQL 10`. MinimumVersion { required: &'static str, }, @@ -72,6 +72,43 @@ pub enum UnsupportedFeature { SqlDump, } +impl UnsupportedFeature { + /// A stable code for each feature, for an app that words an error by + /// its codes. + pub fn code(&self) -> &'static str { + match self { + Self::DatabaseFile => "unsupported.database_file", + Self::NetworkConnection => "unsupported.network_connection", + Self::ForeignKeySuspension => "unsupported.foreign_key_suspension", + Self::MinimumVersion { .. } => "unsupported.minimum_version", + Self::CopyFromStdinInEditor => "unsupported.copy_from_stdin_in_editor", + Self::CopyToStdoutInEditor => "unsupported.copy_to_stdout_in_editor", + Self::CopyFromStdin => "unsupported.copy_from_stdin", + Self::TimestampInRepeatedHour => "unsupported.timestamp_in_repeated_hour", + Self::TimeOutsideOneDay => "unsupported.time_outside_one_day", + Self::TimeWithOffset => "unsupported.time_with_offset", + Self::Interval => "unsupported.interval", + Self::BitString => "unsupported.bit_string", + Self::NumberWiderThan { .. } => "unsupported.number_wider_than", + Self::DecimalOutOfRange { .. } => "unsupported.decimal_out_of_range", + Self::DateOutsideYears { .. } => "unsupported.date_outside_years", + Self::HiddenAttach => "unsupported.hidden_attach", + Self::ServerPaging => "unsupported.server_paging", + Self::Tables => "unsupported.tables", + Self::Keys => "unsupported.keys", + Self::CharacterSets => "unsupported.character_sets", + Self::DatabaseSwitching => "unsupported.database_switching", + Self::DatabaseOptions => "unsupported.database_options", + Self::ObjectDefinitions => "unsupported.object_definitions", + Self::ClrRoutine => "unsupported.clr_routine", + Self::EncryptedDefinition => "unsupported.encrypted_definition", + Self::EditorCommand { .. } => "unsupported.editor_command", + Self::AuthPlugin => "unsupported.auth_plugin", + Self::SqlDump => "unsupported.sql_dump", + } + } +} + impl fmt::Display for UnsupportedFeature { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { diff --git a/core/crates/drivers/postgres/src/catalog/mod.rs b/core/crates/drivers/postgres/src/catalog/mod.rs index bee7d13ecf..b44a7740f4 100644 --- a/core/crates/drivers/postgres/src/catalog/mod.rs +++ b/core/crates/drivers/postgres/src/catalog/mod.rs @@ -6,7 +6,7 @@ mod pg_typmod; mod table_definition; mod type_facts; -pub(crate) use pg_column_row::{COLUMNS_SQL, COLUMNS_SQL_BEFORE_14, PgColumnRow}; +pub(crate) use pg_column_row::{COLUMNS_SQL, PgColumnRow}; pub(crate) use table_definition::{ PARENT_HOLDS_CHILD, PRIMARY_KEY_NAME_SQL, compares_alike_sql, inbound_foreign_key, inbound_foreign_keys_sql, }; diff --git a/core/crates/drivers/postgres/src/catalog/pg_column_row.rs b/core/crates/drivers/postgres/src/catalog/pg_column_row.rs index 026dcda976..d6565067a1 100644 --- a/core/crates/drivers/postgres/src/catalog/pg_column_row.rs +++ b/core/crates/drivers/postgres/src/catalog/pg_column_row.rs @@ -12,14 +12,9 @@ use crate::codec::TextArray; /// `atttypmod` is -1 when the modifier was declared on the domain. /// /// The argument is the compression projection, since -/// `attcompression` arrived in PostgreSQL 14. -/// /// Under the catalog path `format_type` drops a built-in's schema, but a /// cast target runs under the session's path, where a lookalike can win. -macro_rules! columns_sql { - ($compression:literal) => { - concat!( - "\ +pub(crate) const COLUMNS_SQL: &str = "\ WITH RECURSIVE resolved AS ( SELECT a.attnum, a.atttypid AS type_oid, a.atttypmod AS typmod, 0 AS depth FROM pg_catalog.pg_attribute a @@ -56,14 +51,12 @@ SELECT a.attname::text, COALESCE(a.attnum = ANY (pk.conkey), false), pg_catalog.pg_get_expr(d.adbin, d.adrelid)::text, a.attidentity::text, - a.attgenerated::text, + {a.attgenerated}::text, pg_catalog.col_description(a.attrelid, a.attnum::int4)::text, CASE WHEN a.attcollation <> 0::oid AND a.attcollation <> at.typcollation THEN cn.nspname::text END, CASE WHEN a.attcollation <> 0::oid AND a.attcollation <> at.typcollation THEN co.collname::text END, CASE WHEN a.attstorage <> at.typstorage THEN a.attstorage::text END, - ", - $compression, - " + NULLIF({a.attcompression}::text, '') FROM pg_catalog.pg_attribute a JOIN base b ON b.attnum = a.attnum JOIN pg_catalog.pg_type at ON at.oid = a.atttypid @@ -75,13 +68,7 @@ LEFT JOIN pg_catalog.pg_constraint pk ON pk.conrelid = a.attrelid AND pk.contype LEFT JOIN pg_catalog.pg_collation co ON co.oid = a.attcollation LEFT JOIN pg_catalog.pg_namespace cn ON cn.oid = co.collnamespace WHERE a.attrelid = $1::text::oid AND a.attnum > 0 AND NOT a.attisdropped -ORDER BY a.attnum" - ) - }; -} - -pub(crate) const COLUMNS_SQL: &str = columns_sql!("NULLIF(a.attcompression::text, '')"); -pub(crate) const COLUMNS_SQL_BEFORE_14: &str = columns_sql!("NULL::text"); +ORDER BY a.attnum"; #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) struct PgColumnRow { diff --git a/core/crates/drivers/postgres/src/catalog/table_definition.rs b/core/crates/drivers/postgres/src/catalog/table_definition.rs index f57ef32e6a..da1fcb5f8c 100644 --- a/core/crates/drivers/postgres/src/catalog/table_definition.rs +++ b/core/crates/drivers/postgres/src/catalog/table_definition.rs @@ -3,6 +3,7 @@ use tablepro_core::ddl::InboundForeignKey; use tablepro_core::meta::TableRef; use tokio_postgres::Row; +use crate::catalog_release::CatalogRelease; use crate::codec::TextArray; /// The primary key constraint's name and its columns in key order. @@ -37,11 +38,11 @@ JOIN pg_catalog.pg_class t ON t.oid = c.conrelid JOIN pg_catalog.pg_namespace n ON n.oid = t.relnamespace WHERE c.confrelid = $1::text::oid AND c.contype = 'f' AND NOT EXISTS (SELECT 1 FROM pg_catalog.pg_constraint p - WHERE p.oid = c.conparentid AND p.confrelid = c.confrelid) + WHERE p.oid = {c.conparentid} AND p.confrelid = c.confrelid) ORDER BY n.nspname, t.relname, c.conname"; -pub(crate) fn inbound_foreign_keys_sql() -> String { - INBOUND_FOREIGN_KEYS_SQL.replace("{child_compares_alike}", &compares_alike_sql(CHILD_HOLDS_PARENT)) +pub(crate) fn inbound_foreign_keys_sql(release: CatalogRelease) -> String { + release.render(&INBOUND_FOREIGN_KEYS_SQL.replace("{child_compares_alike}", &compares_alike_sql(CHILD_HOLDS_PARENT))) } /// Whether every column pair of the key `c` compares alike when the @@ -63,7 +64,9 @@ NOT coalesce((pg_catalog.to_jsonb(c) OPERATOR(pg_catalog.->>) 'conperiod')::bool JOIN pg_catalog.pg_type ct ON ct.oid = ca.atttypid JOIN pg_catalog.pg_type pt ON pt.oid = pa.atttypid WHERE NOT (ca.attcollation = pa.attcollation - OR (SELECT pg_catalog.bool_and(l.collisdeterministic) FROM pg_catalog.pg_collation l + OR (SELECT pg_catalog.bool_and( + COALESCE((pg_catalog.to_jsonb(l) OPERATOR(pg_catalog.->>) 'collisdeterministic')::boolean, true)) + FROM pg_catalog.pg_collation l WHERE l.oid IN (ca.attcollation, pa.attcollation))) OR NOT (ca.atttypid = pa.atttypid OR (ca.atttypid IN ('pg_catalog.text'::regtype::oid, 'pg_catalog.varchar'::regtype::oid) diff --git a/core/crates/drivers/postgres/src/catalog_release.rs b/core/crates/drivers/postgres/src/catalog_release.rs new file mode 100644 index 0000000000..8977e69f0a --- /dev/null +++ b/core/crates/drivers/postgres/src/catalog_release.rs @@ -0,0 +1,160 @@ +//! Catalog reads are written once for every release the driver supports. +//! A column or function a release added is written as a placeholder at +//! the spot it goes, and each read is rendered for the server it runs on. + +use tablepro_core::ServerInfo; + +/// The release a catalog read is rendered for. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub(crate) struct CatalogRelease { + major: u32, +} + +/// One placeholder: the text from the release that added it on, and +/// what a server before that release has in its place. +struct Fragment { + placeholder: &'static str, + since: u32, + current: &'static str, + before: &'static str, +} + +const FRAGMENTS: &[Fragment] = &[ + // 11 split procedures out of functions; before it an aggregate and a + // window function are flags and every routine is a function. + Fragment { + placeholder: "{p.prokind}", + since: 11, + current: "p.prokind", + before: "CASE WHEN p.proisagg THEN 'a' WHEN p.proiswindow THEN 'w' ELSE 'f' END", + }, + // INCLUDE columns came in 11, so before it every column is a key. + Fragment { + placeholder: "{i.indnkeyatts}", + since: 11, + current: "i.indnkeyatts", + before: "i.indnatts", + }, + // A partition's copy of a key came in 11; before it every key is its + // table's own. + Fragment { + placeholder: "{c.conparentid}", + since: 11, + current: "c.conparentid", + before: "0::pg_catalog.oid", + }, + Fragment { + placeholder: "{k.conparentid}", + since: 11, + current: "k.conparentid", + before: "0::pg_catalog.oid", + }, + Fragment { + placeholder: "{a.attgenerated}", + since: 12, + current: "a.attgenerated", + before: "''::pg_catalog.text", + }, + // Before 13 a partition's copy of its parent's trigger is internal, + // so `NOT tgisinternal` already leaves it out (measured on 11 and 12). + Fragment { + placeholder: "{t.tgparentid}", + since: 13, + current: "t.tgparentid", + before: "0::pg_catalog.oid", + }, + Fragment { + placeholder: "{a.attcompression}", + since: 14, + current: "a.attcompression", + before: "''", + }, + // A table never vacuumed or analysed has reltuples -1 from 14 on. + // Before 14 it has reltuples 0 and relpages 0, which an analysed empty + // table also has. + Fragment { + placeholder: "{c.never_analysed}", + since: 14, + current: "c.reltuples < 0::pg_catalog.float4", + before: "(c.reltuples = 0::pg_catalog.float4 AND c.relpages = 0)", + }, + // A body in standard SQL came in 14 and names the tables it reads. + Fragment { + placeholder: "{p.sql_body_reads_a_table}", + since: 14, + current: "(p.prosqlbody IS NOT NULL AND EXISTS (SELECT 1 FROM pg_catalog.pg_depend dep + WHERE dep.classid = 'pg_catalog.pg_proc'::pg_catalog.regclass AND dep.objid = p.oid + AND dep.refclassid = 'pg_catalog.pg_class'::pg_catalog.regclass))", + before: "false", + }, +]; + +impl CatalogRelease { + pub(crate) const fn new(major: u32) -> Self { + Self { major } + } + + pub(crate) fn of(server: &ServerInfo) -> Self { + Self::new(server.major) + } + + pub(crate) fn render(self, sql: &str) -> String { + FRAGMENTS.iter().fold(sql.to_owned(), |sql, fragment| { + let text = match self.major >= fragment.since { + true => fragment.current, + false => fragment.before, + }; + sql.replace(fragment.placeholder, text) + }) + } +} + +#[cfg(test)] +pub(crate) const SUPPORTED: [CatalogRelease; 9] = [ + CatalogRelease::new(10), + CatalogRelease::new(11), + CatalogRelease::new(12), + CatalogRelease::new(13), + CatalogRelease::new(14), + CatalogRelease::new(15), + CatalogRelease::new(16), + CatalogRelease::new(17), + CatalogRelease::new(18), +]; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn each_placeholder_takes_the_release_that_added_its_column() { + let sql = "SELECT {p.prokind}, {i.indnkeyatts}, {t.tgparentid}"; + assert_eq!( + CatalogRelease::new(10).render(sql), + "SELECT CASE WHEN p.proisagg THEN 'a' WHEN p.proiswindow THEN 'w' ELSE 'f' END, i.indnatts, \ + 0::pg_catalog.oid" + ); + assert_eq!( + CatalogRelease::new(12).render(sql), + "SELECT p.prokind, i.indnkeyatts, 0::pg_catalog.oid" + ); + assert_eq!( + CatalogRelease::new(13).render(sql), + "SELECT p.prokind, i.indnkeyatts, t.tgparentid" + ); + } + + #[test] + fn every_fragment_is_a_distinct_placeholder() { + for (index, fragment) in FRAGMENTS.iter().enumerate() { + assert!(fragment.placeholder.starts_with('{') && fragment.placeholder.ends_with('}')); + assert!( + FRAGMENTS[index + 1..] + .iter() + .all(|other| other.placeholder != fragment.placeholder), + "{}", + fragment.placeholder + ); + } + } +} diff --git a/core/crates/drivers/postgres/src/connection.rs b/core/crates/drivers/postgres/src/connection.rs index 716c551fcd..296368c068 100644 --- a/core/crates/drivers/postgres/src/connection.rs +++ b/core/crates/drivers/postgres/src/connection.rs @@ -22,7 +22,7 @@ use tokio_util::sync::{CancellationToken, WaitForCancellationFutureOwned}; use tokio_util::task::TaskTracker; use crate::cancel::{PgStop, StopProgress}; -use crate::catalog; +use crate::catalog_release::CatalogRelease; use crate::commit_resolution::resolve_op; use crate::dialect::PgDialect; use crate::dump; @@ -49,6 +49,7 @@ pub(crate) struct PgConnection { settings: WorkspaceSettings, server: ServerInfo, dialect: Arc, + release: CatalogRelease, link: LinkWatch, closed: AtomicBool, } @@ -69,6 +70,7 @@ impl PgConnection { calls: OwnedCalls::new(grace), tracker, settings, + release: CatalogRelease::of(&server), server, dialect, link: LinkWatch::new(), @@ -94,13 +96,6 @@ impl PgConnection { self.dialect.qualify(table) } - fn columns_sql(&self) -> &'static str { - match self.server.at_least(14, 0, 0) { - true => catalog::COLUMNS_SQL, - false => catalog::COLUMNS_SQL_BEFORE_14, - } - } - /// Run one read of the user's data, whose names resolve through the /// session's search_path as the user's own SQL does. async fn read(&self, options: CallOptions, op: ReadOp) -> Result { @@ -363,10 +358,11 @@ impl Connection for PgConnection { } async fn list_objects(&self, scope: &ObjectScope, options: CallOptions) -> Result, DriverError> { + let release = self.release; let scope = scope.clone(); self.catalog_read( options, - read_op(move |client| Box::pin(async move { metadata::list_objects(client, &scope).await })), + read_op(move |client| Box::pin(async move { metadata::list_objects(client, release, &scope).await })), ) .await } @@ -376,10 +372,13 @@ impl Connection for PgConnection { object: &ObjectInfo, options: CallOptions, ) -> Result, DriverError> { + let release = self.release; let object = object.clone(); self.catalog_read( options, - read_op(move |client| Box::pin(async move { metadata::fetch_object_definition(client, &object).await })), + read_op(move |client| { + Box::pin(async move { metadata::fetch_object_definition(client, release, &object).await }) + }), ) .await } @@ -388,29 +387,30 @@ impl Connection for PgConnection { /// path, under which the server names every object with its schema. async fn read_dump_catalog(&self, scope: &DumpScope, options: CallOptions) -> Result { let scope = scope.clone(); - let sql_bodies = self.server.at_least(14, 0, 0); + let release = self.release; let begin = self.read_preamble(&options).with_dependent_queries(); self.read_in( options, begin, - read_op(move |client| Box::pin(async move { dump::read_dump_catalog(client, &scope, sql_bodies).await })), + read_op(move |client| Box::pin(async move { dump::read_dump_catalog(client, &scope, release).await })), ) .await } async fn fetch_columns(&self, table: &TableRef, options: CallOptions) -> Result, DriverError> { let relation = self.relation(table); - let columns_sql = self.columns_sql(); + let release = self.release; self.catalog_relation_read(options, relation, move |client, relation| { - Box::pin(async move { metadata::fetch_columns(client, columns_sql, &relation).await }) + Box::pin(async move { metadata::fetch_columns(client, release, &relation).await }) }) .await } async fn fetch_indexes(&self, table: &TableRef, options: CallOptions) -> Result, DriverError> { + let release = self.release; let relation = self.relation(table); self.catalog_relation_read(options, relation, move |client, relation| { - Box::pin(async move { metadata::fetch_indexes(client, &relation).await }) + Box::pin(async move { metadata::fetch_indexes(client, release, &relation).await }) }) .await } @@ -420,9 +420,10 @@ impl Connection for PgConnection { table: &TableRef, options: CallOptions, ) -> Result, DriverError> { + let release = self.release; let relation = self.relation(table); self.catalog_relation_read(options, relation, move |client, relation| { - Box::pin(async move { metadata::fetch_foreign_keys(client, &relation).await }) + Box::pin(async move { metadata::fetch_foreign_keys(client, release, &relation).await }) }) .await } @@ -432,9 +433,10 @@ impl Connection for PgConnection { table: &TableRef, options: CallOptions, ) -> Result, DriverError> { + let release = self.release; let relation = self.relation(table); self.catalog_relation_read(options, relation, move |client, relation| { - Box::pin(async move { metadata::fetch_outbound_foreign_keys(client, &relation).await }) + Box::pin(async move { metadata::fetch_outbound_foreign_keys(client, release, &relation).await }) }) .await } @@ -444,9 +446,10 @@ impl Connection for PgConnection { table: &TableRef, options: CallOptions, ) -> Result, DriverError> { + let release = self.release; let relation = self.relation(table); self.catalog_relation_read(options, relation, move |client, relation| { - Box::pin(async move { metadata::fetch_inbound_foreign_keys(client, &relation).await }) + Box::pin(async move { metadata::fetch_inbound_foreign_keys(client, release, &relation).await }) }) .await } @@ -457,35 +460,36 @@ impl Connection for PgConnection { options: CallOptions, ) -> Result { let relation = self.relation(table); - let columns_sql = self.columns_sql(); + let release = self.release; let table = table.clone(); self.catalog_relation_read(options, relation, move |client, relation| { - Box::pin(async move { metadata::fetch_table_definition(client, columns_sql, &table, &relation).await }) + Box::pin(async move { metadata::fetch_table_definition(client, release, &table, &relation).await }) }) .await } async fn row_identity(&self, table: &TableRef, options: CallOptions) -> Result { + let release = self.release; let relation = self.relation(table); self.catalog_relation_read(options, relation, move |client, relation| { - Box::pin(async move { metadata::row_identity(client, &relation).await }) + Box::pin(async move { metadata::row_identity(client, release, &relation).await }) }) .await } async fn table_estimate(&self, table: &TableRef, options: CallOptions) -> Result { + let release = self.release; let relation = self.relation(table); self.catalog_relation_read(options, relation, move |client, relation| { - Box::pin(async move { metadata::table_estimate(client, &relation).await }) + Box::pin(async move { metadata::table_estimate(client, release, &relation).await }) }) .await } async fn table_info(&self, table: &TableRef, options: CallOptions) -> Result { let relation = self.relation(table); - let partition_tree = self.server.at_least(12, 0, 0); self.catalog_relation_read(options, relation, move |client, relation| { - Box::pin(async move { metadata::table_info(client, &relation, partition_tree).await }) + Box::pin(async move { metadata::table_info(client, &relation).await }) }) .await } diff --git a/core/crates/drivers/postgres/src/dump/catalog_sql.rs b/core/crates/drivers/postgres/src/dump/catalog_sql.rs index 9822dc66d7..7538eb27cb 100644 --- a/core/crates/drivers/postgres/src/dump/catalog_sql.rs +++ b/core/crates/drivers/postgres/src/dump/catalog_sql.rs @@ -5,7 +5,7 @@ /// The schemas a dump covers, the server's own left out. macro_rules! in_scope { () => { - "n.nspname <> 'information_schema' AND NOT pg_catalog.starts_with(n.nspname, 'pg_') + "n.nspname <> 'information_schema' AND pg_catalog.left(n.nspname::text, 3) <> 'pg_' AND ($1 = 'all' OR n.nspname = $2)" }; } @@ -115,8 +115,8 @@ ORDER BY n.nspname, t.typname, k.conname" macro_rules! functions_sql { ($sql_body:expr) => { concat!( - "SELECT n.nspname::text, p.proname::text, p.prokind::text, - CASE WHEN p.prokind <> 'a' THEN pg_catalog.pg_get_functiondef(p.oid)::text END, + "SELECT n.nspname::text, p.proname::text, {p.prokind}::text, + CASE WHEN {p.prokind} <> 'a' THEN pg_catalog.pg_get_functiondef(p.oid)::text END, ", $sql_body, " @@ -153,12 +153,7 @@ macro_rules! after_tables { }; } -pub(crate) const FUNCTIONS_SQL: &str = functions_sql!(after_tables!( - "(p.prosqlbody IS NOT NULL AND EXISTS (SELECT 1 FROM pg_catalog.pg_depend dep - WHERE dep.classid = 'pg_catalog.pg_proc'::pg_catalog.regclass AND dep.objid = p.oid - AND dep.refclassid = 'pg_catalog.pg_class'::pg_catalog.regclass))" -)); -pub(crate) const FUNCTIONS_SQL_BEFORE_14: &str = functions_sql!(after_tables!("false")); +pub(crate) const FUNCTIONS_SQL: &str = functions_sql!(after_tables!("{p.sql_body_reads_a_table}")); /// Every sequence, with the column that owns it (`a`) or whose identity /// it is (`i`), and its position read from the sequence itself: @@ -240,7 +235,7 @@ pub(crate) const COLUMNS_SQL: &str = concat!( pg_catalog.format_type(a.atttypid, a.atttypmod)::text, cn.nspname::text, co.collname::text, pg_catalog.pg_get_expr(d.adbin, d.adrelid)::text, - a.attidentity::text, a.attgenerated::text, a.attnotnull, + a.attidentity::text, {a.attgenerated}::text, a.attnotnull, pg_catalog.col_description(a.attrelid, a.attnum::pg_catalog.int4)::text FROM pg_catalog.pg_attribute a JOIN pg_catalog.pg_class c ON c.oid = a.attrelid @@ -268,7 +263,7 @@ WHERE c.relkind IN ('r', 'p') AND ", in_scope!(), " AND ((k.contype = 'c' AND k.conislocal) - OR (k.contype IN ('f', 'p', 'u', 'x') AND k.conparentid = 0::pg_catalog.oid)) + OR (k.contype IN ('f', 'p', 'u', 'x') AND {k.conparentid} = 0::pg_catalog.oid)) ORDER BY n.nspname, c.relname, k.conname" ); @@ -322,7 +317,7 @@ pub(crate) const TRIGGERS_SQL: &str = concat!( FROM pg_catalog.pg_trigger t JOIN pg_catalog.pg_class c ON c.oid = t.tgrelid JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace -WHERE NOT t.tgisinternal AND t.tgparentid = 0::pg_catalog.oid AND c.relkind IN ('r', 'p', 'v') AND ", +WHERE NOT t.tgisinternal AND {t.tgparentid} = 0::pg_catalog.oid AND c.relkind IN ('r', 'p', 'v') AND ", in_scope!(), " AND ", diff --git a/core/crates/drivers/postgres/src/dump/mod.rs b/core/crates/drivers/postgres/src/dump/mod.rs index e3baf6b037..05732b53cc 100644 --- a/core/crates/drivers/postgres/src/dump/mod.rs +++ b/core/crates/drivers/postgres/src/dump/mod.rs @@ -18,6 +18,7 @@ use tablepro_core::dump::{ use tablepro_core::meta::TableRef; use tokio_postgres::{Client, Row}; +use crate::catalog_release::CatalogRelease; use crate::errors::map_error; use crate::metadata::text_rows; use catalog_rows::{ @@ -25,8 +26,8 @@ use catalog_rows::{ UserType, View, }; use catalog_sql::{ - COLLATIONS_SQL, COLUMNS_SQL, CONSTRAINTS_SQL, DOMAIN_CHECKS_SQL, EXTENSIONS_SQL, FUNCTIONS_SQL, - FUNCTIONS_SQL_BEFORE_14, INDEXES_SQL, SCHEMAS_SQL, SEQUENCES_SQL, TABLES_SQL, TRIGGERS_SQL, TYPES_SQL, VIEWS_SQL, + COLLATIONS_SQL, COLUMNS_SQL, CONSTRAINTS_SQL, DOMAIN_CHECKS_SQL, EXTENSIONS_SQL, FUNCTIONS_SQL, INDEXES_SQL, + SCHEMAS_SQL, SEQUENCES_SQL, TABLES_SQL, TRIGGERS_SQL, TYPES_SQL, VIEWS_SQL, }; use statements::qualified; @@ -70,7 +71,7 @@ const EMPTY_SEARCH_PATH: &str = "SELECT pg_catalog.set_config('search_path', '', pub(crate) async fn read_dump_catalog( client: &Client, scope: &DumpScope, - sql_bodies: bool, + release: CatalogRelease, ) -> Result { client .batch_execute(EMPTY_SEARCH_PATH) @@ -80,10 +81,36 @@ pub(crate) async fn read_dump_catalog( DumpScope::Database => ["all", ""], DumpScope::Schema(schema) => ["schema", schema.as_str()], }; - let functions_sql = match sql_bodies { - true => FUNCTIONS_SQL, - false => FUNCTIONS_SQL_BEFORE_14, - }; + let [ + schemas_sql, + extensions_sql, + collations_sql, + types_sql, + domain_checks_sql, + functions_sql, + sequences_sql, + tables_sql, + columns_sql, + constraints_sql, + indexes_sql, + views_sql, + triggers_sql, + ] = [ + SCHEMAS_SQL, + EXTENSIONS_SQL, + COLLATIONS_SQL, + TYPES_SQL, + DOMAIN_CHECKS_SQL, + FUNCTIONS_SQL, + SEQUENCES_SQL, + TABLES_SQL, + COLUMNS_SQL, + CONSTRAINTS_SQL, + INDEXES_SQL, + VIEWS_SQL, + TRIGGERS_SQL, + ] + .map(|sql| release.render(sql)); let ( schemas, extensions, @@ -99,19 +126,19 @@ pub(crate) async fn read_dump_catalog( views, triggers, ) = futures_util::try_join!( - text_rows(client, SCHEMAS_SQL, ¶ms), - text_rows(client, EXTENSIONS_SQL, ¶ms), - text_rows(client, COLLATIONS_SQL, ¶ms), - text_rows(client, TYPES_SQL, ¶ms), - text_rows(client, DOMAIN_CHECKS_SQL, ¶ms), - text_rows(client, functions_sql, ¶ms), - text_rows(client, SEQUENCES_SQL, ¶ms), - text_rows(client, TABLES_SQL, ¶ms), - text_rows(client, COLUMNS_SQL, ¶ms), - text_rows(client, CONSTRAINTS_SQL, ¶ms), - text_rows(client, INDEXES_SQL, ¶ms), - text_rows(client, VIEWS_SQL, ¶ms), - text_rows(client, TRIGGERS_SQL, ¶ms), + text_rows(client, &schemas_sql, ¶ms), + text_rows(client, &extensions_sql, ¶ms), + text_rows(client, &collations_sql, ¶ms), + text_rows(client, &types_sql, ¶ms), + text_rows(client, &domain_checks_sql, ¶ms), + text_rows(client, &functions_sql, ¶ms), + text_rows(client, &sequences_sql, ¶ms), + text_rows(client, &tables_sql, ¶ms), + text_rows(client, &columns_sql, ¶ms), + text_rows(client, &constraints_sql, ¶ms), + text_rows(client, &indexes_sql, ¶ms), + text_rows(client, &views_sql, ¶ms), + text_rows(client, &triggers_sql, ¶ms), )?; let facts = CatalogFacts { schemas: decoded(&schemas, catalog_rows::schema_name)?, @@ -1183,7 +1210,6 @@ mod tests { TYPES_SQL, DOMAIN_CHECKS_SQL, FUNCTIONS_SQL, - FUNCTIONS_SQL_BEFORE_14, SEQUENCES_SQL, TABLES_SQL, COLUMNS_SQL, diff --git a/core/crates/drivers/postgres/src/editor/mod.rs b/core/crates/drivers/postgres/src/editor/mod.rs index 725e746d4c..ab2506fb58 100644 --- a/core/crates/drivers/postgres/src/editor/mod.rs +++ b/core/crates/drivers/postgres/src/editor/mod.rs @@ -8,6 +8,8 @@ mod editor_dispatch; mod editor_session; mod notice_queue; mod result_origin; +#[cfg(test)] +pub(crate) use result_origin::ORIGIN_SQL; mod run; mod session_core; mod session_status; diff --git a/core/crates/drivers/postgres/src/editor/result_origin.rs b/core/crates/drivers/postgres/src/editor/result_origin.rs index aef73940d0..a775f57c62 100644 --- a/core/crates/drivers/postgres/src/editor/result_origin.rs +++ b/core/crates/drivers/postgres/src/editor/result_origin.rs @@ -16,7 +16,7 @@ pub(super) const ROLLBACK_TO_SAVEPOINT: &str = // The open cursor holds a lock on the relation its statement read, so a relation of the same name // created since the DECLARE is not taken for it. -const ORIGIN_SQL: &str = "\ +pub(crate) const ORIGIN_SQL: &str = "\ SELECT n.nspname::text, c.relname::text, a.attname::text FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace @@ -25,7 +25,7 @@ WHERE c.oid = pg_catalog.to_regclass($1) AND c.relkind IN ('r', 'p') AND c.relpersistence IN ('p', 'u') AND n.nspname <> 'information_schema' - AND NOT pg_catalog.starts_with(n.nspname, 'pg_') + AND pg_catalog.left(n.nspname::text, 3) <> 'pg_' AND EXISTS ( SELECT 1 FROM pg_catalog.pg_locks l WHERE l.locktype = 'relation' AND l.relation = c.oid AND l.pid = pg_catalog.pg_backend_pid() diff --git a/core/crates/drivers/postgres/src/lib.rs b/core/crates/drivers/postgres/src/lib.rs index f58020fdea..e287804ef7 100644 --- a/core/crates/drivers/postgres/src/lib.rs +++ b/core/crates/drivers/postgres/src/lib.rs @@ -9,6 +9,7 @@ mod cancel; mod capabilities; mod catalog; +mod catalog_release; mod codec; mod commit_resolution; mod connection; diff --git a/core/crates/drivers/postgres/src/metadata/database_choices.rs b/core/crates/drivers/postgres/src/metadata/database_choices.rs index 513375c093..dbe7465ccb 100644 --- a/core/crates/drivers/postgres/src/metadata/database_choices.rs +++ b/core/crates/drivers/postgres/src/metadata/database_choices.rs @@ -9,7 +9,7 @@ use super::{decode_error, text_rows}; pub(super) const OWNERS_SQL: &str = "\ SELECT r.rolname::text FROM pg_catalog.pg_roles r -WHERE NOT pg_catalog.starts_with(r.rolname, 'pg_') +WHERE pg_catalog.left(r.rolname::text, 3) <> 'pg_' ORDER BY 1"; pub(super) const TEMPLATES_SQL: &str = "\ diff --git a/core/crates/drivers/postgres/src/metadata/definitions.rs b/core/crates/drivers/postgres/src/metadata/definitions.rs index 5cfbb6e43f..084f1fa61b 100644 --- a/core/crates/drivers/postgres/src/metadata/definitions.rs +++ b/core/crates/drivers/postgres/src/metadata/definitions.rs @@ -4,6 +4,7 @@ use tablepro_core::{DriverError, UnsupportedFeature}; use tokio_postgres::Client; use super::{decode_error, text_rows}; +use crate::catalog_release::CatalogRelease; /// `prokind` keeps a function and a procedure of one name apart, and /// leaves out aggregates, which `pg_get_functiondef` refuses. @@ -11,7 +12,7 @@ pub(super) const FUNCTIONS_SQL: &str = "\ SELECT pg_catalog.pg_get_functiondef(p.oid)::text FROM pg_catalog.pg_proc p JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace -WHERE n.nspname::text = $1 AND p.proname::text = $2 AND p.prokind::text = $3 +WHERE n.nspname::text = $1 AND p.proname::text = $2 AND {p.prokind}::text = $3 ORDER BY pg_catalog.pg_get_function_identity_arguments(p.oid), p.oid"; /// Every clause CREATE SEQUENCE takes: the settings, whether it is @@ -64,13 +65,14 @@ struct SequenceFacts { /// Every text names the object with its schema, so it runs in any tab. pub(crate) async fn fetch_object_definition( client: &Client, + release: CatalogRelease, object: &ObjectInfo, ) -> Result, DriverError> { let schema = object.schema.as_deref().unwrap_or_default(); let name = object.name.as_str(); let sql = match (object.kind, object.parent_table.as_deref()) { - (ObjectKind::Function, _) => function_definitions(client, schema, name, "f").await?, - (ObjectKind::Procedure, _) => function_definitions(client, schema, name, "p").await?, + (ObjectKind::Function, _) => function_definitions(client, release, schema, name, "f").await?, + (ObjectKind::Procedure, _) => function_definitions(client, release, schema, name, "p").await?, (ObjectKind::Sequence, _) => return sequence_definition(client, schema, name).await, (ObjectKind::Trigger, Some(table)) => trigger_definition(client, schema, name, table).await?, _ => { @@ -88,13 +90,14 @@ pub(crate) async fn fetch_object_definition( async fn function_definitions( client: &Client, + release: CatalogRelease, schema: &str, name: &str, prokind: &str, ) -> Result, DriverError> { let field = decode_error("pg_proc"); let mut definitions = Vec::new(); - for row in text_rows(client, FUNCTIONS_SQL, &[schema, name, prokind]).await? { + for row in text_rows(client, &release.render(FUNCTIONS_SQL), &[schema, name, prokind]).await? { let text: Option = row.try_get(0).map_err(&field)?; definitions.extend(text.map(|text| terminated(&text))); } diff --git a/core/crates/drivers/postgres/src/metadata/estimate.rs b/core/crates/drivers/postgres/src/metadata/estimate.rs index 216a0a5c11..cb704128af 100644 --- a/core/crates/drivers/postgres/src/metadata/estimate.rs +++ b/core/crates/drivers/postgres/src/metadata/estimate.rs @@ -3,12 +3,13 @@ use tablepro_core::meta::{RowCountEstimate, TableEstimate}; use tokio_postgres::Client; use super::{decode_error, text_rows}; +use crate::catalog_release::CatalogRelease; /// The planner's row count summed over the table and every descendant, /// so a partitioned or inherited table counts its children. A table never -/// analysed has `reltuples` -1 from PostgreSQL 14 on (0 before), which is -/// no estimate at all. The heap size in blocks is what sizes a ctid -/// window. +/// analysed has no estimate at all; `{c.never_analysed}` is how each +/// release says so, and before 14 an analysed empty table says the same. +/// The heap size in blocks is what sizes a ctid window. pub(super) const ESTIMATE_SQL: &str = "\ WITH RECURSIVE tree AS ( SELECT $1::text::oid AS oid @@ -16,15 +17,19 @@ WITH RECURSIVE tree AS ( SELECT i.inhrelid FROM pg_catalog.pg_inherits i JOIN tree t ON i.inhparent = t.oid ) SELECT COALESCE(pg_catalog.sum(GREATEST(c.reltuples, 0)), 0)::float8, - COALESCE(pg_catalog.bool_and(c.reltuples < 0::float4), true), + COALESCE(pg_catalog.bool_and({c.never_analysed}), true), (pg_catalog.pg_relation_size($1::text::oid) / pg_catalog.current_setting('block_size')::int8)::int8 FROM tree JOIN pg_catalog.pg_class c ON c.oid = tree.oid"; -pub(crate) async fn table_estimate(client: &Client, relation: &str) -> Result { +pub(crate) async fn table_estimate( + client: &Client, + release: CatalogRelease, + relation: &str, +) -> Result { let field = decode_error("pg_class"); - let rows = text_rows(client, ESTIMATE_SQL, &[relation]).await?; + let rows = text_rows(client, &release.render(ESTIMATE_SQL), &[relation]).await?; let Some(row) = rows.first() else { return Ok(TableEstimate { rows: RowCountEstimate::Unknown, diff --git a/core/crates/drivers/postgres/src/metadata/foreign_keys.rs b/core/crates/drivers/postgres/src/metadata/foreign_keys.rs index 5c666ab153..7ce30b4b13 100644 --- a/core/crates/drivers/postgres/src/metadata/foreign_keys.rs +++ b/core/crates/drivers/postgres/src/metadata/foreign_keys.rs @@ -4,6 +4,7 @@ use tokio_postgres::{Client, Row}; use super::{decode_error, text_rows}; use crate::catalog::{PARENT_HOLDS_CHILD, compares_alike_sql}; +use crate::catalog_release::CatalogRelease; use crate::codec::TextArray; /// A key to a partitioned table has a clone on the same table for each @@ -29,15 +30,19 @@ JOIN pg_catalog.pg_class t ON t.oid = c.confrelid JOIN pg_catalog.pg_namespace n ON n.oid = t.relnamespace WHERE c.conrelid = $1::text::oid AND c.contype = 'f' AND NOT EXISTS (SELECT 1 FROM pg_catalog.pg_constraint p - WHERE p.oid = c.conparentid AND p.conrelid = c.conrelid) + WHERE p.oid = {c.conparentid} AND p.conrelid = c.conrelid) ORDER BY c.conname"; -pub(super) fn foreign_keys_sql() -> String { - FOREIGN_KEYS_SQL.replace("{parent_compares_alike}", &compares_alike_sql(PARENT_HOLDS_CHILD)) +pub(super) fn foreign_keys_sql(release: CatalogRelease) -> String { + release.render(&FOREIGN_KEYS_SQL.replace("{parent_compares_alike}", &compares_alike_sql(PARENT_HOLDS_CHILD))) } -pub(crate) async fn fetch_foreign_keys(client: &Client, relation: &str) -> Result, DriverError> { - Ok(fetch_outbound_foreign_keys(client, relation) +pub(crate) async fn fetch_foreign_keys( + client: &Client, + release: CatalogRelease, + relation: &str, +) -> Result, DriverError> { + Ok(fetch_outbound_foreign_keys(client, release, relation) .await? .into_iter() .map(|outbound| outbound.key) @@ -46,9 +51,10 @@ pub(crate) async fn fetch_foreign_keys(client: &Client, relation: &str) -> Resul pub(crate) async fn fetch_outbound_foreign_keys( client: &Client, + release: CatalogRelease, relation: &str, ) -> Result, DriverError> { - text_rows(client, &foreign_keys_sql(), &[relation]) + text_rows(client, &foreign_keys_sql(release), &[relation]) .await? .iter() .map(outbound_foreign_key) diff --git a/core/crates/drivers/postgres/src/metadata/identity.rs b/core/crates/drivers/postgres/src/metadata/identity.rs index 0f6721a69d..4d9fa28f4d 100644 --- a/core/crates/drivers/postgres/src/metadata/identity.rs +++ b/core/crates/drivers/postgres/src/metadata/identity.rs @@ -3,6 +3,7 @@ use tablepro_core::meta::{EngineRowId, RowIdentity}; use tokio_postgres::Client; use super::{decode_error, text_rows}; +use crate::catalog_release::CatalogRelease; use crate::codec::TextArray; /// The relation's kind, its primary key, and the first unique index that @@ -17,7 +18,7 @@ SELECT c.relkind::text, WHERE p.conrelid = c.oid AND p.contype = 'p' ORDER BY k.ord), ARRAY(SELECT a.attname::text - FROM (SELECT i.indrelid, i.indkey, i.indnkeyatts + FROM (SELECT i.indrelid, i.indkey, {i.indnkeyatts} AS indnkeyatts FROM pg_catalog.pg_index i JOIN pg_catalog.pg_class ic ON ic.oid = i.indexrelid WHERE i.indrelid = c.oid @@ -30,7 +31,7 @@ SELECT c.relkind::text, FROM pg_catalog.unnest(i.indkey::int2[]) WITH ORDINALITY AS u(attnum, ord) JOIN pg_catalog.pg_attribute ua ON ua.attrelid = i.indrelid AND ua.attnum = u.attnum - WHERE u.ord <= i.indnkeyatts AND NOT ua.attnotnull) + WHERE u.ord <= {i.indnkeyatts} AND NOT ua.attnotnull) ORDER BY ic.relname LIMIT 1) best CROSS JOIN LATERAL pg_catalog.unnest(best.indkey::int2[]) WITH ORDINALITY AS k(attnum, ord) @@ -40,9 +41,13 @@ SELECT c.relkind::text, FROM pg_catalog.pg_class c WHERE c.oid = $1::text::oid"; -pub(crate) async fn row_identity(client: &Client, relation: &str) -> Result { +pub(crate) async fn row_identity( + client: &Client, + release: CatalogRelease, + relation: &str, +) -> Result { let field = decode_error("pg_class"); - let rows = text_rows(client, IDENTITY_SQL, &[relation]).await?; + let rows = text_rows(client, &release.render(IDENTITY_SQL), &[relation]).await?; let Some(row) = rows.first() else { return Ok(RowIdentity::Unordered); }; diff --git a/core/crates/drivers/postgres/src/metadata/indexes.rs b/core/crates/drivers/postgres/src/metadata/indexes.rs index 1cff852590..ac462eabe8 100644 --- a/core/crates/drivers/postgres/src/metadata/indexes.rs +++ b/core/crates/drivers/postgres/src/metadata/indexes.rs @@ -5,6 +5,7 @@ use tablepro_core::meta::{IndexInfo, IndexKey}; use tokio_postgres::Client; use super::{decode_error, text_rows}; +use crate::catalog_release::CatalogRelease; /// One row per key column, the INCLUDE columns past `indnkeyatts` left /// out. Attribute number 0 marks an expression, which only @@ -21,13 +22,17 @@ FROM pg_catalog.pg_index i JOIN pg_catalog.pg_class ic ON ic.oid = i.indexrelid CROSS JOIN LATERAL pg_catalog.unnest(i.indkey::int2[]) WITH ORDINALITY AS k(attnum, ord) LEFT JOIN pg_catalog.pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = k.attnum AND k.attnum > 0 -WHERE i.indrelid = $1::text::oid AND k.ord <= i.indnkeyatts +WHERE i.indrelid = $1::text::oid AND k.ord <= {i.indnkeyatts} ORDER BY ic.relname, k.ord"; -pub(crate) async fn fetch_indexes(client: &Client, relation: &str) -> Result, DriverError> { +pub(crate) async fn fetch_indexes( + client: &Client, + release: CatalogRelease, + relation: &str, +) -> Result, DriverError> { let field = decode_error("pg_index"); let mut indexes: Vec = Vec::new(); - for row in text_rows(client, INDEXES_SQL, &[relation]).await? { + for row in text_rows(client, &release.render(INDEXES_SQL), &[relation]).await? { let name: String = row.try_get(0).map_err(&field)?; let column: Option = row.try_get(4).map_err(&field)?; let expression: String = row.try_get(5).map_err(&field)?; diff --git a/core/crates/drivers/postgres/src/metadata/mod.rs b/core/crates/drivers/postgres/src/metadata/mod.rs index 2e2c43f475..8b5c8104ae 100644 --- a/core/crates/drivers/postgres/src/metadata/mod.rs +++ b/core/crates/drivers/postgres/src/metadata/mod.rs @@ -29,8 +29,10 @@ use tablepro_core::meta::TableRef; use tokio_postgres::{Client, Row}; use crate::catalog::{ - PRIMARY_KEY_NAME_SQL, PgColumnRow, column_definition, column_info, inbound_foreign_key, inbound_foreign_keys_sql, + COLUMNS_SQL, PRIMARY_KEY_NAME_SQL, PgColumnRow, column_definition, column_info, inbound_foreign_key, + inbound_foreign_keys_sql, }; +use crate::catalog_release::CatalogRelease; use crate::codec::TextArray; use crate::errors::map_error; @@ -56,19 +58,22 @@ pub(crate) fn decode_error(table: &'static str) -> impl Fn(tokio_postgres::Error /// `relation` is the table's quoted, qualified name, which `::regclass` /// resolves the same way the server resolves it in a query. -/// `columns_sql` is the column query for the server's release. pub(crate) async fn fetch_columns( client: &Client, - columns_sql: &str, + release: CatalogRelease, relation: &str, ) -> Result, DriverError> { - column_rows(client, columns_sql, relation) + column_rows(client, release, relation) .await .map(|rows| rows.iter().map(column_info).collect()) } -async fn column_rows(client: &Client, columns_sql: &str, relation: &str) -> Result, DriverError> { - text_rows(client, columns_sql, &[relation]) +async fn column_rows( + client: &Client, + release: CatalogRelease, + relation: &str, +) -> Result, DriverError> { + text_rows(client, &release.render(COLUMNS_SQL), &[relation]) .await? .iter() .map(PgColumnRow::from_row) @@ -77,9 +82,10 @@ async fn column_rows(client: &Client, columns_sql: &str, relation: &str) -> Resu pub(crate) async fn fetch_inbound_foreign_keys( client: &Client, + release: CatalogRelease, relation: &str, ) -> Result, DriverError> { - text_rows(client, &inbound_foreign_keys_sql(), &[relation]) + text_rows(client, &inbound_foreign_keys_sql(release), &[relation]) .await? .iter() .map(inbound_foreign_key) @@ -88,7 +94,7 @@ pub(crate) async fn fetch_inbound_foreign_keys( pub(crate) async fn fetch_table_definition( client: &Client, - columns_sql: &str, + release: CatalogRelease, table: &TableRef, relation: &str, ) -> Result { @@ -96,12 +102,12 @@ pub(crate) async fn fetch_table_definition( // them run inside the flight's transaction, ahead of its COMMIT. let params = [relation]; let (columns, primary_key, mut indexes, mut statements, foreign_keys, inbound_foreign_keys) = futures_util::try_join!( - column_rows(client, columns_sql, relation), + column_rows(client, release, relation), text_rows(client, PRIMARY_KEY_NAME_SQL, ¶ms), - fetch_indexes(client, relation), + fetch_indexes(client, release, relation), indexes::fetch_index_statements(client, relation), - fetch_foreign_keys(client, relation), - fetch_inbound_foreign_keys(client, relation), + fetch_foreign_keys(client, release, relation), + fetch_inbound_foreign_keys(client, release, relation), )?; for index in &mut indexes { index.definition = statements.remove(&index.name); @@ -132,7 +138,7 @@ pub(crate) async fn fetch_table_definition( #[cfg(test)] mod tests { use super::*; - use crate::catalog::COLUMNS_SQL_BEFORE_14; + use crate::catalog_release::SUPPORTED; use crate::dump::catalog_sql as dump; /// Words that take a parenthesis without calling a function by name. @@ -179,45 +185,94 @@ mod tests { calls } + /// Every catalog statement the driver sends, rendered for `release`. + fn catalog_statements(release: CatalogRelease) -> Vec<(&'static str, String)> { + let rendered = [ + ("schemas", objects::SCHEMAS_SQL), + ("objects", objects::OBJECTS_SQL), + ("databases", objects::DATABASES_SQL), + ("owners", database_choices::OWNERS_SQL), + ("templates", database_choices::TEMPLATES_SQL), + ("locales", database_choices::LOCALES_SQL), + ("database defaults", database_choices::DEFAULTS_SQL), + ("function definitions", definitions::FUNCTIONS_SQL), + ("sequence definition", definitions::SEQUENCE_SQL), + ("trigger definition", definitions::TRIGGER_SQL), + ("identity", identity::IDENTITY_SQL), + ("indexes", indexes::INDEXES_SQL), + ("index statements", indexes::INDEX_STATEMENTS_SQL), + ("estimate", estimate::ESTIMATE_SQL), + ("table info", table_info::TABLE_INFO_SQL), + ("primary key", PRIMARY_KEY_NAME_SQL), + ("columns", COLUMNS_SQL), + ("result origin", crate::editor::ORIGIN_SQL), + ("dump schemas", dump::SCHEMAS_SQL), + ("dump extensions", dump::EXTENSIONS_SQL), + ("dump collations", dump::COLLATIONS_SQL), + ("dump types", dump::TYPES_SQL), + ("dump domain checks", dump::DOMAIN_CHECKS_SQL), + ("dump functions", dump::FUNCTIONS_SQL), + ("dump sequences", dump::SEQUENCES_SQL), + ("dump tables", dump::TABLES_SQL), + ("dump columns", dump::COLUMNS_SQL), + ("dump constraints", dump::CONSTRAINTS_SQL), + ("dump indexes", dump::INDEXES_SQL), + ("dump views", dump::VIEWS_SQL), + ("dump triggers", dump::TRIGGERS_SQL), + ] + .map(|(name, sql)| (name, release.render(sql))); + rendered + .into_iter() + .chain([ + ("foreign keys", foreign_keys::foreign_keys_sql(release)), + ("inbound foreign keys", inbound_foreign_keys_sql(release)), + ]) + .collect() + } + #[test] fn every_catalog_read_names_its_functions_in_pg_catalog() { - for (name, sql) in [ - ("schemas", objects::SCHEMAS_SQL.to_owned()), - ("objects", objects::OBJECTS_SQL.to_owned()), - ("databases", objects::DATABASES_SQL.to_owned()), - ("owners", database_choices::OWNERS_SQL.to_owned()), - ("templates", database_choices::TEMPLATES_SQL.to_owned()), - ("locales", database_choices::LOCALES_SQL.to_owned()), - ("database defaults", database_choices::DEFAULTS_SQL.to_owned()), - ("function definitions", definitions::FUNCTIONS_SQL.to_owned()), - ("sequence definition", definitions::SEQUENCE_SQL.to_owned()), - ("trigger definition", definitions::TRIGGER_SQL.to_owned()), - ("identity", identity::IDENTITY_SQL.to_owned()), - ("indexes", indexes::INDEXES_SQL.to_owned()), - ("index statements", indexes::INDEX_STATEMENTS_SQL.to_owned()), - ("estimate", estimate::ESTIMATE_SQL.to_owned()), - ("table info", table_info::TABLE_INFO_SQL.to_owned()), - ("table info before 12", table_info::TABLE_INFO_SQL_BEFORE_12.to_owned()), - ("foreign keys", foreign_keys::foreign_keys_sql()), - ("inbound foreign keys", inbound_foreign_keys_sql()), - ("primary key", PRIMARY_KEY_NAME_SQL.to_owned()), - ("columns", crate::catalog::COLUMNS_SQL.to_owned()), - ("columns before 14", COLUMNS_SQL_BEFORE_14.to_owned()), - ("dump schemas", dump::SCHEMAS_SQL.to_owned()), - ("dump extensions", dump::EXTENSIONS_SQL.to_owned()), - ("dump types", dump::TYPES_SQL.to_owned()), - ("dump domain checks", dump::DOMAIN_CHECKS_SQL.to_owned()), - ("dump functions", dump::FUNCTIONS_SQL.to_owned()), - ("dump functions before 14", dump::FUNCTIONS_SQL_BEFORE_14.to_owned()), - ("dump sequences", dump::SEQUENCES_SQL.to_owned()), - ("dump tables", dump::TABLES_SQL.to_owned()), - ("dump columns", dump::COLUMNS_SQL.to_owned()), - ("dump constraints", dump::CONSTRAINTS_SQL.to_owned()), - ("dump indexes", dump::INDEXES_SQL.to_owned()), - ("dump views", dump::VIEWS_SQL.to_owned()), - ("dump triggers", dump::TRIGGERS_SQL.to_owned()), - ] { - assert_eq!(bare_calls(&sql), Vec::::new(), "{name}"); + for release in SUPPORTED { + for (name, sql) in catalog_statements(release) { + assert_eq!(bare_calls(&sql), Vec::::new(), "{name} on {release:?}"); + } + } + } + + #[test] + fn every_placeholder_is_rendered_for_every_release() { + for release in SUPPORTED { + for (name, sql) in catalog_statements(release) { + assert!(!sql.contains('{') && !sql.contains('}'), "{name} on {release:?}: {sql}"); + } + } + } + + #[test] + fn a_release_reads_no_column_it_does_not_have() { + let added = [ + ( + 11, + ["p.prokind", "i.indnkeyatts", "c.conparentid", "k.conparentid"].as_slice(), + ), + (12, ["a.attgenerated"].as_slice()), + (13, ["t.tgparentid"].as_slice()), + (14, ["a.attcompression", "p.prosqlbody"].as_slice()), + ]; + for release in SUPPORTED { + for (name, sql) in catalog_statements(release) { + for (since, columns) in added { + for column in columns { + let reads = sql.contains(column); + assert!( + release >= CatalogRelease::new(since) || !reads, + "{name} on {release:?} reads {column}" + ); + } + } + assert!(!sql.contains("starts_with"), "{name}"); + assert!(!sql.contains(".collisdeterministic"), "{name}"); + } } } diff --git a/core/crates/drivers/postgres/src/metadata/objects.rs b/core/crates/drivers/postgres/src/metadata/objects.rs index 69e6f11117..fcd3438d70 100644 --- a/core/crates/drivers/postgres/src/metadata/objects.rs +++ b/core/crates/drivers/postgres/src/metadata/objects.rs @@ -3,6 +3,7 @@ use tablepro_core::meta::{ObjectInfo, ObjectKind, ObjectScope, SchemaInfo}; use tokio_postgres::Client; use super::{decode_error, text_rows}; +use crate::catalog_release::CatalogRelease; /// Schemas this session can use: no TOAST schemas, and no other /// session's temporary schema. The default is the session's first @@ -10,9 +11,9 @@ use super::{decode_error, text_rows}; pub(super) const SCHEMAS_SQL: &str = "\ SELECT n.nspname::text, COALESCE(n.nspname = pg_catalog.current_setting('tablepro.catalog_default_schema'), false), - n.nspname = 'information_schema' OR pg_catalog.starts_with(n.nspname, 'pg_') + n.nspname = 'information_schema' OR pg_catalog.left(n.nspname::text, 3) = 'pg_' FROM pg_catalog.pg_namespace n -WHERE NOT pg_catalog.starts_with(n.nspname, 'pg_toast') +WHERE pg_catalog.left(n.nspname::text, 8) <> 'pg_toast' AND NOT pg_catalog.pg_is_other_temp_schema(n.oid) ORDER BY n.nspname"; @@ -24,21 +25,21 @@ FROM ( FROM pg_catalog.pg_class c WHERE c.relkind IN ('r', 'p', 'v', 'm', 'f', 'S') UNION ALL - SELECT p.pronamespace, p.proname::text, CASE p.prokind WHEN 'f' THEN 'fn' ELSE 'pr' END, NULL::text + SELECT p.pronamespace, p.proname::text, CASE {p.prokind} WHEN 'f' THEN 'fn' ELSE 'pr' END, NULL::text FROM pg_catalog.pg_proc p - WHERE p.prokind IN ('f', 'p') + WHERE {p.prokind} IN ('f', 'p') UNION ALL SELECT c.relnamespace, t.tgname::text, 'tg', c.relname::text FROM pg_catalog.pg_trigger t JOIN pg_catalog.pg_class c ON c.oid = t.tgrelid - WHERE NOT t.tgisinternal AND t.tgparentid = 0::oid + WHERE NOT t.tgisinternal AND {t.tgparentid} = 0::pg_catalog.oid ) o JOIN pg_catalog.pg_namespace n ON n.oid = o.namespace WHERE NOT pg_catalog.pg_is_other_temp_schema(n.oid) AND CASE $1 WHEN 'default' THEN n.nspname = pg_catalog.current_setting('tablepro.catalog_default_schema') WHEN 'schema' THEN n.nspname = $2 - ELSE n.nspname <> 'information_schema' AND NOT pg_catalog.starts_with(n.nspname, 'pg_') + ELSE n.nspname <> 'information_schema' AND pg_catalog.left(n.nspname::text, 3) <> 'pg_' END ORDER BY 1, 2, 3, 4"; @@ -83,14 +84,18 @@ pub(crate) async fn list_databases(client: &Client) -> Result, D .collect() } -pub(crate) async fn list_objects(client: &Client, scope: &ObjectScope) -> Result, DriverError> { +pub(crate) async fn list_objects( + client: &Client, + release: CatalogRelease, + scope: &ObjectScope, +) -> Result, DriverError> { let (mode, schema) = match scope { ObjectScope::DefaultSchema => ("default", ""), ObjectScope::Schema(schema) => ("schema", schema.as_str()), ObjectScope::AllSchemas => ("all", ""), }; let field = decode_error("pg_class"); - let rows = text_rows(client, OBJECTS_SQL, &[mode, schema]).await?; + let rows = text_rows(client, &release.render(OBJECTS_SQL), &[mode, schema]).await?; let mut objects = Vec::with_capacity(rows.len()); for row in &rows { let code: String = row.try_get(2).map_err(&field)?; diff --git a/core/crates/drivers/postgres/src/metadata/table_info.rs b/core/crates/drivers/postgres/src/metadata/table_info.rs index d751223df2..70e763b1bd 100644 --- a/core/crates/drivers/postgres/src/metadata/table_info.rs +++ b/core/crates/drivers/postgres/src/metadata/table_info.rs @@ -6,7 +6,9 @@ use super::{decode_error, text_rows}; /// The relation's kind, its comment, and the sizes of what it stores: /// its own for a table or materialized view, its leaf partitions' for a -/// partitioned table, which stores nothing itself. +/// partitioned table, which stores nothing itself. The leaves are found +/// through `pg_inherits`, which every release has; `pg_partition_tree` +/// came in 12 and finds the same ones. pub(super) const TABLE_INFO_SQL: &str = "\ SELECT c.relkind::text, pg_catalog.obj_description(c.oid, 'pg_class'), @@ -15,47 +17,24 @@ SELECT c.relkind::text, sizes.total_bytes FROM pg_catalog.pg_class c CROSS JOIN LATERAL ( - SELECT COALESCE(pg_catalog.sum(pg_catalog.pg_table_size(part.relid)), 0)::int8, - COALESCE(pg_catalog.sum(pg_catalog.pg_indexes_size(part.relid)), 0)::int8, - COALESCE(pg_catalog.sum(pg_catalog.pg_total_relation_size(part.relid)), 0)::int8 - FROM (SELECT c.oid WHERE c.relkind IN ('r', 'm') - UNION ALL - SELECT leaf.oid - FROM pg_catalog.pg_partition_tree(c.oid) AS tree - JOIN pg_catalog.pg_class leaf ON leaf.oid = tree.relid::pg_catalog.oid - WHERE c.relkind = 'p' AND leaf.relkind = 'r') AS part(relid) + WITH RECURSIVE tree AS ( + SELECT c.oid AS relid + UNION ALL + SELECT h.inhrelid FROM pg_catalog.pg_inherits h JOIN tree ON h.inhparent = tree.relid + WHERE c.relkind = 'p' + ) + SELECT COALESCE(pg_catalog.sum(pg_catalog.pg_table_size(leaf.oid)), 0)::int8, + COALESCE(pg_catalog.sum(pg_catalog.pg_indexes_size(leaf.oid)), 0)::int8, + COALESCE(pg_catalog.sum(pg_catalog.pg_total_relation_size(leaf.oid)), 0)::int8 + FROM tree + JOIN pg_catalog.pg_class leaf ON leaf.oid = tree.relid + WHERE leaf.relkind IN ('r', 'm') ) AS sizes(data_bytes, index_bytes, total_bytes) WHERE c.oid = $1::text::oid"; -/// `pg_partition_tree` came in PostgreSQL 12, so before it a partitioned -/// table reports its own sizes. -pub(super) const TABLE_INFO_SQL_BEFORE_12: &str = "\ -SELECT c.relkind::text, - pg_catalog.obj_description(c.oid, 'pg_class'), - sizes.data_bytes, - sizes.index_bytes, - sizes.total_bytes -FROM pg_catalog.pg_class c -CROSS JOIN LATERAL ( - SELECT COALESCE(pg_catalog.sum(pg_catalog.pg_table_size(part.relid)), 0)::int8, - COALESCE(pg_catalog.sum(pg_catalog.pg_indexes_size(part.relid)), 0)::int8, - COALESCE(pg_catalog.sum(pg_catalog.pg_total_relation_size(part.relid)), 0)::int8 - FROM (SELECT c.oid WHERE c.relkind IN ('r', 'm', 'p')) AS part(relid) -) AS sizes(data_bytes, index_bytes, total_bytes) -WHERE c.oid = $1::text::oid"; - -/// `partition_tree` says the server has `pg_partition_tree`. -pub(crate) async fn table_info( - client: &Client, - relation: &str, - partition_tree: bool, -) -> Result { - let sql = match partition_tree { - true => TABLE_INFO_SQL, - false => TABLE_INFO_SQL_BEFORE_12, - }; +pub(crate) async fn table_info(client: &Client, relation: &str) -> Result { let field = decode_error("pg_class"); - let rows = text_rows(client, sql, &[relation]).await?; + let rows = text_rows(client, TABLE_INFO_SQL, &[relation]).await?; let Some(row) = rows.first() else { return Ok(TableInfo::default()); }; diff --git a/core/crates/drivers/postgres/src/physical.rs b/core/crates/drivers/postgres/src/physical.rs index 24beaf647b..3ea2292dc4 100644 --- a/core/crates/drivers/postgres/src/physical.rs +++ b/core/crates/drivers/postgres/src/physical.rs @@ -5,7 +5,7 @@ use std::time::Duration; use secrecy::ExposeSecret; use tablepro_core::{ APPLICATION_NAME, ConfigError, Credentials, DriverError, LivenessPolicy, NetworkTarget, ServerInfo, TimeoutPhase, - Transport, + Transport, UnsupportedFeature, }; use tokio_postgres::config::ChannelBinding; use tokio_postgres::{CancelToken, Client, Config, SimpleQueryMessage}; @@ -190,10 +190,27 @@ pub(crate) async fn server_info(client: &Client) -> Result Result<(), DriverError> { + if number < MIN_SERVER_VERSION_NUM { + return Err(DriverError::Unsupported { + feature: UnsupportedFeature::MinimumVersion { + required: "PostgreSQL 10", + }, + }); + } + Ok(()) +} + /// `server_version_num` is major * 10000 + minor from PostgreSQL 10 on, /// which is two numbers: there is no patch to read. fn split_version_number(number: u32) -> (u32, u32) { @@ -204,6 +221,20 @@ fn split_version_number(number: u32) -> (u32, u32) { mod tests { use super::*; + #[test] + fn a_server_before_10_is_refused() { + assert!(matches!( + check_server_version(90_624), + Err(DriverError::Unsupported { + feature: UnsupportedFeature::MinimumVersion { + required: "PostgreSQL 10" + } + }) + )); + assert!(check_server_version(100_000).is_ok()); + assert!(check_server_version(120_022).is_ok()); + } + #[test] fn version_numbers_split_into_major_and_minor() { assert_eq!(split_version_number(130_016), (13, 16)); diff --git a/core/crates/drivers/postgres/tests/integration/metadata.rs b/core/crates/drivers/postgres/tests/integration/metadata.rs index edd8b66854..db83b13da4 100644 --- a/core/crates/drivers/postgres/tests/integration/metadata.rs +++ b/core/crates/drivers/postgres/tests/integration/metadata.rs @@ -5,12 +5,13 @@ use tablepro_core::column::{ BoolStorage, ColumnKind, FloatWidth, IntegerKind, IntegerWidth, NetworkFamily, ReadForm, TemporalZone, TextLength, }; use tablepro_core::ddl::{CollationName, GeneratedStorage, IdentityStyle}; +use tablepro_core::dump::DumpScope; use tablepro_core::edit::CellInput; use tablepro_core::meta::{ EditorRefusal, EngineRowId, IndexKey, ObjectInfo, ObjectKind, ObjectScope, RowCountEstimate, RowIdentity, TableRef, }; use tablepro_core::save::{ChangeSet, RowChange, RowUpdate, plan_save}; -use tablepro_core::{Connection, DriverError, Value, WriteKind}; +use tablepro_core::{CommitResolution, CommitToken, Connection, DriverError, ResultEvent, Value, WriteKind}; use tablepro_test_fixtures::{HbaMode, PostgresFixture, PostgresVersion}; use crate::support::{CALL, apply, connect, rows, run_ok, scalar, session, setup, start, text, within}; @@ -872,9 +873,9 @@ const CATALOG_TABLE: &[&str] = &[ )", ]; -async fn catalog_matches_information_schema(fixture: PostgresFixture) { +async fn catalog_matches_information_schema(fixture: &PostgresFixture) { let version = fixture.version(); - let connection = connect(&fixture, false).await; + let connection = connect(fixture, false).await; assert_eq!( connection.server_info().major, version.major(), @@ -1007,17 +1008,272 @@ fn typed_kinds() -> Vec<(&'static str, ColumnKind, ReadForm)> { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[ignore = "requires docker"] -async fn catalog_matches_information_schema_on_13() { - let fixture = PostgresFixture::start_version(PostgresVersion::V13, HbaMode::Password) - .await - .expect("a PostgreSQL container"); - catalog_matches_information_schema(fixture).await; +async fn catalog_matches_information_schema_on_the_selected_release() { + catalog_matches_information_schema(&start().await).await; } +/// Releases past their end of life whose catalogs the driver still reads. +/// One container each, sharing every check, so CI pays four starts. +const BEFORE_14: [PostgresVersion; 4] = [ + PostgresVersion::V10, + PostgresVersion::V11, + PostgresVersion::V12, + PostgresVersion::V13, +]; + +const OLD_RELEASE_SCHEMA: &[&str] = &[ + "CREATE TABLE parent (id int GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, label text NOT NULL) \ + WITH (autovacuum_enabled = false)", + "CREATE INDEX parent_label ON parent (label)", + "CREATE TABLE child (id int PRIMARY KEY, parent_id int REFERENCES parent (id))", + "CREATE TABLE parted (id int NOT NULL, at date NOT NULL) PARTITION BY RANGE (at)", + "CREATE TABLE parted_2026 PARTITION OF parted FOR VALUES FROM ('2026-01-01') TO ('2027-01-01')", + "INSERT INTO parted SELECT n, '2026-06-01' FROM generate_series(1, 2000) AS n", + "CREATE FUNCTION touch() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RETURN NEW; END $$", + "CREATE TRIGGER child_touch BEFORE INSERT ON child FOR EACH ROW EXECUTE PROCEDURE touch()", + "CREATE VIEW labels AS SELECT label FROM parent", + "CREATE SEQUENCE counter", +]; + +/// What 11 added that the reads have to tell apart: a covering index, a +/// procedure, a key on a partitioned table and a trigger on one, both of +/// which the server copies onto each partition. +const OLD_RELEASE_SCHEMA_FROM_11: &[&str] = &[ + "CREATE INDEX parent_covering ON parent (id) INCLUDE (label)", + "CREATE PROCEDURE noop() LANGUAGE sql AS 'SELECT 1'", + "CREATE TABLE refs (parent_id int REFERENCES parent (id)) PARTITION BY LIST (parent_id)", + "CREATE TABLE refs_rest PARTITION OF refs DEFAULT", + "CREATE TRIGGER parted_touch AFTER INSERT ON parted FOR EACH ROW EXECUTE PROCEDURE touch()", +]; + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[ignore = "requires docker"] -async fn catalog_matches_information_schema_on_the_selected_release() { - catalog_matches_information_schema(start().await).await; +async fn every_read_and_a_save_work_before_14() { + for version in BEFORE_14 { + let fixture = PostgresFixture::start_version(version, HbaMode::Password) + .await + .expect("a PostgreSQL container"); + catalog_matches_information_schema(&fixture).await; + reads_and_writes_on(&fixture, version).await; + } +} + +async fn reads_and_writes_on(fixture: &PostgresFixture, version: PostgresVersion) { + let major = version.major(); + let connection = connect(fixture, false).await; + let connection = connection.as_ref(); + setup(connection, OLD_RELEASE_SCHEMA).await; + if major >= 11 { + setup(connection, OLD_RELEASE_SCHEMA_FROM_11).await; + } + let objects = sidebar_reads_on(connection, major).await; + table_reads_on(connection, major, &objects).await; + dump_and_editor_on(connection, major).await; + save_and_commit_on(connection, major).await; +} + +async fn sidebar_reads_on(connection: &dyn Connection, major: u32) -> Vec { + let schemas = connection.list_schemas(within(CALL)).await.expect("the schemas"); + assert!( + schemas + .iter() + .any(|schema| schema.name == "public" && schema.is_default), + "{major}" + ); + assert!( + !schemas.iter().any(|schema| schema.name.starts_with("pg_toast")), + "{major}: {schemas:?}" + ); + + let objects = connection + .list_objects(&ObjectScope::DefaultSchema, within(CALL)) + .await + .expect("the objects"); + let named = |kind: ObjectKind, name: &str| { + objects + .iter() + .filter(|object| object.kind == kind && object.name == name) + .count() + }; + assert_eq!(named(ObjectKind::Table, "parent"), 1, "{major}"); + assert_eq!(named(ObjectKind::Function, "touch"), 1, "{major}"); + assert_eq!(named(ObjectKind::Trigger, "child_touch"), 1, "{major}"); + if major >= 11 { + assert_eq!(named(ObjectKind::Procedure, "noop"), 1, "{major}"); + let parted_touch: Vec<_> = objects.iter().filter(|object| object.name == "parted_touch").collect(); + assert_eq!( + parted_touch.len(), + 1, + "{major}: a partition's copy was listed: {parted_touch:?}" + ); + assert_eq!(parted_touch[0].parent_table.as_deref(), Some("parted"), "{major}"); + } + + objects +} + +async fn table_reads_on(connection: &dyn Connection, major: u32, objects: &[ObjectInfo]) { + let columns = connection + .fetch_columns(&table("parent"), within(CALL)) + .await + .expect("the columns"); + assert_eq!( + columns.iter().map(|column| column.name.as_str()).collect::>(), + ["id", "label"], + "{major}" + ); + let indexes = connection + .fetch_indexes(&table("parent"), within(CALL)) + .await + .expect("the indexes"); + let keys = |name: &str| { + indexes + .iter() + .find(|index| index.name == name) + .map(|index| index.keys.clone()) + }; + assert_eq!( + keys("parent_label"), + Some(vec![IndexKey::Column { + name: "label".to_owned(), + descending: false + }]), + "{major}" + ); + if major >= 11 { + assert_eq!( + keys("parent_covering"), + Some(vec![IndexKey::Column { + name: "id".to_owned(), + descending: false + }]), + "{major}: an INCLUDE column was read as a key" + ); + } + let outbound = connection + .fetch_foreign_keys(&table("child"), within(CALL)) + .await + .expect("the keys"); + assert_eq!(outbound.len(), 1, "{major}: {outbound:?}"); + let inbound = connection + .fetch_inbound_foreign_keys(&table("parent"), within(CALL)) + .await + .expect("the keys pointing here"); + assert_eq!(inbound.len(), if major >= 11 { 2 } else { 1 }, "{major}: {inbound:?}"); + assert_eq!( + connection + .row_identity(&table("parent"), within(CALL)) + .await + .expect("the identity"), + RowIdentity::UniqueKey { + columns: vec!["id".to_owned()] + }, + "{major}" + ); + connection + .fetch_table_definition(&table("parent"), within(CALL)) + .await + .expect("the table definition"); + let touch = objects + .iter() + .find(|object| object.name == "touch") + .expect("the function"); + let definition = connection + .fetch_object_definition(touch, within(CALL)) + .await + .expect("the definition") + .expect("a definition"); + assert!( + definition.sql.contains("FUNCTION public.touch()"), + "{major}: {}", + definition.sql + ); + + let never_analysed = connection + .table_estimate(&table("parent"), within(CALL)) + .await + .expect("an estimate"); + assert_eq!(never_analysed.rows, RowCountEstimate::Unknown, "{major}"); + let sizes = connection + .table_info(&table("parted"), within(CALL)) + .await + .expect("the sizes"); + assert!(sizes.data_bytes.is_some_and(|bytes| bytes > 0), "{major}: {sizes:?}"); +} + +async fn dump_and_editor_on(connection: &dyn Connection, major: u32) { + let dump = connection + .read_dump_catalog(&DumpScope::Database, within(CALL)) + .await + .expect("the dump catalog"); + let dumped = |name: &str| dump.objects.iter().filter(|object| object.name == name).count(); + assert_eq!(dumped("child_touch"), 1, "{major}"); + if major >= 11 { + assert_eq!(dumped("parted_touch"), 1, "{major}"); + } + + let editor = session(connection).await; + let read = run_ok(editor.as_ref(), "SELECT id, label FROM parent").await; + assert!( + read.all().into_iter().any(|event| matches!( + event, + ResultEvent::ResultSetStarted { columns } if columns.iter().all(|column| column.origin.is_some()) + )), + "{major}: the editor's result has no origin, so it is not editable" + ); + + editor.close().await; +} + +async fn save_and_commit_on(connection: &dyn Connection, major: u32) { + let editor = session(connection).await; + setup(connection, &["INSERT INTO parent (label) VALUES ('old')"]).await; + let target = table("parent"); + let columns = connection + .fetch_columns(&target, within(CALL)) + .await + .expect("the columns"); + let identity = connection + .row_identity(&target, within(CALL)) + .await + .expect("the identity"); + let changes = ChangeSet { + changes: vec![RowChange::Update(RowUpdate { + key: vec![Value::Int(1)], + assignments: vec![(1, CellInput::Value(Value::Text("new".to_owned())))], + read: Vec::new(), + })], + }; + let dialect = connection.dialect(); + let plan = plan_save(dialect.as_ref(), &target, &columns, &identity, &changes).expect("a plan"); + connection + .write_batch(&plan.batch, within(CALL)) + .await + .expect("the save"); + assert_eq!( + text(&scalar(connection, "SELECT label FROM parent").await), + "new", + "{major}" + ); + setup(connection, &["ANALYZE parent"]).await; + let analysed = connection + .table_estimate(&target, within(CALL)) + .await + .expect("an estimate"); + assert_eq!(analysed.rows, RowCountEstimate::Approximate(1), "{major}"); + + let xid = run_ok(editor.as_ref(), "SELECT pg_catalog.txid_current()::text").await; + let xid: u64 = text(&xid.rows()[0][0]).parse().expect("a transaction id"); + let token = CommitToken::PostgresXid { + xid, + legacy_txid: major < 13, + }; + assert_eq!( + connection.resolve_commit(&token, within(CALL)).await, + Ok(CommitResolution::Applied), + "{major}" + ); + editor.close().await; } /// No statement is cached under a name, so a column added after the pool @@ -1094,9 +1350,10 @@ async fn lookalikes_in_public_never_run_in_a_catalog_read() { "CREATE TABLE accounts (id int PRIMARY KEY, state mood)".to_owned(), "CREATE TABLE orders (id int PRIMARY KEY, account int REFERENCES accounts (id))".to_owned(), "CREATE INDEX orders_account ON orders (account)".to_owned(), - trap("starts_with", "name, text", "boolean"), + trap("left", "text, int4", "text"), trap("unnest", "int2[]", "SETOF int2"), trap("to_jsonb", "pg_catalog.pg_constraint", "jsonb"), + trap("to_jsonb", "pg_catalog.pg_collation", "jsonb"), trap("array_agg_step", "text[], text", "text[]"), "CREATE AGGREGATE public.array_agg(text) (SFUNC = public.array_agg_step, STYPE = text[])".to_owned(), trap("oid_is_regclass", "oid, regclass", "boolean"), diff --git a/core/crates/ffi/src/error.rs b/core/crates/ffi/src/error.rs index ceed70b51b..7fafa9a284 100644 --- a/core/crates/ffi/src/error.rs +++ b/core/crates/ffi/src/error.rs @@ -220,6 +220,7 @@ fn driver_codes(error: &DriverError, codes: &mut Vec) { } } DriverError::Config(config) => codes.push(config.code().to_owned()), + DriverError::Unsupported { feature } => codes.push(feature.code().to_owned()), DriverError::RolledBack { source, .. } | DriverError::CommitOutcomeUnknown { source, .. } | DriverError::PartiallyApplied { source, .. } => driver_codes(source, codes), diff --git a/core/crates/ffi/src/session.rs b/core/crates/ffi/src/session.rs index feb4cd5300..406fa6be04 100644 --- a/core/crates/ffi/src/session.rs +++ b/core/crates/ffi/src/session.rs @@ -1019,7 +1019,7 @@ mod tests { .await .unwrap_err(); - assert_eq!(refused.code(), "driver.unsupported"); + assert_eq!(refused.code(), "unsupported.database_switching"); assert!(editor.is_closed(), "the editor was left open in the wrong database"); } diff --git a/core/crates/ffi/tests/browse.rs b/core/crates/ffi/tests/browse.rs index 325c7696bc..846222aa55 100644 --- a/core/crates/ffi/tests/browse.rs +++ b/core/crates/ffi/tests/browse.rs @@ -561,7 +561,14 @@ async fn a_trigger_reads_back_and_a_function_is_unsupported_on_sqlite() { let CoreError::Failed { info } = function else { unreachable!("a function was read: {function:?}") }; - assert_eq!(info.codes, ["operation.driver", "driver.unsupported"]); + assert_eq!( + info.codes, + [ + "operation.driver", + "driver.unsupported", + "unsupported.object_definitions" + ] + ); assert_eq!(key.code(), "ffi.no_definition"); } @@ -576,7 +583,7 @@ async fn an_editor_moves_to_a_database_only_where_the_engine_switches_one() { editor.close().await.unwrap(); session.close().await.unwrap(); - assert_eq!(refused.code(), "driver.unsupported"); + assert_eq!(refused.code(), "unsupported.database_switching"); } const REFERENCES: &str = "CREATE TABLE parent (code TEXT NOT NULL, region INTEGER NOT NULL, \ diff --git a/core/crates/session/tests/session_postgres.rs b/core/crates/session/tests/session_postgres.rs index d16d83ec29..fcd3207658 100644 --- a/core/crates/session/tests/session_postgres.rs +++ b/core/crates/session/tests/session_postgres.rs @@ -27,7 +27,8 @@ use tablepro_session::{ }; use tablepro_ssh::{SshAuth, SshConfig, SshDestination, SshRuntimeCell, SshServices}; use tablepro_test_fixtures::{ - FixtureCredentials, HbaMode, OpenSshFixture, PostgresFixture, SshAuthVariant, SshKeyPair, TestNetwork, + FixtureCredentials, HbaMode, OpenSshFixture, PostgresFixture, PostgresVersion, SshAuthVariant, SshKeyPair, + TestNetwork, }; use tokio_util::sync::CancellationToken; use uuid::Uuid; @@ -207,6 +208,28 @@ fn within(limit: Duration) -> CallOptions { CallOptions::new(Some(tokio::time::Instant::now() + limit), CancellationToken::new()) } +// Connecting reads the schemas and the default schema's objects before +// the session is handed over, so a catalog column the release lacks +// failed the whole connect (#4609). +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[ignore = "requires docker"] +async fn a_release_before_13_connects() { + let fixture = PostgresFixture::start_version(PostgresVersion::V12, HbaMode::Password) + .await + .expect("PostgreSQL 12"); + let connector = connector(isolated_ssh().services); + let session = start( + connector.clone(), + establish(&connector, request(direct_target(&fixture))).await, + ); + assert_eq!( + scalar(&session, OperationKind::Metadata, "SELECT 1").await, + Ok(Value::Int(1)) + ); + let report = session.begin_shutdown().await.expect("the close task"); + assert_eq!(report, tablepro_session::CloseReport::Closed); +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[ignore = "requires docker"] async fn pg_terminate_backend_next_query_succeeds() { diff --git a/core/crates/test-fixtures/src/fixture_image.rs b/core/crates/test-fixtures/src/fixture_image.rs index 5d5e9c4e66..c1ab4c1c73 100644 --- a/core/crates/test-fixtures/src/fixture_image.rs +++ b/core/crates/test-fixtures/src/fixture_image.rs @@ -11,6 +11,18 @@ impl FixtureImage { name: "postgres", tag: "17-alpine", }; + pub const POSTGRES_10: Self = Self { + name: "postgres", + tag: "10-alpine", + }; + pub const POSTGRES_11: Self = Self { + name: "postgres", + tag: "11-alpine", + }; + pub const POSTGRES_12: Self = Self { + name: "postgres", + tag: "12-alpine", + }; pub const POSTGRES_13: Self = Self { name: "postgres", tag: "13-alpine", diff --git a/core/crates/test-fixtures/src/postgres_version.rs b/core/crates/test-fixtures/src/postgres_version.rs index fa6bd2cb18..973c01d442 100644 --- a/core/crates/test-fixtures/src/postgres_version.rs +++ b/core/crates/test-fixtures/src/postgres_version.rs @@ -2,10 +2,13 @@ use crate::{FixtureImage, ServerVersion}; /// The PostgreSQL major a fixture runs. /// -/// 13 is past its end of life, and stays for the catalog query the -/// driver keeps for servers before 14. +/// 10 to 13 are past their end of life. The driver still reads their +/// catalogs, and a test checks each of them. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] pub enum PostgresVersion { + V10, + V11, + V12, V13, V14, V15, @@ -17,6 +20,9 @@ pub enum PostgresVersion { impl PostgresVersion { pub fn major(self) -> u32 { match self { + Self::V10 => 10, + Self::V11 => 11, + Self::V12 => 12, Self::V13 => 13, Self::V14 => 14, Self::V15 => 15, @@ -28,10 +34,22 @@ impl PostgresVersion { impl ServerVersion for PostgresVersion { const VARIABLE: &'static str = "TABLEPRO_TEST_POSTGRES"; - const ALL: &'static [Self] = &[Self::V13, Self::V14, Self::V15, Self::V17, Self::V18]; + const ALL: &'static [Self] = &[ + Self::V10, + Self::V11, + Self::V12, + Self::V13, + Self::V14, + Self::V15, + Self::V17, + Self::V18, + ]; fn name(self) -> &'static str { match self { + Self::V10 => "10", + Self::V11 => "11", + Self::V12 => "12", Self::V13 => "13", Self::V14 => "14", Self::V15 => "15", @@ -42,6 +60,9 @@ impl ServerVersion for PostgresVersion { fn image(self) -> FixtureImage { match self { + Self::V10 => FixtureImage::POSTGRES_10, + Self::V11 => FixtureImage::POSTGRES_11, + Self::V12 => FixtureImage::POSTGRES_12, Self::V13 => FixtureImage::POSTGRES_13, Self::V14 => FixtureImage::POSTGRES_14, Self::V15 => FixtureImage::POSTGRES_15, diff --git a/linux/README.md b/linux/README.md index 6f1e2ef68b..d965be4628 100644 --- a/linux/README.md +++ b/linux/README.md @@ -8,25 +8,26 @@ The public beta is available as [0.1.0-beta.3](https://github.com/TableProApp/Ta ## Supported servers -TablePro supports the server releases their vendors still support. CI runs each driver's whole Docker suite on every release in the second column ([docs/testing.md](docs/testing.md#server-releases)). +TablePro supports the server releases their vendors still support, and PostgreSQL back to 10. CI runs each driver's whole Docker suite on every release in the second column ([docs/testing.md](docs/testing.md#server-releases)). | Engine | Tested releases | Not supported | |---|---|---| -| PostgreSQL | 14, 15, 17 and 18 | 13 and older, past end of life (13 on 2025-11-13). 19 until it is released | +| PostgreSQL | 14, 15, 17 and 18 | 9.6 and older, which the driver refuses when it connects. 19 until it is released | | MySQL | 8.0, 8.4 and 9.7 | 8.1 to 9.6, innovation releases past end of life. 5.7 and older | | MariaDB | 10.11, 11.4 and 12.3 | 10.6 and older, past end of life (10.6 on 2026-07-06). Rolling releases such as 13.0 | | SQL Server | 2017, 2019, 2022 and 2025 | 2016 and older, past extended support (2016 on 2026-07-14) | | ClickHouse | 26.3 and 26.8 | Monthly releases between long-term ones. 25.8 and older long-term releases, past end of life (25.8 on 2026-08-29) | | Apache Cassandra | 4.0 and 5.0 | 3.11 and older, past end of life. 6.0 until it is released | | ScyllaDB | 2025.1 and 2026.1 | Feature releases between long-term ones, such as 2026.3. Enterprise 2024.1 and older, past end of life | -| SQLite | the system library, 3.37.0 or newer | older libraries, which the driver refuses when it opens a file | +| SQLite | the system library, 3.43.0 or newer | older libraries, which the driver refuses when it opens a file | | DuckDB | 2.0.1, compiled into the app ([ADR 0031](docs/decisions/0031-duckdb-2.md)) | files a newer DuckDB wrote in a storage format 2.0.1 cannot read | | Redis | 7.4 and 8.10 | 7.2 and older, past end of life. Cluster and Sentinel deployments. Valkey answers the same commands and is not tested | | MongoDB | 7.0 and 8.0 | 6.0 and older, past end of life (6.0 on 2025-07-31). Minor releases between major ones, such as 8.2, are not tested. A sharded cluster is reached through `mongos` and is not tested | -- PostgreSQL 14 reaches end of life on 2026-11-12, and 15, the oldest release after it, is tested already. +- PostgreSQL 14 reached end of life on 2026-11-12, and 15, the oldest release after it, is tested already. - MySQL 8.0 reached end of life on 2026-04-30, but Amazon RDS keeps 8.0 instances under paid Extended Support until 2029-07-31, so it stays tested. - MariaDB 11.8, PostgreSQL 16 and Cassandra 4.1 are supported between the tested releases, which bound them. +- PostgreSQL 10 to 13 are past end of life and work: CI checks every catalog read, a row save and connecting on them, not the whole suite. Redshift, CockroachDB, TiDB, OceanBase and Databend are untested on Linux. PostgreSQL or MySQL protocol compatibility, or importing a connection from another app, does not establish support. Add a product here only after connect, catalog, read and write tests against that product pass on Linux. diff --git a/linux/changelog.d/4613.changed.md b/linux/changelog.d/4613.changed.md new file mode 100644 index 0000000000..49806a75f6 --- /dev/null +++ b/linux/changelog.d/4613.changed.md @@ -0,0 +1 @@ +A PostgreSQL server older than 10 is refused when connecting, with a message naming 10 as the minimum. diff --git a/linux/changelog.d/4613.fixed.md b/linux/changelog.d/4613.fixed.md new file mode 100644 index 0000000000..14f2828b89 --- /dev/null +++ b/linux/changelog.d/4613.fixed.md @@ -0,0 +1 @@ +Connecting to PostgreSQL 10, 11 or 12 failed on a catalog column the server does not have, such as tgparentid. diff --git a/linux/docs/drivers/postgresql.md b/linux/docs/drivers/postgresql.md index 15ebb632e9..2d54e4e094 100644 --- a/linux/docs/drivers/postgresql.md +++ b/linux/docs/drivers/postgresql.md @@ -1,6 +1,6 @@ # PostgreSQL -Driver id `postgres`, crate `core/crates/drivers/postgres`. It runs on tokio-postgres 0.7.18 with postgres-types and postgres-protocol, deadpool-postgres 0.14.2 for the pool and tokio-postgres-rustls 0.14 for TLS, all from crates.io ([ADR 0016](../decisions/0016-driver-contract-v2.md)). The integration suite runs against PostgreSQL 17, and CI runs it again on 14, 15 and 18; the catalogue is also checked on 13 ([supported servers](../../README.md#supported-servers)). The contract it implements is in [adding-drivers.md](../adding-drivers.md). +Driver id `postgres`, crate `core/crates/drivers/postgres`. It runs on tokio-postgres 0.7.18 with postgres-types and postgres-protocol, deadpool-postgres 0.14.2 for the pool and tokio-postgres-rustls 0.14 for TLS, all from crates.io ([ADR 0016](../decisions/0016-driver-contract-v2.md)). The integration suite runs against PostgreSQL 17, and CI runs it again on 14, 15 and 18; every catalogue read and a row save are also checked on 10 to 13, and a server before 10 is refused when it connects (`UnsupportedFeature::MinimumVersion`) ([supported servers](../../README.md#supported-servers)). A catalogue read writes a column a later release added as a placeholder that `CatalogRelease` renders for the server it runs on. The contract it implements is in [adding-drivers.md](../adding-drivers.md). ## Connections @@ -40,7 +40,7 @@ COMMIT - `statement_timeout` is the nearer of the call's deadline and the workspace's 60 s. `lock_timeout` is 10 s, so a blocked edit reports the lock instead of a generic timeout. - `SET LOCAL` ends with the transaction, so nothing is left on a server connection a pooler shares. - A catalog read's transaction also runs `SELECT pg_catalog.set_config('search_path', ..., true)`, which puts `pg_catalog` ahead of the session's own search_path until the COMMIT. The default schema is captured before the path changes. A table name resolves to its OID on the session's original path in the same transaction, before metadata reads use the protected path. Empty paths remain valid. Every function is written `pg_catalog.`, and every operator compares two values of one built-in type, cast where they differ (`attrelid = $1::text::regclass::oid`), or is written `OPERATOR(pg_catalog.)`. A lookalike another user creates on the path can then only tie with the built-in, and `pg_catalog` wins the tie even when the session's path names it after another schema. `bare_calls` in `metadata/mod.rs` checks every catalog statement for an unqualified call. Grid reads and counts keep the session's path, as the user's own SQL does. -- The sidebar lists functions, procedures, sequences and user triggers in their schema's section, a trigger with the table it fires on beside it. Two triggers of one name on different tables are both kept, and a partition's clone of its parent's trigger (`tgparentid` set) is left out. A definition comes from `pg_get_functiondef` (every overload), `pg_get_triggerdef` without pretty printing, which names the table with its schema, or for a sequence a `CREATE SEQUENCE` built from `pg_sequences` with every clause the statement takes: `UNLOGGED` or `TEMPORARY` from `relpersistence`, and `OWNED BY` the column a `pg_depend` row of type `a` names. An identity column's sequence (type `i`) is made with its table, so its text does not open in the editor. +- The sidebar lists functions, procedures, sequences and user triggers in their schema's section, a trigger with the table it fires on beside it. Two triggers of one name on different tables are both kept, and a partition's clone of its parent's trigger is left out: `tgparentid` is set on it from 13 on, and before 13 it is internal. A definition comes from `pg_get_functiondef` (every overload), `pg_get_triggerdef` without pretty printing, which names the table with its schema, or for a sequence a `CREATE SEQUENCE` built from `pg_sequences` with every clause the statement takes: `UNLOGGED` or `TEMPORARY` from `relpersistence`, and `OWNED BY` the column a `pg_depend` row of type `a` names. An identity column's sequence (type `i`) is made with its table, so its text does not open in the editor. - Generated SQL runs on the unnamed statement (`query_typed_raw`, `execute_typed`) with typed parameters. Nothing is prepared under a name. - A connection whose flight did not end with an acknowledged COMMIT or ROLLBACK is taken out of the pool, because deadpool's recycle check (`RecyclingMethod::Verified`) passes inside a half-finished transaction. - A read that returns no rows still has its columns: the statement runs once more as a subquery right-joined to one row on a false condition, in a read-only transaction of its own. diff --git a/linux/docs/testing.md b/linux/docs/testing.md index 3a16bb0c14..4427226cc8 100644 --- a/linux/docs/testing.md +++ b/linux/docs/testing.md @@ -400,7 +400,7 @@ A fixture starts its engine's default release unless the engine's variable names | Variable | Releases | Default | |---|---|---| -| `TABLEPRO_TEST_POSTGRES` | 13, 14, 15, 17, 18 | 17 | +| `TABLEPRO_TEST_POSTGRES` | 10, 11, 12, 13, 14, 15, 17, 18 | 17 | | `TABLEPRO_TEST_MYSQL` | 8.0, 8.4, 9.7 | 8.4 | | `TABLEPRO_TEST_MARIADB` | 10.11, 11.4, 12.3 | 11.4 | | `TABLEPRO_TEST_MSSQL` | 2017, 2019, 2022, 2025 | 2022 | @@ -411,7 +411,7 @@ A fixture starts its engine's default release unless the engine's variable names | `TABLEPRO_TEST_MONGO` | 7.0, 8.0 | 8.0 | | `TABLEPRO_TEST_OPENSSH` | 9.9, 10.3 | 10.3 | -`core/crates/test-fixtures/src/fixture_image.rs` pins each release's image, and each engine's version type (`PostgresVersion`, `MysqlVersion`, `MariadbVersion`, `MssqlVersion`, `ClickHouseVersion`, `CassandraVersion`, `ScyllaVersion`, `RedisVersion`, `MongoVersion`, `OpenSshVersion`) reads its variable through `ServerVersion::selected`. An empty value picks the default; a release the fixtures do not pin fails the fixture with the ones they do. PostgreSQL 13 is past end of life and stays only for the catalogue test of the driver's query for servers before 14. +`core/crates/test-fixtures/src/fixture_image.rs` pins each release's image, and each engine's version type (`PostgresVersion`, `MysqlVersion`, `MariadbVersion`, `MssqlVersion`, `ClickHouseVersion`, `CassandraVersion`, `ScyllaVersion`, `RedisVersion`, `MongoVersion`, `OpenSshVersion`) reads its variable through `ServerVersion::selected`. An empty value picks the default; a release the fixtures do not pin fails the fixture with the ones they do. PostgreSQL 10 to 13 are past end of life and stay for `every_read_and_a_save_work_before_14`, which starts each of them, and for the session's connect test on 12. The `integration` job runs each driver's suite on the defaults on every Linux change. The nightly's `integration-releases` job runs it once more for each other release: PostgreSQL 14, 15 and 18, MySQL 8.0 with MariaDB 10.11, MySQL 9.7 with MariaDB 12.3, SQL Server 2017, 2019 and 2025, ClickHouse 26.3, Cassandra 4.0 with ScyllaDB 2025.1, Redis 7.4, MongoDB 7.0, and OpenSSH 9.9 for `tablepro-ssh`. The README's [supported servers](../README.md#supported-servers) table says why those releases and not others. A test that checks the server's version reads it from the fixture (`PostgresFixture::version`, `MysqlFixture::server_version`, `MssqlFixture::version`, `ClickHouseFixture::version`, `CassandraFixture::server_version`, `RedisFixture::version`, `MongoFixture::version`, `OpenSshFixture::version`), never from a literal, so it holds on every release. @@ -421,7 +421,7 @@ Locally, set the variables for the run: TABLEPRO_TEST_MYSQL=8.0 TABLEPRO_TEST_MARIADB=10.11 cargo nextest run -p tablepro-driver-mysql --run-ignored only ``` -A new release gets its image in `fixture_image.rs`, a variant in its version type, an `integration-releases` entry in `.github/workflows/build-linux.yml` and a row in the README table. A release past its vendor's end of life loses all four. +A new release gets its image in `fixture_image.rs`, a variant in its version type, an `integration-releases` entry in `.github/workflows/build-linux.yml` and a row in the README table. A release past its vendor's end of life loses all four, except PostgreSQL 10 to 13, which keep their image and variant for the old-release test. ### Docker or Podman diff --git a/windows/src/TablePro.App/Strings/en-US/Resources.resw b/windows/src/TablePro.App/Strings/en-US/Resources.resw index e08d42201e..4f4c210d57 100644 --- a/windows/src/TablePro.App/Strings/en-US/Resources.resw +++ b/windows/src/TablePro.App/Strings/en-US/Resources.resw @@ -2474,6 +2474,9 @@ New fingerprint: {2} This database doesn't support that. + + This server's version is older than TablePro supports. + The database's structure is larger than TablePro reads at once. diff --git a/windows/tests/TablePro.Interop.Tests/BrowseTests.cs b/windows/tests/TablePro.Interop.Tests/BrowseTests.cs index 62187b71a2..6bfa4dc1a5 100644 --- a/windows/tests/TablePro.Interop.Tests/BrowseTests.cs +++ b/windows/tests/TablePro.Interop.Tests/BrowseTests.cs @@ -242,7 +242,8 @@ await database.ExecuteAsync( Assert.Contains("people_noted", source.Sql, StringComparison.Ordinal); Assert.True(source.OpensInEditor); Assert.Null(source.Database); - Assert.Equal("driver.unsupported", function.Code); + Assert.Equal("unsupported.object_definitions", function.Code); + Assert.Contains("driver.unsupported", function.Error.Codes); } private static TableFilter Rules(params FilterRule[] rules) => new(FilterCombinator.And, rules, null); diff --git a/windows/tests/TablePro.Interop.Tests/DatabaseSwitchTests.cs b/windows/tests/TablePro.Interop.Tests/DatabaseSwitchTests.cs index bcc8892d6d..d3bb774562 100644 --- a/windows/tests/TablePro.Interop.Tests/DatabaseSwitchTests.cs +++ b/windows/tests/TablePro.Interop.Tests/DatabaseSwitchTests.cs @@ -14,7 +14,8 @@ public async Task AFileHasOneDatabaseAndListsNoOthers() Assert.Equal(DatabaseLayout.OneDatabase, database.Session.Layout); Assert.Null(database.Session.Database); - Assert.Equal("driver.unsupported", listing.Error.Code); + Assert.Equal("unsupported.database_switching", listing.Error.Code); + Assert.Contains("driver.unsupported", listing.Error.Codes); } [Fact] @@ -27,7 +28,8 @@ public async Task AnEditorAskedForAnotherDatabaseOfAFileIsRefusedAndNotLeftOpen( () => database.Session.OpenEditorAsync("shop", cancellationToken)); await using var editor = await database.Session.OpenEditorAsync(null, cancellationToken); - Assert.Equal("driver.unsupported", refused.Error.Code); + Assert.Equal("unsupported.database_switching", refused.Error.Code); + Assert.Contains("driver.unsupported", refused.Error.Codes); Assert.Null(editor.Database); }