Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 39 additions & 2 deletions core/crates/core/src/unsupported_feature.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
},
Expand Down Expand Up @@ -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 {
Expand Down
2 changes: 1 addition & 1 deletion core/crates/drivers/postgres/src/catalog/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
};
Expand Down
21 changes: 4 additions & 17 deletions core/crates/drivers/postgres/src/catalog/pg_column_row.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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 {
Expand Down
11 changes: 7 additions & 4 deletions core/crates/drivers/postgres/src/catalog/table_definition.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand All @@ -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)
Expand Down
160 changes: 160 additions & 0 deletions core/crates/drivers/postgres/src/catalog_release.rs
Original file line number Diff line number Diff line change
@@ -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
);
}
}
}
Loading
Loading