use fraiseql_error::FraiseQLError;
use crate::types::{DatabaseType, sql_hints::OrderByFieldType};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Feature {
JsonbPathOps,
Subscriptions,
Mutations,
WindowFunctions,
CommonTableExpressions,
FullTextSearch,
AdvisoryLocks,
StddevVariance,
Upsert,
ArrayTypes,
BackwardPagination,
}
impl Feature {
const fn display_name(self) -> &'static str {
match self {
Self::JsonbPathOps => "JSONB path expressions",
Self::Subscriptions => "Subscriptions (real-time push)",
Self::Mutations => "Mutations (INSERT/UPDATE/DELETE via mutation_response)",
Self::WindowFunctions => "Window functions (RANK, ROW_NUMBER, LAG, etc.)",
Self::CommonTableExpressions => "Common Table Expressions (WITH clause)",
Self::FullTextSearch => "Full-text search",
Self::AdvisoryLocks => "Advisory locks",
Self::StddevVariance => "STDDEV/VARIANCE aggregates",
Self::Upsert => "Upsert (ON CONFLICT / INSERT OR REPLACE)",
Self::ArrayTypes => "Array column types",
Self::BackwardPagination => "Backward keyset pagination",
}
}
}
impl DatabaseType {
#[must_use]
pub fn json_field_expr(self, key: &str) -> String {
match self {
Self::PostgreSQL => format!("data->>'{key}'"),
Self::MySQL => format!("JSON_UNQUOTE(JSON_EXTRACT(data, '$.{key}'))"),
Self::SQLite => format!("json_extract(data, '$.{key}')"),
Self::SQLServer => format!("JSON_VALUE(data, '$.{key}')"),
}
}
#[allow(clippy::unreachable)]
#[must_use]
pub fn typed_json_field_expr(self, key: &str, field_type: OrderByFieldType) -> String {
use OrderByFieldType as F;
if field_type == F::Text {
return self.json_field_expr(key);
}
let base = self.json_field_expr(key);
match self {
Self::PostgreSQL => {
let pg_type = match field_type {
F::Text => unreachable!("F::Text returned early at function top"),
F::Integer => "bigint",
F::Numeric => "numeric",
F::Boolean => "boolean",
F::DateTime => "timestamptz",
F::Date => "date",
F::Time => "time",
};
format!("({base})::{pg_type}")
},
Self::MySQL => {
let mysql_type = match field_type {
F::Text => unreachable!("F::Text returned early at function top"),
F::Integer => "SIGNED",
F::Numeric => "DECIMAL(38,12)",
F::Boolean => "UNSIGNED",
F::DateTime => "DATETIME",
F::Date => "DATE",
F::Time => "TIME",
};
format!("CAST({base} AS {mysql_type})")
},
Self::SQLite => {
let sqlite_type = match field_type {
F::Text => unreachable!("F::Text returned early at function top"),
F::Integer | F::Boolean => "INTEGER",
F::Numeric => "REAL",
F::DateTime | F::Date | F::Time => "TEXT", };
format!("CAST({base} AS {sqlite_type})")
},
Self::SQLServer => {
let sqlserver_type = match field_type {
F::Text => unreachable!("F::Text returned early at function top"),
F::Integer => "BIGINT",
F::Numeric => "DECIMAL(38,12)",
F::Boolean => "BIT",
F::DateTime => "DATETIME2",
F::Date => "DATE",
F::Time => "TIME",
};
format!("CAST({base} AS {sqlserver_type})")
},
}
}
#[must_use]
pub const fn supports(self, feature: Feature) -> bool {
match (self, feature) {
(Self::PostgreSQL, _) => true,
(
Self::MySQL,
Feature::JsonbPathOps
| Feature::Subscriptions
| Feature::AdvisoryLocks
| Feature::StddevVariance
| Feature::ArrayTypes,
) => false,
(Self::MySQL, _) => true,
(
Self::SQLServer,
Feature::JsonbPathOps
| Feature::Subscriptions
| Feature::AdvisoryLocks
| Feature::ArrayTypes,
) => false,
(Self::SQLServer, _) => true,
(Self::SQLite, Feature::CommonTableExpressions | Feature::Upsert) => true,
(Self::SQLite, _) => false,
}
}
#[must_use]
pub const fn suggestion_for(self, feature: Feature) -> Option<&'static str> {
match (self, feature) {
(Self::MySQL, Feature::JsonbPathOps) => {
Some("Use `json_extract(column, '$.key')` syntax instead of JSONB path operators.")
},
(Self::MySQL, Feature::StddevVariance) => {
Some("MySQL does not provide STDDEV/VARIANCE; compute them in application code.")
},
(Self::SQLite, Feature::Mutations) => Some(
"SQLite mutations are not supported. Use PostgreSQL or MySQL for mutation support.",
),
(Self::SQLite, Feature::WindowFunctions) => Some(
"SQLite 3.25+ supports basic window functions; upgrade your SQLite version or use PostgreSQL.",
),
(Self::SQLite, Feature::Subscriptions) => {
Some("Subscriptions require a database with LISTEN/NOTIFY. Use PostgreSQL.")
},
_ => None,
}
}
}
pub struct DialectCapabilityGuard;
impl DialectCapabilityGuard {
pub fn check(dialect: DatabaseType, feature: Feature) -> Result<(), FraiseQLError> {
if dialect.supports(feature) {
return Ok(());
}
let suggestion =
dialect.suggestion_for(feature).map(|s| format!(" {s}")).unwrap_or_default();
Err(FraiseQLError::Unsupported {
message: format!(
"{} is not supported on {}.{suggestion} \
See docs/database-compatibility.md for the full feature matrix.",
feature.display_name(),
dialect.as_str(),
),
})
}
pub fn check_all(dialect: DatabaseType, features: &[Feature]) -> Result<(), FraiseQLError> {
let failures: Vec<String> = features
.iter()
.copied()
.filter(|&f| !dialect.supports(f))
.map(|f| {
let suggestion =
dialect.suggestion_for(f).map(|s| format!(" {s}")).unwrap_or_default();
format!("- {}{suggestion}", f.display_name())
})
.collect();
if failures.is_empty() {
return Ok(());
}
Err(FraiseQLError::Unsupported {
message: format!(
"The following features are not supported on {}:\n{}\n\
See docs/database-compatibility.md for the full feature matrix.",
dialect.as_str(),
failures.join("\n"),
),
})
}
}
#[cfg(test)]
mod tests;