use fraiseql_error::{FraiseQLError, Result};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FieldKind {
Text,
Native,
Composite,
ObjectList,
}
const MAX_PAIRS_PER_CALL: usize = 50;
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ObjectPair {
key: String,
value: String,
}
impl ObjectPair {
pub(crate) fn new(key_literal: impl Into<String>, value: impl Into<String>) -> Self {
Self {
key: key_literal.into(),
value: value.into(),
}
}
}
pub(crate) fn jsonb_object_sql(pairs: &[ObjectPair]) -> String {
let render = |chunk: &[ObjectPair]| {
let args: Vec<String> = chunk.iter().map(|p| format!("{}, {}", p.key, p.value)).collect();
format!("jsonb_build_object({})", args.join(","))
};
if pairs.len() <= MAX_PAIRS_PER_CALL {
return render(pairs);
}
let calls: Vec<String> = pairs.chunks(MAX_PAIRS_PER_CALL).map(render).collect();
format!("({})", calls.join(" || "))
}
pub(crate) fn json_object_sql(pairs: &[ObjectPair]) -> String {
if pairs.is_empty() {
return "JSON_OBJECT(RETURNING json)".to_string();
}
let args: Vec<String> = pairs.iter().map(|p| format!("{} VALUE {}", p.key, p.value)).collect();
format!("JSON_OBJECT({} RETURNING json)", args.join(", "))
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ComputedExpr(String);
impl ComputedExpr {
pub(crate) const fn from_validated_parts(sql: String) -> Self {
Self(sql)
}
#[must_use]
pub fn as_sql(&self) -> &str {
&self.0
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProjectionField {
pub name: String,
pub source: String,
pub kind: FieldKind,
pub sub_fields: Option<Vec<ProjectionField>>,
pub localized: Option<LocalizedRead>,
pub computed: Option<ComputedExpr>,
}
impl ProjectionField {
#[must_use]
pub fn scalar(name: impl Into<String>) -> Self {
let name = name.into();
Self {
source: name.clone(),
name,
kind: FieldKind::Text,
sub_fields: None,
localized: None,
computed: None,
}
}
#[must_use]
pub fn native(name: impl Into<String>) -> Self {
let name = name.into();
Self {
source: name.clone(),
name,
kind: FieldKind::Native,
sub_fields: None,
localized: None,
computed: None,
}
}
#[must_use]
pub fn composite(name: impl Into<String>) -> Self {
let name = name.into();
Self {
source: name.clone(),
name,
kind: FieldKind::Composite,
sub_fields: None,
localized: None,
computed: None,
}
}
#[must_use]
pub fn composite_with_sub_fields(name: impl Into<String>, sub_fields: Vec<Self>) -> Self {
let name = name.into();
Self {
source: name.clone(),
name,
kind: FieldKind::Composite,
sub_fields: Some(sub_fields),
localized: None,
computed: None,
}
}
#[must_use]
pub fn computed(name: impl Into<String>, expr: ComputedExpr) -> Self {
let name = name.into();
Self {
source: name.clone(),
name,
kind: FieldKind::Native,
sub_fields: None,
localized: None,
computed: Some(expr),
}
}
#[must_use]
pub fn typename(name: impl Into<String>, type_name: &str) -> Self {
let literal = PostgresProjectionGenerator::escape_sql_string(type_name);
Self::computed(name, ComputedExpr::from_validated_parts(format!("'{literal}'::text")))
}
#[must_use]
pub fn masked(name: impl Into<String>, list: bool) -> Self {
let value = if list { "'[]'::json" } else { "NULL::json" };
Self::computed(name, ComputedExpr::from_validated_parts(value.to_string()))
}
#[must_use]
pub fn object_list(name: impl Into<String>, sub_fields: Vec<Self>) -> Self {
Self {
kind: FieldKind::ObjectList,
..Self::composite_with_sub_fields(name, sub_fields)
}
}
#[must_use]
pub const fn is_composite(&self) -> bool {
matches!(self.kind, FieldKind::Composite | FieldKind::ObjectList)
}
}
impl From<String> for ProjectionField {
fn from(name: String) -> Self {
Self::scalar(name)
}
}
fn validate_field_name(field: &str) -> Result<()> {
if field.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
Ok(())
} else {
Err(FraiseQLError::Validation {
message: format!(
"field name '{}' contains characters that cannot be safely projected; \
only ASCII alphanumeric characters and underscores are allowed",
field
),
path: None,
})
}
}
use crate::utils::to_snake_case;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum LocalizedRead {
Label(Vec<String>),
Translations {
allowed: Vec<String>,
keys: Vec<(String, TranslationPart)>,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TranslationPart {
Locale,
Value,
Typename,
}
fn checked_tag(tag: &str) -> Result<&str> {
if tag.is_empty() || !tag.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-') {
return Err(FraiseQLError::validation(format!("locale `{tag}` is not a language tag")));
}
Ok(tag)
}
pub fn localized_text_expr(field_path: &str, chain: &[String]) -> Result<String> {
if chain.is_empty() {
return Ok("NULL::text".to_string());
}
let arms = chain
.iter()
.map(|tag| {
let tag = checked_tag(tag)?;
Ok(format!(
"CASE WHEN jsonb_typeof({field_path}->'{tag}') = 'string' THEN \
{field_path}->>'{tag}' END"
))
})
.collect::<Result<Vec<_>>>()?;
Ok(format!(
"CASE WHEN jsonb_typeof({field_path}) = 'string' THEN {field_path} #>> '{{}}' ELSE \
COALESCE({}) END",
arms.join(", ")
))
}
pub fn localized_key_expr(
column: &str,
path: &[String],
chain: &[String],
collation: Option<&str>,
) -> Result<String> {
let mut map = column.to_string();
for segment in path {
map.push_str("->'");
map.push_str(&crate::path_escape::escape_postgres_jsonb_segment(segment));
map.push('\'');
}
crate::order_by::collated(&localized_text_expr(&map, chain)?, collation)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LocalizedIndex {
pub name: String,
pub ddl: String,
pub key: String,
}
pub fn localized_index(
table: &str,
field: &str,
locale: &str,
chain: &[String],
collation: Option<&str>,
) -> Result<LocalizedIndex> {
let key = localized_key_expr("data", &[field.to_string()], chain, collation)?;
let relation = table.rsplit('.').next().unwrap_or(table);
let full = format!("ix_{relation}_{field}_{}", locale.to_ascii_lowercase().replace('-', "_"));
let name = if full.len() <= 63 {
full
} else {
let hash = full.bytes().fold(0xcbf2_9ce4_8422_2325_u64, |h, b| {
(h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3)
});
let mut cut = 54;
while !full.is_char_boundary(cut) {
cut -= 1;
}
format!("{}_{:08x}", &full[..cut], hash & 0xffff_ffff)
};
let quoted_table = crate::identifier::quote_postgres_identifier(table);
let ddl = format!(
"CREATE INDEX CONCURRENTLY IF NOT EXISTS {} ON {quoted_table} (({key}));",
crate::identifier::quote_postgres_identifier(&name)
);
Ok(LocalizedIndex { name, ddl, key })
}
pub fn localized_translations_expr(
field_path: &str,
allowed: &[String],
keys: &[(String, TranslationPart)],
) -> Result<String> {
let tags = allowed
.iter()
.map(|tag| checked_tag(tag).map(|tag| format!("'{tag}'")))
.collect::<Result<Vec<_>>>()?;
if tags.is_empty() {
return Ok("'[]'::jsonb".to_string());
}
let pairs: Vec<ObjectPair> = keys
.iter()
.map(|(key, part)| {
let value = match part {
TranslationPart::Locale => "fraiseql_l.tag".to_string(),
TranslationPart::Value => format!("{field_path}->>fraiseql_l.tag"),
TranslationPart::Typename => "'LocalizedString'".to_string(),
};
ObjectPair::new(format!("'{}'", key.replace('\'', "''")), value)
})
.collect();
Ok(format!(
"COALESCE((SELECT jsonb_agg({} ORDER BY fraiseql_l.ord) FROM \
unnest(ARRAY[{}]::text[]) WITH ORDINALITY AS fraiseql_l(tag, ord) WHERE \
jsonb_typeof({field_path}->fraiseql_l.tag) = 'string'), '[]'::jsonb)",
jsonb_object_sql(&pairs),
tags.join(", ")
))
}
pub struct PostgresProjectionGenerator {
jsonb_column: String,
}
impl PostgresProjectionGenerator {
#[must_use]
pub fn new() -> Self {
Self::with_column("data")
}
#[must_use]
pub fn with_column(jsonb_column: &str) -> Self {
Self {
jsonb_column: jsonb_column.to_string(),
}
}
pub fn generate_projection_sql(&self, fields: &[String]) -> Result<String> {
if fields.is_empty() {
return Ok(format!("\"{}\"", self.jsonb_column));
}
for field in fields {
validate_field_name(field)?;
}
let field_pairs: Vec<ObjectPair> = fields
.iter()
.map(|field| {
let safe_field = Self::escape_sql_string(field);
let jsonb_key = to_snake_case(field);
let safe_jsonb_key = Self::escape_sql_string(&jsonb_key);
ObjectPair::new(
format!("'{safe_field}'"),
format!("\"{}\"->>'{}'", self.jsonb_column, safe_jsonb_key),
)
})
.collect();
Ok(json_object_sql(&field_pairs))
}
pub fn generate_typed_projection_sql(&self, fields: &[ProjectionField]) -> Result<String> {
if fields.is_empty() {
return Ok("jsonb_build_object()".to_string());
}
let path = format!("\"{}\"", self.jsonb_column);
let field_pairs = fields
.iter()
.map(|field| Self::render_field(field, &path))
.collect::<Result<Vec<_>>>()?;
Ok(json_object_sql(&field_pairs))
}
pub fn generate_merged_projection_sql(&self, computed: &[ProjectionField]) -> Result<String> {
if computed.is_empty() {
return Ok(format!("\"{}\"", self.jsonb_column));
}
let path = format!("\"{}\"", self.jsonb_column);
let pairs = computed
.iter()
.map(|field| Self::render_field(field, &path))
.collect::<Result<Vec<_>>>()?;
Ok(format!("{path} || {}", jsonb_object_sql(&pairs)))
}
fn render_field(field: &ProjectionField, path: &str) -> Result<ObjectPair> {
let resp_key = Self::escape_sql_string(&field.name);
if let Some(expr) = &field.computed {
return Ok(ObjectPair::new(format!("'{resp_key}'"), format!("({})", expr.as_sql())));
}
let jsonb_key = to_snake_case(&field.source);
let safe_jsonb_key = Self::escape_sql_string(&jsonb_key);
if let Some(read) = &field.localized {
let field_path = format!("{path}->'{safe_jsonb_key}'");
let expr = match read {
LocalizedRead::Label(chain) => localized_text_expr(&field_path, chain)?,
LocalizedRead::Translations { allowed, keys } => {
localized_translations_expr(&field_path, allowed, keys)?
},
};
return Ok(ObjectPair::new(format!("'{resp_key}'"), expr));
}
if let Some(subs) = &field.sub_fields {
let nested_path = format!("{}->'{}'", path, safe_jsonb_key);
if field.kind == FieldKind::ObjectList {
let element = format!("e{}", path.matches(".value").count());
let item = format!("{element}.value");
let inner = subs
.iter()
.map(|sf| Self::render_field(sf, &item))
.collect::<Result<Vec<_>>>()?;
return Ok(ObjectPair::new(
format!("'{resp_key}'"),
format!(
"CASE WHEN jsonb_typeof({nested_path}) = 'array' THEN (SELECT \
COALESCE(JSON_ARRAYAGG(CASE WHEN jsonb_typeof({item}) = 'object' THEN \
{} END ORDER BY {element}.ordinality NULL ON NULL RETURNING json), \
'[]'::json) FROM jsonb_array_elements({nested_path}) WITH ORDINALITY \
AS {element}) END",
json_object_sql(&inner)
),
));
}
let inner = subs
.iter()
.map(|sf| Self::render_field(sf, &nested_path))
.collect::<Result<Vec<_>>>()?;
return Ok(ObjectPair::new(
format!("'{resp_key}'"),
format!(
"CASE WHEN jsonb_typeof({nested_path}) = 'object' THEN {} END",
json_object_sql(&inner)
),
));
}
let op = if field.kind == FieldKind::Text {
"->>"
} else {
"->"
};
Ok(ObjectPair::new(
format!("'{resp_key}'"),
format!("{path}{op}'{safe_jsonb_key}'"),
))
}
pub fn generate_select_clause(&self, table_alias: &str, fields: &[String]) -> Result<String> {
let projection = self.generate_projection_sql(fields)?;
Ok(format!(
"SELECT {} as \"{}\" FROM \"{}\" ",
projection, self.jsonb_column, table_alias
))
}
fn escape_sql_string(s: &str) -> String {
s.replace('\'', "''")
}
#[allow(dead_code)] fn escape_identifier(field: &str) -> String {
format!("\"{}\"", field.replace('"', "\"\""))
}
}
impl Default for PostgresProjectionGenerator {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests;