Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

test(soup): dynamic filters (#174)

Sean Aye68a63493d777
diff --git a/rust/cloud-storage/filter_ast/Cargo.toml b/rust/cloud-storage/filter_ast/Cargo.toml
index f31d5a65d6..e57c3464a8 100644
--- a/rust/cloud-storage/filter_ast/Cargo.toml
+++ b/rust/cloud-storage/filter_ast/Cargo.toml
@@ -4,6 +4,7 @@ name = "filter_ast"
publish = false
version = "0.1.0"
+
[dependencies]
recursion = { workspace = true }
serde = { workspace = true }
diff --git a/rust/cloud-storage/item_filters/Cargo.toml b/rust/cloud-storage/item_filters/Cargo.toml
index c2ac5ed5eb..08946501d1 100644
--- a/rust/cloud-storage/item_filters/Cargo.toml
+++ b/rust/cloud-storage/item_filters/Cargo.toml
@@ -4,6 +4,9 @@ name = "item_filters"
publish = false
version = "0.1.0"
+[features]
+mock = []
+
[dependencies]
chrono = { workspace = true }
filter_ast = { path = "../filter_ast" }
diff --git a/rust/cloud-storage/item_filters/src/ast.rs b/rust/cloud-storage/item_filters/src/ast.rs
index 00b176a86d..1d2685cd5d 100644
--- a/rust/cloud-storage/item_filters/src/ast.rs
+++ b/rust/cloud-storage/item_filters/src/ast.rs
@@ -92,6 +92,18 @@ impl EntityFilterAst {
}),
}))
}
+
+ /// mock function to create the an empty ast
+ #[cfg(feature = "mock")]
+ pub fn mock_empty() -> Self {
+ Self {
+ inner: Arc::new(EntityFilterInner {
+ document_filter: None,
+ project_filter: None,
+ chat_filter: None,
+ }),
+ }
+ }
}
impl IsEmpty for EntityFilterAst {
diff --git a/rust/cloud-storage/macro_db_client/fixtures/entity_filter_tests.sql b/rust/cloud-storage/macro_db_client/fixtures/entity_filter_tests.sql
new file mode 100644
index 0000000000..8dc1af926b
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/fixtures/entity_filter_tests.sql
@@ -0,0 +1,101 @@
+-- Disable foreign key constraints temporarily for easier setup
+SET session_replication_role = 'replica';
+
+---------------------------------
+-- BASE SETUP: USER & ORG
+---------------------------------
+
+-- Create Organization (needed for User foreign key)
+INSERT INTO public."Organization" ("id", "name", "status")
+VALUES (1, 'Test Organization', 'PILOT')
+ON CONFLICT DO NOTHING;
+
+-- Insert user
+INSERT INTO public."User" ("id", "email", "stripeCustomerId", "organizationId")
+VALUES ('macro|[email protected]', '[email protected]', 'stripe_id_1', 1)
+ON CONFLICT DO NOTHING;
+
+---------------------------------
+-- PROJECT HIERARCHY SETUP with UUIDs
+---------------------------------
+
+INSERT INTO public."Project" ("id", "name", "userId", "parentId", "createdAt", "updatedAt")
+VALUES
+ ('11111111-1111-1111-1111-111111111111', 'Project A', 'macro|[email protected]', NULL, '2023-01-01 10:00:00', '2023-01-01 10:00:00'),
+ ('22222222-2222-2222-2222-222222222222', 'Project B', 'macro|[email protected]', '11111111-1111-1111-1111-111111111111', '2023-01-01 11:00:00', '2023-01-01 11:00:00'),
+ ('33333333-3333-3333-3333-333333333333', 'Project C', 'macro|[email protected]', '22222222-2222-2222-2222-222222222222', '2023-01-01 12:00:00', '2023-01-01 12:00:00'),
+ ('44444444-4444-4444-4444-444444444444', 'Project D', 'macro|[email protected]', NULL, '2023-01-02 10:00:00', '2023-01-02 10:00:00'),
+ ('55555555-5555-5555-5555-555555555555', 'Project Isolated', 'macro|[email protected]', NULL, '2023-01-03 10:00:00', '2023-01-03 10:00:00');
+
+---------------------------------------------------
+-- DOCUMENTS, CHATS, AND THEIR DEPENDENCIES
+---------------------------------------------------
+
+-- Document Families
+INSERT INTO public."DocumentFamily" ("id", "rootDocumentId")
+VALUES
+ (1, 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa'),
+ (2, 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb'),
+ (3, 'cccccccc-cccc-cccc-cccc-cccccccccccc'),
+ (4, 'dddddddd-dddd-dddd-dddd-dddddddddddd'),
+ (5, 'eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee'),
+ (6, 'ffffffff-ffff-ffff-ffff-ffffffffffff');
+
+-- Documents with UUID IDs
+INSERT INTO public."Document" ("id", "name", "owner", "projectId", "documentFamilyId", "fileType", "createdAt", "updatedAt")
+VALUES
+ ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'Document in A', 'macro|[email protected]', '11111111-1111-1111-1111-111111111111', 1, 'pdf', '2023-01-05 10:00:00', '2023-01-05 10:00:00'),
+ ('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'Document in B', 'macro|[email protected]', '22222222-2222-2222-2222-222222222222', 2, 'pdf', '2023-01-05 11:00:00', '2023-01-05 11:00:00'),
+ ('cccccccc-cccc-cccc-cccc-cccccccccccc', 'Document in C', 'macro|[email protected]', '33333333-3333-3333-3333-333333333333', 3, 'md', '2023-01-05 12:00:00', '2023-01-05 12:00:00'),
+ ('dddddddd-dddd-dddd-dddd-dddddddddddd', 'Document in D', 'macro|[email protected]', '44444444-4444-4444-4444-444444444444', 4, 'pdf', '2023-01-05 13:00:00', '2023-01-05 13:00:00'),
+ ('eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', 'Standalone Document', 'macro|[email protected]', NULL, 5, 'pdf', '2023-01-05 14:00:00', '2023-01-05 14:00:00'),
+ ('ffffffff-ffff-ffff-ffff-ffffffffffff', 'Isolated Document', 'macro|[email protected]', '55555555-5555-5555-5555-555555555555', 6, 'pdf', '2023-01-05 15:00:00', '2023-01-05 15:00:00');
+
+-- Document Instances
+INSERT INTO public."DocumentInstance" ("id", "documentId", "sha", "createdAt", "updatedAt")
+VALUES
+ (1, 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'sha_A', '2023-01-05 10:00:00', '2023-01-05 10:00:00'),
+ (2, 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'sha_B', '2023-01-05 11:00:00', '2023-01-05 11:00:00'),
+ (3, 'cccccccc-cccc-cccc-cccc-cccccccccccc', 'sha_C', '2023-01-05 12:00:00', '2023-01-05 12:00:00'),
+ (4, 'dddddddd-dddd-dddd-dddd-dddddddddddd', 'sha_D', '2023-01-05 13:00:00', '2023-01-05 13:00:00'),
+ (5, 'eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', 'sha_standalone', '2023-01-05 14:00:00', '2023-01-05 14:00:00'),
+ (6, 'ffffffff-ffff-ffff-ffff-ffffffffffff', 'sha_isolated', '2023-01-05 15:00:00', '2023-01-05 15:00:00');
+
+-- Chats with UUID IDs
+INSERT INTO public."Chat" ("id", "name", "userId", "projectId", "createdAt", "updatedAt")
+VALUES
+ ('a1a1a1a1-a1a1-a1a1-a1a1-a1a1a1a1a1a1', 'Chat in A', 'macro|[email protected]', '11111111-1111-1111-1111-111111111111', '2023-01-06 10:00:00', '2023-01-06 10:00:00'),
+ ('b2b2b2b2-b2b2-b2b2-b2b2-b2b2b2b2b2b2', 'Chat in B', 'macro|[email protected]', '22222222-2222-2222-2222-222222222222', '2023-01-06 11:00:00', '2023-01-06 11:00:00'),
+ ('c3c3c3c3-c3c3-c3c3-c3c3-c3c3c3c3c3c3', 'Chat in C', 'macro|[email protected]', '33333333-3333-3333-3333-333333333333', '2023-01-06 12:00:00', '2023-01-06 12:00:00'),
+ ('d4d4d4d4-d4d4-d4d4-d4d4-d4d4d4d4d4d4', 'Standalone Chat', 'macro|[email protected]', NULL, '2023-01-06 13:00:00', '2023-01-06 13:00:00'),
+ ('e5e5e5e5-e5e5-e5e5-e5e5-e5e5e5e5e5e5', 'Isolated Chat', 'macro|[email protected]', '55555555-5555-5555-5555-555555555555', '2023-01-06 14:00:00', '2023-01-06 14:00:00');
+
+---------------------------------------------------
+-- USER ACCESS PERMISSIONS (UserItemAccess)
+---------------------------------------------------
+
+INSERT INTO public."UserItemAccess" ("id", "user_id", "item_id", "item_type", "access_level")
+VALUES
+-- User gets 'view' on project-A (gives access to A, B, C and their contents)
+(gen_random_uuid(), 'macro|[email protected]', '11111111-1111-1111-1111-111111111111', 'project', 'view'),
+
+-- Direct 'edit' on doc-in-B
+(gen_random_uuid(), 'macro|[email protected]', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'document', 'edit'),
+
+-- User gets 'owner' on project-D
+(gen_random_uuid(), 'macro|[email protected]', '44444444-4444-4444-4444-444444444444', 'project', 'owner'),
+
+-- Direct access to standalone items
+(gen_random_uuid(), 'macro|[email protected]', 'eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', 'document', 'owner'),
+(gen_random_uuid(), 'macro|[email protected]', 'd4d4d4d4-d4d4-d4d4-d4d4-d4d4d4d4d4d4', 'chat', 'owner');
+
+-- User history
+INSERT INTO public."UserHistory" ("userId", "itemId", "itemType", "createdAt", "updatedAt")
+VALUES
+ ('macro|[email protected]', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'document', '2024-01-01 00:00:00', '2024-01-10 10:00:00'),
+ ('macro|[email protected]', 'd4d4d4d4-d4d4-d4d4-d4d4-d4d4d4d4d4d4', 'chat', '2024-01-01 00:00:00', '2024-01-09 10:00:00'),
+ ('macro|[email protected]', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'document', '2024-01-01 00:00:00', '2024-01-08 10:00:00'),
+ ('macro|[email protected]', 'a1a1a1a1-a1a1-a1a1-a1a1-a1a1a1a1a1a1', 'chat', '2024-01-01 00:00:00', '2024-01-07 10:00:00');
+
+-- Re-enable foreign key constraints
+SET session_replication_role = 'origin';
diff --git a/rust/cloud-storage/models_soup/Cargo.toml b/rust/cloud-storage/models_soup/Cargo.toml
index 6e289c887e..321e2fac66 100644
--- a/rust/cloud-storage/models_soup/Cargo.toml
+++ b/rust/cloud-storage/models_soup/Cargo.toml
@@ -4,6 +4,9 @@ name = "models_soup"
publish = false
version = "0.1.0"
+[features]
+mock = []
+
[dependencies]
anyhow = { workspace = true }
chrono = { workspace = true }
diff --git a/rust/cloud-storage/models_soup/src/chat.rs b/rust/cloud-storage/models_soup/src/chat.rs
index 75e47c233d..3807765ec2 100644
--- a/rust/cloud-storage/models_soup/src/chat.rs
+++ b/rust/cloud-storage/models_soup/src/chat.rs
@@ -3,6 +3,7 @@ use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
#[derive(Serialize, Clone, Deserialize, Debug, ToSchema)]
+#[cfg_attr(feature = "mock", derive(PartialEq, Eq))]
#[serde(rename_all = "camelCase")]
pub struct SoupChat {
/// The chat uuid
diff --git a/rust/cloud-storage/models_soup/src/document.rs b/rust/cloud-storage/models_soup/src/document.rs
index cb11a3b0e4..61fee9a9a2 100644
--- a/rust/cloud-storage/models_soup/src/document.rs
+++ b/rust/cloud-storage/models_soup/src/document.rs
@@ -2,6 +2,7 @@ use chrono::Utc;
use utoipa::ToSchema;
#[derive(serde::Serialize, serde::Deserialize, Debug, ToSchema, Clone)]
+#[cfg_attr(feature = "mock", derive(PartialEq, Eq))]
#[serde(rename_all = "camelCase")]
pub struct SoupDocument {
/// The document id
diff --git a/rust/cloud-storage/models_soup/src/item.rs b/rust/cloud-storage/models_soup/src/item.rs
index 454085cf38..55daa16e05 100644
--- a/rust/cloud-storage/models_soup/src/item.rs
+++ b/rust/cloud-storage/models_soup/src/item.rs
@@ -18,6 +18,7 @@ pub enum SoupItemType {
}
#[derive(Deserialize, Clone, ToSchema, Debug)]
+#[cfg_attr(feature = "mock", derive(PartialEq, Eq))]
#[serde(untagged)]
#[schema(discriminator(property_name = "type", mapping(
("document" = "#/components/schemas/SoupDocument"),
diff --git a/rust/cloud-storage/models_soup/src/project.rs b/rust/cloud-storage/models_soup/src/project.rs
index 87351925ff..0acd70417d 100644
--- a/rust/cloud-storage/models_soup/src/project.rs
+++ b/rust/cloud-storage/models_soup/src/project.rs
@@ -3,6 +3,7 @@ use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
#[derive(Serialize, Clone, Deserialize, Debug, ToSchema)]
+#[cfg_attr(feature = "mock", derive(PartialEq, Eq))]
#[serde(rename_all = "camelCase")]
pub struct SoupProject {
/// The id of the project
diff --git a/rust/cloud-storage/soup/Cargo.toml b/rust/cloud-storage/soup/Cargo.toml
index 79f975dbc7..93b71d63ee 100644
--- a/rust/cloud-storage/soup/Cargo.toml
+++ b/rust/cloud-storage/soup/Cargo.toml
@@ -39,9 +39,11 @@ uuid = { workspace = true }
[dev-dependencies]
cool_asserts = "2"
+filter_ast = { path = "../filter_ast" }
frecency = { path = "../frecency", features = ["mock"] }
futures = { workspace = true }
http-body-util = { workspace = true }
+item_filters = { path = "../item_filters", features = ["mock"] }
macro_db_migrator = { path = "../macro_db_migrator" }
mockall = { workspace = true }
ordered-float = "5"
diff --git a/rust/cloud-storage/soup/src/outbound/pg_soup_repo.rs b/rust/cloud-storage/soup/src/outbound/pg_soup_repo.rs
index d8bc6630e7..90b77ebaf2 100644
--- a/rust/cloud-storage/soup/src/outbound/pg_soup_repo.rs
+++ b/rust/cloud-storage/soup/src/outbound/pg_soup_repo.rs
@@ -28,7 +28,7 @@ impl SoupRepo for PgSoupRepo {
) -> impl Future<Output = Result<Vec<SoupItem>, Self::Err>> + Send {
match req.cursor {
SimpleSortQuery::ItemsAndFrecencyFilter(_) => {
- Either::Left(Either::Left(Box::pin(async move { todo!() })))
+ Either::Left(Either::Left(not_implemented(req)))
}
SimpleSortQuery::ItemsFilter(ast) => Either::Left(Either::Right(
expanded::dynamic::expanded_dynamic_cursor_soup(
@@ -62,23 +62,26 @@ impl SoupRepo for PgSoupRepo {
req: SimpleSortRequest<'a>,
) -> impl Future<Output = Result<Vec<SoupItem>, Self::Err>> + Send {
match req.cursor {
- SimpleSortQuery::ItemsFilter(_) | SimpleSortQuery::ItemsAndFrecencyFilter(_) => todo!(),
- SimpleSortQuery::FilterFrecency(f) => {
- Either::Left(expanded::by_cursor::no_frecency_expanded_generic_soup(
+ SimpleSortQuery::ItemsFilter(_) => Either::Left(Either::Left(not_implemented(req))),
+ SimpleSortQuery::ItemsAndFrecencyFilter(_) => {
+ Either::Left(Either::Right(not_implemented(req)))
+ }
+ SimpleSortQuery::FilterFrecency(f) => Either::Right(Either::Left(
+ expanded::by_cursor::no_frecency_expanded_generic_soup(
&self.inner,
req.user_id,
req.limit,
f,
- ))
- }
- SimpleSortQuery::NoFilter(f) => {
- Either::Right(unexpanded::by_cursor::unexpanded_generic_cursor_soup(
+ ),
+ )),
+ SimpleSortQuery::NoFilter(f) => Either::Right(Either::Right(
+ unexpanded::by_cursor::unexpanded_generic_cursor_soup(
&self.inner,
req.user_id,
req.limit,
f,
- ))
- }
+ ),
+ )),
}
}
@@ -96,3 +99,10 @@ impl SoupRepo for PgSoupRepo {
unexpanded::by_ids::unexpanded_soup_by_ids(&self.inner, req.user_id, req.entities)
}
}
+
+#[tracing::instrument(err)]
+async fn not_implemented<Ok>(_req: SimpleSortRequest<'_>) -> Result<Ok, sqlx::Error> {
+ Err(sqlx::Error::InvalidArgument(
+ "Unexpanded soup ast filters are not yet supported".to_string(),
+ ))
+}
diff --git a/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/by_cursor.rs b/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/by_cursor.rs
index 8f9131b3ad..17e35954dd 100644
--- a/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/by_cursor.rs
+++ b/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/by_cursor.rs
@@ -179,7 +179,7 @@ r#"
ORDER BY "sort_ts!" DESC, "updated_at!" DESC
LIMIT $3
"#,
- user_id.as_ref(), // $1
+ user_id.as_ref(), // $1
sort_method_str, // $2
query_limit, // $3
cursor_timestamp, // $4
diff --git a/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/dynamic.rs b/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/dynamic.rs
index d707fdf0ab..6037a8cc36 100644
--- a/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/dynamic.rs
+++ b/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/dynamic.rs
@@ -58,17 +58,17 @@ static PREFIX: &str = r#"
static DOCUMENT_CLAUSE: &str = r#"
SELECT
- 'document' as "item_type!",
- d.id as "id!",
+ 'document' as "item_type",
+ d.id as "id",
CAST(COALESCE(di.id, db.id) as TEXT) as "document_version_id",
- d.owner as "user_id!",
- d.name as "name!",
+ d.owner as "user_id",
+ d.name as "name",
d."branchedFromId" as "branched_from_id",
d."branchedFromVersionId" as "branched_from_version_id",
d."documentFamilyId" as "document_family_id",
d."fileType" as "file_type",
- d."createdAt"::timestamptz as "created_at!",
- d."updatedAt"::timestamptz as "updated_at!",
+ d."createdAt"::timestamptz as "created_at",
+ d."updatedAt"::timestamptz as "updated_at",
d."projectId" as "project_id",
NULL as "is_persistent",
di.sha as "sha",
@@ -78,23 +78,23 @@ static DOCUMENT_CLAUSE: &str = r#"
WHEN 'viewed_at' THEN COALESCE(uh."updatedAt", '1970-01-01 00:00:00+00')
WHEN 'created_at' THEN d."createdAt"
ELSE d."updatedAt"
- END::timestamptz as "sort_ts!"
+ END::timestamptz as "sort_ts"
FROM "Document" d
INNER JOIN UserAccessibleItems uai ON uai.item_id = d.id AND uai.item_type = 'document'
-- This MUST be a LEFT JOIN to support all three sort methods
LEFT JOIN "UserHistory" uh ON uh."itemId" = d.id AND uh."itemType" = 'document' AND uh."userId" = $1
LEFT JOIN LATERAL (
- SELECT b.id
- FROM "DocumentBom" b
- WHERE b."documentId" = d.id
- ORDER BY b."createdAt" DESC
+ SELECT b.id
+ FROM "DocumentBom" b
+ WHERE b."documentId" = d.id
+ ORDER BY b."createdAt" DESC
LIMIT 1
) db ON true
LEFT JOIN LATERAL (
- SELECT i.id, i.sha
- FROM "DocumentInstance" i
- WHERE i."documentId" = d.id
- ORDER BY i."updatedAt" DESC
+ SELECT i.id, i.sha
+ FROM "DocumentInstance" i
+ WHERE i."documentId" = d.id
+ ORDER BY i."updatedAt" DESC
LIMIT 1
) di ON true
WHERE d."deletedAt" IS NULL
@@ -102,17 +102,17 @@ static DOCUMENT_CLAUSE: &str = r#"
static CHAT_CLAUSE: &str = r#"
SELECT
- 'chat' as "item_type!",
- c.id as "id!",
+ 'chat' as "item_type",
+ c.id as "id",
NULL as "document_version_id",
- c."userId" as "user_id!",
- c.name as "name!",
+ c."userId" as "user_id",
+ c.name as "name",
NULL as "branched_from_id",
NULL as "branched_from_version_id",
NULL as "document_family_id",
NULL as "file_type",
- c."createdAt"::timestamptz as "created_at!",
- c."updatedAt"::timestamptz as "updated_at!",
+ c."createdAt"::timestamptz as "created_at",
+ c."updatedAt"::timestamptz as "updated_at",
c."projectId" as "project_id",
c."isPersistent" as "is_persistent",
NULL as "sha",
@@ -122,7 +122,7 @@ static CHAT_CLAUSE: &str = r#"
WHEN 'viewed_at' THEN COALESCE(uh."updatedAt", '1970-01-01 00:00:00+00')
WHEN 'created_at' THEN c."createdAt"
ELSE c."updatedAt"
- END::timestamptz as "sort_ts!"
+ END::timestamptz as "sort_ts"
FROM "Chat" c
INNER JOIN UserAccessibleItems uai ON uai.item_id = c.id AND uai.item_type = 'chat'
LEFT JOIN "UserHistory" uh ON uh."itemId" = c.id AND uh."itemType" = 'chat' AND uh."userId" = $1
@@ -131,17 +131,17 @@ static CHAT_CLAUSE: &str = r#"
static PROJECT_CLAUSE: &str = r#"
SELECT
- 'project' as "item_type!",
- p.id as "id!",
+ 'project' as "item_type",
+ p.id as "id",
NULL as "document_version_id",
- p."userId" as "user_id!",
- p.name as "name!",
+ p."userId" as "user_id",
+ p.name as "name",
NULL as "branched_from_id",
NULL as "branched_from_version_id",
NULL as "document_family_id",
NULL as "file_type",
- p."createdAt"::timestamptz as "created_at!",
- p."updatedAt"::timestamptz as "updated_at!",
+ p."createdAt"::timestamptz as "created_at",
+ p."updatedAt"::timestamptz as "updated_at",
p."parentId" as "project_id",
NULL as "is_persistent",
NULL as "sha",
@@ -151,7 +151,7 @@ static PROJECT_CLAUSE: &str = r#"
WHEN 'viewed_at' THEN COALESCE(uh."updatedAt", '1970-01-01 00:00:00+00')
WHEN 'created_at' THEN p."createdAt"
ELSE p."updatedAt"
- END::timestamptz as "sort_ts!"
+ END::timestamptz as "sort_ts"
FROM "Project" p
INNER JOIN UserAccessibleItems uai
ON uai.item_id = p.id
@@ -168,15 +168,14 @@ static SUFFIX: &str = r#"
WHERE
($4::timestamptz IS NULL)
OR
- ("sort_ts!", "id!") < ($4, $5)
- ORDER BY "sort_ts!" DESC, "updated_at!" DESC
+ ("sort_ts", "id") < ($4, $5)
+ ORDER BY "sort_ts" DESC, "updated_at" DESC
LIMIT $3
"#;
-fn build_document_clause(ast: Option<&Expr<DocumentLiteral>>) -> QueryBuilder<'static, Postgres> {
- let mut res = sqlx::QueryBuilder::new(DOCUMENT_CLAUSE);
+fn build_document_filter(ast: Option<&Expr<DocumentLiteral>>) -> String {
let Some(expr) = ast else {
- return res;
+ return String::new();
};
let formatting = expr.collapse_frames(|frame| match frame {
filter_ast::ExprFrame::And(a, b) => format!("({a} AND {b})"),
@@ -191,15 +190,16 @@ fn build_document_clause(ast: Option<&Expr<DocumentLiteral>>) -> QueryBuilder<'s
}
filter_ast::ExprFrame::Literal(DocumentLiteral::Owner(o)) => format!("d.owner = '{o}'"),
});
- res.push(formatting);
-
- res
+ if formatting.is_empty() {
+ String::new()
+ } else {
+ format!(" AND {}", formatting)
+ }
}
-fn build_chat_clause(ast: Option<&Expr<ChatLiteral>>) -> QueryBuilder<'static, Postgres> {
- let mut res = sqlx::QueryBuilder::new(CHAT_CLAUSE);
+fn build_chat_filter(ast: Option<&Expr<ChatLiteral>>) -> String {
let Some(expr) = ast else {
- return res;
+ return String::new();
};
let formatting = expr.collapse_frames(|frame| match frame {
filter_ast::ExprFrame::And(a, b) => format!("({a} AND {b})"),
@@ -213,40 +213,59 @@ fn build_chat_clause(ast: Option<&Expr<ChatLiteral>>) -> QueryBuilder<'static, P
filter_ast::ExprFrame::Literal(ChatLiteral::ChatId(i)) => format!("c.id = '{i}'"),
filter_ast::ExprFrame::Literal(ChatLiteral::Owner(o)) => format!("c.owner = '{o}'"),
});
- res.push(formatting);
-
- res
+ if formatting.is_empty() {
+ String::new()
+ } else {
+ format!(" AND {}", formatting)
+ }
}
-fn build_project_clause(ast: Option<&Expr<ProjectLiteral>>) -> QueryBuilder<'static, Postgres> {
- let mut res = sqlx::QueryBuilder::new(PROJECT_CLAUSE);
+fn build_project_filter(ast: Option<&Expr<ProjectLiteral>>) -> String {
let Some(expr) = ast else {
- return res;
+ return String::new();
};
let formatting = expr.collapse_frames(|frame| match frame {
filter_ast::ExprFrame::And(a, b) => format!("({a} AND {b})"),
filter_ast::ExprFrame::Or(a, b) => format!("({a} OR {b})"),
filter_ast::ExprFrame::Not(a) => format!("(NOT {a})"),
filter_ast::ExprFrame::Literal(ProjectLiteral::ProjectId(p)) => {
- format!("c.id = '{p}'")
+ format!("p.id = '{p}'")
}
- filter_ast::ExprFrame::Literal(ProjectLiteral::Owner(o)) => format!("c.owner = '{o}'"),
+ filter_ast::ExprFrame::Literal(ProjectLiteral::Owner(o)) => format!("p.owner = '{o}'"),
});
- res.push(formatting);
-
- res
+ if formatting.is_empty() {
+ String::new()
+ } else {
+ format!(" AND {}", formatting)
+ }
}
fn build_query(filter_ast: &EntityFilterAst) -> QueryBuilder<'_, Postgres> {
let mut builder = sqlx::QueryBuilder::new(PREFIX);
- builder
- .push("Combined AS (")
- .separated("UNION_ALL")
- .push(build_document_clause(filter_ast.inner.document_filter.as_ref()).sql())
- .push(build_chat_clause(filter_ast.inner.chat_filter.as_ref()).sql())
- .push(build_project_clause(filter_ast.inner.project_filter.as_ref()).sql())
- .push_unseparated(") ")
- .push(SUFFIX);
+ builder.push("Combined AS (");
+
+ // Document clause
+ builder.push(DOCUMENT_CLAUSE);
+ builder.push(build_document_filter(
+ filter_ast.inner.document_filter.as_ref(),
+ ));
+
+ builder.push(" UNION ALL ");
+
+ // Chat clause
+ builder.push(CHAT_CLAUSE);
+ builder.push(build_chat_filter(filter_ast.inner.chat_filter.as_ref()));
+
+ builder.push(" UNION ALL ");
+
+ // Project clause
+ builder.push(PROJECT_CLAUSE);
+ builder.push(build_project_filter(
+ filter_ast.inner.project_filter.as_ref(),
+ ));
+
+ builder.push(") ");
+ builder.push(SUFFIX);
builder
}
@@ -397,6 +416,7 @@ pub async fn expanded_dynamic_cursor_soup(
let query_limit = limit as i64;
let sort_method_str = cursor.sort_method().to_string();
let (cursor_id, cursor_timestamp) = cursor.vals();
+
build_query(cursor.filter())
.build()
.bind(user_id.as_ref())
diff --git a/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/tests.rs b/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/tests.rs
index 172fe195eb..17744d04af 100644
--- a/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/tests.rs
+++ b/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/tests.rs
@@ -1,6 +1,7 @@
use crate::outbound::pg_soup_repo::expanded::{
by_cursor::{expanded_generic_cursor_soup, no_frecency_expanded_generic_soup},
by_ids::expanded_soup_by_ids,
+ dynamic::expanded_dynamic_cursor_soup,
};
use item_filters::ast::EntityFilterAst;
use macro_db_migrator::MACRO_DB_MIGRATIONS;
@@ -8,7 +9,7 @@ use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
use model_entity::EntityType;
use models_pagination::{Frecency, PaginateOn, Query, SimpleSortMethod};
use models_soup::item::SoupItem;
-use sqlx::{Pool, Postgres};
+use sqlx::{PgPool, Pool, Postgres};
use std::collections::HashSet;
// 2 items have no viewing history, so they should be last in the response when sorting by viewed_at
@@ -23,7 +24,7 @@ async fn test_viewed_at_orders_nulls_last(pool: Pool<Postgres>) -> anyhow::Resul
let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
let items = expanded_generic_cursor_soup(
&pool,
- user_id,
+ user_id.copied(),
20,
Query::Sort(SimpleSortMethod::ViewedAt, ()),
)
@@ -169,7 +170,7 @@ async fn test_get_user_items_expanded_cursor(pool: Pool<Postgres>) -> anyhow::Re
let items = expanded_generic_cursor_soup(
&pool,
- user_id,
+ user_id.copied(),
1,
Query::new(
result.next_cursor.map(|s| s.decode_json().unwrap()),
@@ -280,7 +281,7 @@ async fn test_expanded_generic_sorting_methods(pool: Pool<Postgres>) -> anyhow::
{
let items = expanded_generic_cursor_soup(
&pool,
- user_id,
+ user_id.copied(),
10,
Query::Sort(SimpleSortMethod::CreatedAt, ()),
)
@@ -414,7 +415,7 @@ async fn test_no_frecency_expanded_filters_out_frecency_items(
// Test with UpdatedAt sort - should return only items without frecency
let items = no_frecency_expanded_generic_soup(
&pool,
- user_id,
+ user_id.copied(),
20,
Query::Sort(SimpleSortMethod::UpdatedAt, Frecency),
)
@@ -552,7 +553,7 @@ async fn test_no_frecency_expanded_sorting_methods(pool: Pool<Postgres>) -> anyh
{
let items = no_frecency_expanded_generic_soup(
&pool,
- user_id,
+ user_id.copied(),
20,
Query::Sort(SimpleSortMethod::ViewedAt, Frecency),
)
@@ -628,7 +629,7 @@ async fn test_no_frecency_expanded_cursor_pagination(pool: Pool<Postgres>) -> an
// Get second page using cursor
let items = no_frecency_expanded_generic_soup(
&pool,
- user_id,
+ user_id.copied(),
2,
Query::new(
result.next_cursor.map(|s| s.decode_json().unwrap()),
@@ -663,3 +664,1226 @@ async fn test_no_frecency_expanded_cursor_pagination(pool: Pool<Postgres>) -> an
Ok(())
}
+
+#[sqlx::test(
+ fixtures(
+ path = "../../../../../macro_db_client/fixtures",
+ scripts("mixed_items_expanded")
+ ),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn empty_ast_returns_same_as_static_query(db: PgPool) {
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let ast_res = expanded_dynamic_cursor_soup(
+ &db,
+ user_id.clone(),
+ 20,
+ Query::Sort(SimpleSortMethod::CreatedAt, EntityFilterAst::mock_empty()),
+ )
+ .await
+ .unwrap();
+ let static_res = expanded_generic_cursor_soup(
+ &db,
+ user_id.copied(),
+ 20,
+ Query::Sort(SimpleSortMethod::CreatedAt, ()),
+ )
+ .await
+ .unwrap();
+
+ // Compare the IDs since SoupItem doesn't implement PartialEq
+ let ast_ids: Vec<String> = ast_res
+ .iter()
+ .map(|item| match item {
+ SoupItem::Chat(c) => c.id.clone(),
+ SoupItem::Document(d) => d.id.clone(),
+ SoupItem::Project(p) => p.id.clone(),
+ })
+ .collect();
+
+ let static_ids: Vec<String> = static_res
+ .iter()
+ .map(|item| match item {
+ SoupItem::Chat(c) => c.id.clone(),
+ SoupItem::Document(d) => d.id.clone(),
+ SoupItem::Project(p) => p.id.clone(),
+ })
+ .collect();
+
+ assert_eq!(ast_ids, static_ids);
+}
+
+// ============================================================================
+// EntityFilter Tests with UUID-based fixture
+// ============================================================================
+
+// Test filtering by document file type
+#[sqlx::test(
+ fixtures(
+ path = "../../../../../macro_db_client/fixtures",
+ scripts("entity_filter_tests")
+ ),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn test_filter_by_document_file_type(db: PgPool) -> anyhow::Result<()> {
+ use item_filters::{DocumentFilters, EntityFilters};
+
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+
+ // Filter for only PDF documents
+ let entity_filters = EntityFilters {
+ document_filters: DocumentFilters {
+ file_types: vec!["pdf".to_string()],
+ ..Default::default()
+ },
+ ..Default::default()
+ };
+
+ let filters = EntityFilterAst::new_from_filters(entity_filters)?.unwrap();
+
+ let items = expanded_dynamic_cursor_soup(
+ &db,
+ user_id.copied(),
+ 20,
+ Query::Sort(SimpleSortMethod::CreatedAt, filters),
+ )
+ .await?;
+
+ // Should get PDF documents (filtered), and all chats and all projects
+ let mut pdf_count = 0;
+ let mut chat_count = 0;
+ let mut project_count = 0;
+
+ for item in &items {
+ match item {
+ SoupItem::Document(doc) => {
+ assert_eq!(
+ doc.file_type.as_deref(),
+ Some("pdf"),
+ "All documents should be PDFs"
+ );
+ pdf_count += 1;
+ }
+ SoupItem::Chat(_) => {
+ chat_count += 1;
+ }
+ SoupItem::Project(_) => {
+ project_count += 1;
+ }
+ }
+ }
+
+ // Should get 4 accessible PDF documents (doc-in-C is MD, doc-isolated not accessible)
+ assert_eq!(pdf_count, 4, "Should get 4 PDF documents");
+ // Should get all 4 accessible chats
+ assert_eq!(chat_count, 4, "Should get all chats");
+ // Should get all 2 accessible projects
+ assert_eq!(project_count, 4, "Should get all projects");
+
+ Ok(())
+}
+
+// Test filtering by specific document IDs
+#[sqlx::test(
+ fixtures(
+ path = "../../../../../macro_db_client/fixtures",
+ scripts("entity_filter_tests")
+ ),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn test_filter_by_document_ids(db: PgPool) -> anyhow::Result<()> {
+ use item_filters::{DocumentFilters, EntityFilters};
+
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+
+ // Filter for specific document IDs
+ let entity_filters = EntityFilters {
+ document_filters: DocumentFilters {
+ document_ids: vec![
+ "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa".to_string(),
+ "eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee".to_string(),
+ ],
+ ..Default::default()
+ },
+ ..Default::default()
+ };
+
+ let filters = EntityFilterAst::new_from_filters(entity_filters)?.unwrap();
+
+ let items = expanded_dynamic_cursor_soup(
+ &db,
+ user_id.copied(),
+ 20,
+ Query::Sort(SimpleSortMethod::CreatedAt, filters),
+ )
+ .await?;
+
+ // Should get 2 documents (filtered), all chats, and all projects
+ let mut document_ids: HashSet<String> = HashSet::new();
+ let mut chat_count = 0;
+ let mut project_count = 0;
+
+ for item in &items {
+ match item {
+ SoupItem::Document(d) => {
+ document_ids.insert(d.id.clone());
+ }
+ SoupItem::Chat(_) => {
+ chat_count += 1;
+ }
+ SoupItem::Project(_) => {
+ project_count += 1;
+ }
+ }
+ }
+
+ assert_eq!(document_ids.len(), 2, "Should get exactly 2 documents");
+ assert_eq!(chat_count, 4, "Should get all chats");
+ assert_eq!(project_count, 4, "Should get all projects");
+
+ let returned_ids = document_ids;
+
+ let expected_ids: HashSet<String> = [
+ "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa",
+ "eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee",
+ ]
+ .iter()
+ .map(|&s| s.to_string())
+ .collect();
+
+ assert_eq!(
+ returned_ids, expected_ids,
+ "Should get the correct documents"
+ );
+
+ Ok(())
+}
+
+// Test filtering by project ID (documents)
+#[sqlx::test(
+ fixtures(
+ path = "../../../../../macro_db_client/fixtures",
+ scripts("entity_filter_tests")
+ ),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn test_filter_documents_by_project_id(db: PgPool) -> anyhow::Result<()> {
+ use item_filters::{DocumentFilters, EntityFilters};
+
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+
+ // Filter documents in project-A only
+ let entity_filters = EntityFilters {
+ document_filters: DocumentFilters {
+ project_ids: vec!["11111111-1111-1111-1111-111111111111".to_string()],
+ ..Default::default()
+ },
+ ..Default::default()
+ };
+
+ let filters = EntityFilterAst::new_from_filters(entity_filters)?.unwrap();
+
+ let items = expanded_dynamic_cursor_soup(
+ &db,
+ user_id.copied(),
+ 20,
+ Query::Sort(SimpleSortMethod::CreatedAt, filters),
+ )
+ .await?;
+
+ // Should get 1 document in project-A, all chats, and all projects
+ let mut doc_count = 0;
+ let mut chat_count = 0;
+ let mut project_count = 0;
+ let mut found_doc_id = None;
+
+ for item in &items {
+ match item {
+ SoupItem::Document(doc) => {
+ assert_eq!(
+ doc.project_id.as_deref(),
+ Some("11111111-1111-1111-1111-111111111111")
+ );
+ found_doc_id = Some(doc.id.clone());
+ doc_count += 1;
+ }
+ SoupItem::Chat(_) => {
+ chat_count += 1;
+ }
+ SoupItem::Project(_) => {
+ project_count += 1;
+ }
+ }
+ }
+
+ assert_eq!(doc_count, 1, "Should get 1 document in project-A");
+ assert_eq!(
+ found_doc_id.as_deref(),
+ Some("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")
+ );
+ assert_eq!(chat_count, 4, "Should get all chats");
+ assert_eq!(project_count, 4, "Should get all projects");
+
+ Ok(())
+}
+
+// Test filtering chats by project ID
+#[sqlx::test(
+ fixtures(
+ path = "../../../../../macro_db_client/fixtures",
+ scripts("entity_filter_tests")
+ ),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn test_filter_chats_by_project_id(db: PgPool) -> anyhow::Result<()> {
+ use item_filters::{ChatFilters, EntityFilters};
+
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+
+ // Filter chats in project-B
+ let entity_filters = EntityFilters {
+ chat_filters: ChatFilters {
+ project_ids: vec!["22222222-2222-2222-2222-222222222222".to_string()],
+ ..Default::default()
+ },
+ ..Default::default()
+ };
+
+ let filters = EntityFilterAst::new_from_filters(entity_filters)?.unwrap();
+
+ let items = expanded_dynamic_cursor_soup(
+ &db,
+ user_id.copied(),
+ 20,
+ Query::Sort(SimpleSortMethod::CreatedAt, filters),
+ )
+ .await?;
+
+ // Should get 1 chat in project-B, all documents, and all projects
+ let mut doc_count = 0;
+ let mut chat_count = 0;
+ let mut project_count = 0;
+ let mut found_chat_id = None;
+
+ for item in &items {
+ match item {
+ SoupItem::Document(_) => {
+ doc_count += 1;
+ }
+ SoupItem::Chat(chat) => {
+ assert_eq!(
+ chat.project_id.as_deref(),
+ Some("22222222-2222-2222-2222-222222222222")
+ );
+ found_chat_id = Some(chat.id.clone());
+ chat_count += 1;
+ }
+ SoupItem::Project(_) => {
+ project_count += 1;
+ }
+ }
+ }
+
+ assert_eq!(chat_count, 1, "Should get 1 chat in project-B");
+ assert_eq!(
+ found_chat_id.as_deref(),
+ Some("b2b2b2b2-b2b2-b2b2-b2b2-b2b2b2b2b2b2")
+ );
+ assert_eq!(doc_count, 5, "Should get all documents");
+ assert_eq!(project_count, 4, "Should get all projects");
+
+ Ok(())
+}
+
+// Test filtering by specific chat IDs
+#[sqlx::test(
+ fixtures(
+ path = "../../../../../macro_db_client/fixtures",
+ scripts("entity_filter_tests")
+ ),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn test_filter_by_chat_ids(db: PgPool) -> anyhow::Result<()> {
+ use item_filters::{ChatFilters, EntityFilters};
+
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+
+ // Filter for specific chat IDs
+ let entity_filters = EntityFilters {
+ chat_filters: ChatFilters {
+ chat_ids: vec![
+ "a1a1a1a1-a1a1-a1a1-a1a1-a1a1a1a1a1a1".to_string(),
+ "d4d4d4d4-d4d4-d4d4-d4d4-d4d4d4d4d4d4".to_string(),
+ ],
+ ..Default::default()
+ },
+ ..Default::default()
+ };
+
+ let filters = EntityFilterAst::new_from_filters(entity_filters)?.unwrap();
+
+ let items = expanded_dynamic_cursor_soup(
+ &db,
+ user_id.copied(),
+ 20,
+ Query::Sort(SimpleSortMethod::CreatedAt, filters),
+ )
+ .await?;
+
+ // Should get 2 chats (filtered), all documents, and all projects
+ let mut chat_ids: HashSet<String> = HashSet::new();
+ let mut doc_count = 0;
+ let mut project_count = 0;
+
+ for item in &items {
+ match item {
+ SoupItem::Chat(c) => {
+ chat_ids.insert(c.id.clone());
+ }
+ SoupItem::Document(_) => {
+ doc_count += 1;
+ }
+ SoupItem::Project(_) => {
+ project_count += 1;
+ }
+ }
+ }
+
+ assert_eq!(chat_ids.len(), 2, "Should get exactly 2 chats");
+ assert_eq!(doc_count, 5, "Should get all documents");
+ assert_eq!(project_count, 4, "Should get all projects");
+
+ let returned_ids = chat_ids;
+
+ let expected_ids: HashSet<String> = [
+ "a1a1a1a1-a1a1-a1a1-a1a1-a1a1a1a1a1a1",
+ "d4d4d4d4-d4d4-d4d4-d4d4-d4d4d4d4d4d4",
+ ]
+ .iter()
+ .map(|&s| s.to_string())
+ .collect();
+
+ assert_eq!(returned_ids, expected_ids, "Should get the correct chats");
+
+ Ok(())
+}
+
+// Test filtering projects by specific project IDs
+#[sqlx::test(
+ fixtures(
+ path = "../../../../../macro_db_client/fixtures",
+ scripts("entity_filter_tests")
+ ),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn test_filter_by_project_ids(db: PgPool) -> anyhow::Result<()> {
+ use item_filters::{EntityFilters, ProjectFilters};
+
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+
+ // Filter for specific project IDs
+ let entity_filters = EntityFilters {
+ project_filters: ProjectFilters {
+ project_ids: vec![
+ "11111111-1111-1111-1111-111111111111".to_string(),
+ "44444444-4444-4444-4444-444444444444".to_string(),
+ ],
+ ..Default::default()
+ },
+ ..Default::default()
+ };
+
+ let filters = EntityFilterAst::new_from_filters(entity_filters)?.unwrap();
+
+ let items = expanded_dynamic_cursor_soup(
+ &db,
+ user_id.copied(),
+ 20,
+ Query::Sort(SimpleSortMethod::CreatedAt, filters),
+ )
+ .await?;
+
+ // Should get 2 projects (filtered), all documents, and all chats
+ let mut project_ids: HashSet<String> = HashSet::new();
+ let mut doc_count = 0;
+ let mut chat_count = 0;
+
+ for item in &items {
+ match item {
+ SoupItem::Project(p) => {
+ project_ids.insert(p.id.clone());
+ }
+ SoupItem::Document(_) => {
+ doc_count += 1;
+ }
+ SoupItem::Chat(_) => {
+ chat_count += 1;
+ }
+ }
+ }
+
+ assert_eq!(project_ids.len(), 2, "Should get exactly 2 projects");
+ assert_eq!(doc_count, 5, "Should get all documents");
+ assert_eq!(chat_count, 4, "Should get all chats");
+
+ let returned_ids = project_ids;
+
+ let expected_ids: HashSet<String> = [
+ "11111111-1111-1111-1111-111111111111",
+ "44444444-4444-4444-4444-444444444444",
+ ]
+ .iter()
+ .map(|&s| s.to_string())
+ .collect();
+
+ assert_eq!(
+ returned_ids, expected_ids,
+ "Should get the correct projects"
+ );
+
+ Ok(())
+}
+
+// Test combined filters across multiple entity types
+#[sqlx::test(
+ fixtures(
+ path = "../../../../../macro_db_client/fixtures",
+ scripts("entity_filter_tests")
+ ),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn test_combined_entity_filters(db: PgPool) -> anyhow::Result<()> {
+ use item_filters::{ChatFilters, DocumentFilters, EntityFilters, ProjectFilters};
+
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+
+ // Filter for:
+ // - Documents in project-A OR project-B
+ // - Chat with ID chat-standalone
+ // - Project with ID project-D
+ let entity_filters = EntityFilters {
+ document_filters: DocumentFilters {
+ project_ids: vec![
+ "11111111-1111-1111-1111-111111111111".to_string(),
+ "22222222-2222-2222-2222-222222222222".to_string(),
+ ],
+ ..Default::default()
+ },
+ chat_filters: ChatFilters {
+ chat_ids: vec!["d4d4d4d4-d4d4-d4d4-d4d4-d4d4d4d4d4d4".to_string()],
+ ..Default::default()
+ },
+ project_filters: ProjectFilters {
+ project_ids: vec!["44444444-4444-4444-4444-444444444444".to_string()],
+ ..Default::default()
+ },
+ ..Default::default()
+ };
+
+ let filters = EntityFilterAst::new_from_filters(entity_filters)?.unwrap();
+
+ let items = expanded_dynamic_cursor_soup(
+ &db,
+ user_id.copied(),
+ 20,
+ Query::Sort(SimpleSortMethod::CreatedAt, filters),
+ )
+ .await?;
+
+ // Should get: doc-in-A, doc-in-B, chat-standalone, project-D = 4 items
+ assert_eq!(items.len(), 4, "Should get 4 items total");
+
+ let mut doc_count = 0;
+ let mut chat_count = 0;
+ let mut project_count = 0;
+
+ for item in &items {
+ match item {
+ SoupItem::Document(doc) => {
+ doc_count += 1;
+ assert!(
+ doc.id == "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
+ || doc.id == "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb",
+ "Document should be in project-A or project-B"
+ );
+ }
+ SoupItem::Chat(chat) => {
+ chat_count += 1;
+ assert_eq!(
+ chat.id, "d4d4d4d4-d4d4-d4d4-d4d4-d4d4d4d4d4d4",
+ "Should only get standalone chat"
+ );
+ }
+ SoupItem::Project(project) => {
+ project_count += 1;
+ assert_eq!(
+ project.id, "44444444-4444-4444-4444-444444444444",
+ "Should only get project-D"
+ );
+ }
+ }
+ }
+
+ assert_eq!(doc_count, 2, "Should get 2 documents");
+ assert_eq!(chat_count, 1, "Should get 1 chat");
+ assert_eq!(project_count, 1, "Should get 1 project");
+
+ Ok(())
+}
+
+// Test filtering by multiple criteria on documents (AND logic)
+#[sqlx::test(
+ fixtures(
+ path = "../../../../../macro_db_client/fixtures",
+ scripts("entity_filter_tests")
+ ),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn test_multiple_filter_criteria_documents(db: PgPool) -> anyhow::Result<()> {
+ use item_filters::{DocumentFilters, EntityFilters};
+
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+
+ // Filter for documents: specific IDs AND in specific projects AND specific file type
+ // This uses AND logic across different filter criteria
+ let entity_filters = EntityFilters {
+ document_filters: DocumentFilters {
+ document_ids: vec![
+ "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa".to_string(),
+ "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb".to_string(),
+ ],
+ project_ids: vec![
+ "11111111-1111-1111-1111-111111111111".to_string(),
+ "22222222-2222-2222-2222-222222222222".to_string(),
+ ],
+ file_types: vec!["pdf".to_string()],
+ ..Default::default()
+ },
+ ..Default::default()
+ };
+
+ let filters = EntityFilterAst::new_from_filters(entity_filters)?.unwrap();
+
+ let items = expanded_dynamic_cursor_soup(
+ &db,
+ user_id.copied(),
+ 20,
+ Query::Sort(SimpleSortMethod::CreatedAt, filters),
+ )
+ .await?;
+
+ // Should get 2 documents matching all criteria, all chats, and all projects
+ let mut document_ids: HashSet<String> = HashSet::new();
+ let mut chat_count = 0;
+ let mut project_count = 0;
+
+ for item in &items {
+ match item {
+ SoupItem::Document(d) => {
+ document_ids.insert(d.id.clone());
+ }
+ SoupItem::Chat(_) => {
+ chat_count += 1;
+ }
+ SoupItem::Project(_) => {
+ project_count += 1;
+ }
+ }
+ }
+
+ assert_eq!(
+ document_ids.len(),
+ 2,
+ "Should get 2 documents matching all criteria"
+ );
+ assert_eq!(chat_count, 4, "Should get all chats");
+ assert_eq!(project_count, 4, "Should get all projects");
+
+ let returned_ids = document_ids;
+
+ let expected_ids: HashSet<String> = [
+ "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa",
+ "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb",
+ ]
+ .iter()
+ .map(|&s| s.to_string())
+ .collect();
+
+ assert_eq!(returned_ids, expected_ids);
+
+ Ok(())
+}
+
+// Test that inaccessible items are filtered out
+#[sqlx::test(
+ fixtures(
+ path = "../../../../../macro_db_client/fixtures",
+ scripts("entity_filter_tests")
+ ),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn test_filters_respect_access_control(db: PgPool) -> anyhow::Result<()> {
+ use item_filters::{DocumentFilters, EntityFilters};
+
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+
+ // Try to request doc-isolated (which user doesn't have access to)
+ let entity_filters = EntityFilters {
+ document_filters: DocumentFilters {
+ document_ids: vec!["ffffffff-ffff-ffff-ffff-ffffffffffff".to_string()],
+ ..Default::default()
+ },
+ ..Default::default()
+ };
+
+ let filters = EntityFilterAst::new_from_filters(entity_filters)?.unwrap();
+
+ let items = expanded_dynamic_cursor_soup(
+ &db,
+ user_id.copied(),
+ 20,
+ Query::Sort(SimpleSortMethod::CreatedAt, filters),
+ )
+ .await?;
+
+ // Should get 0 documents (inaccessible), but all chats and all projects
+ let mut doc_count = 0;
+ let mut chat_count = 0;
+ let mut project_count = 0;
+
+ for item in &items {
+ match item {
+ SoupItem::Document(_) => {
+ doc_count += 1;
+ }
+ SoupItem::Chat(_) => {
+ chat_count += 1;
+ }
+ SoupItem::Project(_) => {
+ project_count += 1;
+ }
+ }
+ }
+
+ assert_eq!(
+ doc_count, 0,
+ "Should not return inaccessible documents even when filtered"
+ );
+ assert_eq!(chat_count, 4, "Should get all chats");
+ assert_eq!(project_count, 4, "Should get all projects");
+
+ Ok(())
+}
+
+// Test filtering by owner
+#[sqlx::test(
+ fixtures(
+ path = "../../../../../macro_db_client/fixtures",
+ scripts("entity_filter_tests")
+ ),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn test_filter_by_owner(db: PgPool) -> anyhow::Result<()> {
+ use item_filters::{DocumentFilters, EntityFilters};
+
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+
+ // Filter documents by owner
+ let entity_filters = EntityFilters {
+ document_filters: DocumentFilters {
+ owners: vec!["macro|[email protected]".to_string()],
+ ..Default::default()
+ },
+ ..Default::default()
+ };
+
+ let filters = EntityFilterAst::new_from_filters(entity_filters)?.unwrap();
+
+ let items = expanded_dynamic_cursor_soup(
+ &db,
+ user_id.copied(),
+ 20,
+ Query::Sort(SimpleSortMethod::CreatedAt, filters),
+ )
+ .await?;
+
+ // Should get 5 documents owned by user-1, all chats, and all projects
+ let mut doc_count = 0;
+ let mut chat_count = 0;
+ let mut project_count = 0;
+
+ for item in &items {
+ match item {
+ SoupItem::Document(doc) => {
+ assert_eq!(
+ doc.owner_id, "macro|[email protected]",
+ "All documents should be owned by user-1"
+ );
+ doc_count += 1;
+ }
+ SoupItem::Chat(_) => {
+ chat_count += 1;
+ }
+ SoupItem::Project(_) => {
+ project_count += 1;
+ }
+ }
+ }
+
+ assert_eq!(doc_count, 5, "Should get 5 documents owned by user-1");
+ assert_eq!(chat_count, 4, "Should get all chats");
+ assert_eq!(project_count, 4, "Should get all projects");
+
+ Ok(())
+}
+
+// Test filtering for non-existent items returns empty
+#[sqlx::test(
+ fixtures(
+ path = "../../../../../macro_db_client/fixtures",
+ scripts("entity_filter_tests")
+ ),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn test_filter_non_existent_items(db: PgPool) -> anyhow::Result<()> {
+ use item_filters::{ChatFilters, EntityFilters};
+
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+
+ // Filter for non-existent chat IDs
+ let entity_filters = EntityFilters {
+ chat_filters: ChatFilters {
+ chat_ids: vec!["00000000-0000-0000-0000-000000000000".to_string()],
+ ..Default::default()
+ },
+ ..Default::default()
+ };
+
+ let filters = EntityFilterAst::new_from_filters(entity_filters)?.unwrap();
+
+ let items = expanded_dynamic_cursor_soup(
+ &db,
+ user_id.copied(),
+ 20,
+ Query::Sort(SimpleSortMethod::CreatedAt, filters),
+ )
+ .await?;
+
+ // Should get 0 chats (non-existent), but all documents and all projects
+ let mut doc_count = 0;
+ let mut chat_count = 0;
+ let mut project_count = 0;
+
+ for item in &items {
+ match item {
+ SoupItem::Document(_) => {
+ doc_count += 1;
+ }
+ SoupItem::Chat(_) => {
+ chat_count += 1;
+ }
+ SoupItem::Project(_) => {
+ project_count += 1;
+ }
+ }
+ }
+
+ assert_eq!(chat_count, 0, "Should return 0 chats for non-existent IDs");
+ assert_eq!(doc_count, 5, "Should get all documents");
+ assert_eq!(project_count, 4, "Should get all projects");
+
+ Ok(())
+}
+
+// Test cursor-based pagination with document filters
+#[sqlx::test(
+ fixtures(
+ path = "../../../../../macro_db_client/fixtures",
+ scripts("entity_filter_tests")
+ ),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn test_cursor_pagination_with_document_filter(db: PgPool) -> anyhow::Result<()> {
+ use item_filters::{DocumentFilters, EntityFilters};
+
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+
+ // Filter for only PDF documents
+ let entity_filters = EntityFilters {
+ document_filters: DocumentFilters {
+ file_types: vec!["pdf".to_string()],
+ ..Default::default()
+ },
+ ..Default::default()
+ };
+
+ let filters = EntityFilterAst::new_from_filters(entity_filters.clone())?.unwrap();
+
+ // First page - get 3 items
+ let result = expanded_dynamic_cursor_soup(
+ &db,
+ user_id.copied(),
+ 3,
+ Query::Sort(SimpleSortMethod::CreatedAt, filters.clone()),
+ )
+ .await?
+ .into_iter()
+ .paginate_on(3, SimpleSortMethod::CreatedAt)
+ .into_page();
+
+ let first_page_items = result.items;
+ assert_eq!(first_page_items.len(), 3, "First page should have 3 items");
+
+ // Verify any documents on first page are PDFs
+ for item in &first_page_items {
+ if let SoupItem::Document(doc) = item {
+ assert_eq!(
+ doc.file_type.as_deref(),
+ Some("pdf"),
+ "All documents should be PDFs"
+ );
+ }
+ }
+
+ // Get second page using cursor
+ let next_cursor = result.next_cursor.expect("Should have a next cursor");
+ let cursor_decoded = next_cursor.decode_json()?;
+
+ let filters_for_cursor = EntityFilterAst::new_from_filters(entity_filters)?.unwrap();
+
+ let second_page_items = expanded_dynamic_cursor_soup(
+ &db,
+ user_id.copied(),
+ 3,
+ Query::Cursor(models_pagination::Cursor {
+ id: cursor_decoded.id,
+ limit: cursor_decoded.limit,
+ val: cursor_decoded.val,
+ filter: filters_for_cursor,
+ }),
+ )
+ .await?;
+
+ assert!(second_page_items.len() > 0, "Second page should have items");
+
+ // Verify filter still applies on second page
+ for item in &second_page_items {
+ match item {
+ SoupItem::Document(doc) => {
+ assert_eq!(
+ doc.file_type.as_deref(),
+ Some("pdf"),
+ "All documents should be PDFs on second page"
+ );
+ }
+ SoupItem::Chat(_) => {
+ // Chats are fine
+ }
+ SoupItem::Project(_) => {
+ // Projects are fine
+ }
+ }
+ }
+
+ // Verify no duplicate items between pages
+ let first_page_ids: HashSet<String> = first_page_items
+ .iter()
+ .map(|item| match item {
+ SoupItem::Document(d) => d.id.clone(),
+ SoupItem::Chat(c) => c.id.clone(),
+ SoupItem::Project(p) => p.id.clone(),
+ })
+ .collect();
+
+ for item in &second_page_items {
+ let id = match item {
+ SoupItem::Document(d) => &d.id,
+ SoupItem::Chat(c) => &c.id,
+ SoupItem::Project(p) => &p.id,
+ };
+ assert!(
+ !first_page_ids.contains(id),
+ "No item should appear on both pages"
+ );
+ }
+
+ Ok(())
+}
+
+// Test cursor-based pagination with multiple entity filters
+#[sqlx::test(
+ fixtures(
+ path = "../../../../../macro_db_client/fixtures",
+ scripts("entity_filter_tests")
+ ),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn test_cursor_pagination_with_combined_filters(db: PgPool) -> anyhow::Result<()> {
+ use item_filters::{ChatFilters, DocumentFilters, EntityFilters};
+
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+
+ // Filter for documents in specific projects AND specific chats
+ let entity_filters = EntityFilters {
+ document_filters: DocumentFilters {
+ project_ids: vec![
+ "11111111-1111-1111-1111-111111111111".to_string(),
+ "22222222-2222-2222-2222-222222222222".to_string(),
+ ],
+ ..Default::default()
+ },
+ chat_filters: ChatFilters {
+ chat_ids: vec!["a1a1a1a1-a1a1-a1a1-a1a1-a1a1a1a1a1a1".to_string()],
+ ..Default::default()
+ },
+ ..Default::default()
+ };
+
+ let filters = EntityFilterAst::new_from_filters(entity_filters.clone())?.unwrap();
+
+ // First page - get 2 items
+ let result = expanded_dynamic_cursor_soup(
+ &db,
+ user_id.copied(),
+ 2,
+ Query::Sort(SimpleSortMethod::CreatedAt, filters.clone()),
+ )
+ .await?
+ .into_iter()
+ .paginate_on(2, SimpleSortMethod::CreatedAt)
+ .into_page();
+
+ assert_eq!(result.items.len(), 2, "First page should have 2 items");
+
+ // Get second page
+ if let Some(next_cursor) = result.next_cursor {
+ let cursor_decoded = next_cursor.decode_json()?;
+ let filters_for_cursor = EntityFilterAst::new_from_filters(entity_filters)?.unwrap();
+
+ let second_page_items = expanded_dynamic_cursor_soup(
+ &db,
+ user_id.copied(),
+ 2,
+ Query::Cursor(models_pagination::Cursor {
+ id: cursor_decoded.id,
+ limit: cursor_decoded.limit,
+ val: cursor_decoded.val,
+ filter: filters_for_cursor,
+ }),
+ )
+ .await?;
+
+ // Verify filters still apply on second page
+ for item in &second_page_items {
+ match item {
+ SoupItem::Document(doc) => {
+ let project_id = doc.project_id.as_deref().unwrap();
+ assert!(
+ project_id == "11111111-1111-1111-1111-111111111111"
+ || project_id == "22222222-2222-2222-2222-222222222222",
+ "Documents should be in filtered projects"
+ );
+ }
+ SoupItem::Chat(chat) => {
+ assert_eq!(
+ chat.id, "a1a1a1a1-a1a1-a1a1-a1a1-a1a1a1a1a1a1",
+ "Only the filtered chat should appear"
+ );
+ }
+ SoupItem::Project(_) => {
+ // All projects should be included
+ }
+ }
+ }
+ }
+
+ Ok(())
+}
+
+// Test cursor pagination maintains filter consistency across pages
+#[sqlx::test(
+ fixtures(
+ path = "../../../../../macro_db_client/fixtures",
+ scripts("entity_filter_tests")
+ ),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn test_cursor_pagination_filter_consistency(db: PgPool) -> anyhow::Result<()> {
+ use item_filters::{DocumentFilters, EntityFilters};
+
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+
+ // Filter for documents by specific IDs
+ let entity_filters = EntityFilters {
+ document_filters: DocumentFilters {
+ document_ids: vec![
+ "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa".to_string(),
+ "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb".to_string(),
+ ],
+ ..Default::default()
+ },
+ ..Default::default()
+ };
+
+ let filters = EntityFilterAst::new_from_filters(entity_filters.clone())?.unwrap();
+
+ // Collect all items across multiple pages with small page size
+ let mut all_items = Vec::new();
+ let mut current_query = Query::Sort(SimpleSortMethod::CreatedAt, filters.clone());
+ let page_size: u16 = 2;
+
+ loop {
+ let result = expanded_dynamic_cursor_soup(&db, user_id.copied(), page_size, current_query)
+ .await?
+ .into_iter()
+ .paginate_on(page_size as usize, SimpleSortMethod::CreatedAt)
+ .into_page();
+
+ all_items.extend(result.items);
+
+ match result.next_cursor {
+ Some(cursor) => {
+ let cursor_decoded = cursor.decode_json()?;
+ let filters_for_cursor =
+ EntityFilterAst::new_from_filters(entity_filters.clone())?.unwrap();
+ current_query = Query::Cursor(models_pagination::Cursor {
+ id: cursor_decoded.id,
+ limit: cursor_decoded.limit,
+ val: cursor_decoded.val,
+ filter: filters_for_cursor,
+ });
+ }
+ None => break,
+ }
+ }
+
+ // Count filtered documents across all pages
+ let mut filtered_doc_count = 0;
+ let expected_doc_ids: HashSet<String> = [
+ "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa",
+ "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb",
+ ]
+ .iter()
+ .map(|&s| s.to_string())
+ .collect();
+
+ for item in &all_items {
+ if let SoupItem::Document(doc) = item {
+ assert!(
+ expected_doc_ids.contains(&doc.id),
+ "Document {} should be in the filtered set",
+ doc.id
+ );
+ filtered_doc_count += 1;
+ }
+ }
+
+ // Should get exactly the 2 filtered documents
+ assert_eq!(
+ filtered_doc_count, 2,
+ "Should get exactly 2 filtered documents across all pages"
+ );
+
+ // Verify no duplicate items
+ let all_ids: Vec<String> = all_items
+ .iter()
+ .map(|item| match item {
+ SoupItem::Document(d) => d.id.clone(),
+ SoupItem::Chat(c) => c.id.clone(),
+ SoupItem::Project(p) => p.id.clone(),
+ })
+ .collect();
+
+ let unique_ids: HashSet<_> = all_ids.iter().collect();
+ assert_eq!(
+ all_ids.len(),
+ unique_ids.len(),
+ "Should have no duplicate items across pages"
+ );
+
+ Ok(())
+}
+
+// Test cursor pagination with empty filter results on subsequent pages
+#[sqlx::test(
+ fixtures(
+ path = "../../../../../macro_db_client/fixtures",
+ scripts("entity_filter_tests")
+ ),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn test_cursor_pagination_with_single_item_filter(db: PgPool) -> anyhow::Result<()> {
+ use item_filters::{ChatFilters, EntityFilters};
+
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+
+ // Filter for a single chat ID
+ let entity_filters = EntityFilters {
+ chat_filters: ChatFilters {
+ chat_ids: vec!["a1a1a1a1-a1a1-a1a1-a1a1-a1a1a1a1a1a1".to_string()],
+ ..Default::default()
+ },
+ ..Default::default()
+ };
+
+ let filters = EntityFilterAst::new_from_filters(entity_filters.clone())?.unwrap();
+
+ // Get first page with limit 5
+ let result = expanded_dynamic_cursor_soup(
+ &db,
+ user_id.copied(),
+ 5,
+ Query::Sort(SimpleSortMethod::CreatedAt, filters.clone()),
+ )
+ .await?
+ .into_iter()
+ .paginate_on(5, SimpleSortMethod::CreatedAt)
+ .into_page();
+
+ // Count the filtered chat in first page
+ let chat_count_page1 = result
+ .items
+ .iter()
+ .filter(|item| matches!(item, SoupItem::Chat(c) if c.id == "a1a1a1a1-a1a1-a1a1-a1a1-a1a1a1a1a1a1"))
+ .count();
+
+ // We should see the filtered chat (it might be on page 1 or later depending on sort order)
+ if let Some(next_cursor) = result.next_cursor {
+ let cursor_decoded = next_cursor.decode_json()?;
+ let filters_for_cursor = EntityFilterAst::new_from_filters(entity_filters)?.unwrap();
+
+ let second_page_items = expanded_dynamic_cursor_soup(
+ &db,
+ user_id.copied(),
+ 5,
+ Query::Cursor(models_pagination::Cursor {
+ id: cursor_decoded.id,
+ limit: cursor_decoded.limit,
+ val: cursor_decoded.val,
+ filter: filters_for_cursor,
+ }),
+ )
+ .await?;
+
+ // Count the filtered chat in second page
+ let chat_count_page2 = second_page_items
+ .iter()
+ .filter(|item| matches!(item, SoupItem::Chat(c) if c.id == "a1a1a1a1-a1a1-a1a1-a1a1-a1a1a1a1a1a1"))
+ .count();
+
+ // Across both pages, we should see exactly 1 instance of the filtered chat
+ assert_eq!(
+ chat_count_page1 + chat_count_page2,
+ 1,
+ "Should see the filtered chat exactly once across pages"
+ );
+ } else {
+ // If no second page, the chat should be on the first page
+ assert_eq!(
+ chat_count_page1, 1,
+ "Should see the filtered chat on first page"
+ );
+ }
+
+ Ok(())
+}