Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| e061db2a94 | |||
| 4379da4986 | |||
| b699061f2f | |||
| 15e826cbcb | |||
| f17ee3b543 |
@ -374,7 +374,7 @@ The Queryer transforms Postgres into a pre-compiled Semantic Query Engine, desig
|
||||
* **Multi-Table Branching**: If the Physical Table is a parent to other tables (e.g. `organization` has variations `["organization", "bot", "person"]`), the compiler generates a dynamic `CASE WHEN type = '...' THEN ...` query, expanding into sub-queries for each variation. To ensure safe resolution, the compiler dynamically evaluates correlation boundaries: it attempts standard Relational Edge discovery first. If no explicit relational edge exists (indicating pure Table Inheritance rather than a standard foreign-key graph relationship), it safely invokes a **Table Parity Fallback**. This generates an explicit ID correlation constraint (`AND inner.id = outer.id`), perfectly binding the structural variations back to the parent row to eliminate Cartesian products.
|
||||
* **Single-Table Bypass**: If the Physical Table is a leaf node with only one variation (e.g. `person` has variations `["person"]`), the compiler cleanly bypasses `CASE` generation and compiles a simple `SELECT` across the base table, as all schema extensions (e.g. `light.person`, `full.person`) are guaranteed to reside in the exact same physical row.
|
||||
* **Polymorphic Relation Type Filtering**: When a relationship maps to a polymorphic target with variations, the Queryer compiles an `IN` clause containing all allowed table variations (e.g., `counterparty_type IN ('bot', 'organization', 'person')`) rather than matching the base type literal, ensuring all polymorphic types are loaded correctly.
|
||||
* **Tenant Scoping & ReBAC Filtering**: When `jspg_query` compiles root-level or relationship-level entity queries, the generated SQL queries evaluate within the calling PostgreSQL transaction's session configuration (e.g. `auth.organization_ids`, `auth.roles`). The compiled queries seamlessly interact with PostgreSQL Row Level Security (RLS) policies on base tables (such as `agreego.entity`) and pre-materialized Zanzibar graph edges (`agreego.relationship`), ensuring multi-tenant isolation and $O(1)$ query evaluation without requiring manual WHERE scoping logic across every application punc.
|
||||
* **Tenant Scoping & ReBAC Filtering**: When `jspg_query` compiles root-level or relationship-level entity queries, the generated SQL queries evaluate within the calling PostgreSQL transaction's session configuration (e.g. `punc.cue.organization_ids`, `punc.cue.roles`). The compiled queries seamlessly interact with PostgreSQL Row Level Security (RLS) policies on base tables (such as `agreego.entity`) and pre-materialized Zanzibar graph edges (`agreego.relationship`), ensuring multi-tenant isolation and $O(1)$ query evaluation without requiring manual WHERE scoping logic across every application punc.
|
||||
* **Static Relation Constraints (Kind Constraints)**: When a relationship (such as a nested object or array) is defined with a schema that constrains a field value statically using a `const` or `enum` keyword (for example, `kind` constrained to `"cover"` in a `cover_attachment`), the Queryer automatically extracts these static assertions during AST compilation. It injects them directly as static filters into the SQL subquery's `WHERE` clause (e.g. `AND attachment.kind = 'cover'`), allowing developers to query pre-filtered subsets of related tables natively through the schema.
|
||||
* **Proxy Schema Dereferencing / Resolution**: To support punc endpoints that return non-polymorphic table-backed shapes (using `type: "full.X"` proxy schemas at the root response level), the Queryer compiler automatically dereferences non-table schema pointers to their target schemas prior to checking the types. This allows the Queryer to correctly resolve the table relationship edges pre-compiled on the full schema, while avoiding polluting the database registry with relations on ad-hoc punc response schemas during setup.
|
||||
|
||||
|
||||
372
fixtures/composition.json
Normal file
372
fixtures/composition.json
Normal file
@ -0,0 +1,372 @@
|
||||
[
|
||||
{
|
||||
"description": "Composition: the self-referential base edge (entity.parent_id -> entity) \u2014 an array lists the children, a scalar reaches the parent",
|
||||
"database": {
|
||||
"puncs": [],
|
||||
"enums": [],
|
||||
"relations": [
|
||||
{
|
||||
"id": "44444444-4444-4444-4444-444444444441",
|
||||
"type": "relation",
|
||||
"constraint": "fk_entity_parent",
|
||||
"source_type": "entity",
|
||||
"source_columns": [
|
||||
"parent_id"
|
||||
],
|
||||
"destination_type": "entity",
|
||||
"destination_columns": [
|
||||
"id"
|
||||
]
|
||||
}
|
||||
],
|
||||
"types": [
|
||||
{
|
||||
"name": "entity",
|
||||
"hierarchy": [
|
||||
"entity"
|
||||
],
|
||||
"fields": [
|
||||
"id",
|
||||
"type",
|
||||
"archived",
|
||||
"created_at",
|
||||
"parent_id",
|
||||
"ancestors"
|
||||
],
|
||||
"grouped_fields": {
|
||||
"entity": [
|
||||
"id",
|
||||
"type",
|
||||
"archived",
|
||||
"created_at",
|
||||
"parent_id",
|
||||
"ancestors"
|
||||
]
|
||||
},
|
||||
"field_types": {
|
||||
"id": "uuid",
|
||||
"type": "text",
|
||||
"archived": "boolean",
|
||||
"created_at": "timestamptz",
|
||||
"parent_id": "uuid",
|
||||
"ancestors": "uuid[]"
|
||||
},
|
||||
"schemas": {
|
||||
"entity": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "string",
|
||||
"format": "uuid"
|
||||
},
|
||||
"type": {
|
||||
"type": "string"
|
||||
},
|
||||
"archived": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"created_at": {
|
||||
"type": "string",
|
||||
"format": "date-time"
|
||||
},
|
||||
"created": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"parent_id": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
],
|
||||
"format": "uuid"
|
||||
},
|
||||
"ancestors": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string",
|
||||
"format": "uuid"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"lookup_fields": [],
|
||||
"historical": true,
|
||||
"relationship": false,
|
||||
"variations": [
|
||||
"entity",
|
||||
"invoice",
|
||||
"invoice_line"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "invoice",
|
||||
"hierarchy": [
|
||||
"entity",
|
||||
"invoice"
|
||||
],
|
||||
"fields": [
|
||||
"id",
|
||||
"type",
|
||||
"total",
|
||||
"archived",
|
||||
"created_at",
|
||||
"parent_id",
|
||||
"ancestors"
|
||||
],
|
||||
"grouped_fields": {
|
||||
"invoice": [
|
||||
"id",
|
||||
"type",
|
||||
"total"
|
||||
],
|
||||
"entity": [
|
||||
"id",
|
||||
"type",
|
||||
"archived",
|
||||
"created_at",
|
||||
"parent_id",
|
||||
"ancestors"
|
||||
]
|
||||
},
|
||||
"field_types": {
|
||||
"id": "uuid",
|
||||
"type": "text",
|
||||
"archived": "boolean",
|
||||
"created_at": "timestamptz",
|
||||
"parent_id": "uuid",
|
||||
"ancestors": "uuid[]",
|
||||
"total": "numeric"
|
||||
},
|
||||
"schemas": {
|
||||
"invoice": {
|
||||
"type": "entity",
|
||||
"properties": {
|
||||
"total": {
|
||||
"type": "number"
|
||||
},
|
||||
"lines": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "invoice_line"
|
||||
}
|
||||
},
|
||||
"first_line": {
|
||||
"type": "invoice_line"
|
||||
}
|
||||
}
|
||||
},
|
||||
"lite.invoice": {
|
||||
"type": "entity",
|
||||
"properties": {
|
||||
"total": {
|
||||
"type": "number"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"lookup_fields": [],
|
||||
"historical": true,
|
||||
"relationship": false,
|
||||
"variations": [
|
||||
"invoice"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "invoice_line",
|
||||
"hierarchy": [
|
||||
"entity",
|
||||
"invoice_line"
|
||||
],
|
||||
"fields": [
|
||||
"id",
|
||||
"type",
|
||||
"price",
|
||||
"archived",
|
||||
"created_at",
|
||||
"parent_id",
|
||||
"ancestors"
|
||||
],
|
||||
"grouped_fields": {
|
||||
"invoice_line": [
|
||||
"id",
|
||||
"type",
|
||||
"price"
|
||||
],
|
||||
"entity": [
|
||||
"id",
|
||||
"type",
|
||||
"archived",
|
||||
"created_at",
|
||||
"parent_id",
|
||||
"ancestors"
|
||||
]
|
||||
},
|
||||
"field_types": {
|
||||
"id": "uuid",
|
||||
"type": "text",
|
||||
"archived": "boolean",
|
||||
"created_at": "timestamptz",
|
||||
"parent_id": "uuid",
|
||||
"ancestors": "uuid[]",
|
||||
"price": "numeric"
|
||||
},
|
||||
"schemas": {
|
||||
"invoice_line": {
|
||||
"type": "entity",
|
||||
"properties": {
|
||||
"price": {
|
||||
"type": "number"
|
||||
},
|
||||
"invoice": {
|
||||
"type": "lite.invoice"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"lookup_fields": [],
|
||||
"historical": true,
|
||||
"relationship": false,
|
||||
"variations": [
|
||||
"invoice_line"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "An array include lists the children: line.parent_id = invoice.id",
|
||||
"action": "query",
|
||||
"schema_id": "invoice",
|
||||
"expect": {
|
||||
"success": true,
|
||||
"sql": [
|
||||
[
|
||||
"((SELECT jsonb_strip_nulls((",
|
||||
" SELECT jsonb_build_object(",
|
||||
" 'id', invoice_2.id,",
|
||||
" 'type', invoice_2.type,",
|
||||
" 'archived', entity_1.archived,",
|
||||
" 'created_at', entity_1.created_at,",
|
||||
" 'parent_id', entity_1.parent_id,",
|
||||
" 'ancestors', entity_1.ancestors,",
|
||||
" 'total', invoice_2.total,",
|
||||
" 'lines', (",
|
||||
" SELECT COALESCE(jsonb_agg(jsonb_build_object(",
|
||||
" 'id', invoice_line_4.id,",
|
||||
" 'type', invoice_line_4.type,",
|
||||
" 'archived', entity_3.archived,",
|
||||
" 'created_at', entity_3.created_at,",
|
||||
" 'parent_id', entity_3.parent_id,",
|
||||
" 'ancestors', entity_3.ancestors,",
|
||||
" 'price', invoice_line_4.price,",
|
||||
" 'invoice', (",
|
||||
" SELECT jsonb_build_object(",
|
||||
" 'id', invoice_6.id,",
|
||||
" 'type', invoice_6.type,",
|
||||
" 'archived', entity_5.archived,",
|
||||
" 'created_at', entity_5.created_at,",
|
||||
" 'parent_id', entity_5.parent_id,",
|
||||
" 'ancestors', entity_5.ancestors,",
|
||||
" 'total', invoice_6.total",
|
||||
" )",
|
||||
" FROM agreego.entity entity_5",
|
||||
" JOIN agreego.invoice invoice_6 ON invoice_6.id = entity_5.id",
|
||||
" WHERE",
|
||||
" NOT entity_5.archived",
|
||||
" AND entity_3.parent_id = entity_5.id",
|
||||
" )",
|
||||
" )), '[]'::jsonb)",
|
||||
" FROM agreego.entity entity_3",
|
||||
" JOIN agreego.invoice_line invoice_line_4 ON invoice_line_4.id = entity_3.id",
|
||||
" WHERE",
|
||||
" NOT entity_3.archived",
|
||||
" AND entity_3.parent_id = entity_1.id",
|
||||
" ),",
|
||||
" 'first_line', (",
|
||||
" SELECT jsonb_build_object(",
|
||||
" 'id', invoice_line_8.id,",
|
||||
" 'type', invoice_line_8.type,",
|
||||
" 'archived', entity_7.archived,",
|
||||
" 'created_at', entity_7.created_at,",
|
||||
" 'parent_id', entity_7.parent_id,",
|
||||
" 'ancestors', entity_7.ancestors,",
|
||||
" 'price', invoice_line_8.price,",
|
||||
" 'invoice', (",
|
||||
" SELECT jsonb_build_object(",
|
||||
" 'id', invoice_10.id,",
|
||||
" 'type', invoice_10.type,",
|
||||
" 'archived', entity_9.archived,",
|
||||
" 'created_at', entity_9.created_at,",
|
||||
" 'parent_id', entity_9.parent_id,",
|
||||
" 'ancestors', entity_9.ancestors,",
|
||||
" 'total', invoice_10.total",
|
||||
" )",
|
||||
" FROM agreego.entity entity_9",
|
||||
" JOIN agreego.invoice invoice_10 ON invoice_10.id = entity_9.id",
|
||||
" WHERE",
|
||||
" NOT entity_9.archived",
|
||||
" AND entity_7.parent_id = entity_9.id",
|
||||
" )",
|
||||
" )",
|
||||
" FROM agreego.entity entity_7",
|
||||
" JOIN agreego.invoice_line invoice_line_8 ON invoice_line_8.id = entity_7.id",
|
||||
" WHERE",
|
||||
" NOT entity_7.archived",
|
||||
" AND entity_1.parent_id = entity_7.id",
|
||||
" )",
|
||||
" )",
|
||||
" FROM agreego.entity entity_1",
|
||||
" JOIN agreego.invoice invoice_2 ON invoice_2.id = entity_1.id",
|
||||
" WHERE",
|
||||
" NOT entity_1.archived",
|
||||
"))))"
|
||||
]
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"description": "A scalar include reaches the parent: line.parent_id = invoice.id, read from the line",
|
||||
"action": "query",
|
||||
"schema_id": "invoice_line",
|
||||
"expect": {
|
||||
"success": true,
|
||||
"sql": [
|
||||
[
|
||||
"((SELECT jsonb_strip_nulls((",
|
||||
" SELECT jsonb_build_object(",
|
||||
" 'id', invoice_line_2.id,",
|
||||
" 'type', invoice_line_2.type,",
|
||||
" 'archived', entity_1.archived,",
|
||||
" 'created_at', entity_1.created_at,",
|
||||
" 'parent_id', entity_1.parent_id,",
|
||||
" 'ancestors', entity_1.ancestors,",
|
||||
" 'price', invoice_line_2.price,",
|
||||
" 'invoice', (",
|
||||
" SELECT jsonb_build_object(",
|
||||
" 'id', invoice_4.id,",
|
||||
" 'type', invoice_4.type,",
|
||||
" 'archived', entity_3.archived,",
|
||||
" 'created_at', entity_3.created_at,",
|
||||
" 'parent_id', entity_3.parent_id,",
|
||||
" 'ancestors', entity_3.ancestors,",
|
||||
" 'total', invoice_4.total",
|
||||
" )",
|
||||
" FROM agreego.entity entity_3",
|
||||
" JOIN agreego.invoice invoice_4 ON invoice_4.id = entity_3.id",
|
||||
" WHERE",
|
||||
" NOT entity_3.archived",
|
||||
" AND entity_1.parent_id = entity_3.id",
|
||||
" )",
|
||||
" )",
|
||||
" FROM agreego.entity entity_1",
|
||||
" JOIN agreego.invoice_line invoice_line_2 ON invoice_line_2.id = entity_1.id",
|
||||
" WHERE",
|
||||
" NOT entity_1.archived",
|
||||
"))))"
|
||||
]
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
@ -1246,8 +1246,7 @@
|
||||
" )",
|
||||
" FROM agreego.entity entity_1",
|
||||
" WHERE",
|
||||
" NOT entity_1.archived",
|
||||
" AND entity_1.archived = ($1 #>> '{}')::BOOLEAN",
|
||||
" entity_1.archived = ($1 #>> '{}')::BOOLEAN",
|
||||
" AND entity_1.archived <> ($2 #>> '{}')::BOOLEAN",
|
||||
" AND entity_1.created_at = ($3 #>> '{}')::TIMESTAMPTZ",
|
||||
" AND entity_1.created_at > ($4 #>> '{}')::TIMESTAMPTZ",
|
||||
@ -1718,8 +1717,7 @@
|
||||
" JOIN agreego.organization organization_2 ON organization_2.id = entity_1.id",
|
||||
" JOIN agreego.person person_3 ON person_3.id = organization_2.id",
|
||||
" WHERE",
|
||||
" NOT entity_1.archived",
|
||||
" AND person_3.age = ($1 #>> '{}')::NUMERIC",
|
||||
" person_3.age = ($1 #>> '{}')::NUMERIC",
|
||||
" AND person_3.age > ($2 #>> '{}')::NUMERIC",
|
||||
" AND person_3.age >= ($3 #>> '{}')::NUMERIC",
|
||||
" AND person_3.age < ($4 #>> '{}')::NUMERIC",
|
||||
@ -2702,4 +2700,4 @@
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
]
|
||||
|
||||
@ -13,7 +13,8 @@ pub struct MockState {
|
||||
pub query_responses: Vec<Result<Value, String>>,
|
||||
pub execute_responses: Vec<Result<(), String>>,
|
||||
pub mocks: Vec<Value>,
|
||||
pub punc_external: bool,
|
||||
pub cue_created_by: Option<String>,
|
||||
pub cue_external: bool,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@ -24,12 +25,12 @@ impl MockState {
|
||||
query_responses: Default::default(),
|
||||
execute_responses: Default::default(),
|
||||
mocks: Default::default(),
|
||||
punc_external: false,
|
||||
cue_created_by: Some("00000000-0000-0000-0000-000000000000".to_string()),
|
||||
cue_external: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
pub static MOCK_STATE: RefCell<MockState> = RefCell::new(MockState::new());
|
||||
@ -80,16 +81,22 @@ impl DatabaseExecutor for MockExecutor {
|
||||
})
|
||||
}
|
||||
|
||||
fn auth_user_id(&self) -> Result<String, String> {
|
||||
Ok("00000000-0000-0000-0000-000000000000".to_string())
|
||||
fn cue_created_by(&self) -> Result<String, String> {
|
||||
MOCK_STATE.with(|state| {
|
||||
state
|
||||
.borrow()
|
||||
.cue_created_by
|
||||
.clone()
|
||||
.ok_or_else(|| "Missing cue.created_by in session context".to_string())
|
||||
})
|
||||
}
|
||||
|
||||
fn timestamp(&self) -> Result<String, String> {
|
||||
Ok("2026-03-10T00:00:00Z".to_string())
|
||||
}
|
||||
|
||||
fn punc_external(&self) -> Result<bool, String> {
|
||||
Ok(MOCK_STATE.with(|state| state.borrow().punc_external))
|
||||
fn cue_external(&self) -> Result<bool, String> {
|
||||
Ok(MOCK_STATE.with(|state| state.borrow().cue_external))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@ -112,21 +119,27 @@ impl DatabaseExecutor for MockExecutor {
|
||||
s.query_responses.clear();
|
||||
s.execute_responses.clear();
|
||||
s.mocks.clear();
|
||||
s.punc_external = false;
|
||||
s.cue_created_by = Some("00000000-0000-0000-0000-00000000000".to_string());
|
||||
s.cue_external = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
impl MockExecutor {
|
||||
pub fn set_punc_external(&self, external: bool) {
|
||||
pub fn set_cue_external(&self, external: bool) {
|
||||
MOCK_STATE.with(|state| {
|
||||
state.borrow_mut().punc_external = external;
|
||||
state.borrow_mut().cue_external = external;
|
||||
});
|
||||
}
|
||||
|
||||
pub fn set_cue_created_by(&self, created_by: Option<String>) {
|
||||
MOCK_STATE.with(|state| {
|
||||
state.borrow_mut().cue_created_by = created_by;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#[cfg(test)]
|
||||
fn parse_and_match_mocks(sql: &str, mocks: &[Value]) -> Option<Vec<Value>> {
|
||||
let sql_upper = sql.to_uppercase();
|
||||
@ -155,7 +168,8 @@ fn parse_and_match_mocks(sql: &str, mocks: &[Value]) -> Option<Vec<Value>> {
|
||||
let q_upper = query.to_uppercase();
|
||||
|
||||
// Check if mock type matches the table or any joined tables in this query
|
||||
let table_regex = Regex::new(r#"(?i)\s+(?:FROM|JOIN)\s+(?:[a-zA-Z_]\w*\.)?"?([a-zA-Z_]\w*)"?"#).ok()?;
|
||||
let table_regex =
|
||||
Regex::new(r#"(?i)\s+(?:FROM|JOIN)\s+(?:[a-zA-Z_]\w*\.)?"?([a-zA-Z_]\w*)"?"#).ok()?;
|
||||
let tables: Vec<String> = table_regex
|
||||
.captures_iter(query)
|
||||
.filter_map(|c| c.get(1).map(|m| m.as_str().to_string()))
|
||||
@ -174,7 +188,9 @@ fn parse_and_match_mocks(sql: &str, mocks: &[Value]) -> Option<Vec<Value>> {
|
||||
where_end = limit_idx;
|
||||
}
|
||||
}
|
||||
where_clause = query[where_idx + 7..where_end].trim_end_matches(')').to_string();
|
||||
where_clause = query[where_idx + 7..where_end]
|
||||
.trim_end_matches(')')
|
||||
.to_string();
|
||||
}
|
||||
|
||||
if where_clause.is_empty() {
|
||||
|
||||
@ -14,14 +14,14 @@ pub trait DatabaseExecutor: Send + Sync {
|
||||
/// Executes an operation (INSERT, UPDATE, DELETE, or pg_notify) that does not return rows.
|
||||
fn execute(&self, sql: &str, args: Option<Vec<Value>>) -> Result<(), String>;
|
||||
|
||||
/// Returns the current authenticated user's ID
|
||||
fn auth_user_id(&self) -> Result<String, String>;
|
||||
/// Returns the current authenticated user's ID (from cue.created_by)
|
||||
fn cue_created_by(&self) -> Result<String, String>;
|
||||
|
||||
/// Returns the current transaction timestamp
|
||||
fn timestamp(&self) -> Result<String, String>;
|
||||
|
||||
/// Returns true if the current execution context is marked as an external client API cue (punc.external = true)
|
||||
fn punc_external(&self) -> Result<bool, String>;
|
||||
/// Returns true if the current execution context is marked as an external client API cue (cue.external = true)
|
||||
fn cue_external(&self) -> Result<bool, String>;
|
||||
|
||||
#[cfg(test)]
|
||||
fn get_queries(&self) -> Vec<String>;
|
||||
|
||||
@ -113,12 +113,12 @@ impl DatabaseExecutor for SpiExecutor {
|
||||
})
|
||||
}
|
||||
|
||||
fn auth_user_id(&self) -> Result<String, String> {
|
||||
fn cue_created_by(&self) -> Result<String, String> {
|
||||
self.transact(|| {
|
||||
Spi::connect(|client| {
|
||||
let mut tup_table = client
|
||||
.select(
|
||||
"SELECT COALESCE(current_setting('auth.user_id', true), 'ffffffff-ffff-ffff-ffff-ffffffffffff')",
|
||||
"SELECT NULLIF(current_setting('punc.cue', true), '')::jsonb->>'created_by'",
|
||||
None,
|
||||
&[],
|
||||
)
|
||||
@ -126,10 +126,10 @@ impl DatabaseExecutor for SpiExecutor {
|
||||
|
||||
let row = tup_table
|
||||
.next()
|
||||
.ok_or("No user id setting returned from context".to_string())?;
|
||||
.ok_or("No cue setting returned from context".to_string())?;
|
||||
let user_id: Option<String> = row.get(1).map_err(|e| e.to_string())?;
|
||||
|
||||
user_id.ok_or("Missing user_id".to_string())
|
||||
user_id.ok_or("Missing cue.created_by in session context".to_string())
|
||||
})
|
||||
})
|
||||
}
|
||||
@ -151,12 +151,12 @@ impl DatabaseExecutor for SpiExecutor {
|
||||
})
|
||||
}
|
||||
|
||||
fn punc_external(&self) -> Result<bool, String> {
|
||||
fn cue_external(&self) -> Result<bool, String> {
|
||||
self.transact(|| {
|
||||
Spi::connect(|client| {
|
||||
let mut tup_table = client
|
||||
.select(
|
||||
"SELECT COALESCE(current_setting('punc.external', true), 'false')::boolean",
|
||||
"SELECT COALESCE((NULLIF(current_setting('punc.cue', true), '')::jsonb->>'external')::boolean, false)",
|
||||
None,
|
||||
&[],
|
||||
)
|
||||
@ -172,4 +172,3 @@ impl DatabaseExecutor for SpiExecutor {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -232,9 +232,9 @@ impl Database {
|
||||
self.executor.execute(sql, args)
|
||||
}
|
||||
|
||||
/// Returns the current authenticated user's ID
|
||||
pub fn auth_user_id(&self) -> Result<String, String> {
|
||||
self.executor.auth_user_id()
|
||||
/// Returns the current authenticated user's ID (from cue.created_by)
|
||||
pub fn cue_created_by(&self) -> Result<String, String> {
|
||||
self.executor.cue_created_by()
|
||||
}
|
||||
|
||||
/// Returns the current transaction timestamp
|
||||
@ -242,6 +242,11 @@ impl Database {
|
||||
self.executor.timestamp()
|
||||
}
|
||||
|
||||
/// Returns true if the current execution context is marked as an external client API cue (cue.external = true)
|
||||
pub fn cue_external(&self) -> Result<bool, String> {
|
||||
self.executor.cue_external()
|
||||
}
|
||||
|
||||
pub fn compile(&mut self, errors: &mut Vec<crate::drop::Error>) {
|
||||
// Phase 1: Registration
|
||||
self.collect_schemas(errors);
|
||||
@ -495,6 +500,14 @@ impl Database {
|
||||
let is_reverse = p_def.hierarchy.contains(&rel.destination_type)
|
||||
&& c_def.hierarchy.contains(&rel.source_type);
|
||||
|
||||
// A self-referential edge on a shared ancestor table (entity.parent_id -> entity) matches
|
||||
// both ways for every type pair, so cardinality decides: an array lists the children
|
||||
// (reverse), a scalar reaches the parent (forward). A single child through this edge is
|
||||
// declared as a one-element array, never as a scalar.
|
||||
if is_forward && is_reverse {
|
||||
is_forward = !is_array;
|
||||
}
|
||||
|
||||
// Structural Cardinality Filtration:
|
||||
// If the schema requires a collection (Array), it is mathematically impossible for a pure
|
||||
// Forward scalar edge (where the parent holds exactly one UUID pointer) to fulfill a One-to-Many request.
|
||||
|
||||
@ -351,8 +351,8 @@ impl Merger {
|
||||
current_org_id = parent_org_id.clone();
|
||||
}
|
||||
|
||||
let user_id = self.db.auth_user_id().map_err(|e| Error {
|
||||
code: "AUTH_USER_FAILED".to_string(),
|
||||
let user_id = self.db.cue_created_by().map_err(|e| Error {
|
||||
code: "CUE_CREATED_BY_FAILED".to_string(),
|
||||
values: Some(IndexMap::from([("error".to_string(), e.clone())])),
|
||||
details: ErrorDetails {
|
||||
cause: Some(e),
|
||||
|
||||
@ -578,8 +578,20 @@ impl<'a> Compiler<'a> {
|
||||
let mut where_clauses = Vec::new();
|
||||
|
||||
// Dynamically apply the 'active-only' default ONLY if the client
|
||||
// didn't explicitly request to filter on 'archived' themselves!
|
||||
let has_archived_override = self.filter_keys.iter().any(|k| k == "archived");
|
||||
// didn't explicitly request to filter on 'archived' themselves — for THIS node.
|
||||
// Keys arrive as "path/field:$op" (extract_filters), so match this node's own archived
|
||||
// path, never the bare name: compared to "archived" alone it never matched (an explicit
|
||||
// archived filter could not return archived rows), and matched on any key it would lift
|
||||
// the default from every nested include the filter never mentioned.
|
||||
let archived_path = if node.ast_path.is_empty() {
|
||||
"archived".to_string()
|
||||
} else {
|
||||
format!("{}/archived", node.ast_path)
|
||||
};
|
||||
let has_archived_override = self
|
||||
.filter_keys
|
||||
.iter()
|
||||
.any(|k| k.split(':').next().unwrap_or(k) == archived_path);
|
||||
|
||||
if !has_archived_override {
|
||||
where_clauses.push(format!("NOT {}.archived", entity_alias));
|
||||
|
||||
@ -3803,6 +3803,18 @@ fn test_required_5_0() {
|
||||
crate::tests::runner::run_test_case(&path, 5, 0).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_composition_0_0() {
|
||||
let path = format!("{}/fixtures/composition.json", env!("CARGO_MANIFEST_DIR"));
|
||||
crate::tests::runner::run_test_case(&path, 0, 0).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_composition_0_1() {
|
||||
let path = format!("{}/fixtures/composition.json", env!("CARGO_MANIFEST_DIR"));
|
||||
crate::tests::runner::run_test_case(&path, 0, 1).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_multiple_of_0_0() {
|
||||
let path = format!("{}/fixtures/multipleOf.json", env!("CARGO_MANIFEST_DIR"));
|
||||
|
||||
@ -180,7 +180,7 @@ impl<'a> ValidationContext<'a> {
|
||||
}
|
||||
|
||||
if !self.response {
|
||||
let is_external = self.db.executor.punc_external().unwrap_or(false);
|
||||
let is_external = self.db.cue_external().unwrap_or(false);
|
||||
if let Some(compiled_props) = self.schema.compiled_properties.get() {
|
||||
for (key, sub_schema) in compiled_props {
|
||||
if sub_schema.is_immutable(is_external) && obj.contains_key(key) {
|
||||
|
||||
Reference in New Issue
Block a user