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.

feat(drive): drag databases and forms into folders (#9339)

Wolf Mermelstein76c018e64225
diff --git a/.sqlx/query-f2af84dbfa64cd884cae988fb76db056c11f32b0cff76152c069724b1fcf035c.json b/.sqlx/query-414511b5955036e2b7509bbafde6c7cdc67282d591d72031d53535ff20db546f.json
similarity index 68%
rename from .sqlx/query-f2af84dbfa64cd884cae988fb76db056c11f32b0cff76152c069724b1fcf035c.json
rename to .sqlx/query-414511b5955036e2b7509bbafde6c7cdc67282d591d72031d53535ff20db546f.json
index 81dff081ff..aa89454036 100644
--- a/.sqlx/query-f2af84dbfa64cd884cae988fb76db056c11f32b0cff76152c069724b1fcf035c.json
+++ b/.sqlx/query-414511b5955036e2b7509bbafde6c7cdc67282d591d72031d53535ff20db546f.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT database_id AS id, name, user_id AS owner_id, created_at, trashed_at\n FROM database_entities\n WHERE database_id = ANY($1)\n ORDER BY created_at\n ",
+ "query": "\n SELECT database_id AS id, name, user_id AS owner_id, created_at, trashed_at, project_id\n FROM database_entities\n WHERE database_id = ANY($1)\n ORDER BY created_at\n ",
"describe": {
"columns": [
{
@@ -27,6 +27,11 @@
"ordinal": 4,
"name": "trashed_at",
"type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 5,
+ "name": "project_id",
+ "type_info": "Text"
}
],
"parameters": {
@@ -39,8 +44,9 @@
false,
false,
false,
+ true,
true
]
},
- "hash": "f2af84dbfa64cd884cae988fb76db056c11f32b0cff76152c069724b1fcf035c"
+ "hash": "414511b5955036e2b7509bbafde6c7cdc67282d591d72031d53535ff20db546f"
}
diff --git a/.sqlx/query-4c2396ca61a5060acd24cd3c0d37322a8450d9f8cbf90e43e1906ba6432a4e95.json b/.sqlx/query-4c2396ca61a5060acd24cd3c0d37322a8450d9f8cbf90e43e1906ba6432a4e95.json
new file mode 100644
index 0000000000..828d0cbb91
--- /dev/null
+++ b/.sqlx/query-4c2396ca61a5060acd24cd3c0d37322a8450d9f8cbf90e43e1906ba6432a4e95.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE database_entities SET project_id = $2, updated_at = now() WHERE database_id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "4c2396ca61a5060acd24cd3c0d37322a8450d9f8cbf90e43e1906ba6432a4e95"
+}
diff --git a/.sqlx/query-975bf71677894db62cf76b39e2069e7ae91dcd985c11006bee7edd262e6fe8b5.json b/.sqlx/query-975bf71677894db62cf76b39e2069e7ae91dcd985c11006bee7edd262e6fe8b5.json
new file mode 100644
index 0000000000..0b543049c7
--- /dev/null
+++ b/.sqlx/query-975bf71677894db62cf76b39e2069e7ae91dcd985c11006bee7edd262e6fe8b5.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n DELETE FROM entity_access\n WHERE entity_id = $1\n AND entity_type = $2\n AND granted_from_project_id = ANY($3)\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "TextArray"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "975bf71677894db62cf76b39e2069e7ae91dcd985c11006bee7edd262e6fe8b5"
+}
diff --git a/.sqlx/query-eb692208e1273bce856a1ccb7178b6c9fde96993bff24aed441f5119e5079f93.json b/.sqlx/query-a0d8f93ed3ea9193ed2a2365c0951e3518e6976d42074d483e916153bf5bb17c.json
similarity index 91%
rename from .sqlx/query-eb692208e1273bce856a1ccb7178b6c9fde96993bff24aed441f5119e5079f93.json
rename to .sqlx/query-a0d8f93ed3ea9193ed2a2365c0951e3518e6976d42074d483e916153bf5bb17c.json
index 203c75c53a..816ec1d12e 100644
--- a/.sqlx/query-eb692208e1273bce856a1ccb7178b6c9fde96993bff24aed441f5119e5079f93.json
+++ b/.sqlx/query-a0d8f93ed3ea9193ed2a2365c0951e3518e6976d42074d483e916153bf5bb17c.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n UPDATE forms SET updated_at = $2\n WHERE id = $1 AND trashed_at IS NULL\n RETURNING id, name, description, owner_id, database_id, table_id,\n submitted_column_id, respondent_column_id, audience, tally_visible,\n status, closes_at, confirmation_message, logo_file_id, cover_file_id, accent_color,\n created_at, updated_at, trashed_at,\n name_follows_database, is_hidden_in_drive\n ",
+ "query": "\n UPDATE forms SET updated_at = $2\n WHERE id = $1 AND trashed_at IS NULL\n RETURNING id, name, description, owner_id, database_id, table_id,\n submitted_column_id, respondent_column_id, audience, tally_visible,\n status, closes_at, confirmation_message, logo_file_id, cover_file_id, accent_color,\n created_at, updated_at, trashed_at,\n name_follows_database, is_hidden_in_drive, project_id\n ",
"describe": {
"columns": [
{
@@ -107,6 +107,11 @@
"ordinal": 20,
"name": "is_hidden_in_drive",
"type_info": "Bool"
+ },
+ {
+ "ordinal": 21,
+ "name": "project_id",
+ "type_info": "Text"
}
],
"parameters": {
@@ -136,8 +141,9 @@
false,
true,
false,
- false
+ false,
+ true
]
},
- "hash": "eb692208e1273bce856a1ccb7178b6c9fde96993bff24aed441f5119e5079f93"
+ "hash": "a0d8f93ed3ea9193ed2a2365c0951e3518e6976d42074d483e916153bf5bb17c"
}
diff --git a/.sqlx/query-ef9fd96657a6b0d5e101362ea2b6551efb6368d1add53d977df6f0b48f6ef178.json b/.sqlx/query-a2e0f51aba93255ed3bceac95c46eb847dc49e19f505c52e6c8498ae8190a2bd.json
similarity index 93%
rename from .sqlx/query-ef9fd96657a6b0d5e101362ea2b6551efb6368d1add53d977df6f0b48f6ef178.json
rename to .sqlx/query-a2e0f51aba93255ed3bceac95c46eb847dc49e19f505c52e6c8498ae8190a2bd.json
index 84e5fcd079..46eb8e8510 100644
--- a/.sqlx/query-ef9fd96657a6b0d5e101362ea2b6551efb6368d1add53d977df6f0b48f6ef178.json
+++ b/.sqlx/query-a2e0f51aba93255ed3bceac95c46eb847dc49e19f505c52e6c8498ae8190a2bd.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n UPDATE forms SET name = $2, updated_at = $3\n WHERE id = $1 AND trashed_at IS NULL\n RETURNING id, name, description, owner_id, database_id, table_id,\n submitted_column_id, respondent_column_id, audience, tally_visible,\n status, closes_at, confirmation_message, logo_file_id, cover_file_id, accent_color,\n created_at, updated_at, trashed_at,\n name_follows_database, is_hidden_in_drive\n ",
+ "query": "\n UPDATE forms SET name = $2, updated_at = $3\n WHERE id = $1 AND trashed_at IS NULL\n RETURNING id, name, description, owner_id, database_id, table_id,\n submitted_column_id, respondent_column_id, audience, tally_visible,\n status, closes_at, confirmation_message, logo_file_id, cover_file_id, accent_color,\n created_at, updated_at, trashed_at,\n name_follows_database, is_hidden_in_drive, project_id\n ",
"describe": {
"columns": [
{
@@ -107,6 +107,11 @@
"ordinal": 20,
"name": "is_hidden_in_drive",
"type_info": "Bool"
+ },
+ {
+ "ordinal": 21,
+ "name": "project_id",
+ "type_info": "Text"
}
],
"parameters": {
@@ -137,8 +142,9 @@
false,
true,
false,
- false
+ false,
+ true
]
},
- "hash": "ef9fd96657a6b0d5e101362ea2b6551efb6368d1add53d977df6f0b48f6ef178"
+ "hash": "a2e0f51aba93255ed3bceac95c46eb847dc49e19f505c52e6c8498ae8190a2bd"
}
diff --git a/.sqlx/query-6b904d2c71124ca1553d2179f55196c0d2a8da2f193aa569845004f333982513.json b/.sqlx/query-a3841844b065903908a54e516428ec90b5fcf028dcc1181bbf81c650f97d4c8b.json
similarity index 89%
rename from .sqlx/query-6b904d2c71124ca1553d2179f55196c0d2a8da2f193aa569845004f333982513.json
rename to .sqlx/query-a3841844b065903908a54e516428ec90b5fcf028dcc1181bbf81c650f97d4c8b.json
index 1f6ed07e99..0904b176a0 100644
--- a/.sqlx/query-6b904d2c71124ca1553d2179f55196c0d2a8da2f193aa569845004f333982513.json
+++ b/.sqlx/query-a3841844b065903908a54e516428ec90b5fcf028dcc1181bbf81c650f97d4c8b.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT id, name, description, owner_id, database_id, table_id,\n submitted_column_id, respondent_column_id, audience, tally_visible,\n status, closes_at, confirmation_message, logo_file_id, cover_file_id, accent_color,\n created_at, updated_at, trashed_at,\n name_follows_database, is_hidden_in_drive\n FROM forms WHERE id = ANY($1) AND trashed_at IS NULL\n ORDER BY id\n ",
+ "query": "\n SELECT id, name, description, owner_id, database_id, table_id,\n submitted_column_id, respondent_column_id, audience, tally_visible,\n status, closes_at, confirmation_message, logo_file_id, cover_file_id, accent_color,\n created_at, updated_at, trashed_at,\n name_follows_database, is_hidden_in_drive, project_id\n FROM forms WHERE id = ANY($1) AND trashed_at IS NULL\n ORDER BY id\n ",
"describe": {
"columns": [
{
@@ -107,6 +107,11 @@
"ordinal": 20,
"name": "is_hidden_in_drive",
"type_info": "Bool"
+ },
+ {
+ "ordinal": 21,
+ "name": "project_id",
+ "type_info": "Text"
}
],
"parameters": {
@@ -135,8 +140,9 @@
false,
true,
false,
- false
+ false,
+ true
]
},
- "hash": "6b904d2c71124ca1553d2179f55196c0d2a8da2f193aa569845004f333982513"
+ "hash": "a3841844b065903908a54e516428ec90b5fcf028dcc1181bbf81c650f97d4c8b"
}
diff --git a/.sqlx/query-ba41441ec2985fd12f23b524b0ba7d6b475a136c43ae56c1ec6dee28e929dbd5.json b/.sqlx/query-ba41441ec2985fd12f23b524b0ba7d6b475a136c43ae56c1ec6dee28e929dbd5.json
new file mode 100644
index 0000000000..85f4c408c6
--- /dev/null
+++ b/.sqlx/query-ba41441ec2985fd12f23b524b0ba7d6b475a136c43ae56c1ec6dee28e929dbd5.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT project_id FROM forms WHERE id = $1 AND trashed_at IS NULL FOR UPDATE",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "project_id",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ true
+ ]
+ },
+ "hash": "ba41441ec2985fd12f23b524b0ba7d6b475a136c43ae56c1ec6dee28e929dbd5"
+}
diff --git a/.sqlx/query-c49101cdf10056888b213720b58d902333f644fe03edf00d6a9c7221a3767447.json b/.sqlx/query-c49101cdf10056888b213720b58d902333f644fe03edf00d6a9c7221a3767447.json
new file mode 100644
index 0000000000..ef44a04d9b
--- /dev/null
+++ b/.sqlx/query-c49101cdf10056888b213720b58d902333f644fe03edf00d6a9c7221a3767447.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE forms SET project_id = $2, updated_at = now() WHERE id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "c49101cdf10056888b213720b58d902333f644fe03edf00d6a9c7221a3767447"
+}
diff --git a/.sqlx/query-cd2ae30f38c8fd4467fafbf57d515e303d2c5bed1c53a5c1cf255a172defa46c.json b/.sqlx/query-cd2ae30f38c8fd4467fafbf57d515e303d2c5bed1c53a5c1cf255a172defa46c.json
deleted file mode 100644
index a42c11b623..0000000000
--- a/.sqlx/query-cd2ae30f38c8fd4467fafbf57d515e303d2c5bed1c53a5c1cf255a172defa46c.json
+++ /dev/null
@@ -1,16 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n DELETE FROM entity_access\n WHERE entity_id = $1\n AND entity_type = $2\n AND granted_from_project_id = ANY($3)\n ",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid",
- "Text",
- "TextArray"
- ]
- },
- "nullable": []
- },
- "hash": "cd2ae30f38c8fd4467fafbf57d515e303d2c5bed1c53a5c1cf255a172defa46c"
-}
diff --git a/.sqlx/query-2ff1e25803bb1e35cb53fd6a8b29d4c9e2ef13d66bd6d294bfd504831f69d8c9.json b/.sqlx/query-da2238408d133ae247603484e8e9c8759dd106d3b8edb17a0807a55186f7f17f.json
similarity index 74%
rename from .sqlx/query-2ff1e25803bb1e35cb53fd6a8b29d4c9e2ef13d66bd6d294bfd504831f69d8c9.json
rename to .sqlx/query-da2238408d133ae247603484e8e9c8759dd106d3b8edb17a0807a55186f7f17f.json
index 205818d608..11ccd0ddbf 100644
--- a/.sqlx/query-2ff1e25803bb1e35cb53fd6a8b29d4c9e2ef13d66bd6d294bfd504831f69d8c9.json
+++ b/.sqlx/query-da2238408d133ae247603484e8e9c8759dd106d3b8edb17a0807a55186f7f17f.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "SELECT database_id AS id, name, user_id AS owner_id, created_at, trashed_at FROM database_entities WHERE database_id = $1",
+ "query": "SELECT database_id AS id, name, user_id AS owner_id, created_at, trashed_at, project_id FROM database_entities WHERE database_id = $1",
"describe": {
"columns": [
{
@@ -27,6 +27,11 @@
"ordinal": 4,
"name": "trashed_at",
"type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 5,
+ "name": "project_id",
+ "type_info": "Text"
}
],
"parameters": {
@@ -39,8 +44,9 @@
false,
false,
false,
+ true,
true
]
},
- "hash": "2ff1e25803bb1e35cb53fd6a8b29d4c9e2ef13d66bd6d294bfd504831f69d8c9"
+ "hash": "da2238408d133ae247603484e8e9c8759dd106d3b8edb17a0807a55186f7f17f"
}
diff --git a/.sqlx/query-6bb62869ece5d2438ea8431080ecd647d496b1500dabfdb8921575cb4843c980.json b/.sqlx/query-de50fec8f367e1b82711d9d97d5f2d21b5f9f70bdff53062e856311171513bc7.json
similarity index 91%
rename from .sqlx/query-6bb62869ece5d2438ea8431080ecd647d496b1500dabfdb8921575cb4843c980.json
rename to .sqlx/query-de50fec8f367e1b82711d9d97d5f2d21b5f9f70bdff53062e856311171513bc7.json
index 519d3c54bc..bd308439c0 100644
--- a/.sqlx/query-6bb62869ece5d2438ea8431080ecd647d496b1500dabfdb8921575cb4843c980.json
+++ b/.sqlx/query-de50fec8f367e1b82711d9d97d5f2d21b5f9f70bdff53062e856311171513bc7.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT id, name, description, owner_id, database_id, table_id,\n submitted_column_id, respondent_column_id, audience, tally_visible,\n status, closes_at, confirmation_message, logo_file_id, cover_file_id, accent_color,\n created_at, updated_at, trashed_at,\n name_follows_database, is_hidden_in_drive\n FROM forms WHERE id = $1\n ",
+ "query": "\n SELECT id, name, description, owner_id, database_id, table_id,\n submitted_column_id, respondent_column_id, audience, tally_visible,\n status, closes_at, confirmation_message, logo_file_id, cover_file_id, accent_color,\n created_at, updated_at, trashed_at,\n name_follows_database, is_hidden_in_drive, project_id\n FROM forms WHERE id = $1\n ",
"describe": {
"columns": [
{
@@ -107,6 +107,11 @@
"ordinal": 20,
"name": "is_hidden_in_drive",
"type_info": "Bool"
+ },
+ {
+ "ordinal": 21,
+ "name": "project_id",
+ "type_info": "Text"
}
],
"parameters": {
@@ -135,8 +140,9 @@
false,
true,
false,
- false
+ false,
+ true
]
},
- "hash": "6bb62869ece5d2438ea8431080ecd647d496b1500dabfdb8921575cb4843c980"
+ "hash": "de50fec8f367e1b82711d9d97d5f2d21b5f9f70bdff53062e856311171513bc7"
}
diff --git a/.sqlx/query-5b17a30f841372cce9989af409baf993e24bfe90d3a3553f6851b3e92c8540eb.json b/.sqlx/query-df75ce42686feb18110fe6d8cbe1944315b7b4f222ea6774bf278b38f7bbf49c.json
similarity index 72%
rename from .sqlx/query-5b17a30f841372cce9989af409baf993e24bfe90d3a3553f6851b3e92c8540eb.json
rename to .sqlx/query-df75ce42686feb18110fe6d8cbe1944315b7b4f222ea6774bf278b38f7bbf49c.json
index 3b0277bbdf..29a4b5bd6c 100644
--- a/.sqlx/query-5b17a30f841372cce9989af409baf993e24bfe90d3a3553f6851b3e92c8540eb.json
+++ b/.sqlx/query-df75ce42686feb18110fe6d8cbe1944315b7b4f222ea6774bf278b38f7bbf49c.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n entity_id,\n source_id,\n source_type as \"source_type:EntityAccessSourceType\",\n access_level as \"access_level:AccessLevel\"\n FROM entity_access\n WHERE entity_id = ANY($1) AND entity_type = 'project' AND granted_from_project_id IS NULL\n ",
+ "query": "\n SELECT\n entity_id,\n source_id,\n source_type as \"source_type:EntityAccessSourceType\",\n access_level as \"access_level:AccessLevel\"\n FROM entity_access\n WHERE entity_id = ANY($1) AND entity_type = 'project' AND granted_from_project_id IS NULL\n ",
"describe": {
"columns": [
{
@@ -60,5 +60,5 @@
false
]
},
- "hash": "5b17a30f841372cce9989af409baf993e24bfe90d3a3553f6851b3e92c8540eb"
+ "hash": "df75ce42686feb18110fe6d8cbe1944315b7b4f222ea6774bf278b38f7bbf49c"
}
diff --git a/.sqlx/query-e66d3f6f044aa7cbb613e94bbb9da1ac77a8e0afecba7343169e3812c68a79dd.json b/.sqlx/query-e66d3f6f044aa7cbb613e94bbb9da1ac77a8e0afecba7343169e3812c68a79dd.json
new file mode 100644
index 0000000000..451c1c9081
--- /dev/null
+++ b/.sqlx/query-e66d3f6f044aa7cbb613e94bbb9da1ac77a8e0afecba7343169e3812c68a79dd.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT project_id FROM database_entities WHERE database_id = $1 AND trashed_at IS NULL FOR UPDATE",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "project_id",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ true
+ ]
+ },
+ "hash": "e66d3f6f044aa7cbb613e94bbb9da1ac77a8e0afecba7343169e3812c68a79dd"
+}
diff --git a/.sqlx/query-d3f49ff7d68128de8122f431ea9ea61f708233f45db84b12e93341dccdc036b5.json b/.sqlx/query-e9551200c01710cce8ebd47531f66bd476a4317f9857f9f5f68f886a1da85f55.json
similarity index 80%
rename from .sqlx/query-d3f49ff7d68128de8122f431ea9ea61f708233f45db84b12e93341dccdc036b5.json
rename to .sqlx/query-e9551200c01710cce8ebd47531f66bd476a4317f9857f9f5f68f886a1da85f55.json
index f5578b6051..b6ee0d3d28 100644
--- a/.sqlx/query-d3f49ff7d68128de8122f431ea9ea61f708233f45db84b12e93341dccdc036b5.json
+++ b/.sqlx/query-e9551200c01710cce8ebd47531f66bd476a4317f9857f9f5f68f886a1da85f55.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n INSERT INTO database_entities (database_id, name, user_id)\n VALUES ($1, $2, $3)\n RETURNING database_id AS id, name, user_id AS owner_id, created_at, trashed_at\n ",
+ "query": "\n INSERT INTO database_entities (database_id, name, user_id)\n VALUES ($1, $2, $3)\n RETURNING database_id AS id, name, user_id AS owner_id, created_at, trashed_at, project_id\n ",
"describe": {
"columns": [
{
@@ -27,6 +27,11 @@
"ordinal": 4,
"name": "trashed_at",
"type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 5,
+ "name": "project_id",
+ "type_info": "Text"
}
],
"parameters": {
@@ -41,8 +46,9 @@
false,
false,
false,
+ true,
true
]
},
- "hash": "d3f49ff7d68128de8122f431ea9ea61f708233f45db84b12e93341dccdc036b5"
+ "hash": "e9551200c01710cce8ebd47531f66bd476a4317f9857f9f5f68f886a1da85f55"
}
diff --git a/.sqlx/query-f6a7499d3079d346afe5d866734ffc5d4ac3f9f1a8c2a5714ef130e53d11145f.json b/.sqlx/query-eb60260e926ddd63f789da6804ba0dd2db2e3997a14a51ae9d7d1ceb68e1a23b.json
similarity index 69%
rename from .sqlx/query-f6a7499d3079d346afe5d866734ffc5d4ac3f9f1a8c2a5714ef130e53d11145f.json
rename to .sqlx/query-eb60260e926ddd63f789da6804ba0dd2db2e3997a14a51ae9d7d1ceb68e1a23b.json
index c718076a09..acee0aab2f 100644
--- a/.sqlx/query-f6a7499d3079d346afe5d866734ffc5d4ac3f9f1a8c2a5714ef130e53d11145f.json
+++ b/.sqlx/query-eb60260e926ddd63f789da6804ba0dd2db2e3997a14a51ae9d7d1ceb68e1a23b.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n WITH RECURSIVE child_projects AS (\n SELECT id FROM \"Project\" WHERE id = $1\n\n UNION ALL\n\n SELECT p.id FROM \"Project\" p\n INNER JOIN child_projects cp ON p.\"parentId\" = cp.id\n )\n SELECT id as \"entity_id!\", 'project' as \"entity_type!\" FROM child_projects\n\n UNION ALL\n\n SELECT d.id as \"entity_id!\", 'document' as \"entity_type!\" FROM \"Document\" d\n WHERE d.\"projectId\" IN (SELECT id FROM child_projects)\n\n UNION ALL\n\n SELECT c.id as \"entity_id!\", 'chat' as \"entity_type!\" FROM \"Chat\" c\n WHERE c.\"projectId\" IN (SELECT id FROM child_projects)\n\n UNION ALL\n\n SELECT et.id::text as \"entity_id!\", 'email_thread' as \"entity_type!\" FROM email_threads et\n WHERE et.project_id IN (SELECT id FROM child_projects)\n ",
+ "query": "\n WITH RECURSIVE child_projects AS (\n SELECT id FROM \"Project\" WHERE id = $1\n\n UNION ALL\n\n SELECT p.id FROM \"Project\" p\n INNER JOIN child_projects cp ON p.\"parentId\" = cp.id\n )\n SELECT id as \"entity_id!\", 'project' as \"entity_type!\" FROM child_projects\n\n UNION ALL\n\n SELECT d.id as \"entity_id!\", 'document' as \"entity_type!\" FROM \"Document\" d\n WHERE d.\"projectId\" IN (SELECT id FROM child_projects)\n\n UNION ALL\n\n SELECT c.id as \"entity_id!\", 'chat' as \"entity_type!\" FROM \"Chat\" c\n WHERE c.\"projectId\" IN (SELECT id FROM child_projects)\n\n UNION ALL\n\n SELECT et.id::text as \"entity_id!\", 'email_thread' as \"entity_type!\" FROM email_threads et\n WHERE et.project_id IN (SELECT id FROM child_projects)\n\n UNION ALL\n\n SELECT de.database_id::text as \"entity_id!\", 'database' as \"entity_type!\" FROM database_entities de\n WHERE de.project_id IN (SELECT id FROM child_projects)\n\n UNION ALL\n\n SELECT f.id::text as \"entity_id!\", 'form' as \"entity_type!\" FROM forms f\n WHERE f.project_id IN (SELECT id FROM child_projects)\n ",
"describe": {
"columns": [
{
@@ -24,5 +24,5 @@
null
]
},
- "hash": "f6a7499d3079d346afe5d866734ffc5d4ac3f9f1a8c2a5714ef130e53d11145f"
+ "hash": "eb60260e926ddd63f789da6804ba0dd2db2e3997a14a51ae9d7d1ceb68e1a23b"
}
diff --git a/.sqlx/query-ea44656ddebaee025a59c283b3d87f4f962a0954efbe1765757f48dc01381039.json b/.sqlx/query-f3479ddd35d19a7e2cbddf56e4d7ceae6053583db8563c3840eceb7fbd71da8e.json
similarity index 94%
rename from .sqlx/query-ea44656ddebaee025a59c283b3d87f4f962a0954efbe1765757f48dc01381039.json
rename to .sqlx/query-f3479ddd35d19a7e2cbddf56e4d7ceae6053583db8563c3840eceb7fbd71da8e.json
index 4d4f172749..af019e46dd 100644
--- a/.sqlx/query-ea44656ddebaee025a59c283b3d87f4f962a0954efbe1765757f48dc01381039.json
+++ b/.sqlx/query-f3479ddd35d19a7e2cbddf56e4d7ceae6053583db8563c3840eceb7fbd71da8e.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n UPDATE forms SET\n description = COALESCE($2, description),\n confirmation_message = COALESCE($3, confirmation_message),\n audience = COALESCE($4, audience),\n status = COALESCE($5, status),\n closes_at = CASE WHEN $6 THEN $7 ELSE closes_at END,\n tally_visible = COALESCE($8, tally_visible),\n logo_file_id = CASE WHEN $10 THEN $11 ELSE logo_file_id END,\n cover_file_id = CASE WHEN $12 THEN $13 ELSE cover_file_id END,\n accent_color = CASE WHEN $14 THEN $15 ELSE accent_color END,\n updated_at = $9\n WHERE id = $1\n RETURNING id, name, description, owner_id, database_id, table_id,\n submitted_column_id, respondent_column_id, audience, tally_visible,\n status, closes_at, confirmation_message, logo_file_id, cover_file_id, accent_color,\n created_at, updated_at, trashed_at,\n name_follows_database, is_hidden_in_drive\n ",
+ "query": "\n UPDATE forms SET\n description = COALESCE($2, description),\n confirmation_message = COALESCE($3, confirmation_message),\n audience = COALESCE($4, audience),\n status = COALESCE($5, status),\n closes_at = CASE WHEN $6 THEN $7 ELSE closes_at END,\n tally_visible = COALESCE($8, tally_visible),\n logo_file_id = CASE WHEN $10 THEN $11 ELSE logo_file_id END,\n cover_file_id = CASE WHEN $12 THEN $13 ELSE cover_file_id END,\n accent_color = CASE WHEN $14 THEN $15 ELSE accent_color END,\n updated_at = $9\n WHERE id = $1\n RETURNING id, name, description, owner_id, database_id, table_id,\n submitted_column_id, respondent_column_id, audience, tally_visible,\n status, closes_at, confirmation_message, logo_file_id, cover_file_id, accent_color,\n created_at, updated_at, trashed_at,\n name_follows_database, is_hidden_in_drive, project_id\n ",
"describe": {
"columns": [
{
@@ -107,6 +107,11 @@
"ordinal": 20,
"name": "is_hidden_in_drive",
"type_info": "Bool"
+ },
+ {
+ "ordinal": 21,
+ "name": "project_id",
+ "type_info": "Text"
}
],
"parameters": {
@@ -149,8 +154,9 @@
false,
true,
false,
- false
+ false,
+ true
]
},
- "hash": "ea44656ddebaee025a59c283b3d87f4f962a0954efbe1765757f48dc01381039"
+ "hash": "f3479ddd35d19a7e2cbddf56e4d7ceae6053583db8563c3840eceb7fbd71da8e"
}
diff --git a/.sqlx/query-7299880543d00414f154d2b35943d15a763e6360cb21dd0e0197f80298a754b9.json b/.sqlx/query-f3f399f1d58a27770e86a900b4315dbaa2a286a6f13498e6bdeff753672b2283.json
similarity index 88%
rename from .sqlx/query-7299880543d00414f154d2b35943d15a763e6360cb21dd0e0197f80298a754b9.json
rename to .sqlx/query-f3f399f1d58a27770e86a900b4315dbaa2a286a6f13498e6bdeff753672b2283.json
index ae4fe51815..e0df2313e5 100644
--- a/.sqlx/query-7299880543d00414f154d2b35943d15a763e6360cb21dd0e0197f80298a754b9.json
+++ b/.sqlx/query-f3f399f1d58a27770e86a900b4315dbaa2a286a6f13498e6bdeff753672b2283.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT id, name, description, owner_id, database_id, table_id,\n submitted_column_id, respondent_column_id, audience, tally_visible,\n status, closes_at, confirmation_message, logo_file_id, cover_file_id, accent_color,\n created_at, updated_at, trashed_at,\n name_follows_database, is_hidden_in_drive\n FROM forms WHERE database_id = $1 AND trashed_at IS NULL\n ORDER BY created_at, id\n ",
+ "query": "\n SELECT id, name, description, owner_id, database_id, table_id,\n submitted_column_id, respondent_column_id, audience, tally_visible,\n status, closes_at, confirmation_message, logo_file_id, cover_file_id, accent_color,\n created_at, updated_at, trashed_at,\n name_follows_database, is_hidden_in_drive, project_id\n FROM forms WHERE database_id = $1 AND trashed_at IS NULL\n ORDER BY created_at, id\n ",
"describe": {
"columns": [
{
@@ -107,6 +107,11 @@
"ordinal": 20,
"name": "is_hidden_in_drive",
"type_info": "Bool"
+ },
+ {
+ "ordinal": 21,
+ "name": "project_id",
+ "type_info": "Text"
}
],
"parameters": {
@@ -135,8 +140,9 @@
false,
true,
false,
- false
+ false,
+ true
]
},
- "hash": "7299880543d00414f154d2b35943d15a763e6360cb21dd0e0197f80298a754b9"
+ "hash": "f3f399f1d58a27770e86a900b4315dbaa2a286a6f13498e6bdeff753672b2283"
}
diff --git a/apps/web/src/components/app/split-layout/components/SplitFileMenu.tsx b/apps/web/src/components/app/split-layout/components/SplitFileMenu.tsx
index cf017e512b..374ed689aa 100644
--- a/apps/web/src/components/app/split-layout/components/SplitFileMenu.tsx
+++ b/apps/web/src/components/app/split-layout/components/SplitFileMenu.tsx
@@ -623,11 +623,7 @@ export function SplitFileMenu(props: SplitFileMenuProps) {
return {
label: t('entityActions.moveToFolder'),
action: () => {
- const entity = buildEntityData({
- id: props.id,
- name: props.name,
- blockName: props.entityKind,
- });
+ const entity = menuEntity();
if (!entity) return;
setOpen(false);
openBulkEditModal({
diff --git a/apps/web/src/features/block-database/browser-test/document-data.ts b/apps/web/src/features/block-database/browser-test/document-data.ts
index 29feb73ae4..ca79688c5c 100644
--- a/apps/web/src/features/block-database/browser-test/document-data.ts
+++ b/apps/web/src/features/block-database/browser-test/document-data.ts
@@ -14,6 +14,7 @@ export function documentDatabaseDetail(): DatabaseDetail {
owner_id: 'macro|[email protected]',
created_at: '2026-10-09T00:00:00Z',
trashed_at: null,
+ project_id: null,
},
grant: 'owner',
tables: [
diff --git a/apps/web/src/features/block-database/browser-test/rename-data.ts b/apps/web/src/features/block-database/browser-test/rename-data.ts
index e1339e1887..365bf5b0c0 100644
--- a/apps/web/src/features/block-database/browser-test/rename-data.ts
+++ b/apps/web/src/features/block-database/browser-test/rename-data.ts
@@ -8,6 +8,7 @@ export const RENAME_DETAIL: DatabaseDetail = {
owner_id: 'owner',
created_at: '',
trashed_at: null,
+ project_id: null,
},
grant: 'owner',
tables: [
diff --git a/apps/web/src/features/block-database/component/TableTabs.test.tsx b/apps/web/src/features/block-database/component/TableTabs.test.tsx
index 43c5321317..4ec72e778d 100644
--- a/apps/web/src/features/block-database/component/TableTabs.test.tsx
+++ b/apps/web/src/features/block-database/component/TableTabs.test.tsx
@@ -52,6 +52,7 @@ const detail: DatabaseDetail = {
owner_id: 'owner',
created_at: '',
trashed_at: null,
+ project_id: null,
},
grant: 'owner',
tables: [
diff --git a/apps/web/src/features/block-database/component/TopBar.tsx b/apps/web/src/features/block-database/component/TopBar.tsx
index 5deee678b8..fadca96053 100644
--- a/apps/web/src/features/block-database/component/TopBar.tsx
+++ b/apps/web/src/features/block-database/component/TopBar.tsx
@@ -1,9 +1,12 @@
+import { openBulkEditModal } from '@app/features/entity/bulk-edit/BulkEditEntityModal';
+import { toastMovedToFolder } from '@app/features/entity/bulk-edit/moved-to-folder-toast';
import {
makeCopyEntityIdAction,
makeCopyLinkAction,
makeFavoriteAction,
} from '@app/features/next-soup/actions';
import { useFeatureFlag } from '@app/lib/analytics/posthog';
+import { t } from '@app/lib/i18n';
import { HeaderActionGroup } from '@components/app/HeaderActionGroup';
import { ResponsivePermissionsBadge } from '@components/app/ResponsiveBlockToolbar';
import {
@@ -92,6 +95,7 @@ export function TopBar(props: {
name: detail.database.name,
ownerId: detail.database.owner_id,
grant: detail.grant,
+ projectId: detail.database.project_id ?? undefined,
});
const entityActions = (detail: DatabaseDetail): DatabaseEntityActions => ({
favorited: favoriteAction.isFavorited(entity(detail)),
@@ -110,6 +114,17 @@ export function TopBar(props: {
copyEntityIdAction.executeById(databaseId),
'database-actions'
),
+ onMoveToFolder:
+ detail.grant === 'owner'
+ ? () =>
+ openBulkEditModal({
+ view: 'moveToProject',
+ entities: [entity(detail)],
+ onMoved: (folder) => toastMovedToFolder(1, folder.id),
+ onError: () =>
+ toast.failure(t('entityActions.toastMoveToFolderFailed')),
+ })
+ : undefined,
});
const rename = (next: string) => {
renameDatabase(getEntityGraphqlClient(), databaseId, next).mapErr(
diff --git a/apps/web/src/features/block-database/queries/create-table.test.ts b/apps/web/src/features/block-database/queries/create-table.test.ts
index 662c08556c..f7de258f04 100644
--- a/apps/web/src/features/block-database/queries/create-table.test.ts
+++ b/apps/web/src/features/block-database/queries/create-table.test.ts
@@ -67,6 +67,7 @@ function detail(columns: ColumnDetail[]): DatabaseDetail {
owner_id: 'owner',
created_at: '',
trashed_at: null,
+ project_id: null,
},
grant: 'owner',
tables: [
diff --git a/apps/web/src/features/block-database/queries/database-relations.test.tsx b/apps/web/src/features/block-database/queries/database-relations.test.tsx
index 542af33b89..85710ad828 100644
--- a/apps/web/src/features/block-database/queries/database-relations.test.tsx
+++ b/apps/web/src/features/block-database/queries/database-relations.test.tsx
@@ -52,6 +52,7 @@ const detail: DatabaseDetail = {
owner_id: 'owner',
created_at: '',
trashed_at: null,
+ project_id: null,
},
grant: 'owner',
tables: [
diff --git a/apps/web/src/features/block-database/queries/database-search.test.ts b/apps/web/src/features/block-database/queries/database-search.test.ts
index 54cf907096..ef1047a630 100644
--- a/apps/web/src/features/block-database/queries/database-search.test.ts
+++ b/apps/web/src/features/block-database/queries/database-search.test.ts
@@ -9,6 +9,7 @@ const partyPlanner: DatabaseDetail = {
owner_id: 'owner',
created_at: '',
trashed_at: null,
+ project_id: null,
},
grant: 'owner',
tables: [
diff --git a/apps/web/src/features/block-database/queries/options.test.ts b/apps/web/src/features/block-database/queries/options.test.ts
index 833d7f080f..b746fb1676 100644
--- a/apps/web/src/features/block-database/queries/options.test.ts
+++ b/apps/web/src/features/block-database/queries/options.test.ts
@@ -32,6 +32,7 @@ const detail: DatabaseDetail = {
owner_id: 'owner',
created_at: '',
trashed_at: null,
+ project_id: null,
},
grant: 'owner',
tables: [
diff --git a/apps/web/src/features/block-database/queries/reorder-tables.test.ts b/apps/web/src/features/block-database/queries/reorder-tables.test.ts
index d8d02c8318..2b14e6c6d4 100644
--- a/apps/web/src/features/block-database/queries/reorder-tables.test.ts
+++ b/apps/web/src/features/block-database/queries/reorder-tables.test.ts
@@ -42,6 +42,7 @@ const detail: DatabaseDetail = {
owner_id: 'owner',
created_at: '',
trashed_at: null,
+ project_id: null,
},
grant: 'owner',
tables: [
diff --git a/apps/web/src/features/block-database/queries/table-rows.test.tsx b/apps/web/src/features/block-database/queries/table-rows.test.tsx
index f3bbb2c94d..24ef4fc499 100644
--- a/apps/web/src/features/block-database/queries/table-rows.test.tsx
+++ b/apps/web/src/features/block-database/queries/table-rows.test.tsx
@@ -89,6 +89,7 @@ function detail(sqlName = '"guests"'): DatabaseDetail {
owner_id: 'owner',
created_at: '',
trashed_at: null,
+ project_id: null,
},
grant: 'owner',
tables: [
diff --git a/apps/web/src/features/block-database/queries/transfer.test.ts b/apps/web/src/features/block-database/queries/transfer.test.ts
index 8fc805ea54..f1c5514ebb 100644
--- a/apps/web/src/features/block-database/queries/transfer.test.ts
+++ b/apps/web/src/features/block-database/queries/transfer.test.ts
@@ -147,6 +147,7 @@ const database: DatabaseDetail = {
owner_id: 'owner',
created_at: '',
trashed_at: null,
+ project_id: null,
},
grant: 'view',
tables: [table],
diff --git a/apps/web/src/features/block-database/queries/views.test.ts b/apps/web/src/features/block-database/queries/views.test.ts
index d3b808ec87..cde0699633 100644
--- a/apps/web/src/features/block-database/queries/views.test.ts
+++ b/apps/web/src/features/block-database/queries/views.test.ts
@@ -38,6 +38,7 @@ const detail: DatabaseDetail = {
owner_id: 'owner',
created_at: '',
trashed_at: null,
+ project_id: null,
},
grant: 'owner',
tables: [
diff --git a/apps/web/src/features/block-database/views/database-page-actions.tsx b/apps/web/src/features/block-database/views/database-page-actions.tsx
index bf9a8e78e1..c323b7a775 100644
--- a/apps/web/src/features/block-database/views/database-page-actions.tsx
+++ b/apps/web/src/features/block-database/views/database-page-actions.tsx
@@ -1,5 +1,7 @@
+import { t } from '@app/lib/i18n';
import { fireAndForget } from '@core/util/fireAndForget';
import { downloadFile } from '@filesystem/download';
+import ArrowRightIcon from '@icon/system/regular/arrow-right.svg';
import CaretRightIcon from '@icon/system/regular/caret-right.svg';
import CopyIcon from '@icon/system/regular/copy.svg';
import DotsThreeIcon from '@icon/system/regular/dots-three.svg';
@@ -46,6 +48,8 @@ export type DatabaseEntityActions = {
onToggleFavorite: () => void;
onCopyLink: () => void;
onCopyId: () => void;
+ /** Present for the owner, who alone may file it in a folder. */
+ onMoveToFolder?: () => void;
};
export function DatabasePageActions(props: {
@@ -197,6 +201,14 @@ export function DatabasePageActions(props: {
<StarIcon class="size-4 shrink-0" />
{actions().favorited ? 'Unfavorite' : 'Favorite'}
</Dropdown.Item>
+ <Show when={actions().onMoveToFolder}>
+ {(moveToFolder) => (
+ <Dropdown.Item onSelect={moveToFolder()}>
+ <ArrowRightIcon class="size-4 shrink-0" />
+ {t('entityActions.moveToFolder')}
+ </Dropdown.Item>
+ )}
+ </Show>
</Dropdown.Group>
</>
)}
diff --git a/apps/web/src/features/block-form/form-block.tsx b/apps/web/src/features/block-form/form-block.tsx
index 0094d78da5..d8a7a61b29 100644
--- a/apps/web/src/features/block-form/form-block.tsx
+++ b/apps/web/src/features/block-form/form-block.tsx
@@ -179,7 +179,7 @@ function FormBlockContent(props: {
access: detail().access,
}}
permissions={getPermissions(detail().access)}
- ops={[]}
+ ops={[{ op: 'moveToProject' }]}
buttonClass={isTouchDevice() ? 'order-last' : 'order-first'}
/>
</SplitTitleFileMenu>
diff --git a/apps/web/src/features/block-form/form-global-sharing.test.tsx b/apps/web/src/features/block-form/form-global-sharing.test.tsx
index d8e9dc20fc..bd7e5db99f 100644
--- a/apps/web/src/features/block-form/form-global-sharing.test.tsx
+++ b/apps/web/src/features/block-form/form-global-sharing.test.tsx
@@ -207,6 +207,7 @@ describe('openFormShareModal', () => {
respondentColumnId: null,
createdAt: '2026-10-05T12:00:00Z',
updatedAt: '2026-10-05T12:00:00Z',
+ projectId: null,
isHiddenInDrive: false,
},
sections: [],
diff --git a/apps/web/src/features/block-form/queries/form-detail.test.ts b/apps/web/src/features/block-form/queries/form-detail.test.ts
index 6c8b655bb1..4bed6047b6 100644
--- a/apps/web/src/features/block-form/queries/form-detail.test.ts
+++ b/apps/web/src/features/block-form/queries/form-detail.test.ts
@@ -119,6 +119,7 @@ describe('the booking step', () => {
respondentColumnId: null,
createdAt: '2026-10-01T12:00:00Z',
updatedAt: '2026-10-01T12:00:00Z',
+ projectId: null,
isHiddenInDrive: false,
} as const;
diff --git a/apps/web/src/features/block-form/queries/form-publication.test.ts b/apps/web/src/features/block-form/queries/form-publication.test.ts
index 3bc4ba289e..cb04733f57 100644
--- a/apps/web/src/features/block-form/queries/form-publication.test.ts
+++ b/apps/web/src/features/block-form/queries/form-publication.test.ts
@@ -20,6 +20,7 @@ const detail: FormCollaboration['detail'] = {
branding: { logoFileId: null, coverFileId: null, accentColor: null },
createdAt: '2026-10-05T09:00:00Z',
updatedAt: '2026-10-05T09:00:00Z',
+ projectId: null,
isHiddenInDrive: false,
},
access: 'edit',
diff --git a/apps/web/src/features/database-query/database-query.test.tsx b/apps/web/src/features/database-query/database-query.test.tsx
index 0fbaca71ab..927d72112a 100644
--- a/apps/web/src/features/database-query/database-query.test.tsx
+++ b/apps/web/src/features/database-query/database-query.test.tsx
@@ -153,6 +153,7 @@ const detail: DatabaseDetail = {
owner_id: 'owner',
created_at: '',
trashed_at: null,
+ project_id: null,
},
grant: 'owner',
tables: [],
diff --git a/apps/web/src/features/database-query/queries/app-query-source.test.ts b/apps/web/src/features/database-query/queries/app-query-source.test.ts
index 266f14d3f5..22be113bf7 100644
--- a/apps/web/src/features/database-query/queries/app-query-source.test.ts
+++ b/apps/web/src/features/database-query/queries/app-query-source.test.ts
@@ -31,6 +31,7 @@ const databases: DatabaseDetail[] = ['first', 'second'].map((id) => ({
owner_id: 'owner',
created_at: '',
trashed_at: null,
+ project_id: null,
},
grant: 'view',
tables: [
diff --git a/apps/web/src/features/database-query/queries/query-source.test.tsx b/apps/web/src/features/database-query/queries/query-source.test.tsx
index c26f33f68b..57457ceb10 100644
--- a/apps/web/src/features/database-query/queries/query-source.test.tsx
+++ b/apps/web/src/features/database-query/queries/query-source.test.tsx
@@ -27,6 +27,7 @@ describe('query schema', () => {
owner_id: 'owner',
created_at: '',
trashed_at: null,
+ project_id: null,
},
grant: 'owner',
tables: [
@@ -208,6 +209,7 @@ const workspace: DatabaseDetail = {
owner_id: 'owner',
created_at: '',
trashed_at: null,
+ project_id: null,
},
grant: 'edit',
tables: [
diff --git a/apps/web/src/features/database-query/queries/question-capabilities.test.ts b/apps/web/src/features/database-query/queries/question-capabilities.test.ts
index bab97a679e..255168e7d6 100644
--- a/apps/web/src/features/database-query/queries/question-capabilities.test.ts
+++ b/apps/web/src/features/database-query/queries/question-capabilities.test.ts
@@ -17,6 +17,7 @@ const detail: DatabaseDetail = {
owner_id: 'owner',
created_at: '',
trashed_at: null,
+ project_id: null,
},
grant: 'view',
tables: ['Tickets', 'Customers'].map((name) => ({
diff --git a/apps/web/src/features/drive-view/drive-create-menu.tsx b/apps/web/src/features/drive-view/drive-create-menu.tsx
index 4bc21d7903..8816035a47 100644
--- a/apps/web/src/features/drive-view/drive-create-menu.tsx
+++ b/apps/web/src/features/drive-view/drive-create-menu.tsx
@@ -86,7 +86,7 @@ export function DriveCreateMenu(props: {
'form',
].includes(block.blockName) &&
isEnabled(block.blockName) &&
- // Databases and forms have no folder membership.
+ // New databases and forms start at the root; they are moved in after.
((block.blockName !== 'database' && block.blockName !== 'form') ||
!state.projectId())
);
diff --git a/apps/web/src/features/drive-view/queries/drive-data-source.test.ts b/apps/web/src/features/drive-view/queries/drive-data-source.test.ts
index 44e126a9c9..a38123dfb5 100644
--- a/apps/web/src/features/drive-view/queries/drive-data-source.test.ts
+++ b/apps/web/src/features/drive-view/queries/drive-data-source.test.ts
@@ -81,6 +81,7 @@ function setup() {
owner_id: 'me',
created_at: '2026-09-01T00:00:00Z',
trashed_at: null,
+ project_id: null,
},
grant: 'owner',
tables: [],
diff --git a/apps/web/src/features/drive-view/queries/drive-data-source.ts b/apps/web/src/features/drive-view/queries/drive-data-source.ts
index 8cb4767351..82186b3184 100644
--- a/apps/web/src/features/drive-view/queries/drive-data-source.ts
+++ b/apps/web/src/features/drive-view/queries/drive-data-source.ts
@@ -75,25 +75,20 @@ export function createDriveDataSource(options: {
const searchContext = useOptionalSearchContext();
const databasesQuery = useDatabasesQuery();
- const includesDatabases = () => {
- const current = selection();
- return (
- options.databasesEnabled() &&
- current.location.kind === 'tab' &&
- current.location.tab !== 'recent' &&
- current.scope !== 'attachments'
- );
+ // Databases and forms come from their own lists, in file tabs and in the
+ // folder they are filed in.
+ const listsDatabasesAndForms = () => {
+ const { location, scope } = selection();
+ if (scope === 'attachments') return false;
+ return location.kind === 'tab'
+ ? location.tab !== 'recent'
+ : Boolean(location.id);
};
+ const includesDatabases = () =>
+ options.databasesEnabled() && listsDatabasesAndForms();
const formsQuery = useFormsQuery();
- const includesForms = () => {
- const current = selection();
- return (
- options.formsEnabled() &&
- current.location.kind === 'tab' &&
- current.location.tab !== 'recent' &&
- current.scope !== 'attachments'
- );
- };
+ const includesForms = () =>
+ options.formsEnabled() && listsDatabasesAndForms();
// Wait for the forms list, which names the databases made for polls.
const databaseEntities = () =>
includesDatabases() &&
diff --git a/apps/web/src/features/drive-view/queries/drive-databases.test.ts b/apps/web/src/features/drive-view/queries/drive-databases.test.ts
index e975a9ecd4..20208e1b7a 100644
--- a/apps/web/src/features/drive-view/queries/drive-databases.test.ts
+++ b/apps/web/src/features/drive-view/queries/drive-databases.test.ts
@@ -26,6 +26,7 @@ const listed: ListedDatabase[] = [
owner_id: 'me',
created_at: '2026-09-01T00:00:00Z',
trashed_at: null,
+ project_id: null,
},
grant: 'owner',
tables: [],
@@ -37,6 +38,7 @@ const listed: ListedDatabase[] = [
owner_id: 'other',
created_at: '2026-09-02T00:00:00Z',
trashed_at: null,
+ project_id: null,
},
grant: 'view',
tables: [],
@@ -48,6 +50,7 @@ const listed: ListedDatabase[] = [
owner_id: 'me',
created_at: '2026-09-03T00:00:00Z',
trashed_at: '2026-09-04T00:00:00Z',
+ project_id: null,
},
grant: 'owner',
tables: [],
@@ -108,11 +111,77 @@ describe('Drive database listing', () => {
)
).toEqual([]);
});
- it('does not claim folder membership, attachment status or view history', () => {
+ it("lists a folder's databases, owned or shared, inside that folder only", () => {
+ const filed: ListedDatabase[] = [
+ ...listed,
+ {
+ database: {
+ id: 'filed-mine',
+ name: 'Client intake',
+ owner_id: 'me',
+ created_at: '2026-09-05T00:00:00Z',
+ trashed_at: null,
+ project_id: 'clients',
+ },
+ grant: 'owner',
+ tables: [],
+ },
+ {
+ database: {
+ id: 'filed-shared',
+ name: 'Client contacts',
+ owner_id: 'other',
+ created_at: '2026-09-06T00:00:00Z',
+ trashed_at: null,
+ project_id: 'clients',
+ },
+ grant: 'edit',
+ tables: [],
+ },
+ ];
+ const folder = {
+ ...selection,
+ location: { kind: 'folder', id: 'clients' },
+ } satisfies DriveSelection;
+ const inFolder = selectDriveDatabases(filed, folder, 'me', none);
+ expect(inFolder.map((entity) => entity.id)).toEqual([
+ 'filed-mine',
+ 'filed-shared',
+ ]);
+ expect(inFolder[0]?.projectId).toBe('clients');
+ expect(
+ inFolder.every((entity) =>
+ driveEntityMatchesLocation(entity, folder, 'me')
+ )
+ ).toBe(true);
+ expect(
+ selectDriveDatabases(
+ filed,
+ { ...folder, location: { kind: 'folder', id: 'other-folder' } },
+ 'me',
+ none
+ )
+ ).toEqual([]);
+ expect(
+ selectDriveDatabases(
+ filed,
+ { ...folder, search: 'contacts' },
+ 'me',
+ none
+ ).map((entity) => entity.id)
+ ).toEqual(['filed-shared']);
+ // Tabs stay flat: a filed database is still among the owner's databases.
+ expect(
+ selectDriveDatabases(filed, selection, 'me', none).map(
+ (entity) => entity.id
+ )
+ ).toEqual(['mine', 'filed-mine']);
+ });
+ it('does not claim attachment status or view history', () => {
for (const selected of [
{
...selection,
- location: { kind: 'folder', id: 'folder' },
+ location: { kind: 'folder', id: null },
} satisfies DriveSelection,
{
...selection,
@@ -175,6 +244,7 @@ describe('Drive sidebar databases', () => {
owner_id: 'me',
created_at: '2026-09-05T00:00:00Z',
trashed_at: null,
+ project_id: null,
},
grant: 'owner',
tables: [],
diff --git a/apps/web/src/features/drive-view/queries/drive-databases.ts b/apps/web/src/features/drive-view/queries/drive-databases.ts
index 129f6e1ada..ca8f341f52 100644
--- a/apps/web/src/features/drive-view/queries/drive-databases.ts
+++ b/apps/web/src/features/drive-view/queries/drive-databases.ts
@@ -3,8 +3,9 @@ import type { ListedDatabase } from '@service-storage/generated/schemas/listedDa
import type { DriveSelection } from '../context/drive-source';
/**
- * Databases have no folder membership or view history; list them in file tabs.
- * `hidden` names databases made for a form kept out of Drive, like a poll's.
+ * Databases have no view history; list them in file tabs and in the folder
+ * they are filed in. `hidden` names databases made for a form kept out of
+ * Drive, like a poll's.
*/
export function selectDriveDatabases(
listed: readonly ListedDatabase[],
@@ -13,15 +14,23 @@ export function selectDriveDatabases(
hidden: ReadonlySet<string>
): DatabaseEntity[] {
const { location, scope } = selection;
- if (!userId || location.kind !== 'tab' || location.tab === 'recent')
- return [];
- if (scope === 'attachments') return [];
+ if (!userId || scope === 'attachments') return [];
+ if (location.kind === 'tab' && location.tab === 'recent') return [];
+ if (location.kind === 'folder' && !location.id) return [];
const search = selection.search.trim().toLocaleLowerCase();
return listed.flatMap(({ database, grant }) => {
if (database.trashed_at || hidden.has(database.id)) return [];
- if (location.tab === 'shared' && database.owner_id === userId) return [];
+ if (location.kind === 'folder' && database.project_id !== location.id)
+ return [];
+ if (
+ location.kind === 'tab' &&
+ location.tab === 'shared' &&
+ database.owner_id === userId
+ )
+ return [];
if (
+ location.kind === 'tab' &&
location.tab === 'owned' &&
scope === 'default' &&
database.owner_id !== userId
@@ -37,6 +46,7 @@ export function selectDriveDatabases(
ownerId: database.owner_id,
createdAt: database.created_at,
grant,
+ projectId: database.project_id ?? undefined,
},
];
});
@@ -59,6 +69,7 @@ export function selectSidebarDatabases(
ownerId: database.owner_id,
createdAt: database.created_at,
grant,
+ projectId: database.project_id ?? undefined,
},
]
)
diff --git a/apps/web/src/features/drive-view/queries/drive-forms.test.ts b/apps/web/src/features/drive-view/queries/drive-forms.test.ts
index fbd2017a07..d914bae6e8 100644
--- a/apps/web/src/features/drive-view/queries/drive-forms.test.ts
+++ b/apps/web/src/features/drive-view/queries/drive-forms.test.ts
@@ -29,6 +29,7 @@ const listed: ListedForm[] = [
branding: { logoFileId: null, coverFileId: null, accentColor: null },
createdAt: '2026-10-01T00:00:00Z',
updatedAt: '2026-10-01T00:00:00Z',
+ projectId: null,
isHiddenInDrive: false,
},
access: 'owner',
@@ -51,6 +52,7 @@ const listed: ListedForm[] = [
branding: { logoFileId: null, coverFileId: null, accentColor: null },
createdAt: '2026-10-02T00:00:00Z',
updatedAt: '2026-10-02T00:00:00Z',
+ projectId: null,
isHiddenInDrive: true,
},
access: 'owner',
@@ -65,3 +67,31 @@ describe('Drive form listing', () => {
expect(hiddenFormDatabases(listed)).toEqual(new Set(['poll-database']));
});
});
+
+describe('Drive forms in folders', () => {
+ it("lists a folder's forms inside that folder, and keeps tabs flat", () => {
+ const [rsvp, poll] = listed;
+ if (!rsvp || !poll) throw new Error('fixture');
+ const filed: ListedForm[] = [
+ { ...rsvp, form: { ...rsvp.form, projectId: 'clients' } },
+ { ...poll, form: { ...poll.form, projectId: 'clients' } },
+ ];
+ const folder = {
+ ...selection,
+ location: { kind: 'folder', id: 'clients' },
+ } satisfies DriveSelection;
+ const inFolder = selectDriveForms(filed, folder, 'me');
+ expect(inFolder.map((entity) => entity.id)).toEqual(['rsvp']);
+ expect(inFolder[0]?.projectId).toBe('clients');
+ expect(
+ selectDriveForms(
+ filed,
+ { ...folder, location: { kind: 'folder', id: 'other' } },
+ 'me'
+ )
+ ).toEqual([]);
+ expect(
+ selectDriveForms(filed, selection, 'me').map((entity) => entity.id)
+ ).toEqual(['rsvp']);
+ });
+});
diff --git a/apps/web/src/features/drive-view/queries/drive-forms.ts b/apps/web/src/features/drive-view/queries/drive-forms.ts
index bd0519dfe9..039bab14bf 100644
--- a/apps/web/src/features/drive-view/queries/drive-forms.ts
+++ b/apps/web/src/features/drive-view/queries/drive-forms.ts
@@ -2,21 +2,31 @@ import type { FormEntity } from '@entity';
import type { ListedForm } from '@service-storage/generated/schemas/listedForm';
import type { DriveSelection } from '../context/drive-source';
-/** Forms, like databases, have no folder or view history; list them in file tabs. */
+/**
+ * Forms, like databases, have no view history; list them in file tabs and in
+ * the folder they are filed in.
+ */
export function selectDriveForms(
listed: readonly ListedForm[],
selection: DriveSelection,
userId: string | undefined
): FormEntity[] {
const { location, scope } = selection;
- if (!userId || location.kind !== 'tab' || location.tab === 'recent')
- return [];
- if (scope === 'attachments') return [];
+ if (!userId || scope === 'attachments') return [];
+ if (location.kind === 'tab' && location.tab === 'recent') return [];
+ if (location.kind === 'folder' && !location.id) return [];
const search = selection.search.trim().toLocaleLowerCase();
return listed.flatMap(({ form, access }) => {
if (form.isHiddenInDrive) return [];
- if (location.tab === 'shared' && form.ownerId === userId) return [];
+ if (location.kind === 'folder' && form.projectId !== location.id) return [];
if (
+ location.kind === 'tab' &&
+ location.tab === 'shared' &&
+ form.ownerId === userId
+ )
+ return [];
+ if (
+ location.kind === 'tab' &&
location.tab === 'owned' &&
scope === 'default' &&
form.ownerId !== userId
@@ -31,6 +41,7 @@ export function selectDriveForms(
ownerId: form.ownerId,
createdAt: form.createdAt,
access,
+ projectId: form.projectId ?? undefined,
},
];
});
diff --git a/apps/web/src/features/drive-view/queries/drive-results.ts b/apps/web/src/features/drive-view/queries/drive-results.ts
index 1213e0572a..fd53f6cbc2 100644
--- a/apps/web/src/features/drive-view/queries/drive-results.ts
+++ b/apps/web/src/features/drive-view/queries/drive-results.ts
@@ -28,6 +28,8 @@ function entityMatchesFolder(
case 'document':
case 'chat':
case 'project':
+ case 'database':
+ case 'form':
return entity.projectId === projectId;
case 'email':
if (entity.projectId) return entity.projectId === projectId;
diff --git a/apps/web/src/features/entity/queries/dss.test.tsx b/apps/web/src/features/entity/queries/dss.test.tsx
index 89ad2940d8..76cb04ccff 100644
--- a/apps/web/src/features/entity/queries/dss.test.tsx
+++ b/apps/web/src/features/entity/queries/dss.test.tsx
@@ -89,6 +89,7 @@ import {
type GraphqlSoupDeleteContext,
usePendingGraphqlSoupDeleteKeys,
} from '@queries/soup/graphql/optimistic-deletions';
+import { databasesKeys, formsKeys } from '@queries/storage/keys';
import { BulkDeleteFailure } from './bulk-delete-result';
import {
createBulkCopyDssEntityMutation,
@@ -682,3 +683,98 @@ describe('bulk delete GraphQL optimism', () => {
}
);
});
+
+describe('moving databases and forms between folders', () => {
+ const listedDatabase = {
+ database: {
+ id: 'intake',
+ name: 'Client intake',
+ owner_id: 'viewer',
+ created_at: '2026-10-01T00:00:00Z',
+ trashed_at: null,
+ project_id: null,
+ },
+ grant: 'owner',
+ tables: [],
+ };
+ const listedForm = {
+ form: { id: 'survey', name: 'Survey', projectId: 'old' },
+ access: 'owner',
+ };
+ const filed = () => ({
+ database: (
+ client.getQueryData(databasesKeys.list.queryKey) as
+ | (typeof listedDatabase)[]
+ | undefined
+ )?.[0]?.database.project_id,
+ form: (
+ client.getQueryData(formsKeys.list.queryKey) as
+ | (typeof listedForm)[]
+ | undefined
+ )?.[0]?.form.projectId,
+ });
+ const seed = () => {
+ client.setQueryData(databasesKeys.list.queryKey, [listedDatabase]);
+ client.setQueryData(formsKeys.list.queryKey, [listedForm]);
+ };
+
+ it('files them in the Drive lists at once and moves each through moveToFolder', async () => {
+ seed();
+ const pending = deferred<boolean>();
+ mocks.moveToFolder.mockReturnValue(pending.promise);
+ const mutation = mountMutation(createBulkMoveToProjectDssEntityMutation);
+ const result = mutation.mutateAsync({
+ entities: [
+ { ...entity('intake', 'database'), name: 'Client intake' },
+ { ...entity('survey', 'form'), name: 'Survey' },
+ ],
+ project: { id: 'clients', name: 'Clients' },
+ });
+ await vi.waitFor(() =>
+ expect(filed()).toEqual({ database: 'clients', form: 'clients' })
+ );
+ pending.resolve(true);
+ await result;
+ expect(mocks.moveToFolder.mock.calls).toEqual([
+ [{ itemType: 'database', id: 'intake', folderId: 'clients' }],
+ [{ itemType: 'form', id: 'survey', folderId: 'clients' }],
+ ]);
+ expect(
+ client.getQueryState(databasesKeys.list.queryKey)?.isInvalidated
+ ).toBe(true);
+ expect(client.getQueryState(formsKeys.list.queryKey)?.isInvalidated).toBe(
+ true
+ );
+ });
+
+ it('puts them back when the move fails', async () => {
+ seed();
+ mocks.moveToFolder.mockResolvedValue(false);
+ const mutation = mountMutation(createBulkMoveToProjectDssEntityMutation);
+ await expect(
+ mutation.mutateAsync({
+ entities: [
+ { ...entity('intake', 'database'), name: 'Client intake' },
+ { ...entity('survey', 'form'), name: 'Survey' },
+ ],
+ project: { id: 'clients', name: 'Clients' },
+ })
+ ).rejects.toThrow();
+ expect(filed()).toEqual({ database: null, form: 'old' });
+ });
+
+ it('takes them out of their folder', async () => {
+ seed();
+ const mutation = mountMutation(
+ createBulkRemoveFromProjectDssEntityMutation
+ );
+ await mutation.mutateAsync({
+ entities: [entity('intake', 'database'), entity('survey', 'form')],
+ });
+ expect(filed()).toEqual({ database: null, form: null });
+ expect(mocks.moveToFolder.mock.calls).toEqual([
+ [{ itemType: 'database', id: 'intake', folderId: null }],
+ [{ itemType: 'form', id: 'survey', folderId: null }],
+ ]);
+ });
+});
diff --git a/apps/web/src/features/entity/queries/dss.ts b/apps/web/src/features/entity/queries/dss.ts
index 192a619973..fe52526602 100644
--- a/apps/web/src/features/entity/queries/dss.ts
+++ b/apps/web/src/features/entity/queries/dss.ts
@@ -14,6 +14,7 @@ import {
enableGraphqlSoup,
isFeatureEnabled,
} from '@core/constant/featureFlags';
+import { fireAndForget } from '@core/util/fireAndForget';
import { throwOnErr } from '@core/util/result';
import { deleteAgentSession } from '@queries/agent-session/entity-mutations';
import { callKeys } from '@queries/call/keys';
@@ -37,8 +38,11 @@ import {
import { soupKeys } from '@queries/soup/keys';
import { ownTouchStamp } from '@queries/soup/normalized-cache/own-touch';
import { permanentlyDeleteEntity } from '@queries/storage/entity-mutations';
+import { databasesKeys, formsKeys } from '@queries/storage/keys';
import { callServiceClient } from '@service-call/client';
import { scheduledActionClient } from '@service-scheduled-action/client';
+import type { ListedDatabase } from '@service-storage/generated/schemas/listedDatabase';
+import type { ListedForm } from '@service-storage/generated/schemas/listedForm';
import { getEntityGraphqlClient } from '@service-storage/graphql-soup';
import { useMutation } from '@tanstack/solid-query';
import { batch } from 'solid-js';
@@ -253,6 +257,89 @@ export function createBulkDeleteDssItemsMutation() {
}));
}
+type FolderMovableType =
+ | 'document'
+ | 'chat'
+ | 'project'
+ | 'email'
+ | 'database'
+ | 'form';
+
+const isFolderMovable = (
+ entity: EntityData
+): entity is EntityData & { type: FolderMovableType } =>
+ entity.type === 'document' ||
+ entity.type === 'chat' ||
+ entity.type === 'project' ||
+ entity.type === 'email' ||
+ entity.type === 'database' ||
+ entity.type === 'form';
+
+/**
+ * Databases and forms reach Drive through their own lists, not Soup: refile
+ * them there at once, answering how to put them back.
+ */
+function refileListedEntities(
+ entities: readonly EntityData[],
+ projectId: string | null
+) {
+ const databaseIds = new Set(
+ entities.flatMap((e) => (e.type === 'database' ? [e.id] : []))
+ );
+ const formIds = new Set(
+ entities.flatMap((e) => (e.type === 'form' ? [e.id] : []))
+ );
+ const databases = queryClient.getQueryData<ListedDatabase[]>(
+ databasesKeys.list.queryKey
+ );
+ const forms = queryClient.getQueryData<ListedForm[]>(formsKeys.list.queryKey);
+ if (databases && databaseIds.size > 0) {
+ queryClient.setQueryData<ListedDatabase[]>(
+ databasesKeys.list.queryKey,
+ databases.map((listed) =>
+ databaseIds.has(listed.database.id)
+ ? {
+ ...listed,
+ database: { ...listed.database, project_id: projectId },
+ }
+ : listed
+ )
+ );
+ }
+ if (forms && formIds.size > 0) {
+ queryClient.setQueryData<ListedForm[]>(
+ formsKeys.list.queryKey,
+ forms.map((listed) =>
+ formIds.has(listed.form.id)
+ ? { ...listed, form: { ...listed.form, projectId } }
+ : listed
+ )
+ );
+ }
+ return {
+ rollback: () => {
+ if (databases && databaseIds.size > 0)
+ queryClient.setQueryData(databasesKeys.list.queryKey, databases);
+ if (forms && formIds.size > 0)
+ queryClient.setQueryData(formsKeys.list.queryKey, forms);
+ },
+ };
+}
+
+/** Re-read the database and form lists after their entities moved. */
+function invalidateListedEntities(entities: readonly EntityData[]) {
+ if (entities.some((e) => e.type === 'database'))
+ fireAndForget(
+ queryClient.invalidateQueries({ queryKey: databasesKeys.list.queryKey }),
+ 'entity-move'
+ );
+ if (entities.some((e) => e.type === 'form'))
+ fireAndForget(
+ queryClient.invalidateQueries({ queryKey: formsKeys.list.queryKey }),
+ 'entity-move'
+ );
+}
+
function invalidateAfterMove(
entityIds: string[],
destinationProjectId: string,
@@ -327,26 +414,16 @@ export function createMoveToProjectDssEntityMutation() {
}
export function createBulkRemoveFromProjectDssEntityMutation() {
- const isUnsupportedEntity = (entity: EntityData) => {
- const type = entity.type;
- return (
- type !== 'chat' &&
- type !== 'document' &&
- type !== 'project' &&
- type !== 'email'
- );
- };
-
return useMutation(() => ({
mutationFn: async ({ entities }: { entities: EntityData[] }) => {
- if (entities.some(isUnsupportedEntity)) {
+ if (!entities.every(isFolderMovable)) {
throw new Error(`Unsupported entity type provided`);
}
const results = await Promise.all(
entities.map((entity) =>
moveToFolder({
- itemType: entity.type as 'document' | 'chat' | 'project' | 'email',
+ itemType: entity.type,
id: entity.id,
folderId: null,
})
@@ -392,7 +469,8 @@ export function createBulkRemoveFromProjectDssEntityMutation() {
removeSoupEntitiesFromQueriesReferencing(
new Set(entities.map((e) => e.id)),
sourceProjectIds
- )
+ ),
+ refileListedEntities(entities, null)
);
return { txns, sourceProjectIds };
@@ -410,6 +488,7 @@ export function createBulkRemoveFromProjectDssEntityMutation() {
);
toast.failure('Failed to remove items from folder');
}
+ invalidateListedEntities(entities);
// Queries still containing the entities
for (const entity of entities) {
@@ -507,16 +586,6 @@ export function createBulkCopyDssEntityMutation() {
}
export function createBulkMoveToProjectDssEntityMutation() {
- const isUnsupportedEntity = (entity: EntityData) => {
- const type = entity.type;
- return (
- type !== 'chat' &&
- type !== 'document' &&
- type !== 'project' &&
- type !== 'email'
- );
- };
-
return useMutation(() => ({
mutationFn: async ({
entities,
@@ -525,14 +594,14 @@ export function createBulkMoveToProjectDssEntityMutation() {
entities: (EntityData & { name: string })[];
project: { id: string; name: string };
}) => {
- if (entities.some(isUnsupportedEntity)) {
+ if (!entities.every(isFolderMovable)) {
throw new Error(`Unsupported entity type provided`);
}
const results = await Promise.all(
entities.map((entity) =>
moveToFolder({
- itemType: entity.type as 'document' | 'chat' | 'project' | 'email',
+ itemType: entity.type,
id: entity.id,
folderId: project.id,
})
@@ -557,17 +626,20 @@ export function createBulkMoveToProjectDssEntityMutation() {
(e): e is typeof e & { type: 'document' | 'chat' | 'email' } =>
e.type === 'document' || e.type === 'chat' || e.type === 'email'
);
- return moveableEntities.map((e) => {
- const current = getSoupEntityById(e.id);
- const tag = e.type === 'email' ? 'emailThread' : e.type;
- return optimisticUpdateSoupEntity({
- tag,
- data: { id: e.id, projectId: project.id },
- frecency_score: current?.frecency_score ?? 0,
- // A move is an Edited activity, i.e. a touch (own-touch.ts).
- touched_at: ownTouchStamp(e.id),
- });
- });
+ return [
+ ...moveableEntities.map((e) => {
+ const current = getSoupEntityById(e.id);
+ const tag = e.type === 'email' ? 'emailThread' : e.type;
+ return optimisticUpdateSoupEntity({
+ tag,
+ data: { id: e.id, projectId: project.id },
+ frecency_score: current?.frecency_score ?? 0,
+ // A move is an Edited activity, i.e. a touch (own-touch.ts).
+ touched_at: ownTouchStamp(e.id),
+ });
+ }),
+ refileListedEntities(entities, project.id),
+ ];
},
onSettled: (data, error, { entities, project }, context) => {
@@ -576,6 +648,7 @@ export function createBulkMoveToProjectDssEntityMutation() {
context?.forEach((txn) => txn.rollback());
console.error(`Failed to bulk move dss items`, entities, data, error);
}
+ invalidateListedEntities(entities);
return invalidateAfterMove(
entities.map((e) => e.id),
diff --git a/apps/web/src/features/entity/types/drag.test.ts b/apps/web/src/features/entity/types/drag.test.ts
index cf0499f70c..cf514d18e0 100644
--- a/apps/web/src/features/entity/types/drag.test.ts
+++ b/apps/web/src/features/entity/types/drag.test.ts
@@ -15,6 +15,13 @@ describe('isEntityDragData', () => {
expect(isEntityDragData(validDragData)).toBe(true);
});
+ it.each(['database', 'form'] as const)(
+ 'accepts a dragged %s, which can be filed in a folder',
+ (type) => {
+ expect(isEntityDragData({ ...validDragData, type })).toBe(true);
+ }
+ );
+
it.each(['id', 'name', 'ownerId', 'type', 'operation'] as const)(
'rejects a payload without %s',
(field) => {
diff --git a/apps/web/src/features/entity/types/drag.ts b/apps/web/src/features/entity/types/drag.ts
index 53c9d3599e..72af3fa491 100644
--- a/apps/web/src/features/entity/types/drag.ts
+++ b/apps/web/src/features/entity/types/drag.ts
@@ -40,6 +40,8 @@ const ENTITY_DRAG_TYPES = [
'crm_contact',
'routine',
'calendar_event',
+ 'database',
+ 'form',
'foreign',
] as const satisfies readonly EntityData['type'][];
diff --git a/apps/web/src/features/entity/types/entity.ts b/apps/web/src/features/entity/types/entity.ts
index ab1edefd09..7168ac4db3 100644
--- a/apps/web/src/features/entity/types/entity.ts
+++ b/apps/web/src/features/entity/types/entity.ts
@@ -441,6 +441,8 @@ export type DatabaseEntity = EntityBase & {
type: 'database';
/** What the viewer may do with the database. */
grant: AccessLevel;
+ /** The folder it is filed in. */
+ projectId?: string;
};
/** A Macro Form. Like a database, not a Soup entity: `createdAt` is its only timestamp. */
@@ -448,6 +450,8 @@ export type FormEntity = EntityBase & {
type: 'form';
/** What the viewer may do: view responds, edit builds and reads responses. */
access: 'view' | 'edit' | 'owner';
+ /** The folder it is filed in. */
+ projectId?: string;
};
/** Normalized time shape of a calendar event soup row. */
diff --git a/apps/web/src/features/next-soup/actions/make-move-to-project-action.ts b/apps/web/src/features/next-soup/actions/make-move-to-project-action.ts
index 73e3d6146c..e21cb8fc79 100644
--- a/apps/web/src/features/next-soup/actions/make-move-to-project-action.ts
+++ b/apps/web/src/features/next-soup/actions/make-move-to-project-action.ts
@@ -22,7 +22,9 @@ export const makeMoveToProjectAction = (options: MakeMoveToProjectOptions) => {
entity.type === 'document' ||
entity.type === 'chat' ||
entity.type === 'project' ||
- entity.type === 'email';
+ entity.type === 'email' ||
+ entity.type === 'database' ||
+ entity.type === 'form';
const canExecute = (entity: EntityData): boolean =>
canMoveType(entity) && entity.ownerId === options.userId();
diff --git a/apps/web/src/features/next-soup/actions/make-remove-from-project-action.ts b/apps/web/src/features/next-soup/actions/make-remove-from-project-action.ts
index c639a9e36b..3b68cdee93 100644
--- a/apps/web/src/features/next-soup/actions/make-remove-from-project-action.ts
+++ b/apps/web/src/features/next-soup/actions/make-remove-from-project-action.ts
@@ -14,7 +14,9 @@ export const makeRemoveFromProjectAction = () => {
entity.type === 'document' ||
entity.type === 'chat' ||
entity.type === 'project' ||
- entity.type === 'email';
+ entity.type === 'email' ||
+ entity.type === 'database' ||
+ entity.type === 'form';
const execute = async (entities: EntityData[]): Promise<boolean> => {
// Failure toast is shown by the mutation
diff --git a/apps/web/src/lib/core/component/FileList/itemOperations.test.ts b/apps/web/src/lib/core/component/FileList/itemOperations.test.ts
index 85e8ed487c..d552616a3d 100644
--- a/apps/web/src/lib/core/component/FileList/itemOperations.test.ts
+++ b/apps/web/src/lib/core/component/FileList/itemOperations.test.ts
@@ -132,6 +132,29 @@ describe('flagged entity callers', () => {
}
);
+ it.each([
+ ['database', 'DATABASE'],
+ ['form', 'FORM'],
+ ] as const)(
+ 'moves a %s through the entity mutation, its only route, with or without the GraphQL soup',
+ async (itemType, type) => {
+ for (const graphql of [true, false]) {
+ mocks.graphql = graphql;
+ for (const folderId of ['folder', null]) {
+ mocks.mutation.mockClear();
+ expect(await moveToFolder({ itemType, id: 'source', folderId })).toBe(
+ true
+ );
+ expect(variables()).toEqual({
+ inputs: [{ entity: { type, id: 'source' }, projectId: folderId }],
+ });
+ }
+ }
+ expect(mocks.edit).not.toHaveBeenCalled();
+ expect(mocks.metadata).not.toHaveBeenCalled();
+ }
+ );
+
it.each(['document', 'chat', 'project'] as const)(
'trashes/restores/permanently deletes %s through GraphQL',
async (itemType) => {
diff --git a/apps/web/src/lib/core/component/FileList/itemOperations.ts b/apps/web/src/lib/core/component/FileList/itemOperations.ts
index 9002e8702f..1ace253f47 100644
--- a/apps/web/src/lib/core/component/FileList/itemOperations.ts
+++ b/apps/web/src/lib/core/component/FileList/itemOperations.ts
@@ -282,6 +282,19 @@ export async function moveToFolder(args: {
folderId: string | null;
}): Promise<boolean> {
const { itemType, id, folderId } = args;
+ // Databases and forms move only through the entity mutation; there is no
+ // REST route for them.
+ if (itemType === 'database' || itemType === 'form') {
+ const result = await catchToResult(() =>
+ moveEntity(
+ { type: itemType === 'database' ? 'DATABASE' : 'FORM', id },
+ folderId
+ )
+ );
+ if (result.isErr()) return false;
+ trackMovedToFolder(itemType, id, folderId);
+ return true;
+ }
const graphql = isFeatureEnabled(enableGraphqlSoup);
if (!graphql) {
const accessLevel = await getItemAccessLevel({ itemType, id });
@@ -341,15 +354,22 @@ export async function moveToFolder(args: {
return false;
}
+ trackMovedToFolder(itemType, id, folderId);
+ refetchResources();
+ return true;
+}
+
+function trackMovedToFolder(
+ itemType: ItemType,
+ id: string,
+ folderId: string | null
+) {
analytics.track('update_entity', {
entityType: itemType,
entityId: id,
property: 'parent_project',
newProjectId: folderId,
});
-
- refetchResources();
- return true;
}
export async function bulkMoveToFolder(
diff --git a/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.test.ts b/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.test.ts
index 4534ee8cd6..f2cb278326 100644
--- a/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.test.ts
+++ b/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.test.ts
@@ -1666,6 +1666,7 @@ describe('database command discovery', () => {
owner_id: 'me',
created_at: '2026-09-01T00:00:00Z',
trashed_at: null,
+ project_id: null,
},
grant: 'owner',
tables: [],
diff --git a/apps/web/src/lib/core/database-sql/answer.test.ts b/apps/web/src/lib/core/database-sql/answer.test.ts
index 794e4ec31b..eebfa7ecb1 100644
--- a/apps/web/src/lib/core/database-sql/answer.test.ts
+++ b/apps/web/src/lib/core/database-sql/answer.test.ts
@@ -15,6 +15,7 @@ const party: DatabaseDetail = {
owner_id: 'macro|[email protected]',
created_at: '2026-01-01T00:00:00Z',
trashed_at: null,
+ project_id: null,
},
grant: 'edit',
tables: [
diff --git a/apps/web/src/lib/core/database-sql/catalog.test.ts b/apps/web/src/lib/core/database-sql/catalog.test.ts
index 9ca09c4adf..9de40f4b7b 100644
--- a/apps/web/src/lib/core/database-sql/catalog.test.ts
+++ b/apps/web/src/lib/core/database-sql/catalog.test.ts
@@ -67,6 +67,7 @@ const crm: DatabaseDetail = {
owner_id: 'macro|[email protected]',
created_at: '2026-01-01T00:00:00Z',
trashed_at: null,
+ project_id: null,
},
grant: 'edit',
tables: [
diff --git a/apps/web/src/lib/queries/storage/databases.test.ts b/apps/web/src/lib/queries/storage/databases.test.ts
index 56cc69e6a5..52dbad11c6 100644
--- a/apps/web/src/lib/queries/storage/databases.test.ts
+++ b/apps/web/src/lib/queries/storage/databases.test.ts
@@ -46,6 +46,7 @@ const detail: DatabaseDetail = {
owner_id: 'owner',
created_at: '',
trashed_at: null,
+ project_id: null,
},
grant: 'owner',
tables: [
diff --git a/apps/web/src/lib/queries/storage/forms-preview.test.ts b/apps/web/src/lib/queries/storage/forms-preview.test.ts
index 0eed292f21..19736a5dfe 100644
--- a/apps/web/src/lib/queries/storage/forms-preview.test.ts
+++ b/apps/web/src/lib/queries/storage/forms-preview.test.ts
@@ -70,6 +70,7 @@ it('updates an already cached card title after renaming a form', async () => {
branding: { logoFileId: null, coverFileId: null, accentColor: null },
createdAt: '2026-10-05T00:00:00Z',
updatedAt: '2026-10-05T00:00:00Z',
+ projectId: null,
isHiddenInDrive: false,
},
});
@@ -162,6 +163,7 @@ it('refreshes the linked database’s card after renaming a form, without guessi
branding: { logoFileId: null, coverFileId: null, accentColor: null },
createdAt: '2026-10-05T00:00:00Z',
updatedAt: '2026-10-05T00:00:00Z',
+ projectId: null,
isHiddenInDrive: false,
},
});
@@ -232,6 +234,7 @@ it('refreshes the cards of the forms over a renamed database, and only theirs',
branding: { logoFileId: null, coverFileId: null, accentColor: null },
createdAt: '2026-10-05T00:00:00Z',
updatedAt: '2026-10-05T00:00:00Z',
+ projectId: null,
isHiddenInDrive: false,
},
]
@@ -256,6 +259,7 @@ it('refreshes the cards of the forms over a renamed database, and only theirs',
branding: { logoFileId: null, coverFileId: null, accentColor: null },
createdAt: '2026-10-05T00:00:00Z',
updatedAt: '2026-10-05T00:00:00Z',
+ projectId: null,
isHiddenInDrive: false,
},
},
@@ -278,6 +282,7 @@ it('refreshes the cards of the forms over a renamed database, and only theirs',
branding: { logoFileId: null, coverFileId: null, accentColor: null },
createdAt: '2026-10-05T00:00:00Z',
updatedAt: '2026-10-05T00:00:00Z',
+ projectId: null,
isHiddenInDrive: false,
},
},
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts
index 6477e8adbe..d5268f7035 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts
@@ -3558,6 +3558,7 @@ export const MutationResult = z.object({
}),
createdAt: z.string().datetime({ offset: true }),
updatedAt: z.string().datetime({ offset: true }),
+ projectId: z.union([z.string(), z.null()]).optional(),
isHiddenInDrive: z.boolean(),
}),
layout: z.object({
@@ -11061,6 +11062,7 @@ export const ListResult = z.object({
}),
createdAt: z.string().datetime({ offset: true }),
updatedAt: z.string().datetime({ offset: true }),
+ projectId: z.union([z.string(), z.null()]).optional(),
isHiddenInDrive: z.boolean(),
}),
access: z.any().superRefine((x, ctx) => {
@@ -13811,6 +13813,7 @@ export const ReadResult = z.any().superRefine((x, ctx) => {
}),
createdAt: z.string().datetime({ offset: true }),
updatedAt: z.string().datetime({ offset: true }),
+ projectId: z.union([z.string(), z.null()]).optional(),
isHiddenInDrive: z.boolean(),
}),
layout: z.object({
@@ -14429,6 +14432,7 @@ export const ReadResult = z.any().superRefine((x, ctx) => {
}),
createdAt: z.string().datetime({ offset: true }),
updatedAt: z.string().datetime({ offset: true }),
+ projectId: z.union([z.string(), z.null()]).optional(),
isHiddenInDrive: z.boolean(),
}),
access: z.any().superRefine((x, ctx) => {
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
index b98654024d..72923aafb0 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
@@ -7896,6 +7896,10 @@ export interface Form {
* When its facts or layout last changed.
*/
updatedAt: string;
+ /**
+ * The folder it is filed in; `null` at the root.
+ */
+ projectId?: string | null;
/**
* Whether Drive leaves it, and the database behind it, out of its
* listings, as for a channel poll.
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/database.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/database.ts
index 8c3673f991..1225264477 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/database.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/database.ts
@@ -4,6 +4,7 @@
* document_storage_service
* OpenAPI spec version: 0.1.0
*/
+import type { DatabaseProjectId } from './databaseProjectId';
import type { DatabaseTrashedAt } from './databaseTrashedAt';
/**
@@ -18,6 +19,8 @@ export interface Database {
name: string;
/** Owning user. */
owner_id: string;
+ /** The folder it is filed in; `null` at the root. */
+ project_id: DatabaseProjectId;
/** Set when trashed. */
trashed_at: DatabaseTrashedAt;
}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/databaseProjectId.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/databaseProjectId.ts
new file mode 100644
index 0000000000..de84fc04ed
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/databaseProjectId.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The folder it is filed in; `null` at the root.
+ */
+export type DatabaseProjectId = string | null;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/form.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/form.ts
index a2dc25042b..1e5a95057d 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/form.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/form.ts
@@ -7,6 +7,7 @@
import type { Audience } from './audience';
import type { FormBranding } from './formBranding';
import type { FormClosesAt } from './formClosesAt';
+import type { FormProjectId } from './formProjectId';
import type { FormRespondentColumnId } from './formRespondentColumnId';
import type { FormStatus } from './formStatus';
import type { FormSubmittedColumnId } from './formSubmittedColumnId';
@@ -40,6 +41,8 @@ a form attached to an existing table has its own name. */
name: string;
/** Its owner. */
ownerId: string;
+ /** The folder it is filed in; `null` at the root. */
+ projectId: FormProjectId;
/** The person column each signed-in submission names its respondent in;
`null` once deleted. */
respondentColumnId: FormRespondentColumnId;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/formProjectId.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/formProjectId.ts
new file mode 100644
index 0000000000..ef26db1b5c
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/formProjectId.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The folder it is filed in; `null` at the root.
+ */
+export type FormProjectId = string | null;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
index 6121648fc9..7fc5b34075 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
@@ -671,6 +671,7 @@ export * from './databaseOpOneOfSeven';
export * from './databaseOpOneOfSevenKind';
export * from './databaseOpOneOfThree';
export * from './databaseOpOneOfThreeKind';
+export * from './databaseProjectId';
export * from './databaseQueryRequest';
export * from './databaseQueryRequestBaseVersions';
export * from './databaseQueryRequestDatabaseId';
@@ -1056,6 +1057,7 @@ export * from './formErrorResponse';
export * from './formErrorResponseProblem';
export * from './formErrorResponseQuestion';
export * from './formLayout';
+export * from './formProjectId';
export * from './formPublicationProblem';
export * from './formPublicationProblemOneOf';
export * from './formPublicationProblemOneOfFive';
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
index a66477b18e..486afc1f52 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
@@ -10305,6 +10305,10 @@ export const listDatabasesResponseItem = zod
id: zod.uuid().describe('Identifier.'),
name: zod.string().describe('Display name.'),
owner_id: zod.string().describe('Owning user.'),
+ project_id: zod
+ .string()
+ .nullable()
+ .describe('The folder it is filed in; `null` at the root.'),
trashed_at: zod.iso
.datetime({})
.nullable()
@@ -10825,6 +10829,10 @@ export const getDatabaseResponse = zod
id: zod.uuid().describe('Identifier.'),
name: zod.string().describe('Display name.'),
owner_id: zod.string().describe('Owning user.'),
+ project_id: zod
+ .string()
+ .nullable()
+ .describe('The folder it is filed in; `null` at the root.'),
trashed_at: zod.iso
.datetime({})
.nullable()
@@ -22666,6 +22674,10 @@ export const listFormsResponseItem = zod
'Its display name. A standalone form follows the database it created;\na form attached to an existing table has its own name.'
),
ownerId: zod.string().describe('Its owner.'),
+ projectId: zod
+ .string()
+ .nullable()
+ .describe('The folder it is filed in; `null` at the root.'),
respondentColumnId: zod
.uuid()
.nullable()
@@ -22803,6 +22815,10 @@ export const listAccessibleFormsResponseItem = zod
'Its display name. A standalone form follows the database it created;\na form attached to an existing table has its own name.'
),
ownerId: zod.string().describe('Its owner.'),
+ projectId: zod
+ .string()
+ .nullable()
+ .describe('The folder it is filed in; `null` at the root.'),
respondentColumnId: zod
.uuid()
.nullable()
@@ -22912,6 +22928,10 @@ export const getFormResponse = zod
'Its display name. A standalone form follows the database it created;\na form attached to an existing table has its own name.'
),
ownerId: zod.string().describe('Its owner.'),
+ projectId: zod
+ .string()
+ .nullable()
+ .describe('The folder it is filed in; `null` at the root.'),
respondentColumnId: zod
.uuid()
.nullable()
@@ -23463,6 +23483,10 @@ export const updateFormResponse = zod
'Its display name. A standalone form follows the database it created;\na form attached to an existing table has its own name.'
),
ownerId: zod.string().describe('Its owner.'),
+ projectId: zod
+ .string()
+ .nullable()
+ .describe('The folder it is filed in; `null` at the root.'),
respondentColumnId: zod
.uuid()
.nullable()
@@ -23571,6 +23595,10 @@ export const collaborateFormResponse = zod
'Its display name. A standalone form follows the database it created;\na form attached to an existing table has its own name.'
),
ownerId: zod.string().describe('Its owner.'),
+ projectId: zod
+ .string()
+ .nullable()
+ .describe('The folder it is filed in; `null` at the root.'),
respondentColumnId: zod
.uuid()
.nullable()
@@ -24517,6 +24545,10 @@ export const putFormLayoutResponse = zod
'Its display name. A standalone form follows the database it created;\na form attached to an existing table has its own name.'
),
ownerId: zod.string().describe('Its owner.'),
+ projectId: zod
+ .string()
+ .nullable()
+ .describe('The folder it is filed in; `null` at the root.'),
respondentColumnId: zod
.uuid()
.nullable()
diff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.json
index 68e746afb8..ad0f0759b7 100644
--- a/apps/web/src/lib/service-clients/service-storage/openapi.json
+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json
@@ -27026,7 +27026,14 @@
"Database": {
"type": "object",
"description": "A database: a named collection of tables, owned and shared as one entity.",
- "required": ["id", "name", "owner_id", "created_at", "trashed_at"],
+ "required": [
+ "id",
+ "name",
+ "owner_id",
+ "created_at",
+ "trashed_at",
+ "project_id"
+ ],
"properties": {
"created_at": {
"type": "string",
@@ -27046,6 +27053,10 @@
"type": "string",
"description": "Owning user."
},
+ "project_id": {
+ "type": ["string", "null"],
+ "description": "The folder it is filed in; `null` at the root."
+ },
"trashed_at": {
"type": ["string", "null"],
"format": "date-time",
@@ -31741,6 +31752,7 @@
"branding",
"createdAt",
"updatedAt",
+ "projectId",
"isHiddenInDrive"
],
"properties": {
@@ -31792,6 +31804,10 @@
"type": "string",
"description": "Its owner."
},
+ "projectId": {
+ "type": ["string", "null"],
+ "description": "The folder it is filed in; `null` at the root."
+ },
"respondentColumnId": {
"type": ["string", "null"],
"format": "uuid",
diff --git a/crates/agent_code_mode/src/domain/documentation.json b/crates/agent_code_mode/src/domain/documentation.json
index d77bb618c7..697fc6842a 100644
--- a/crates/agent_code_mode/src/domain/documentation.json
+++ b/crates/agent_code_mode/src/domain/documentation.json
@@ -547,7 +547,7 @@
"CrmTeamSettingsResponse": "# Type Alias: CrmTeamSettingsResponse\n\n> **CrmTeamSettingsResponse** = \\{ `closed_stage_ids?`: `string`[] \\| `null`; `default_team_view_id?`: `string` \\| `null`; `delete_records_role`: `CrmPermissionRole`; `edit_stages_role`: `CrmPermissionRole`; `legacy_stage_ids`: \\{\\[`key`: `string`\\]: `string`; \\}; `move_closed_deals_role`: `CrmPermissionRole`; `team_views`: `unknown`; \\}\n\nThe team's CRM configuration (everything on `team_crm_settings`\nexcept the `crm_enabled` killswitch, which is managed via\n`PATCH /team/crm` on the auth service).\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-closed_stage_ids\"></a> `closed_stage_ids?` | `string`[] \\| `null` | Stage option ids counting as closed deals; absent = the client falls back to its label heuristic. |\n| <a id=\"property-default_team_view_id\"></a> `default_team_view_id?` | `string` \\| `null` | Team view applied by default when a member opens the CRM view. |\n| <a id=\"property-delete_records_role\"></a> `delete_records_role` | `CrmPermissionRole` | Who can delete (hide) CRM records. |\n| <a id=\"property-edit_stages_role\"></a> `edit_stages_role` | `CrmPermissionRole` | Who can change the deal stage set in CRM settings. |\n| <a id=\"property-legacy_stage_ids\"></a> `legacy_stage_ids` | \\{\\[`key`: `string`\\]: `string`; \\} | System stage option id to team stage option id for seeded stages. |\n| <a id=\"property-move_closed_deals_role\"></a> `move_closed_deals_role` | `CrmPermissionRole` | Who can move deals out of a closed stage. |\n| <a id=\"property-team_views\"></a> `team_views` | `unknown` | Team saved views — an opaque JSON array owned by the frontend. |",
"CustomSpeakerAssignment": "# Type Alias: CustomSpeakerAssignment\n\n> **CustomSpeakerAssignment** = \\{ `customSpeaker`: `string`; `diarizedSpeakerId`: `string`; \\}\n\nOne per-diarized-speaker override, used in [`EditCallTranscriptRequest`].\n\n`custom_speaker = None` clears any existing override for this\n`diarized_speaker_id`; `Some(macro_user_id)` sets it. The string is\nexpected to parse as a `MacroUserId` (e.g. `macro|[email protected]`);\nthe service layer rejects malformed values with `400 Bad Request`.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-customspeaker\"></a> `customSpeaker` | `string` | Macro user id to attribute matching rows to, or `None` to clear. |\n| <a id=\"property-diarizedspeakerid\"></a> `diarizedSpeakerId` | `string` | The diarization label whose rows this assignment targets. |",
"storage.DataType": "# Type Alias: DataType\n\n> **DataType** = `\"BOOLEAN\"` \\| `\"DATE\"` \\| `\"DATE_RANGE\"` \\| `\"NUMBER\"` \\| `\"STRING\"` \\| `\"SELECT_NUMBER\"` \\| `\"SELECT_STRING\"` \\| `\"TAG\"` \\| `\"ENTITY\"` \\| `\"LINK\"`\n\nData type for property values, determining storage and validation.",
- "storage.Database": "# Type Alias: Database\n\n> **Database** = \\{ `created_at`: `string`; `id`: `string`; `name`: `string`; `owner_id`: `string`; `trashed_at`: `string` \\| `null`; \\}\n\nA database: a named collection of tables, owned and shared as one entity.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | Creation time. |\n| <a id=\"property-id\"></a> `id` | `string` | Identifier. |\n| <a id=\"property-name\"></a> `name` | `string` | Display name. |\n| <a id=\"property-owner_id\"></a> `owner_id` | `string` | Owning user. |\n| <a id=\"property-trashed_at\"></a> `trashed_at` | `string` \\| `null` | Set when trashed. |",
+ "storage.Database": "# Type Alias: Database\n\n> **Database** = \\{ `created_at`: `string`; `id`: `string`; `name`: `string`; `owner_id`: `string`; `project_id`: `string` \\| `null`; `trashed_at`: `string` \\| `null`; \\}\n\nA database: a named collection of tables, owned and shared as one entity.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | Creation time. |\n| <a id=\"property-id\"></a> `id` | `string` | Identifier. |\n| <a id=\"property-name\"></a> `name` | `string` | Display name. |\n| <a id=\"property-owner_id\"></a> `owner_id` | `string` | Owning user. |\n| <a id=\"property-project_id\"></a> `project_id` | `string` \\| `null` | The folder it is filed in; `null` at the root. |\n| <a id=\"property-trashed_at\"></a> `trashed_at` | `string` \\| `null` | Set when trashed. |",
"DatabaseDetail": "# Type Alias: DatabaseDetail\n\n> **DatabaseDetail** = \\{ `database`: `storage.Database`; `grant`: `storage.AccessLevel`; `tables`: `TableDetail`[]; \\}\n\nEverything a client needs to render and edit one database: tables,\ncolumn placements with their definitions, and the SQL names the query\nsurface exposes them under.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-database\"></a> `database` | `storage.Database` | The database. |\n| <a id=\"property-grant\"></a> `grant` | `storage.AccessLevel` | The viewer's access. |\n| <a id=\"property-tables\"></a> `tables` | `TableDetail`[] | Tables in tab order. |",
"DatabaseId": "# Type Alias: DatabaseId\n\n> **DatabaseId** = `string`\n\nIdentifier of reusable database storage. Its optional Macro entity uses\nthe same identity, so existing routes and grants keep their IDs.",
"DatabaseOp": "# Type Alias: DatabaseOp\n\n> **DatabaseOp** = \\{ `change`: `TableChange`; `kind`: `\"table\"`; `table`: `string`; \\} \\| \\{ `change`: `ColumnChange`; `column`: `string`; `kind`: `\"column\"`; `table`: `string`; \\} \\| \\{ `change`: `RowsChange`; `kind`: `\"rows\"`; `table`: `string`; \\} \\| \\{ `change`: `ViewChange`; `kind`: `\"view\"`; `table`: `string`; `view`: `string`; \\} \\| \\{ `kind`: `\"reorder_tables\"`; `order`: `string`[]; \\}\n\nOne write to a database: its tables, columns, options, rows or views,\ngrouped by the resource it changes. A request's ops apply in order and\ntogether, or not at all, and every op names a table of the database the\nrequest is for (or, creating one, adds it there).\n\n## Union Members\n\n### Type Literal\n\n\\{ `change`: `TableChange`; `kind`: `\"table\"`; `table`: `string`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `change` | `TableChange` | What changes. |\n| `kind` | `\"table\"` | - |\n| `table` | `string` | The table; for a creation, its new id, minted by the client, which later ops of the request may name. |\n\n***\n\n### Type Literal\n\n\\{ `change`: `ColumnChange`; `column`: `string`; `kind`: `\"column\"`; `table`: `string`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `change` | `ColumnChange` | What changes. |\n| `column` | `string` | The column; for a creation, its new id, minted by the client, which later ops of the request may name. |\n| `kind` | `\"column\"` | - |\n| `table` | `string` | The table. |\n\n***\n\n### Type Literal\n\n\\{ `change`: `RowsChange`; `kind`: `\"rows\"`; `table`: `string`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `change` | `RowsChange` | What changes. |\n| `kind` | `\"rows\"` | - |\n| `table` | `string` | The table the rows belong to. |\n\n***\n\n### Type Literal\n\n\\{ `change`: `ViewChange`; `kind`: `\"view\"`; `table`: `string`; `view`: `string`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `change` | `ViewChange` | What changes. |\n| `kind` | `\"view\"` | - |\n| `table` | `string` | The view's table. |\n| `view` | `string` | The view; for a creation, its new id, minted by the client. |\n\n***\n\n### Type Literal\n\n\\{ `kind`: `\"reorder_tables\"`; `order`: `string`[]; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `kind` | `\"reorder_tables\"` | - |\n| `order` | `string`[] | Every table, in its new order. |",
@@ -624,7 +624,7 @@
"FilterTest": "# Type Alias: FilterTest\n\n> **FilterTest** = \\{ `kind`: `\"presence\"`; `operator`: `PresenceOperator`; \\} \\| \\{ `kind`: `\"text\"`; `operator`: `TextOperator`; `value`: `string`; \\} \\| \\{ `kind`: `\"number\"`; `operator`: `NumberOperator`; `value`: `number`; \\} \\| \\{ `kind`: `\"date\"`; `operator`: `DateOperator`; `value`: `string`; \\} \\| \\{ `kind`: `\"dateRange\"`; `operator`: `DateRangeOperator`; `value`: `string`; \\} \\| \\{ `checked`: `boolean`; `kind`: `\"checkbox\"`; \\} \\| \\{ `kind`: `\"options\"`; `operator`: `SetOperator`; `options`: `string`[]; \\} \\| \\{ `entities`: `string`[]; `kind`: `\"entities\"`; `operator`: `SetOperator`; \\}\n\nWhat a column's cell must be, by the kind of value the column holds.\n\n## Union Members\n\n### Type Literal\n\n\\{ `kind`: `\"presence\"`; `operator`: `PresenceOperator`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `kind` | `\"presence\"` | - |\n| `operator` | `PresenceOperator` | Empty, or not. |\n\n***\n\n### Type Literal\n\n\\{ `kind`: `\"text\"`; `operator`: `TextOperator`; `value`: `string`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `kind` | `\"text\"` | - |\n| `operator` | `TextOperator` | How the cell compares. |\n| `value` | `string` | The text compared against, ignoring case for the containment tests. |\n\n***\n\n### Type Literal\n\n\\{ `kind`: `\"number\"`; `operator`: `NumberOperator`; `value`: `number`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `kind` | `\"number\"` | - |\n| `operator` | `NumberOperator` | How the cell compares. |\n| `value` | `number` | The number compared against; finite. |\n\n***\n\n### Type Literal\n\n\\{ `kind`: `\"date\"`; `operator`: `DateOperator`; `value`: `string`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `kind` | `\"date\"` | - |\n| `operator` | `DateOperator` | How the cell compares. |\n| `value` | `string` | The date-time compared against. |\n\n***\n\n### Type Literal\n\n\\{ `kind`: `\"dateRange\"`; `operator`: `DateRangeOperator`; `value`: `string`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `kind` | `\"dateRange\"` | - |\n| `operator` | `DateRangeOperator` | How the cell's range stands to the day. |\n| `value` | `string` | The start of the day compared against. |\n\n***\n\n### Type Literal\n\n\\{ `checked`: `boolean`; `kind`: `\"checkbox\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `checked` | `boolean` | Whether the box is checked. |\n| `kind` | `\"checkbox\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `kind`: `\"options\"`; `operator`: `SetOperator`; `options`: `string`[]; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `kind` | `\"options\"` | - |\n| `operator` | `SetOperator` | How the cell's options relate to these. |\n| `options` | `string`[] | Options of the column; at least one. |\n\n***\n\n### Type Literal\n\n\\{ `entities`: `string`[]; `kind`: `\"entities\"`; `operator`: `SetOperator`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `entities` | `string`[] | Entity ids, or for a relation the related rows' ids; at least one. |\n| `kind` | `\"entities\"` | - |\n| `operator` | `SetOperator` | How the cell's references relate to these. |",
"FollowupState": "# Type Alias: FollowupState\n\n> **FollowupState** = `\"archiving\"` \\| `\"pending\"` \\| `\"returning\"` \\| `\"returned\"` \\| `\"cancelled\"` \\| `\"removed\"`\n\nDurable progress of an email operation.",
"storage.ForeignEntity": "# Type Alias: ForeignEntity\n\n> **ForeignEntity** = \\{ `createdAt`: `string`; `foreignEntityId`: `string`; `foreignEntitySource`: `string`; `id`: `string`; `metadata`: `unknown`; `storedForAuthEntity`: `string`; `storedForId`: `string`; `updatedAt`: `string`; \\}\n\nA persisted mapping to an entity owned by an external system.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-createdat\"></a> `createdAt` | `string` | Timestamp when the record was created. |\n| <a id=\"property-foreignentityid\"></a> `foreignEntityId` | `string` | Identifier assigned by the external system. |\n| <a id=\"property-foreignentitysource\"></a> `foreignEntitySource` | `string` | Source system that owns the external identifier. |\n| <a id=\"property-id\"></a> `id` | `string` | Internal primary key for this foreign entity record. |\n| <a id=\"property-metadata\"></a> `metadata` | `unknown` | Arbitrary metadata stored with the mapping. |\n| <a id=\"property-storedforauthentity\"></a> `storedForAuthEntity` | `string` | Internal auth entity namespace this foreign entity is stored for. |\n| <a id=\"property-storedforid\"></a> `storedForId` | `string` | Internal entity identifier this foreign entity is stored for. |\n| <a id=\"property-updatedat\"></a> `updatedAt` | `string` | Timestamp when the record was last updated. |",
- "storage.Form": "# Type Alias: Form\n\n> **Form** = \\{ `audience`: `Audience`; `branding`: `FormBranding`; `closesAt`: `string` \\| `null`; `confirmationMessage`: `string`; `createdAt`: `string`; `databaseId`: `string`; `description`: `string`; `id`: `string`; `isHiddenInDrive`: `boolean`; `name`: `string`; `ownerId`: `string`; `respondentColumnId`: `string` \\| `null`; `status`: `FormStatus`; `submittedColumnId`: `string` \\| `null`; `tableId`: `string`; `tallyVisible`: `boolean`; `updatedAt`: `string`; \\}\n\nA form: a view of one database table whose rows are its responses.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-audience\"></a> `audience` | `Audience` | Who may respond. |\n| <a id=\"property-branding\"></a> `branding` | `FormBranding` | Its logo, cover image and accent color. |\n| <a id=\"property-closesat\"></a> `closesAt` | `string` \\| `null` | When it stops taking responses, if it does. |\n| <a id=\"property-confirmationmessage\"></a> `confirmationMessage` | `string` | What a respondent reads once their response is saved; empty for the default. |\n| <a id=\"property-createdat\"></a> `createdAt` | `string` | When it was created. |\n| <a id=\"property-databaseid\"></a> `databaseId` | `string` | The database holding its responses. |\n| <a id=\"property-description\"></a> `description` | `string` | What respondents read under the name. |\n| <a id=\"property-id\"></a> `id` | `string` | The form. |\n| <a id=\"property-ishiddenindrive\"></a> `isHiddenInDrive` | `boolean` | Whether Drive leaves it, and the database behind it, out of its listings, as for a channel poll. |\n| <a id=\"property-name\"></a> `name` | `string` | Its display name. A standalone form follows the database it created; a form attached to an existing table has its own name. |\n| <a id=\"property-ownerid\"></a> `ownerId` | `string` | Its owner. |\n| <a id=\"property-respondentcolumnid\"></a> `respondentColumnId` | `string` \\| `null` | The person column each signed-in submission names its respondent in; `null` once deleted. |\n| <a id=\"property-status\"></a> `status` | `FormStatus` | Whether its owner closed it. |\n| <a id=\"property-submittedcolumnid\"></a> `submittedColumnId` | `string` \\| `null` | The date column each submission stamps; `null` once deleted. |\n| <a id=\"property-tableid\"></a> `tableId` | `string` | The table whose rows are its responses. |\n| <a id=\"property-tallyvisible\"></a> `tallyVisible` | `boolean` | Whether respondents may read option tallies. |\n| <a id=\"property-updatedat\"></a> `updatedAt` | `string` | When its facts or layout last changed. |",
+ "storage.Form": "# Type Alias: Form\n\n> **Form** = \\{ `audience`: `Audience`; `branding`: `FormBranding`; `closesAt`: `string` \\| `null`; `confirmationMessage`: `string`; `createdAt`: `string`; `databaseId`: `string`; `description`: `string`; `id`: `string`; `isHiddenInDrive`: `boolean`; `name`: `string`; `ownerId`: `string`; `projectId`: `string` \\| `null`; `respondentColumnId`: `string` \\| `null`; `status`: `FormStatus`; `submittedColumnId`: `string` \\| `null`; `tableId`: `string`; `tallyVisible`: `boolean`; `updatedAt`: `string`; \\}\n\nA form: a view of one database table whose rows are its responses.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-audience\"></a> `audience` | `Audience` | Who may respond. |\n| <a id=\"property-branding\"></a> `branding` | `FormBranding` | Its logo, cover image and accent color. |\n| <a id=\"property-closesat\"></a> `closesAt` | `string` \\| `null` | When it stops taking responses, if it does. |\n| <a id=\"property-confirmationmessage\"></a> `confirmationMessage` | `string` | What a respondent reads once their response is saved; empty for the default. |\n| <a id=\"property-createdat\"></a> `createdAt` | `string` | When it was created. |\n| <a id=\"property-databaseid\"></a> `databaseId` | `string` | The database holding its responses. |\n| <a id=\"property-description\"></a> `description` | `string` | What respondents read under the name. |\n| <a id=\"property-id\"></a> `id` | `string` | The form. |\n| <a id=\"property-ishiddenindrive\"></a> `isHiddenInDrive` | `boolean` | Whether Drive leaves it, and the database behind it, out of its listings, as for a channel poll. |\n| <a id=\"property-name\"></a> `name` | `string` | Its display name. A standalone form follows the database it created; a form attached to an existing table has its own name. |\n| <a id=\"property-ownerid\"></a> `ownerId` | `string` | Its owner. |\n| <a id=\"property-projectid\"></a> `projectId` | `string` \\| `null` | The folder it is filed in; `null` at the root. |\n| <a id=\"property-respondentcolumnid\"></a> `respondentColumnId` | `string` \\| `null` | The person column each signed-in submission names its respondent in; `null` once deleted. |\n| <a id=\"property-status\"></a> `status` | `FormStatus` | Whether its owner closed it. |\n| <a id=\"property-submittedcolumnid\"></a> `submittedColumnId` | `string` \\| `null` | The date column each submission stamps; `null` once deleted. |\n| <a id=\"property-tableid\"></a> `tableId` | `string` | The table whose rows are its responses. |\n| <a id=\"property-tallyvisible\"></a> `tallyVisible` | `boolean` | Whether respondents may read option tallies. |\n| <a id=\"property-updatedat\"></a> `updatedAt` | `string` | When its facts or layout last changed. |",
"FormAccess": "# Type Alias: FormAccess\n\n> **FormAccess** = `\"view\"` \\| `\"edit\"` \\| `\"owner\"`\n\nThe caller's level on a form: view responds, edit changes questions and\nreads responses, owner also sets the audience, closes and trashes it.",
"FormBranding": "# Type Alias: FormBranding\n\n> **FormBranding** = \\{ `accentColor`: `null` \\| `AccentColor`; `coverFileId`: `string` \\| `null`; `logoFileId`: `string` \\| `null`; \\}\n\nA form's logo, cover image and accent color, each unset by default.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-accentcolor\"></a> `accentColor` | `null` \\| `AccentColor` | - |\n| <a id=\"property-coverfileid\"></a> `coverFileId` | `string` \\| `null` | The static file shown as a banner across the top of the page. |\n| <a id=\"property-logofileid\"></a> `logoFileId` | `string` \\| `null` | The static file shown as the logo above the title. |",
"FormDetail": "# Type Alias: FormDetail\n\n> **FormDetail** = \\{ `access`: `FormAccess`; `form`: `storage.Form`; `sections`: `FormSectionDetail`[]; `tableGone`: `boolean`; \\}\n\nA form with its layout, as the caller may see it.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-access\"></a> `access` | `FormAccess` | The caller's level on it. |\n| <a id=\"property-form\"></a> `form` | `storage.Form` | The form's facts. |\n| <a id=\"property-sections\"></a> `sections` | `FormSectionDetail`[] | Its sections, in order. |\n| <a id=\"property-tablegone\"></a> `tableGone` | `boolean` | Whether its database is in the trash, so it has no table to show or write: its sections keep no questions and it takes no responses. |",
diff --git a/crates/ai_tools/src/import_workspace/test.rs b/crates/ai_tools/src/import_workspace/test.rs
index 6521f088d8..a331e12f2d 100644
--- a/crates/ai_tools/src/import_workspace/test.rs
+++ b/crates/ai_tools/src/import_workspace/test.rs
@@ -23,6 +23,7 @@ fn a_new_database_is_written_into_its_starter_table_and_title_column() {
owner_id: "macro|[email protected]".to_string(),
created_at: Utc::now(),
trashed_at: None,
+ project_id: None,
},
grant: AccessLevel::Owner,
tables: vec![TableDetail {
@@ -91,6 +92,7 @@ fn a_new_database_without_a_starter_table_is_refused() {
owner_id: "macro|[email protected]".to_string(),
created_at: Utc::now(),
trashed_at: None,
+ project_id: None,
},
grant: AccessLevel::Owner,
tables: vec![],
@@ -110,6 +112,7 @@ fn a_new_database_whose_starter_table_has_no_column_is_refused() {
owner_id: "macro|[email protected]".to_string(),
created_at: Utc::now(),
trashed_at: None,
+ project_id: None,
},
grant: AccessLevel::Owner,
tables: vec![TableDetail {
diff --git a/crates/chat/src/domain/service/entity_mutation.rs b/crates/chat/src/domain/service/entity_mutation.rs
index 6b55995e81..b3f8aa494b 100644
--- a/crates/chat/src/domain/service/entity_mutation.rs
+++ b/crates/chat/src/domain/service/entity_mutation.rs
@@ -1,14 +1,12 @@
//! Unified entity-mutation capability impls for chats.
-use std::collections::HashSet;
-
use entity_access::domain::models::{
AccessError, EntityAccessReceipt, OwnerAccessLevel, ViewAccessLevel,
};
use entity_mutation::{
DeleteEntityPermanently, DuplicateEntity, EntityMutationEffect, EntityMutationErrorCode,
MoveEntity, RenameEntity, RestoreEntity, TrashEntity, UpdateEntitySharePolicy,
- capability::MoveEntityRequest,
+ capability::MoveEntityRequest, project_refs,
};
use macro_user_id::user_id::MacroUserIdStr;
use model_entity::{Entity, EntityType};
@@ -51,16 +49,6 @@ fn access_error(error: AccessError) -> EntityMutationErrorCode {
}
}
-/// Build affected project entities from optional container ids.
-fn project_refs(ids: impl IntoIterator<Item = Option<String>>) -> Vec<Entity<'static>> {
- let mut seen = HashSet::new();
- ids.into_iter()
- .flatten()
- .filter(|id| !id.is_empty() && seen.insert(id.clone()))
- .map(|id| EntityType::Project.with_entity_string(id))
- .collect()
-}
-
/// Resolve the chat's containing project for affected-record reporting.
async fn chat_project_id<S: ChatService>(
service: &S,
diff --git a/crates/databases/AGENTS.md b/crates/databases/AGENTS.md
index 129432e42b..7391cfc111 100644
--- a/crates/databases/AGENTS.md
+++ b/crates/databases/AGENTS.md
@@ -29,7 +29,7 @@ service with Axum, agent-tool and Postgres adapters.
- Depends on: `entity_access` (permission scoping), `entity_access_db_utils` and
`share_permission_db_utils` (channel grants and the team share), `properties` (cell values),
`macro_event_broker`/`macro_event_topics` (change notifications),
- `connection_gateway_client` (liveness), `entity_mutation` (rename/trash/restore).
+ `connection_gateway_client` (liveness), `entity_mutation` (rename/move/trash/restore).
- Used by: `databases_sql` (agent SQL), `crm` and `forms` (own storage via
`DatabaseStorage`, no `database_entities` row), `ai_tools`, `complete_graph`,
`graphql_crm`. The document storage service mounts `src/inbound/axum_router.rs`.
@@ -56,6 +56,11 @@ service with Axum, agent-tool and Postgres adapters.
other (see README "Storage and app entities").
- Column type changes must convert every value or refuse with the misfit count;
never silently drop data outside an explicit delete.
+- Filing in a folder (`database_entities.project_id`, `MoveEntity`): owner
+ only; the repository swaps the folder-inherited `entity_access` rows in the
+ same transaction (`entity_access_db_utils::project_grants`). Purging the
+ folder returns the database to the root; trashing it does not trash the
+ database, as with email threads.
- Sharing (`src/domain/sharing.rs`): channel grants and a team share; no share
link. The team share's state lives in a `SharePermission` row that
`database_entities.share_permission_id` points at, made the first time the
diff --git a/crates/databases/src/domain/entity_mutation.rs b/crates/databases/src/domain/entity_mutation.rs
index 5d8e0584f5..d5d8d266f3 100644
--- a/crates/databases/src/domain/entity_mutation.rs
+++ b/crates/databases/src/domain/entity_mutation.rs
@@ -1,10 +1,11 @@
-//! The entity-mutation lifecycle capabilities for databases: rename, trash,
-//! restore and permanent delete; the router reports the rest unsupported.
+//! The entity-mutation capabilities for databases: rename, move between
+//! folders, trash, restore and permanent delete; the router reports the rest
+//! unsupported.
use entity_access::domain::models::{EditAccessLevel, EntityAccessReceipt, OwnerAccessLevel};
use entity_mutation::{
- DeleteEntityPermanently, EntityMutationEffect, EntityMutationErrorCode, RenameEntity,
- RestoreEntity, TrashEntity,
+ DeleteEntityPermanently, EntityMutationEffect, EntityMutationErrorCode, MoveEntity,
+ RenameEntity, RestoreEntity, TrashEntity, capability::MoveEntityRequest, project_refs,
};
use macro_event_broker::MacroEventBroker;
use model_entity::Entity;
@@ -57,6 +58,44 @@ where
}
}
+impl<Repository, Definitions, Cells, Events, Access, Broker> MoveEntity
+ for DatabasesServiceImpl<Repository, Definitions, Cells, Events, Access, Broker>
+where
+ Repository: DatabasesRepo,
+ Definitions: ColumnDefinitionStore,
+ Cells: CellStore,
+ Events: TableEventPublisher,
+ Access: AccessDirectory,
+ Broker: MacroEventBroker,
+{
+ /// Filing a database in a folder shares it with the folder's members,
+ /// which only its owner may do.
+ type Receipt = OwnerAccessLevel;
+
+ async fn move_entity(
+ &self,
+ request: MoveEntityRequest<Self::Receipt>,
+ ) -> Result<Vec<EntityMutationEffect>, EntityMutationErrorCode> {
+ let (entity, receipt, project_id) = match request {
+ MoveEntityRequest::MoveToRoot { entity, receipt } => (entity, receipt, None),
+ MoveEntityRequest::MoveToProject {
+ entity,
+ receipt,
+ project_id,
+ project_receipt: _,
+ } => (entity, receipt, Some(project_id)),
+ };
+ let previous_project_id = self.move_database(receipt, project_id.as_deref()).await?;
+ Ok(std::iter::once(EntityMutationEffect::updated(entity))
+ .chain(
+ project_refs([previous_project_id, project_id])
+ .into_iter()
+ .map(EntityMutationEffect::updated),
+ )
+ .collect())
+ }
+}
+
impl<Repository, Definitions, Cells, Events, Access, Broker> TrashEntity
for DatabasesServiceImpl<Repository, Definitions, Cells, Events, Access, Broker>
where
diff --git a/crates/databases/src/domain/models.rs b/crates/databases/src/domain/models.rs
index 553f1435e6..206a077714 100644
--- a/crates/databases/src/domain/models.rs
+++ b/crates/databases/src/domain/models.rs
@@ -45,6 +45,9 @@ pub struct Database {
/// Set when trashed.
#[schema(required = true)]
pub trashed_at: Option<DateTime<Utc>>,
+ /// The folder it is filed in; `null` at the root.
+ #[schema(required = true)]
+ pub project_id: Option<String>,
}
/// One table (tab) of a database.
diff --git a/crates/databases/src/domain/ports.rs b/crates/databases/src/domain/ports.rs
index 2c81fff0a4..07cc6a686d 100644
--- a/crates/databases/src/domain/ports.rs
+++ b/crates/databases/src/domain/ports.rs
@@ -64,6 +64,15 @@ pub trait DatabasesRepo: Send + Sync + 'static {
id: DatabaseId,
) -> impl Future<Output = Result<bool, Self::Error>> + Send;
+ /// File a live database in a folder, or at the root when `project_id`
+ /// is `None`, swapping the grants it inherits from folders to match;
+ /// `false` when it is trashed or gone.
+ fn move_database(
+ &self,
+ id: DatabaseId,
+ project_id: Option<&str>,
+ ) -> impl Future<Output = Result<bool, Self::Error>> + Send;
+
/// Remove a database permanently.
fn delete_database(
&self,
diff --git a/crates/databases/src/domain/service.rs b/crates/databases/src/domain/service.rs
index 1539ed2bc9..4fbe76e43b 100644
--- a/crates/databases/src/domain/service.rs
+++ b/crates/databases/src/domain/service.rs
@@ -437,6 +437,32 @@ where
Ok((database, tables))
}
+ /// File a live database in a folder, or at the root, answering the
+ /// folder it left.
+ #[cfg(feature = "entity_mutation")]
+ pub(super) async fn move_database(
+ &self,
+ receipt: EntityAccessReceipt<OwnerAccessLevel>,
+ project_id: Option<&str>,
+ ) -> Result<Option<String>, DatabaseError> {
+ let database = self.database_by_receipt(&receipt).await?;
+ if database.trashed_at.is_some()
+ || !self
+ .repository
+ .move_database(database.id, project_id)
+ .await
+ .map_err(repository_error)?
+ {
+ return Err(DatabaseError::NotFound);
+ }
+ // The move has committed; a missed liveness ping must not turn it
+ // into a failed write.
+ let _ = self.events.database_changed(database.id).await.inspect_err(|error| {
+ tracing::warn!(error = ?error, database_id = %database.id, "failed to publish database change");
+ });
+ Ok(database.project_id)
+ }
+
/// One column as the client sees it.
async fn column_detail(
&self,
diff --git a/crates/databases/src/domain/service/test/databases.rs b/crates/databases/src/domain/service/test/databases.rs
index 233ed113c4..5e6a60624f 100644
--- a/crates/databases/src/domain/service/test/databases.rs
+++ b/crates/databases/src/domain/service/test/databases.rs
@@ -490,3 +490,84 @@ async fn schema_operations_respect_receipts() {
assert_eq!(detail.grant, AccessLevel::Owner);
assert!(detail.tables[0].columns.iter().all(|c| c.writable));
}
+
+#[cfg(feature = "entity_mutation")]
+#[tokio::test]
+async fn moving_a_database_files_it_and_names_both_folders() {
+ use entity_mutation::{EntityMutationEffect, MoveEntity, capability::MoveEntityRequest};
+
+ let seeded = seeded().await;
+ let (svc, database_id) = (seeded.service, seeded.database_id);
+ let entity = EntityType::Database.with_entity_string(database_id.to_string());
+ let into = |project_id: &str| MoveEntityRequest::MoveToProject {
+ entity: entity.clone(),
+ receipt: receipt::<OwnerAccessLevel>(database_id, OWNER, AccessLevel::Owner),
+ project_id: project_id.to_string(),
+ project_receipt: receipt::<EditAccessLevel>(database_id, OWNER, AccessLevel::Owner),
+ };
+
+ let effects = svc.move_entity(into("clients")).await.unwrap();
+ assert_eq!(
+ effects,
+ vec![
+ EntityMutationEffect::updated(entity.clone()),
+ EntityMutationEffect::updated(EntityType::Project.with_entity_string("clients".into())),
+ ]
+ );
+ let effects = svc.move_entity(into("archive")).await.unwrap();
+ assert_eq!(
+ effects,
+ vec![
+ EntityMutationEffect::updated(entity.clone()),
+ EntityMutationEffect::updated(EntityType::Project.with_entity_string("clients".into())),
+ EntityMutationEffect::updated(EntityType::Project.with_entity_string("archive".into())),
+ ]
+ );
+ let listed = svc.list_databases(viewer(OWNER)).await.unwrap();
+ assert_eq!(listed[0].database.project_id.as_deref(), Some("archive"));
+
+ let effects = svc
+ .move_entity(MoveEntityRequest::MoveToRoot {
+ entity: entity.clone(),
+ receipt: receipt::<OwnerAccessLevel>(database_id, OWNER, AccessLevel::Owner),
+ })
+ .await
+ .unwrap();
+ assert_eq!(
+ effects,
+ vec![
+ EntityMutationEffect::updated(entity.clone()),
+ EntityMutationEffect::updated(EntityType::Project.with_entity_string("archive".into())),
+ ]
+ );
+ let listed = svc.list_databases(viewer(OWNER)).await.unwrap();
+ assert_eq!(listed[0].database.project_id, None);
+}
+
+#[cfg(feature = "entity_mutation")]
+#[tokio::test]
+async fn a_trashed_database_cannot_be_moved() {
+ use entity_mutation::{MoveEntity, capability::MoveEntityRequest};
+
+ let seeded = seeded().await;
+ let (svc, database_id) = (seeded.service, seeded.database_id);
+ svc.trash_database(receipt::<OwnerAccessLevel>(
+ database_id,
+ OWNER,
+ AccessLevel::Owner,
+ ))
+ .await
+ .unwrap();
+
+ let error = svc
+ .move_entity(MoveEntityRequest::MoveToRoot {
+ entity: EntityType::Database.with_entity_string(database_id.to_string()),
+ receipt: receipt::<OwnerAccessLevel>(database_id, OWNER, AccessLevel::Owner),
+ })
+ .await
+ .unwrap_err();
+ assert!(matches!(
+ error,
+ entity_mutation::EntityMutationErrorCode::NotFound(_)
+ ));
+}
diff --git a/crates/databases/src/domain/service/test/fakes.rs b/crates/databases/src/domain/service/test/fakes.rs
index cca6b7b712..0bc64d380d 100644
--- a/crates/databases/src/domain/service/test/fakes.rs
+++ b/crates/databases/src/domain/service/test/fakes.rs
@@ -105,6 +105,7 @@ impl DatabasesRepo for FakeRepo {
owner_id: command.owner_id.as_ref().to_string(),
created_at: Utc::now(),
trashed_at: None,
+ project_id: None,
};
let title = definition(
first_table.title_column,
@@ -207,6 +208,23 @@ impl DatabasesRepo for FakeRepo {
Ok(false)
}
}
+ async fn move_database(
+ &self,
+ id: DatabaseId,
+ project_id: Option<&str>,
+ ) -> Result<bool, FakeError> {
+ let mut world = self.0.lock().unwrap();
+ if let Some(database) = world
+ .databases
+ .iter_mut()
+ .find(|database| database.id == id && database.trashed_at.is_none())
+ {
+ database.project_id = project_id.map(str::to_string);
+ Ok(true)
+ } else {
+ Ok(false)
+ }
+ }
async fn delete_database(&self, id: DatabaseId) -> Result<(), FakeError> {
let mut world = self.0.lock().unwrap();
world.databases.retain(|database| database.id != id);
diff --git a/crates/databases/src/inbound/toolset/test.rs b/crates/databases/src/inbound/toolset/test.rs
index ecdd54b0ff..c4dac59c8b 100644
--- a/crates/databases/src/inbound/toolset/test.rs
+++ b/crates/databases/src/inbound/toolset/test.rs
@@ -75,6 +75,7 @@ fn database() -> Database {
owner_id: USER.to_string(),
created_at: Utc::now(),
trashed_at: None,
+ project_id: None,
}
}
diff --git a/crates/databases/src/outbound/pg_databases_repo.rs b/crates/databases/src/outbound/pg_databases_repo.rs
index c9da7301d0..4a36e50b44 100644
--- a/crates/databases/src/outbound/pg_databases_repo.rs
+++ b/crates/databases/src/outbound/pg_databases_repo.rs
@@ -2,6 +2,7 @@
//! cells are entity properties, written through the properties adapter.
/// The change journal's statements, shared with the cell store's batches.
+mod folders;
pub(crate) mod journal;
/// Row identity statements, shared with the cell store's batches.
pub(crate) mod rows;
@@ -47,6 +48,9 @@ pub enum PgDatabasesRepoError {
/// one decoded.
#[error("failed to encode or decode stored json")]
Json(#[from] serde_json::Error),
+ /// A folder id is not a uuid.
+ #[error("folder id is not a uuid")]
+ FolderId(#[from] uuid::Error),
/// A stored position is not a fractional key.
#[error("stored position")]
Position(#[from] PositionError),
@@ -88,6 +92,7 @@ pub(crate) struct DatabaseRecord {
pub(crate) owner_id: String,
pub(crate) created_at: chrono::DateTime<chrono::Utc>,
pub(crate) trashed_at: Option<chrono::DateTime<chrono::Utc>>,
+ pub(crate) project_id: Option<String>,
}
impl From<DatabaseRecord> for Database {
@@ -98,6 +103,7 @@ impl From<DatabaseRecord> for Database {
owner_id: record.owner_id,
created_at: record.created_at,
trashed_at: record.trashed_at,
+ project_id: record.project_id,
}
}
}
@@ -163,7 +169,7 @@ pub(crate) async fn insert_owned_database(
r#"
INSERT INTO database_entities (database_id, name, user_id)
VALUES ($1, $2, $3)
- RETURNING database_id AS id, name, user_id AS owner_id, created_at, trashed_at
+ RETURNING database_id AS id, name, user_id AS owner_id, created_at, trashed_at, project_id
"#,
database_id.into_uuid(),
name,
@@ -355,7 +361,7 @@ where
) -> Result<Option<(Database, Vec<Table>)>, Self::Error> {
let Some(database) = sqlx::query_as!(
DatabaseRecord,
- r#"SELECT database_id AS id, name, user_id AS owner_id, created_at, trashed_at FROM database_entities WHERE database_id = $1"#,
+ r#"SELECT database_id AS id, name, user_id AS owner_id, created_at, trashed_at, project_id FROM database_entities WHERE database_id = $1"#,
id.into_uuid()
)
.fetch_optional(&self.pool)
@@ -420,6 +426,15 @@ where
Ok(restored.rows_affected() == 1)
}
+ #[tracing::instrument(err, skip(self))]
+ async fn move_database(
+ &self,
+ id: DatabaseId,
+ project_id: Option<&str>,
+ ) -> Result<bool, Self::Error> {
+ folders::move_database(&self.pool, id, project_id).await
+ }
+
/// Deleting the app entity cleans up its owned storage, grants and journal,
/// including the same cleanup used when its owner is deleted.
#[tracing::instrument(err, skip(self))]
@@ -517,7 +532,7 @@ where
Ok(sqlx::query_as!(
DatabaseRecord,
r#"
- SELECT database_id AS id, name, user_id AS owner_id, created_at, trashed_at
+ SELECT database_id AS id, name, user_id AS owner_id, created_at, trashed_at, project_id
FROM database_entities
WHERE database_id = ANY($1)
ORDER BY created_at
diff --git a/crates/databases/src/outbound/pg_databases_repo/folders.rs b/crates/databases/src/outbound/pg_databases_repo/folders.rs
new file mode 100644
index 0000000000..8a10ad9dc1
--- /dev/null
+++ b/crates/databases/src/outbound/pg_databases_repo/folders.rs
@@ -0,0 +1,59 @@
+//! Filing a database in a folder, with the grants the folder passes down.
+
+use entity_access_db_utils::project_grants::{drop_project_grants, inherit_project_grants};
+use entity_access_db_utils::team_share;
+use model_entity::EntityType;
+use sqlx::PgPool;
+use uuid::Uuid;
+
+use super::PgDatabasesRepoError;
+use crate::domain::models::DatabaseId;
+
+/// File a live database in `project_id`, or at the root, swapping the grants
+/// it inherited from its old folder for the new folder's; `false` when it
+/// is trashed or gone.
+pub(super) async fn move_database(
+ pool: &PgPool,
+ id: DatabaseId,
+ project_id: Option<&str>,
+) -> Result<bool, PgDatabasesRepoError> {
+ let mut transaction = pool.begin().await?;
+ // The team-share guard comes before any row lock, as its writer requires.
+ team_share::acquire_guard(&mut transaction).await?;
+ let Some(previous) = sqlx::query_scalar!(
+ "SELECT project_id FROM database_entities WHERE database_id = $1 AND trashed_at IS NULL FOR UPDATE",
+ id.into_uuid(),
+ )
+ .fetch_optional(&mut *transaction)
+ .await?
+ else {
+ return Ok(false);
+ };
+ sqlx::query!(
+ "UPDATE database_entities SET project_id = $2, updated_at = now() WHERE database_id = $1",
+ id.into_uuid(),
+ project_id,
+ )
+ .execute(&mut *transaction)
+ .await?;
+ if let Some(previous) = previous {
+ drop_project_grants(
+ &mut transaction,
+ id.as_uuid(),
+ EntityType::Database,
+ &Uuid::parse_str(&previous)?,
+ )
+ .await?;
+ }
+ if let Some(project_id) = project_id {
+ inherit_project_grants(
+ &mut transaction,
+ id.as_uuid(),
+ EntityType::Database,
+ &Uuid::parse_str(project_id)?,
+ )
+ .await?;
+ }
+ transaction.commit().await?;
+ Ok(true)
+}
diff --git a/crates/databases/src/outbound/pg_databases_repo/test.rs b/crates/databases/src/outbound/pg_databases_repo/test.rs
index 2c8f7be7dc..95c3d9f4b0 100644
--- a/crates/databases/src/outbound/pg_databases_repo/test.rs
+++ b/crates/databases/src/outbound/pg_databases_repo/test.rs
@@ -19,6 +19,7 @@ mod changes;
#[cfg(feature = "gateway")]
mod derived_cells;
mod entity_split;
+mod folders;
#[cfg(feature = "gateway")]
mod journal;
#[cfg(feature = "gateway")]
diff --git a/crates/databases/src/outbound/pg_databases_repo/test/entity_split.rs b/crates/databases/src/outbound/pg_databases_repo/test/entity_split.rs
index d7b460deba..44ec2441b3 100644
--- a/crates/databases/src/outbound/pg_databases_repo/test/entity_split.rs
+++ b/crates/databases/src/outbound/pg_databases_repo/test/entity_split.rs
@@ -14,6 +14,10 @@ const SPLIT_DOWN: &str = include_str!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/../macro_db_client/migrations/20261005183743_separate_database_entity.down.sql"
));
+const FOLDERS_UP: &str = include_str!(concat!(
+ env!("CARGO_MANIFEST_DIR"),
+ "/../macro_db_client/migrations/20261102210628_databases_in_folders.sql"
+));
const WEBHOOKS_DOWN: &str = include_str!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/../macro_db_client/migrations/20261014153433_database_webhooks.down.sql"
@@ -208,6 +212,11 @@ async fn schema_cutover_discards_database_content_and_allows_a_fresh_start(pool:
.execute(&mut *transaction)
.await
.unwrap();
+ // The recreated entity table needs the later folder column back.
+ sqlx::raw_sql(FOLDERS_UP)
+ .execute(&mut *transaction)
+ .await
+ .unwrap();
let remaining = sqlx::query_scalar!(
r#"SELECT (SELECT COUNT(*) FROM databases)
+ (SELECT COUNT(*) FROM database_entities)
diff --git a/crates/databases/src/outbound/pg_databases_repo/test/folders.rs b/crates/databases/src/outbound/pg_databases_repo/test/folders.rs
new file mode 100644
index 0000000000..628fd4d760
--- /dev/null
+++ b/crates/databases/src/outbound/pg_databases_repo/test/folders.rs
@@ -0,0 +1,117 @@
+use super::*;
+
+const FOLDER: &str = "0190f5a0-0000-7000-8000-000000000001";
+const SUBFOLDER: &str = "0190f5a0-0000-7000-8000-000000000002";
+
+/// A folder shared with a channel, and a subfolder inside it.
+async fn shared_folders(pool: &PgPool) {
+ sqlx::query!(
+ r#"INSERT INTO "Project" (id, name, "userId") VALUES ($1, 'Clients', $3), ($2, 'Acme', $3)"#,
+ FOLDER,
+ SUBFOLDER,
+ USER,
+ )
+ .execute(pool)
+ .await
+ .unwrap();
+ sqlx::query!(
+ r#"UPDATE "Project" SET "parentId" = $1 WHERE id = $2"#,
+ FOLDER,
+ SUBFOLDER
+ )
+ .execute(pool)
+ .await
+ .unwrap();
+ sqlx::query!(
+ "INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level) VALUES ($1, 'project', 'channel-1', 'channel', 'view')",
+ Uuid::parse_str(FOLDER).unwrap(),
+ )
+ .execute(pool)
+ .await
+ .unwrap();
+}
+
+async fn grants(pool: &PgPool, database_id: DatabaseId) -> Vec<(String, Option<String>)> {
+ sqlx::query!(
+ "SELECT source_id, granted_from_project_id FROM entity_access WHERE entity_id = $1 AND entity_type = 'database' ORDER BY source_id",
+ database_id.into_uuid(),
+ )
+ .fetch_all(pool)
+ .await
+ .unwrap()
+ .into_iter()
+ .map(|row| (row.source_id, row.granted_from_project_id))
+ .collect()
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn a_database_in_a_folder_holds_the_grants_of_every_folder_above_it(pool: PgPool) {
+ let (repo, table, _) = fixture(&pool).await;
+ shared_folders(&pool).await;
+ let database_id = table.database_id;
+
+ assert!(
+ repo.move_database(database_id, Some(SUBFOLDER))
+ .await
+ .unwrap()
+ );
+ let (database, _) = repo.get_database(database_id).await.unwrap().unwrap();
+ assert_eq!(database.project_id.as_deref(), Some(SUBFOLDER));
+ assert_eq!(
+ grants(&pool, database_id).await,
+ vec![
+ ("channel-1".to_string(), Some(FOLDER.to_string())),
+ (USER.to_string(), None),
+ ]
+ );
+
+ assert!(repo.move_database(database_id, None).await.unwrap());
+ let (database, _) = repo.get_database(database_id).await.unwrap().unwrap();
+ assert_eq!(database.project_id, None);
+ assert_eq!(
+ grants(&pool, database_id).await,
+ vec![(USER.to_string(), None)]
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn a_trashed_or_missing_database_stays_where_it_was(pool: PgPool) {
+ let (repo, table, _) = fixture(&pool).await;
+ shared_folders(&pool).await;
+ let database_id = table.database_id;
+ repo.trash_database(database_id, chrono::Utc::now())
+ .await
+ .unwrap();
+
+ assert!(!repo.move_database(database_id, Some(FOLDER)).await.unwrap());
+ assert!(
+ !repo
+ .move_database(DatabaseId::from_uuid(Uuid::nil()), Some(FOLDER))
+ .await
+ .unwrap()
+ );
+ let (database, _) = repo.get_database(database_id).await.unwrap().unwrap();
+ assert_eq!(database.project_id, None);
+ assert_eq!(
+ grants(&pool, database_id).await,
+ vec![(USER.to_string(), None)]
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn purging_its_folder_returns_a_database_to_the_root(pool: PgPool) {
+ let (repo, table, _) = fixture(&pool).await;
+ shared_folders(&pool).await;
+ let database_id = table.database_id;
+ repo.move_database(database_id, Some(SUBFOLDER))
+ .await
+ .unwrap();
+
+ sqlx::query!(r#"DELETE FROM "Project" WHERE id = $1"#, SUBFOLDER)
+ .execute(&pool)
+ .await
+ .unwrap();
+
+ let (database, _) = repo.get_database(database_id).await.unwrap().unwrap();
+ assert_eq!(database.project_id, None);
+}
diff --git a/crates/databases_sql/src/catalog/test.rs b/crates/databases_sql/src/catalog/test.rs
index 56f6d96574..b75f5b77b5 100644
--- a/crates/databases_sql/src/catalog/test.rs
+++ b/crates/databases_sql/src/catalog/test.rs
@@ -30,6 +30,7 @@ fn details_become_the_schema_the_engine_builds_its_catalog_from() {
owner_id: "macro|[email protected]".into(),
created_at: Utc::now(),
trashed_at: None,
+ project_id: None,
},
grant: AccessLevel::Owner,
tables: vec![TableDetail {
@@ -336,6 +337,7 @@ fn a_shared_relation_definition_relates_each_table_to_its_own_target() {
owner_id: "macro|[email protected]".into(),
created_at: Utc::now(),
trashed_at: None,
+ project_id: None,
},
grant: AccessLevel::Owner,
tables: vec![
diff --git a/crates/databases_sql/src/service/test.rs b/crates/databases_sql/src/service/test.rs
index 95731390a8..cec0c7ebd5 100644
--- a/crates/databases_sql/src/service/test.rs
+++ b/crates/databases_sql/src/service/test.rs
@@ -79,6 +79,7 @@ pub(crate) fn world() -> Shared {
owner_id: OWNER.to_string(),
created_at: Utc::now(),
trashed_at: None,
+ project_id: None,
},
grant: AccessLevel::Owner,
tables: vec![TableDetail {
@@ -248,6 +249,7 @@ pub(crate) fn world() -> Shared {
owner_id: OWNER.to_string(),
created_at: Utc::now(),
trashed_at: None,
+ project_id: None,
},
grant: AccessLevel::Owner,
tables: vec![TableDetail {
@@ -300,6 +302,7 @@ pub(crate) fn world() -> Shared {
owner_id: OWNER.to_string(),
created_at: Utc::now(),
trashed_at: None,
+ project_id: None,
},
grant: AccessLevel::Owner,
tables: vec![TableDetail {
diff --git a/crates/databases_sql/src/test_support.rs b/crates/databases_sql/src/test_support.rs
index 2cbd2c12e7..283c817192 100644
--- a/crates/databases_sql/src/test_support.rs
+++ b/crates/databases_sql/src/test_support.rs
@@ -252,6 +252,7 @@ impl DatabasesService for FakeDatabases {
owner_id: input.owner_id.to_string(),
created_at: Utc::now(),
trashed_at: None,
+ project_id: None,
};
self.0.lock().unwrap().created.push(input);
Ok(database)
diff --git a/crates/databases_sql/src/toolset/test.rs b/crates/databases_sql/src/toolset/test.rs
index 45319293b3..fe81c34917 100644
--- a/crates/databases_sql/src/toolset/test.rs
+++ b/crates/databases_sql/src/toolset/test.rs
@@ -51,6 +51,7 @@ fn world() -> Shared {
owner_id: OWNER.to_string(),
created_at: Utc::now(),
trashed_at: None,
+ project_id: None,
},
grant: AccessLevel::Owner,
tables: vec![TableDetail {
diff --git a/crates/documents/src/domain/entity_mutation.rs b/crates/documents/src/domain/entity_mutation.rs
index 9fbabc5c75..da04cdcdbb 100644
--- a/crates/documents/src/domain/entity_mutation.rs
+++ b/crates/documents/src/domain/entity_mutation.rs
@@ -4,14 +4,12 @@
//! document service's own methods, preconditions, and errors, so the
//! composition layer routes without translating.
-use std::collections::HashSet;
-
use entity_access::domain::models::{
EditAccessLevel, EntityAccessReceipt, OwnerAccessLevel, ViewAccessLevel,
};
use entity_mutation::{
DuplicateEntity, EntityMutationEffect, EntityMutationErrorCode, MoveEntity, RenameEntity,
- TrashEntity, UpdateEntitySharePolicy, capability::MoveEntityRequest,
+ TrashEntity, UpdateEntitySharePolicy, capability::MoveEntityRequest, project_refs,
};
use macro_user_id::user_id::MacroUserIdStr;
use model::document::DocumentBasic;
@@ -47,16 +45,6 @@ impl From<DocumentError> for EntityMutationErrorCode {
}
}
-/// Build affected project entities from optional container ids.
-fn project_refs(ids: impl IntoIterator<Item = Option<String>>) -> Vec<Entity<'static>> {
- let mut seen = HashSet::new();
- ids.into_iter()
- .flatten()
- .filter(|id| !id.is_empty() && seen.insert(id.clone()))
- .map(|id| EntityType::Project.with_entity_string(id))
- .collect()
-}
-
/// Fetch a document and reject the mutation if it is trashed.
async fn live_document<S: DocumentService>(
service: &S,
diff --git a/crates/email/src/domain/service/entity_mutation.rs b/crates/email/src/domain/service/entity_mutation.rs
index 0d2ce8997c..09caa05855 100644
--- a/crates/email/src/domain/service/entity_mutation.rs
+++ b/crates/email/src/domain/service/entity_mutation.rs
@@ -1,12 +1,10 @@
//! Unified entity-mutation capability impls for email threads.
-use std::collections::HashSet;
-
use entity_access::domain::models::EditAccessLevel;
use entity_mutation::{
EntityMutationEffect, EntityMutationErrorCode, MoveEntity, capability::MoveEntityRequest,
+ project_refs,
};
-use model_entity::{Entity, EntityType};
use super::EmailServiceImpl;
use crate::domain::{models::EmailErr, ports::EmailService};
@@ -21,16 +19,6 @@ impl From<EmailErr> for EntityMutationErrorCode {
}
}
-/// Build affected project entities from optional container ids.
-fn project_refs(ids: impl IntoIterator<Item = Option<String>>) -> Vec<Entity<'static>> {
- let mut seen = HashSet::new();
- ids.into_iter()
- .flatten()
- .filter(|id| !id.is_empty() && seen.insert(id.clone()))
- .map(|id| EntityType::Project.with_entity_string(id))
- .collect()
-}
-
impl<T, U, E, CS, Eam, B> MoveEntity for EmailServiceImpl<T, U, E, CS, Eam, B>
where
Self: EmailService,
diff --git a/crates/entity_access_db_utils/AGENTS.md b/crates/entity_access_db_utils/AGENTS.md
index 5b557690d9..fb69a8c9d6 100644
--- a/crates/entity_access_db_utils/AGENTS.md
+++ b/crates/entity_access_db_utils/AGENTS.md
@@ -16,6 +16,9 @@ top of it.
- `src/channel_share.rs`, `src/team_share.rs`: grant helpers scoped to a
channel or team source.
- `src/direct_share.rs`: live ownership facts and direct user grants for access requests.
+- `src/project_grants.rs`: the grants an entity inherits from the folders it
+ is filed in, written when it enters or leaves one; databases and forms call
+ it in the same transaction as their `project_id` write.
## Scope
@@ -31,7 +34,7 @@ top of it.
- Used by: `crates/entity_access_management`, `crates/entity_registry/entity_registry_db_utils`,
and most domain crates that grant access as part of a write
(`channels`, `projects`, `teams`, `crm`, `call`, `chat`, `documents`,
- `macro_db_client`, `crates/scheduled_action`).
+ `databases`, `forms`, `macro_db_client`, `crates/scheduled_action`).
## Recipes
diff --git a/crates/entity_access_db_utils/src/lib.rs b/crates/entity_access_db_utils/src/lib.rs
index 26d69b68ee..5babb139f4 100644
--- a/crates/entity_access_db_utils/src/lib.rs
+++ b/crates/entity_access_db_utils/src/lib.rs
@@ -7,6 +7,7 @@ mod test;
pub mod channel_share;
pub mod direct_share;
+pub mod project_grants;
pub mod source_grants;
pub mod team_share;
@@ -314,6 +315,16 @@ pub async fn get_nested_project_entities(
SELECT et.id::text as "entity_id!", 'email_thread' as "entity_type!" FROM email_threads et
WHERE et.project_id IN (SELECT id FROM child_projects)
+
+ UNION ALL
+
+ SELECT de.database_id::text as "entity_id!", 'database' as "entity_type!" FROM database_entities de
+ WHERE de.project_id IN (SELECT id FROM child_projects)
+
+ UNION ALL
+
+ SELECT f.id::text as "entity_id!", 'form' as "entity_type!" FROM forms f
+ WHERE f.project_id IN (SELECT id FROM child_projects)
"#,
&project_id.to_string()
)
diff --git a/crates/entity_access_db_utils/src/project_grants.rs b/crates/entity_access_db_utils/src/project_grants.rs
new file mode 100644
index 0000000000..34b8dc79d7
--- /dev/null
+++ b/crates/entity_access_db_utils/src/project_grants.rs
@@ -0,0 +1,118 @@
+//! Grants an entity inherits from the folders (projects) it is filed in.
+//!
+//! An entity in a folder holds one `entity_access` row per grant on that
+//! folder or any folder above it, marked with `granted_from_project_id`.
+//! Callers hold [`crate::team_share::acquire_guard`] in the same transaction.
+
+use model_entity::EntityType;
+use models_entity_access_management::EntityAccessSourceType;
+use models_permissions::share_permission::access_level::AccessLevel;
+use sqlx::{Postgres, QueryBuilder, Transaction};
+
+use crate::walk_up_project_tree;
+
+/// A grant made directly on a folder, which the folder's contents inherit.
+#[derive(Clone, Debug)]
+pub struct ProjectGrantSource {
+ /// The folder the grant was made on.
+ pub project_id: macro_uuid::Uuid,
+ /// The user, channel or team granted access.
+ pub source_id: String,
+ /// What kind of grantee `source_id` is.
+ pub source_type: EntityAccessSourceType,
+ /// The level granted.
+ pub access_level: AccessLevel,
+}
+
+/// The grants made directly on any of `project_ids`.
+#[tracing::instrument(skip(transaction), err)]
+pub async fn project_grant_sources(
+ transaction: &mut Transaction<'_, Postgres>,
+ project_ids: &[macro_uuid::Uuid],
+) -> Result<Vec<ProjectGrantSource>, sqlx::Error> {
+ sqlx::query!(
+ r#"
+ SELECT
+ entity_id,
+ source_id,
+ source_type as "source_type:EntityAccessSourceType",
+ access_level as "access_level:AccessLevel"
+ FROM entity_access
+ WHERE entity_id = ANY($1) AND entity_type = 'project' AND granted_from_project_id IS NULL
+ "#,
+ project_ids,
+ )
+ .map(|r| ProjectGrantSource {
+ project_id: r.entity_id,
+ source_id: r.source_id,
+ source_type: r.source_type,
+ access_level: r.access_level,
+ })
+ .fetch_all(transaction.as_mut())
+ .await
+}
+
+/// Give an entity just filed in `project_id` the grants of that folder and
+/// every folder above it.
+#[tracing::instrument(skip(transaction), err)]
+pub async fn inherit_project_grants(
+ transaction: &mut Transaction<'_, Postgres>,
+ entity_id: &macro_uuid::Uuid,
+ entity_type: EntityType,
+ project_id: &macro_uuid::Uuid,
+) -> Result<(), sqlx::Error> {
+ let project_ids = walk_up_project_tree(transaction, project_id).await?;
+ let sources = project_grant_sources(transaction, &project_ids).await?;
+ if sources.is_empty() {
+ return Ok(());
+ }
+ let entity_type: &str = entity_type.into();
+ let mut query: QueryBuilder<Postgres> = QueryBuilder::new(
+ "INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level, granted_from_project_id) ",
+ );
+ query.push_values(&sources, |mut row, source| {
+ row.push_bind(entity_id)
+ .push_bind(entity_type)
+ .push_bind(&source.source_id)
+ .push_bind(source.source_type)
+ .push_bind(source.access_level)
+ .push_bind(source.project_id.to_string());
+ });
+ query.push(" ON CONFLICT DO NOTHING");
+ query.build().execute(transaction.as_mut()).await?;
+ Ok(())
+}
+
+/// Drop the grants an entity inherited from `old_project_id` and every
+/// folder above it, as it leaves that folder.
+#[tracing::instrument(skip(transaction), err)]
+pub async fn drop_project_grants(
+ transaction: &mut Transaction<'_, Postgres>,
+ entity_id: &macro_uuid::Uuid,
+ entity_type: EntityType,
+ old_project_id: &macro_uuid::Uuid,
+) -> Result<(), sqlx::Error> {
+ let project_ids = walk_up_project_tree(transaction, old_project_id)
+ .await?
+ .into_iter()
+ .map(|id| id.to_string())
+ .collect::<Vec<String>>();
+ if project_ids.is_empty() {
+ return Ok(());
+ }
+ let entity_type: &str = entity_type.into();
+ sqlx::query!(
+ r#"
+ DELETE FROM entity_access
+ WHERE entity_id = $1
+ AND entity_type = $2
+ AND granted_from_project_id = ANY($3)
+ "#,
+ entity_id,
+ entity_type,
+ &project_ids,
+ )
+ .execute(transaction.as_mut())
+ .await?;
+ Ok(())
+}
diff --git a/crates/entity_access_management/fixtures/move_project_test_data.sql b/crates/entity_access_management/fixtures/move_project_test_data.sql
index 970e30b7f5..053dc3a1f5 100644
--- a/crates/entity_access_management/fixtures/move_project_test_data.sql
+++ b/crates/entity_access_management/fixtures/move_project_test_data.sql
@@ -111,3 +111,16 @@ INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, acces
VALUES ('d2222222-2222-2222-2222-222222222222', 'document', 'team-1', 'team', 'edit', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb');
INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level, granted_from_project_id)
VALUES ('d2222222-2222-2222-2222-222222222222', 'document', 'macro|[email protected]', 'user', 'owner', 'cccccccc-cccc-cccc-cccc-cccccccccccc');
+
+-- A database and a form filed in PROJECT_C, nested under the moved project.
+INSERT INTO public."macro_user" ("id", "username", "email", "stripe_customer_id")
+ VALUES ('a5555555-5555-5555-5555-555555555555', 'filer', '[email protected]', 'stripe_e');
+INSERT INTO public."User" ("id", "email", "stripeCustomerId", "organizationId", "macro_user_id")
+ VALUES ('macro|[email protected]', '[email protected]', 'stripe_e', 1, 'a5555555-5555-5555-5555-555555555555');
+INSERT INTO databases (id) VALUES ('e1111111-1111-1111-1111-111111111111');
+INSERT INTO database_tables (id, database_id, name, position)
+ VALUES ('e2222222-2222-2222-2222-222222222222', 'e1111111-1111-1111-1111-111111111111', 'Responses', '80');
+INSERT INTO database_entities (database_id, name, user_id, project_id)
+ VALUES ('e1111111-1111-1111-1111-111111111111', 'database-in-c', 'macro|[email protected]', 'cccccccc-cccc-cccc-cccc-cccccccccccc');
+INSERT INTO forms (id, name, owner_id, database_id, table_id, project_id)
+ VALUES ('e3333333-3333-3333-3333-333333333333', 'form-in-c', 'macro|[email protected]', 'e1111111-1111-1111-1111-111111111111', 'e2222222-2222-2222-2222-222222222222', 'cccccccc-cccc-cccc-cccc-cccccccccccc');
diff --git a/crates/entity_access_management/src/outbound/pg_repo.rs b/crates/entity_access_management/src/outbound/pg_repo.rs
index d3edcca5f0..e9c5d09e55 100644
--- a/crates/entity_access_management/src/outbound/pg_repo.rs
+++ b/crates/entity_access_management/src/outbound/pg_repo.rs
@@ -5,24 +5,10 @@ mod test;
use entity_access_db_utils::SimpleEntity;
use model_entity::EntityType;
-use models_permissions::share_permission::access_level::AccessLevel;
use sqlx::{PgPool, Postgres, QueryBuilder, Transaction};
use uuid::Uuid;
-use crate::domain::{models::EntityAccessSourceType, ports::EntityAccessManagementRepository};
-
-/// A source entity we need to update permissions for
-#[derive(Clone, Debug)]
-struct ProjectSourceEntity {
- /// The project entity that was shared
- pub project_id: uuid::Uuid,
- /// This could be a user, channel or a team
- pub source_id: String,
- /// The source type
- pub source_type: EntityAccessSourceType,
- /// The access level for the source entity
- pub access_level: AccessLevel,
-}
+use crate::domain::ports::EntityAccessManagementRepository;
/// PostgreSQL-backed implementation of [`EntityAccessManagementRepository`]
#[derive(Clone)]
@@ -58,39 +44,6 @@ impl PgRepository {
) -> Result<Vec<uuid::Uuid>, sqlx::Error> {
entity_access_db_utils::walk_up_project_tree(transaction, project_id).await
}
-
- /// Given a list of project ids, this will return a list of all source entities (source_id/source_type/access_level) entries that we need to insert rows for the new entity
- #[tracing::instrument(skip(self, transaction), err)]
- async fn get_all_source_entities_for_projects(
- &self,
- transaction: &mut Transaction<'_, Postgres>,
- project_ids: &[uuid::Uuid],
- ) -> Result<Vec<ProjectSourceEntity>, sqlx::Error> {
- // Grab every instance of any project_ids being shared
- // This will allow us to insert records for all these source entities for the new id
- let result = sqlx::query!(
- r#"
- SELECT
- entity_id,
- source_id,
- source_type as "source_type:EntityAccessSourceType",
- access_level as "access_level:AccessLevel"
- FROM entity_access
- WHERE entity_id = ANY($1) AND entity_type = 'project' AND granted_from_project_id IS NULL
- "#,
- project_ids,
- )
- .map(|r| ProjectSourceEntity {
- project_id: r.entity_id,
- source_id: r.source_id,
- source_type: r.source_type,
- access_level: r.access_level,
- })
- .fetch_all(transaction.as_mut())
- .await?;
-
- Ok(result)
- }
}
impl EntityAccessManagementRepository for PgRepository {
@@ -106,33 +59,13 @@ impl EntityAccessManagementRepository for PgRepository {
let mut transaction = self.pool.begin().await?;
entity_access_db_utils::team_share::acquire_guard(&mut transaction).await?;
- let walked_up_project_ids = self
- .walk_up_project_tree(&mut transaction, project_id)
- .await?;
-
- let source_entities = self
- .get_all_source_entities_for_projects(&mut transaction, &walked_up_project_ids)
- .await?;
-
- if !source_entities.is_empty() {
- let entity_type_str: &str = entity_type.into();
-
- let mut qb: QueryBuilder<Postgres> = QueryBuilder::new(
- "INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level, granted_from_project_id) ",
- );
-
- qb.push_values(&source_entities, |mut b, source| {
- b.push_bind(entity_id)
- .push_bind(entity_type_str)
- .push_bind(&source.source_id)
- .push_bind(source.source_type)
- .push_bind(source.access_level)
- .push_bind(source.project_id.to_string());
- });
-
- qb.push(" ON CONFLICT DO NOTHING");
- qb.build().execute(transaction.as_mut()).await?;
- }
+ entity_access_db_utils::project_grants::inherit_project_grants(
+ &mut transaction,
+ entity_id,
+ entity_type,
+ project_id,
+ )
+ .await?;
transaction.commit().await?;
@@ -149,31 +82,14 @@ impl EntityAccessManagementRepository for PgRepository {
let mut transaction = self.pool.begin().await?;
entity_access_db_utils::team_share::acquire_guard(&mut transaction).await?;
- let walked_up_project_ids = self
- .walk_up_project_tree(&mut transaction, old_project_id)
- .await?;
-
- if !walked_up_project_ids.is_empty() {
- let entity_type_str: &str = entity_type.into();
- sqlx::query!(
- r#"
- DELETE FROM entity_access
- WHERE entity_id = $1
- AND entity_type = $2
- AND granted_from_project_id = ANY($3)
- "#,
- entity_id,
- entity_type_str,
- &walked_up_project_ids
- .into_iter()
- .map(|s| s.to_string())
- .collect::<Vec<String>>(),
- )
- .execute(transaction.as_mut())
- .await?;
-
- transaction.commit().await?;
- }
+ entity_access_db_utils::project_grants::drop_project_grants(
+ &mut transaction,
+ entity_id,
+ entity_type,
+ old_project_id,
+ )
+ .await?;
+ transaction.commit().await?;
Ok(())
}
@@ -230,9 +146,11 @@ impl EntityAccessManagementRepository for PgRepository {
.await?;
// get all source entities for the new walked up projects
- let source_entities = self
- .get_all_source_entities_for_projects(&mut transaction, &new_walked_up_project_ids)
- .await?;
+ let source_entities = entity_access_db_utils::project_grants::project_grant_sources(
+ &mut transaction,
+ &new_walked_up_project_ids,
+ )
+ .await?;
if !source_entities.is_empty() {
let mut qb: QueryBuilder<Postgres> = QueryBuilder::new(
diff --git a/crates/entity_access_management/src/outbound/pg_repo/test.rs b/crates/entity_access_management/src/outbound/pg_repo/test.rs
index 19e35266bb..f99467e9b0 100644
--- a/crates/entity_access_management/src/outbound/pg_repo/test.rs
+++ b/crates/entity_access_management/src/outbound/pg_repo/test.rs
@@ -130,13 +130,14 @@ async fn walk_up_nonexistent_project_returns_empty(pool: Pool<Postgres>) {
fixtures(path = "../../../fixtures", scripts("project_tree_test_data"))
)]
async fn source_entities_returns_direct_shares_across_projects(pool: Pool<Postgres>) {
- let repo = PgRepository::new(pool.clone());
let mut tx = pool.begin().await.unwrap();
- let result = repo
- .get_all_source_entities_for_projects(&mut tx, &[ROOT_PROJECT_ID, CHILD_PROJECT_ID])
- .await
- .unwrap();
+ let result = entity_access_db_utils::project_grants::project_grant_sources(
+ &mut tx,
+ &[ROOT_PROJECT_ID, CHILD_PROJECT_ID],
+ )
+ .await
+ .unwrap();
// 3 direct shares: user/edit on root, team/view on root, channel/comment on child
assert_eq!(result.len(), 3);
@@ -174,14 +175,13 @@ async fn source_entities_returns_direct_shares_across_projects(pool: Pool<Postgr
fixtures(path = "../../../fixtures", scripts("project_tree_test_data"))
)]
async fn source_entities_excludes_inherited_access(pool: Pool<Postgres>) {
- let repo = PgRepository::new(pool.clone());
let mut tx = pool.begin().await.unwrap();
// Child project has one direct share (channel/comment) and one inherited (user/view with granted_from_project_id)
- let result = repo
- .get_all_source_entities_for_projects(&mut tx, &[CHILD_PROJECT_ID])
- .await
- .unwrap();
+ let result =
+ entity_access_db_utils::project_grants::project_grant_sources(&mut tx, &[CHILD_PROJECT_ID])
+ .await
+ .unwrap();
assert_eq!(result.len(), 1);
assert_eq!(result[0].source_id, "channel-one");
@@ -196,14 +196,13 @@ async fn source_entities_excludes_inherited_access(pool: Pool<Postgres>) {
fixtures(path = "../../../fixtures", scripts("project_tree_test_data"))
)]
async fn source_entities_excludes_non_project_entity_type(pool: Pool<Postgres>) {
- let repo = PgRepository::new(pool.clone());
let mut tx = pool.begin().await.unwrap();
// Root project has 2 direct project shares + 1 document row (should be excluded)
- let result = repo
- .get_all_source_entities_for_projects(&mut tx, &[ROOT_PROJECT_ID])
- .await
- .unwrap();
+ let result =
+ entity_access_db_utils::project_grants::project_grant_sources(&mut tx, &[ROOT_PROJECT_ID])
+ .await
+ .unwrap();
assert_eq!(result.len(), 2);
assert!(
@@ -219,13 +218,14 @@ async fn source_entities_excludes_non_project_entity_type(pool: Pool<Postgres>)
fixtures(path = "../../../fixtures", scripts("project_tree_test_data"))
)]
async fn source_entities_empty_for_project_without_access(pool: Pool<Postgres>) {
- let repo = PgRepository::new(pool.clone());
let mut tx = pool.begin().await.unwrap();
- let result = repo
- .get_all_source_entities_for_projects(&mut tx, &[GRANDCHILD_PROJECT_ID])
- .await
- .unwrap();
+ let result = entity_access_db_utils::project_grants::project_grant_sources(
+ &mut tx,
+ &[GRANDCHILD_PROJECT_ID],
+ )
+ .await
+ .unwrap();
assert!(result.is_empty());
}
@@ -235,14 +235,13 @@ async fn source_entities_empty_for_project_without_access(pool: Pool<Postgres>)
fixtures(path = "../../../fixtures", scripts("project_tree_test_data"))
)]
async fn source_entities_empty_for_nonexistent_project(pool: Pool<Postgres>) {
- let repo = PgRepository::new(pool.clone());
let mut tx = pool.begin().await.unwrap();
let nonexistent = Uuid::new_v4();
- let result = repo
- .get_all_source_entities_for_projects(&mut tx, &[nonexistent])
- .await
- .unwrap();
+ let result =
+ entity_access_db_utils::project_grants::project_grant_sources(&mut tx, &[nonexistent])
+ .await
+ .unwrap();
assert!(result.is_empty());
}
@@ -280,7 +279,6 @@ async fn source_entities_empty_for_nonexistent_project(pool: Pool<Postgres>) {
fixtures(path = "../../../fixtures", scripts("complex_project_tree_test_data"))
)]
async fn source_entities_for_full_tree_walk_returns_only_direct_shares(pool: Pool<Postgres>) {
- let repo = PgRepository::new(pool.clone());
let mut tx = pool.begin().await.unwrap();
let project_a = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa").unwrap();
@@ -288,10 +286,12 @@ async fn source_entities_for_full_tree_walk_returns_only_direct_shares(pool: Poo
let project_c = Uuid::parse_str("cccccccc-cccc-cccc-cccc-cccccccccccc").unwrap();
// Simulates walk_up_project_tree from PROJECT_C → [A, B, C]
- let result = repo
- .get_all_source_entities_for_projects(&mut tx, &[project_a, project_b, project_c])
- .await
- .unwrap();
+ let result = entity_access_db_utils::project_grants::project_grant_sources(
+ &mut tx,
+ &[project_a, project_b, project_c],
+ )
+ .await
+ .unwrap();
// 6 direct shares total: 3 users + 1 team + 2 channels
// All 6 inherited rows (granted_from_project_id IS NOT NULL) should be excluded
@@ -872,3 +872,63 @@ async fn move_project_from_a_to_d_updates_inherited_access(pool: Pool<Postgres>)
2
);
}
+
+/// A database and a form filed in PROJECT_C move with PROJECT_B: they take
+/// on PROJECT_D's two grants, as the documents beside them do.
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("move_project_test_data"))
+)]
+async fn move_project_carries_inherited_access_to_its_databases_and_forms(pool: Pool<Postgres>) {
+ let repo = PgRepository::new(pool.clone());
+ let project_a = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa").unwrap();
+ let project_b = Uuid::parse_str("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb").unwrap();
+ let project_d = Uuid::parse_str("dddddddd-dddd-dddd-dddd-dddddddddddd").unwrap();
+
+ repo.move_project(&project_b, Some(&project_a), Some(&project_d))
+ .await
+ .unwrap();
+
+ let inherited = |entity_id: Uuid| {
+ let pool = pool.clone();
+ async move {
+ sqlx::query!(
+ r#"
+ SELECT source_id, access_level AS "access_level: AccessLevel"
+ FROM entity_access
+ WHERE entity_id = $1
+ AND granted_from_project_id = 'dddddddd-dddd-dddd-dddd-dddddddddddd'
+ ORDER BY source_id
+ "#,
+ entity_id,
+ )
+ .fetch_all(&pool)
+ .await
+ .unwrap()
+ .into_iter()
+ .map(|row| (row.source_id, row.access_level))
+ .collect::<Vec<_>>()
+ }
+ };
+ let project_d_grants = sqlx::query!(
+ r#"
+ SELECT source_id, access_level AS "access_level: AccessLevel"
+ FROM entity_access
+ WHERE entity_id = $1 AND granted_from_project_id IS NULL
+ ORDER BY source_id
+ "#,
+ project_d,
+ )
+ .fetch_all(&pool)
+ .await
+ .unwrap()
+ .into_iter()
+ .map(|row| (row.source_id, row.access_level))
+ .collect::<Vec<_>>();
+ assert_eq!(project_d_grants.len(), 2);
+
+ let database = Uuid::parse_str("e1111111-1111-1111-1111-111111111111").unwrap();
+ let form = Uuid::parse_str("e3333333-3333-3333-3333-333333333333").unwrap();
+ assert_eq!(inherited(database).await, project_d_grants);
+ assert_eq!(inherited(form).await, project_d_grants);
+}
diff --git a/crates/entity_mutation/src/lib.rs b/crates/entity_mutation/src/lib.rs
index 5ff1e58954..9e9986fe15 100644
--- a/crates/entity_mutation/src/lib.rs
+++ b/crates/entity_mutation/src/lib.rs
@@ -17,5 +17,6 @@ pub use capability::{
pub use models::{
DuplicateEntityRequest, EntityMutationActor, EntityMutationEffect, EntityMutationErrorCode,
EntityMutationSuccess, MoveEntityRequest, RenameEntityRequest, UpdateEntitySharePolicyRequest,
+ project_refs,
};
pub use ports::{EntityMutationService, MutateEntitiesResult, UnavailableEntityMutationService};
diff --git a/crates/entity_mutation/src/models.rs b/crates/entity_mutation/src/models.rs
index d20b6e9233..00fc5ff4ed 100644
--- a/crates/entity_mutation/src/models.rs
+++ b/crates/entity_mutation/src/models.rs
@@ -1,5 +1,7 @@
use macro_user_id::user_id::MacroUserIdStr;
-use model_entity::Entity;
+use std::collections::HashSet;
+
+use model_entity::{Entity, EntityType};
use models_permissions::share_permission::UpdateSharePermissionRequestV2;
/// Authenticated actor performing an entity mutation.
@@ -138,6 +140,17 @@ impl EntityMutationEffect {
}
}
+/// The folders (projects) named by optional container ids, once each; an
+/// empty id means the root and names none.
+pub fn project_refs(ids: impl IntoIterator<Item = Option<String>>) -> Vec<Entity<'static>> {
+ let mut seen = HashSet::new();
+ ids.into_iter()
+ .flatten()
+ .filter(|id| !id.is_empty() && seen.insert(id.clone()))
+ .map(|id| EntityType::Project.with_entity_string(id))
+ .collect()
+}
+
/// Successful mutation outcome with effects in application order.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct EntityMutationSuccess {
diff --git a/crates/forms/AGENTS.md b/crates/forms/AGENTS.md
index 3279e9afe9..fab0a013d3 100644
--- a/crates/forms/AGENTS.md
+++ b/crates/forms/AGENTS.md
@@ -48,6 +48,9 @@ service.
## Gotchas
+- A form is filed in a folder on its own (`forms.project_id`, `MoveEntity`,
+ owner only); its database stays where it is. The folder's inherited grants
+ on the form reach the database through form access, like any form grant.
- `POST /forms` attributes the creation to the SDK token's `agent_id` (code
mode), like the native tool, so channel delivery shares a poll an agent
posts; access checks still run as the plain user.
diff --git a/crates/forms/src/domain/entity_mutation.rs b/crates/forms/src/domain/entity_mutation.rs
index e5635ad890..03c09dc230 100644
--- a/crates/forms/src/domain/entity_mutation.rs
+++ b/crates/forms/src/domain/entity_mutation.rs
@@ -1,13 +1,14 @@
-//! The entity-mutation lifecycle capabilities for forms: rename, trash,
-//! restore and permanent delete. None of them touch the form's database.
+//! The entity-mutation capabilities for forms: rename, move between folders,
+//! trash, restore and permanent delete. None of them touch the form's
+//! database.
use crate::domain::drafts::{FormDraftRepository, FormDraftStore};
use databases::domain::ports::{DatabaseMetadataReads, DatabaseRowReads, DatabasesService};
use entity_access::domain::models::{EditAccessLevel, EntityAccessReceipt, OwnerAccessLevel};
use entity_mutation::{
- DeleteEntityPermanently, EntityMutationEffect, EntityMutationErrorCode, RenameEntity,
- RestoreEntity, TrashEntity,
+ DeleteEntityPermanently, EntityMutationEffect, EntityMutationErrorCode, MoveEntity,
+ RenameEntity, RestoreEntity, TrashEntity, capability::MoveEntityRequest, project_refs,
};
use macro_event_broker::MacroEventBroker;
use model_entity::Entity;
@@ -76,6 +77,46 @@ where
}
}
+impl<Repository, Databases, Access, Events, Now, Broker, Drafts, Images> MoveEntity
+ for FormsServiceImpl<Repository, Databases, Access, Events, Now, Broker, Drafts, Images>
+where
+ Repository: FormsRepo + FormDraftRepository,
+ Databases: DatabasesService + DatabaseRowReads + DatabaseMetadataReads,
+ Access: FormAccessDirectory,
+ Events: FormEventPublisher,
+ Now: Clock,
+ Broker: MacroEventBroker,
+ Drafts: FormDraftStore,
+ Images: FormImageFiles,
+{
+ /// Filing a form in a folder shares it with the folder's members, which
+ /// only its owner may do.
+ type Receipt = OwnerAccessLevel;
+
+ async fn move_entity(
+ &self,
+ request: MoveEntityRequest<Self::Receipt>,
+ ) -> Result<Vec<EntityMutationEffect>, EntityMutationErrorCode> {
+ let (entity, receipt, project_id) = match request {
+ MoveEntityRequest::MoveToRoot { entity, receipt } => (entity, receipt, None),
+ MoveEntityRequest::MoveToProject {
+ entity,
+ receipt,
+ project_id,
+ project_receipt: _,
+ } => (entity, receipt, Some(project_id)),
+ };
+ let previous_project_id = self.move_to_folder(&receipt, project_id.as_deref()).await?;
+ Ok(std::iter::once(EntityMutationEffect::updated(entity))
+ .chain(
+ project_refs([previous_project_id, project_id])
+ .into_iter()
+ .map(EntityMutationEffect::updated),
+ )
+ .collect())
+ }
+}
+
impl<Repository, Databases, Access, Events, Now, Broker, Drafts, Images> TrashEntity
for FormsServiceImpl<Repository, Databases, Access, Events, Now, Broker, Drafts, Images>
where
diff --git a/crates/forms/src/domain/ports.rs b/crates/forms/src/domain/ports.rs
index 525cf03281..c6fb9dfafe 100644
--- a/crates/forms/src/domain/ports.rs
+++ b/crates/forms/src/domain/ports.rs
@@ -193,6 +193,15 @@ pub trait FormsRepo: Send + Sync + 'static {
/// Bring a form back from the trash; `false` when it is gone.
fn restore_form(&self, id: FormId) -> impl Future<Output = Result<bool, Self::Error>> + Send;
+ /// File a live form in a folder, or at the root when `project_id` is
+ /// `None`, swapping the grants it inherits from folders to match;
+ /// `false` when it is trashed or gone.
+ fn move_form(
+ &self,
+ id: FormId,
+ project_id: Option<&str>,
+ ) -> impl Future<Output = Result<bool, Self::Error>> + Send;
+
/// Remove a form, its layout, ledger and grants.
fn delete_form(&self, id: FormId) -> impl Future<Output = Result<(), Self::Error>> + Send;
diff --git a/crates/forms/src/domain/service/create.rs b/crates/forms/src/domain/service/create.rs
index b18fa26de5..3b931c6acd 100644
--- a/crates/forms/src/domain/service/create.rs
+++ b/crates/forms/src/domain/service/create.rs
@@ -468,6 +468,7 @@ where
branding: FormBranding::default(),
created_at: now,
updated_at: now,
+ project_id: None,
is_hidden_in_drive: matches!(
provenance,
Provenance::OwnDatabase {
diff --git a/crates/forms/src/domain/service/lifecycle.rs b/crates/forms/src/domain/service/lifecycle.rs
index 0cea407742..52aaa8fca6 100644
--- a/crates/forms/src/domain/service/lifecycle.rs
+++ b/crates/forms/src/domain/service/lifecycle.rs
@@ -223,6 +223,28 @@ where
Ok(())
}
+ /// File a live form in a folder, or at the root, answering the folder
+ /// it left. Its database stays where it is.
+ #[cfg(feature = "entity_mutation")]
+ pub(crate) async fn move_to_folder(
+ &self,
+ receipt: &EntityAccessReceipt<OwnerAccessLevel>,
+ project_id: Option<&str>,
+ ) -> Result<Option<String>, FormError> {
+ let stored = self.stored_form(receipt_form_id(receipt)?).await?;
+ if stored.trashed_at.is_some()
+ || !self
+ .repository
+ .move_form(stored.form.id, project_id)
+ .await
+ .map_err(repository_error)?
+ {
+ return Err(FormError::NotFound);
+ }
+ self.announce(stored.form.id).await;
+ Ok(stored.form.project_id)
+ }
+
pub(super) async fn restore(
&self,
receipt: &EntityAccessReceipt<OwnerAccessLevel>,
diff --git a/crates/forms/src/domain/service/test.rs b/crates/forms/src/domain/service/test.rs
index f4f6a4107a..41217e8b60 100644
--- a/crates/forms/src/domain/service/test.rs
+++ b/crates/forms/src/domain/service/test.rs
@@ -298,6 +298,7 @@ fn seed_rsvp(world: &Shared, audience: Audience) {
branding: FormBranding::default(),
created_at: now,
updated_at: now,
+ project_id: None,
is_hidden_in_drive: false,
},
trashed_at: None,
diff --git a/crates/forms/src/domain/service/test/create.rs b/crates/forms/src/domain/service/test/create.rs
index 3a03e4067a..704907c3ab 100644
--- a/crates/forms/src/domain/service/test/create.rs
+++ b/crates/forms/src/domain/service/test/create.rs
@@ -99,6 +99,7 @@ async fn a_form_over_a_table_asks_every_column_and_adds_the_managed_ones() {
branding: FormBranding::default(),
created_at: start_of_tests(),
updated_at: start_of_tests(),
+ project_id: None,
is_hidden_in_drive: false,
},
access: FormAccess::Owner,
diff --git a/crates/forms/src/domain/service/test/end_to_end.rs b/crates/forms/src/domain/service/test/end_to_end.rs
index e7e597a475..d8c0e1e6ff 100644
--- a/crates/forms/src/domain/service/test/end_to_end.rs
+++ b/crates/forms/src/domain/service/test/end_to_end.rs
@@ -82,6 +82,7 @@ async fn a_form_over_a_new_database_writes_a_passing_response_as_a_row_and_stops
branding: FormBranding::default(),
created_at: Utc.with_ymd_and_hms(2026, 9, 1, 9, 0, 0).unwrap(),
updated_at: Utc.with_ymd_and_hms(2026, 9, 1, 9, 0, 0).unwrap(),
+ project_id: None,
is_hidden_in_drive: false,
},
access: FormAccess::Owner,
diff --git a/crates/forms/src/domain/service/test/fakes.rs b/crates/forms/src/domain/service/test/fakes.rs
index 6d6ede268b..db6b93cfad 100644
--- a/crates/forms/src/domain/service/test/fakes.rs
+++ b/crates/forms/src/domain/service/test/fakes.rs
@@ -545,6 +545,23 @@ impl FormsRepo for FakeRepo {
)
}
+ async fn move_form(&self, id: FormId, project_id: Option<&str>) -> Result<bool, FakeError> {
+ let mut world = self.0.lock().unwrap();
+ Ok(
+ match world
+ .forms
+ .iter_mut()
+ .find(|stored| stored.form.id == id && stored.trashed_at.is_none())
+ {
+ Some(stored) => {
+ stored.form.project_id = project_id.map(str::to_string);
+ true
+ }
+ None => false,
+ },
+ )
+ }
+
async fn delete_form(&self, id: FormId) -> Result<(), FakeError> {
let mut world = self.0.lock().unwrap();
world.forms.retain(|stored| stored.form.id != id);
diff --git a/crates/forms/src/domain/service/test/fakes/databases.rs b/crates/forms/src/domain/service/test/fakes/databases.rs
index 45158333f2..7a2cd224ae 100644
--- a/crates/forms/src/domain/service/test/fakes/databases.rs
+++ b/crates/forms/src/domain/service/test/fakes/databases.rs
@@ -191,6 +191,7 @@ fn detail(database: &FakeDatabase, grant: AccessLevel) -> DatabaseDetail {
owner_id: database.owner.clone(),
created_at: the_epoch(),
trashed_at: None,
+ project_id: None,
},
grant,
tables: database
@@ -541,6 +542,7 @@ impl DatabasesService for FakeDatabases {
owner_id: command.owner_id.to_string(),
created_at: the_epoch(),
trashed_at: None,
+ project_id: None,
})
}
@@ -608,6 +610,7 @@ impl DatabasesService for FakeDatabases {
owner_id: database.owner.clone(),
created_at: the_epoch(),
trashed_at: None,
+ project_id: None,
})
}
@@ -820,6 +823,7 @@ impl DatabaseMetadataReads for FakeDatabases {
owner_id: database.owner.clone(),
created_at: the_epoch(),
trashed_at: database.trashed.then(the_epoch),
+ project_id: None,
})
.ok_or(DatabaseError::NotFound)
}
diff --git a/crates/forms/src/domain/service/test/layout.rs b/crates/forms/src/domain/service/test/layout.rs
index e560feac2e..8735ccae1c 100644
--- a/crates/forms/src/domain/service/test/layout.rs
+++ b/crates/forms/src/domain/service/test/layout.rs
@@ -27,6 +27,7 @@ fn respondent_details_withhold_the_booking_destination() {
branding: FormBranding::default(),
created_at: start_of_tests(),
updated_at: start_of_tests(),
+ project_id: None,
is_hidden_in_drive: false,
};
let layout = FormLayout {
diff --git a/crates/forms/src/domain/service/test/lifecycle.rs b/crates/forms/src/domain/service/test/lifecycle.rs
index e9bd7454ea..233fe68062 100644
--- a/crates/forms/src/domain/service/test/lifecycle.rs
+++ b/crates/forms/src/domain/service/test/lifecycle.rs
@@ -275,6 +275,64 @@ async fn a_database_receipt_is_not_a_form_receipt() {
assert!(matches!(refused, Err(FormError::NotFound)));
}
+#[cfg(feature = "entity_mutation")]
+#[tokio::test]
+async fn moving_a_form_files_it_names_both_folders_and_leaves_its_database() {
+ use entity_mutation::{
+ EntityMutationEffect, EntityMutationErrorCode, MoveEntity, capability::MoveEntityRequest,
+ };
+ use model_entity::EntityType;
+
+ let world = world();
+ seed_rsvp(&world, Audience::Members);
+ let forms = service(&world);
+ let entity = EntityType::Form.with_entity_string(RSVP_FORM.to_string());
+ let owner = || form_receipt::<OwnerAccessLevel>(RSVP_FORM, OWNER, AccessLevel::Owner);
+ let into = |project_id: &str| MoveEntityRequest::MoveToProject {
+ entity: entity.clone(),
+ receipt: owner(),
+ project_id: project_id.to_string(),
+ project_receipt: form_receipt::<EditAccessLevel>(RSVP_FORM, OWNER, AccessLevel::Owner),
+ };
+
+ assert_eq!(
+ forms.move_entity(into("clients")).await.unwrap(),
+ vec![
+ EntityMutationEffect::updated(entity.clone()),
+ EntityMutationEffect::updated(EntityType::Project.with_entity_string("clients".into())),
+ ]
+ );
+ assert_eq!(
+ forms
+ .move_entity(MoveEntityRequest::MoveToRoot {
+ entity: entity.clone(),
+ receipt: owner(),
+ })
+ .await
+ .unwrap(),
+ vec![
+ EntityMutationEffect::updated(entity.clone()),
+ EntityMutationEffect::updated(EntityType::Project.with_entity_string("clients".into())),
+ ]
+ );
+ forms.move_entity(into("archive")).await.unwrap();
+ assert_eq!(
+ world.lock().unwrap().forms[0].form.project_id.as_deref(),
+ Some("archive")
+ );
+ assert!(world.lock().unwrap().batches.is_empty());
+
+ forms.trash_form(owner()).await.unwrap();
+ assert!(matches!(
+ forms.move_entity(into("clients")).await,
+ Err(EntityMutationErrorCode::NotFound(_))
+ ));
+ assert_eq!(
+ world.lock().unwrap().forms[0].form.project_id.as_deref(),
+ Some("archive")
+ );
+}
+
#[tokio::test]
async fn an_editor_brands_the_form_with_images_they_uploaded() {
let logo = Uuid::from_u128(0x1060);
diff --git a/crates/forms/src/domain/service/test/names.rs b/crates/forms/src/domain/service/test/names.rs
index de4b1751fe..aab2f8ea19 100644
--- a/crates/forms/src/domain/service/test/names.rs
+++ b/crates/forms/src/domain/service/test/names.rs
@@ -131,6 +131,7 @@ async fn which_name_a_new_form_goes_by_is_recorded_from_where_it_was_created() {
branding: FormBranding::default(),
created_at: start_of_tests(),
updated_at: start_of_tests(),
+ project_id: None,
is_hidden_in_drive: false,
},
trashed_at: None,
diff --git a/crates/forms/src/inbound/axum_router/test/fakes.rs b/crates/forms/src/inbound/axum_router/test/fakes.rs
index c928c6bd6a..9a58277079 100644
--- a/crates/forms/src/inbound/axum_router/test/fakes.rs
+++ b/crates/forms/src/inbound/axum_router/test/fakes.rs
@@ -257,6 +257,7 @@ pub(super) fn form() -> Form {
branding: FormBranding::default(),
created_at: at,
updated_at: at,
+ project_id: None,
is_hidden_in_drive: false,
}
}
diff --git a/crates/forms/src/outbound/pg_forms_repo.rs b/crates/forms/src/outbound/pg_forms_repo.rs
index 31a9af169b..63e7c94d7d 100644
--- a/crates/forms/src/outbound/pg_forms_repo.rs
+++ b/crates/forms/src/outbound/pg_forms_repo.rs
@@ -3,6 +3,7 @@
//! access crate's helpers.
mod drafts;
+mod folders;
mod layout;
mod ledger;
mod sharing;
@@ -33,6 +34,9 @@ pub enum PgFormsRepoError {
/// ones decoded.
#[error("failed to encode or decode stored gate rules")]
Json(#[from] serde_json::Error),
+ /// A folder id is not a uuid.
+ #[error("folder id is not a uuid")]
+ FolderId(#[from] uuid::Error),
/// Positions could not be minted for a layout.
#[error("layout position")]
Position(#[from] PositionError),
@@ -98,6 +102,7 @@ struct FormRow {
trashed_at: Option<DateTime<Utc>>,
name_follows_database: bool,
is_hidden_in_drive: bool,
+ project_id: Option<String>,
}
impl TryFrom<FormRow> for StoredForm {
@@ -136,6 +141,7 @@ impl TryFrom<FormRow> for StoredForm {
},
created_at: row.created_at,
updated_at: row.updated_at,
+ project_id: row.project_id,
is_hidden_in_drive: row.is_hidden_in_drive,
},
trashed_at: row.trashed_at,
@@ -258,7 +264,7 @@ impl crate::domain::ports::FormsRepo for PgFormsRepo {
submitted_column_id, respondent_column_id, audience, tally_visible,
status, closes_at, confirmation_message, logo_file_id, cover_file_id, accent_color,
created_at, updated_at, trashed_at,
- name_follows_database, is_hidden_in_drive
+ name_follows_database, is_hidden_in_drive, project_id
FROM forms WHERE id = $1
"#,
id.into_uuid(),
@@ -279,7 +285,7 @@ impl crate::domain::ports::FormsRepo for PgFormsRepo {
submitted_column_id, respondent_column_id, audience, tally_visible,
status, closes_at, confirmation_message, logo_file_id, cover_file_id, accent_color,
created_at, updated_at, trashed_at,
- name_follows_database, is_hidden_in_drive
+ name_follows_database, is_hidden_in_drive, project_id
FROM forms WHERE id = ANY($1) AND trashed_at IS NULL
ORDER BY id
"#,
@@ -313,7 +319,7 @@ impl crate::domain::ports::FormsRepo for PgFormsRepo {
submitted_column_id, respondent_column_id, audience, tally_visible,
status, closes_at, confirmation_message, logo_file_id, cover_file_id, accent_color,
created_at, updated_at, trashed_at,
- name_follows_database, is_hidden_in_drive
+ name_follows_database, is_hidden_in_drive, project_id
FROM forms WHERE database_id = $1 AND trashed_at IS NULL
ORDER BY created_at, id
"#,
@@ -404,7 +410,7 @@ impl crate::domain::ports::FormsRepo for PgFormsRepo {
submitted_column_id, respondent_column_id, audience, tally_visible,
status, closes_at, confirmation_message, logo_file_id, cover_file_id, accent_color,
created_at, updated_at, trashed_at,
- name_follows_database, is_hidden_in_drive
+ name_follows_database, is_hidden_in_drive, project_id
"#,
id.into_uuid(),
changes.description.as_deref(),
@@ -448,7 +454,7 @@ impl crate::domain::ports::FormsRepo for PgFormsRepo {
submitted_column_id, respondent_column_id, audience, tally_visible,
status, closes_at, confirmation_message, logo_file_id, cover_file_id, accent_color,
created_at, updated_at, trashed_at,
- name_follows_database, is_hidden_in_drive
+ name_follows_database, is_hidden_in_drive, project_id
"#,
id.into_uuid(),
name,
@@ -475,7 +481,7 @@ impl crate::domain::ports::FormsRepo for PgFormsRepo {
submitted_column_id, respondent_column_id, audience, tally_visible,
status, closes_at, confirmation_message, logo_file_id, cover_file_id, accent_color,
created_at, updated_at, trashed_at,
- name_follows_database, is_hidden_in_drive
+ name_follows_database, is_hidden_in_drive, project_id
"#,
id.into_uuid(),
updated_at,
@@ -511,6 +517,11 @@ impl crate::domain::ports::FormsRepo for PgFormsRepo {
> 0)
}
+ #[tracing::instrument(err, skip(self))]
+ async fn move_form(&self, id: FormId, project_id: Option<&str>) -> Result<bool, Self::Error> {
+ folders::move_form(&self.pool, id, project_id).await
+ }
+
#[tracing::instrument(err, skip(self))]
async fn delete_form(&self, id: FormId) -> Result<(), Self::Error> {
let mut transaction = self.pool.begin().await?;
diff --git a/crates/forms/src/outbound/pg_forms_repo/folders.rs b/crates/forms/src/outbound/pg_forms_repo/folders.rs
new file mode 100644
index 0000000000..6ed46d443f
--- /dev/null
+++ b/crates/forms/src/outbound/pg_forms_repo/folders.rs
@@ -0,0 +1,59 @@
+//! Filing a form in a folder, with the grants the folder passes down.
+
+use entity_access_db_utils::project_grants::{drop_project_grants, inherit_project_grants};
+use entity_access_db_utils::team_share;
+use model_entity::EntityType;
+use sqlx::PgPool;
+use uuid::Uuid;
+
+use super::PgFormsRepoError;
+use crate::domain::models::FormId;
+
+/// File a live form in `project_id`, or at the root, swapping the grants it
+/// inherited from its old folder for the new folder's; `false` when it is
+/// trashed or gone.
+pub(super) async fn move_form(
+ pool: &PgPool,
+ id: FormId,
+ project_id: Option<&str>,
+) -> Result<bool, PgFormsRepoError> {
+ let mut transaction = pool.begin().await?;
+ // The team-share guard comes before any row lock, as its writer requires.
+ team_share::acquire_guard(&mut transaction).await?;
+ let Some(previous) = sqlx::query_scalar!(
+ "SELECT project_id FROM forms WHERE id = $1 AND trashed_at IS NULL FOR UPDATE",
+ id.into_uuid(),
+ )
+ .fetch_optional(&mut *transaction)
+ .await?
+ else {
+ return Ok(false);
+ };
+ sqlx::query!(
+ "UPDATE forms SET project_id = $2, updated_at = now() WHERE id = $1",
+ id.into_uuid(),
+ project_id,
+ )
+ .execute(&mut *transaction)
+ .await?;
+ if let Some(previous) = previous {
+ drop_project_grants(
+ &mut transaction,
+ id.as_uuid(),
+ EntityType::Form,
+ &Uuid::parse_str(&previous)?,
+ )
+ .await?;
+ }
+ if let Some(project_id) = project_id {
+ inherit_project_grants(
+ &mut transaction,
+ id.as_uuid(),
+ EntityType::Form,
+ &Uuid::parse_str(project_id)?,
+ )
+ .await?;
+ }
+ transaction.commit().await?;
+ Ok(true)
+}
diff --git a/crates/forms/src/outbound/pg_forms_repo/test.rs b/crates/forms/src/outbound/pg_forms_repo/test.rs
index 1990255466..379f3de053 100644
--- a/crates/forms/src/outbound/pg_forms_repo/test.rs
+++ b/crates/forms/src/outbound/pg_forms_repo/test.rs
@@ -13,6 +13,7 @@ use super::*;
mod booking;
mod drafts;
+mod folders;
mod names;
mod protections;
mod races;
@@ -173,6 +174,7 @@ fn form_over(table: &Table) -> Form {
branding: FormBranding::default(),
created_at: at(9),
updated_at: at(9),
+ project_id: None,
is_hidden_in_drive: false,
}
}
diff --git a/crates/forms/src/outbound/pg_forms_repo/test/drafts.rs b/crates/forms/src/outbound/pg_forms_repo/test/drafts.rs
index 8ff7a5ddd4..bf30e36b4c 100644
--- a/crates/forms/src/outbound/pg_forms_repo/test/drafts.rs
+++ b/crates/forms/src/outbound/pg_forms_repo/test/drafts.rs
@@ -22,6 +22,7 @@ async fn a_projection_commits_its_layout_and_revision_together(pool: PgPool) {
branding: FormBranding::default(),
created_at: at(9),
updated_at: at(9),
+ project_id: None,
is_hidden_in_drive: false,
};
let layout = FormLayout {
diff --git a/crates/forms/src/outbound/pg_forms_repo/test/folders.rs b/crates/forms/src/outbound/pg_forms_repo/test/folders.rs
new file mode 100644
index 0000000000..2f8a51c110
--- /dev/null
+++ b/crates/forms/src/outbound/pg_forms_repo/test/folders.rs
@@ -0,0 +1,106 @@
+use super::*;
+
+const FOLDER: &str = "0190f5a0-0000-7000-8000-000000000001";
+const SUBFOLDER: &str = "0190f5a0-0000-7000-8000-000000000002";
+
+/// A folder shared with a channel, and a subfolder inside it.
+async fn shared_folders(pool: &PgPool) {
+ sqlx::query!(
+ r#"INSERT INTO "Project" (id, name, "userId") VALUES ($1, 'Clients', $3), ($2, 'Acme', $3)"#,
+ FOLDER,
+ SUBFOLDER,
+ OWNER,
+ )
+ .execute(pool)
+ .await
+ .unwrap();
+ sqlx::query!(
+ r#"UPDATE "Project" SET "parentId" = $1 WHERE id = $2"#,
+ FOLDER,
+ SUBFOLDER
+ )
+ .execute(pool)
+ .await
+ .unwrap();
+ sqlx::query!(
+ "INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level) VALUES ($1, 'project', 'channel-1', 'channel', 'edit')",
+ Uuid::parse_str(FOLDER).unwrap(),
+ )
+ .execute(pool)
+ .await
+ .unwrap();
+}
+
+async fn grants(pool: &PgPool, form: FormId) -> Vec<(String, Option<String>)> {
+ sqlx::query!(
+ "SELECT source_id, granted_from_project_id FROM entity_access WHERE entity_id = $1 AND entity_type = 'form' ORDER BY source_id",
+ form.into_uuid(),
+ )
+ .fetch_all(pool)
+ .await
+ .unwrap()
+ .into_iter()
+ .map(|row| (row.source_id, row.granted_from_project_id))
+ .collect()
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn a_form_in_a_folder_holds_the_grants_of_every_folder_above_it(pool: PgPool) {
+ let table = insert_table(&pool).await;
+ shared_folders(&pool).await;
+ let repo = PgFormsRepo::new(pool.clone());
+ let form = form_over(&table);
+ repo.create_form(&form, &layout_over(&table), false)
+ .await
+ .unwrap();
+
+ assert!(repo.move_form(form.id, Some(SUBFOLDER)).await.unwrap());
+ assert_eq!(
+ repo.forms_by_ids(&[form.id]).await.unwrap()[0]
+ .project_id
+ .as_deref(),
+ Some(SUBFOLDER)
+ );
+ assert_eq!(
+ grants(&pool, form.id).await,
+ vec![
+ ("channel-1".to_string(), Some(FOLDER.to_string())),
+ (OWNER.to_string(), None),
+ ]
+ );
+
+ assert!(repo.move_form(form.id, None).await.unwrap());
+ assert_eq!(
+ repo.forms_by_ids(&[form.id]).await.unwrap()[0].project_id,
+ None
+ );
+ assert_eq!(
+ grants(&pool, form.id).await,
+ vec![(OWNER.to_string(), None)]
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn a_trashed_form_stays_where_it_was_and_a_purged_folder_frees_a_form(pool: PgPool) {
+ let table = insert_table(&pool).await;
+ shared_folders(&pool).await;
+ let repo = PgFormsRepo::new(pool.clone());
+ let form = form_over(&table);
+ repo.create_form(&form, &layout_over(&table), false)
+ .await
+ .unwrap();
+ repo.move_form(form.id, Some(SUBFOLDER)).await.unwrap();
+
+ repo.trash_form(form.id, at(10)).await.unwrap();
+ assert!(!repo.move_form(form.id, None).await.unwrap());
+ assert!(!repo.move_form(FormId::new(), None).await.unwrap());
+ let stored = repo.form(form.id).await.unwrap().unwrap();
+ assert_eq!(stored.form.project_id.as_deref(), Some(SUBFOLDER));
+
+ sqlx::query!(r#"DELETE FROM "Project" WHERE id = $1"#, SUBFOLDER)
+ .execute(&pool)
+ .await
+ .unwrap();
+ let stored = repo.form(form.id).await.unwrap().unwrap();
+ assert_eq!(stored.form.project_id, None);
+}
diff --git a/crates/macro_db_client/migrations/20261102210628_databases_in_folders.sql b/crates/macro_db_client/migrations/20261102210628_databases_in_folders.sql
new file mode 100644
index 0000000000..9ac453ea78
--- /dev/null
+++ b/crates/macro_db_client/migrations/20261102210628_databases_in_folders.sql
@@ -0,0 +1,5 @@
+-- Databases can be filed into a folder, like documents, chats and email
+-- threads. Purging the folder returns them to the root.
+ALTER TABLE database_entities ADD COLUMN project_id TEXT
+ REFERENCES "Project"(id) ON UPDATE CASCADE ON DELETE SET NULL;
+CREATE INDEX database_entities_project_id_idx ON database_entities (project_id);
diff --git a/crates/macro_db_client/migrations/20261102210629_forms_in_folders.sql b/crates/macro_db_client/migrations/20261102210629_forms_in_folders.sql
new file mode 100644
index 0000000000..33064455bf
--- /dev/null
+++ b/crates/macro_db_client/migrations/20261102210629_forms_in_folders.sql
@@ -0,0 +1,5 @@
+-- Forms can be filed into a folder, like databases. Purging the folder
+-- returns them to the root.
+ALTER TABLE forms ADD COLUMN project_id TEXT
+ REFERENCES "Project"(id) ON UPDATE CASCADE ON DELETE SET NULL;
+CREATE INDEX forms_project_id_idx ON forms (project_id);
diff --git a/crates/model-entity/src/lib.rs b/crates/model-entity/src/lib.rs
index a48bb76e22..36891ff8f8 100644
--- a/crates/model-entity/src/lib.rs
+++ b/crates/model-entity/src/lib.rs
@@ -133,16 +133,16 @@ impl EntityType {
// Initiatives hold `entity_access` rows but are not something
// you file into a project.
EntityType::Initiative => false,
- // A database's permissions are `entity_access` rows - the creator
- // as owner, plus whoever it is later shared with - but, like agent
- // sessions, a database is not something you file into a project.
- EntityType::Database => false,
+ // A database's permissions are `entity_access` rows: the creator
+ // as owner, whoever it is later shared with, and the grants of
+ // the folder it is filed in.
+ EntityType::Database => true,
// Rows carry no `entity_access` rows of their own; access
// resolves through the parent database.
EntityType::DatabaseRow => false,
- // A form's grants are `entity_access` rows, but, like a
- // database, a form is not something you file into a project.
- EntityType::Form => false,
+ // A form's grants are `entity_access` rows, including those of
+ // the folder it is filed in.
+ EntityType::Form => true,
EntityType::ExternalChat => true,
}
}
diff --git a/crates/model-entity/src/tests.rs b/crates/model-entity/src/tests.rs
index 20d38e768f..99663cac59 100644
--- a/crates/model-entity/src/tests.rs
+++ b/crates/model-entity/src/tests.rs
@@ -79,8 +79,3 @@ fn form_round_trips_as_snake_case() {
assert_eq!(EntityType::Form.as_ref(), "form");
assert_eq!(EntityType::from_str("form").unwrap(), EntityType::Form);
}
-
-#[test]
-fn form_is_not_an_entity_access_entity() {
- assert!(!EntityType::Form.is_valid_entity_access_entity());
-}
diff --git a/crates/models_forms/src/form.rs b/crates/models_forms/src/form.rs
index d3f87b6fd0..8ce96958cc 100644
--- a/crates/models_forms/src/form.rs
+++ b/crates/models_forms/src/form.rs
@@ -132,6 +132,9 @@ pub struct Form {
pub created_at: DateTime<Utc>,
/// When its facts or layout last changed.
pub updated_at: DateTime<Utc>,
+ /// The folder it is filed in; `null` at the root.
+ #[schema(required = true)]
+ pub project_id: Option<String>,
/// Whether Drive leaves it, and the database behind it, out of its
/// listings, as for a channel poll.
pub is_hidden_in_drive: bool,
diff --git a/crates/models_forms/src/test.rs b/crates/models_forms/src/test.rs
index 6c8909bf14..1dc949c9e8 100644
--- a/crates/models_forms/src/test.rs
+++ b/crates/models_forms/src/test.rs
@@ -60,6 +60,7 @@ fn a_form_detail_reads_as_the_web_client_expects() {
branding: FormBranding::default(),
created_at: Utc.with_ymd_and_hms(2026, 9, 1, 9, 0, 0).unwrap(),
updated_at: Utc.with_ymd_and_hms(2026, 9, 2, 9, 0, 0).unwrap(),
+ project_id: None,
is_hidden_in_drive: false,
},
access: FormAccess::Edit,
@@ -123,6 +124,7 @@ fn a_form_detail_reads_as_the_web_client_expects() {
"branding": { "logoFileId": null, "coverFileId": null, "accentColor": null },
"createdAt": "2026-09-01T09:00:00Z",
"updatedAt": "2026-09-02T09:00:00Z",
+ "projectId": null,
"isHiddenInDrive": false,
},
"access": "edit",
@@ -414,6 +416,7 @@ fn a_form_takes_responses_while_open_and_before_it_closes() {
branding: FormBranding::default(),
created_at: now,
updated_at: now,
+ project_id: None,
is_hidden_in_drive: false,
};
assert!(form(FormStatus::Open, None).accepts_responses_at(now));
@@ -445,6 +448,7 @@ fn a_listed_form_names_the_callers_access_beside_the_form() {
branding: FormBranding::default(),
created_at: now,
updated_at: now,
+ project_id: None,
is_hidden_in_drive: false,
},
access: FormAccess::View,
@@ -469,6 +473,7 @@ fn a_listed_form_names_the_callers_access_beside_the_form() {
"branding": { "logoFileId": null, "coverFileId": null, "accentColor": null },
"createdAt": "2026-09-01T09:00:00Z",
"updatedAt": "2026-09-01T09:00:00Z",
+ "projectId": null,
"isHiddenInDrive": false,
},
"access": "view",
@@ -536,6 +541,7 @@ fn form_and_response_schemas_require_every_field_they_always_serialize() {
branding: FormBranding::default(),
created_at: now,
updated_at: now,
+ project_id: None,
is_hidden_in_drive: false,
};
let response = FormResponse {
@@ -593,6 +599,7 @@ fn a_form_sends_its_branding_with_its_facts() {
},
created_at: now,
updated_at: now,
+ project_id: None,
is_hidden_in_drive: false,
};
assert_eq!(
diff --git a/crates/projects/src/domain/entity_mutation.rs b/crates/projects/src/domain/entity_mutation.rs
index 3af550170c..5f01552f58 100644
--- a/crates/projects/src/domain/entity_mutation.rs
+++ b/crates/projects/src/domain/entity_mutation.rs
@@ -1,7 +1,5 @@
//! Unified entity-mutation capability impls for projects.
-use std::collections::HashSet;
-
use entity_access::domain::models::{
AccessError, EditAccessLevel, EntityAccessReceipt, OwnerAccessLevel,
};
@@ -9,7 +7,7 @@ use entity_access_management::domain::ports::EntityAccessManagementService;
use entity_mutation::{
DeleteEntityPermanently, EntityMutationEffect, EntityMutationErrorCode, MoveEntity,
RenameEntity, RestoreEntity, TrashEntity, UpdateEntitySharePolicy,
- capability::MoveEntityRequest,
+ capability::MoveEntityRequest, project_refs,
};
use macro_event_broker::MacroEventBroker;
use model::project::{BasicProject, request::PatchProjectRequestV2};
@@ -61,16 +59,6 @@ fn access_error(error: AccessError) -> EntityMutationErrorCode {
}
}
-/// Build affected project entities from optional container ids.
-fn project_refs(ids: impl IntoIterator<Item = Option<String>>) -> Vec<Entity<'static>> {
- let mut seen = HashSet::new();
- ids.into_iter()
- .flatten()
- .filter(|id| !id.is_empty() && seen.insert(id.clone()))
- .map(|id| EntityType::Project.with_entity_string(id))
- .collect()
-}
-
/// Deduplicate effects while preserving their domain-defined order.
fn unique_effects(
effects: impl IntoIterator<Item = EntityMutationEffect>,
diff --git a/docs/agent-guide/files.md b/docs/agent-guide/files.md
index bffebc073d..e122e735d7 100644
--- a/docs/agent-guide/files.md
+++ b/docs/agent-guide/files.md
@@ -43,15 +43,21 @@ With `enable-databases` enabled, **My Files** includes owned databases and
also includes accessible databases owned by others. **Search Drive** matches
database names and **Filter → Type → Database** narrows the list. **New →
Database** creates and opens a database from file tabs or the folder overview;
-it is absent inside a folder because databases have no folder membership yet.
+it is absent inside a folder because a new database starts at the root.
Database rows open their database block, including Enter and Open in new split.
Right-click (or long-press) a database for the same entity actions as other
Drive rows: Open in new split, Rename (edit or owner), Favorite, Copy Link,
-Copy ID, Share, and Delete (owner). Duplicate and Move to folder stay omitted
-because databases have no folder membership and no duplicate API.
-Databases have no view history and do not appear in **Recent**, folder contents,
-or **Email attachments**. Creation time orders them when the selected sort has
-no corresponding database timestamp.
+Copy ID, Share, Move to folder and Remove from folder (owner), and Delete
+(owner). Duplicate stays omitted because databases have no duplicate API.
+The owner can also drag a database or form row onto a folder (a sidebar folder
+or a folder row), or pick **Move to folder** from the database page's ⋯ menu or
+the form's title menu. A filed database or form appears in that folder's
+contents for everyone who can open it, inherits the folder's sharing like a
+document, and stays in the file tabs. Verify moving one into a nested folder
+shared with another user, that user opening it from the folder, and moving it
+back to root. Databases have no view history and do not appear in **Recent** or
+**Email attachments**. Creation time orders them when the selected sort has no
+corresponding database timestamp.
On touch devices (phones and tablets), the Drive header is a scrollable pill
strip — **Recent**, **My Files**, **Shared with me**, and **Folders** — with a
diff --git a/docs/agent-guide/forms.md b/docs/agent-guide/forms.md
index c0a6f6f89b..7b44a5d5d9 100644
--- a/docs/agent-guide/forms.md
+++ b/docs/agent-guide/forms.md
@@ -158,7 +158,10 @@ rows stay.
## Finding forms
Drive lists forms you can open (type facet **Form**) and opens them inline at
-`/app/drive/form/<uuid>`, and Quick Access has a
+`/app/drive/form/<uuid>`. The owner can file a form in a folder by dragging its
+row onto the folder or with **Move to folder** in the form's title menu; it
+then appears in that folder's contents and inherits the folder's sharing, while
+its database stays where it was. Quick Access has a
Forms bucket. Both come from `/forms/accessible`, so a form shared with you
appears without access to its database. Deleting a database table warns which
forms it deletes; deleting a column warns which forms ask it (both say so
diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/Database.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/Database.md
index 50754e8e72..df04581b2e 100644
--- a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/Database.md
+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/Database.md
@@ -1,6 +1,6 @@
# Type Alias: Database
-> **Database** = \{ `created_at`: `string`; `id`: `string`; `name`: `string`; `owner_id`: `string`; `trashed_at`: `string` \| `null`; \}
+> **Database** = \{ `created_at`: `string`; `id`: `string`; `name`: `string`; `owner_id`: `string`; `project_id`: `string` \| `null`; `trashed_at`: `string` \| `null`; \}
A database: a named collection of tables, owned and shared as one entity.
@@ -12,4 +12,5 @@ A database: a named collection of tables, owned and shared as one entity.
| <a id="property-id"></a> `id` | `string` | Identifier. |
| <a id="property-name"></a> `name` | `string` | Display name. |
| <a id="property-owner_id"></a> `owner_id` | `string` | Owning user. |
+| <a id="property-project_id"></a> `project_id` | `string` \| `null` | The folder it is filed in; `null` at the root. |
| <a id="property-trashed_at"></a> `trashed_at` | `string` \| `null` | Set when trashed. |
diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/Form.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/Form.md
index 1be6b77c99..dcc3e6afe9 100644
--- a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/Form.md
+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/Form.md
@@ -1,6 +1,6 @@
# Type Alias: Form
-> **Form** = \{ `audience`: [`Audience`](Audience.md); `branding`: [`FormBranding`](FormBranding.md); `closesAt`: `string` \| `null`; `confirmationMessage`: `string`; `createdAt`: `string`; `databaseId`: `string`; `description`: `string`; `id`: `string`; `isHiddenInDrive`: `boolean`; `name`: `string`; `ownerId`: `string`; `respondentColumnId`: `string` \| `null`; `status`: [`FormStatus`](FormStatus.md); `submittedColumnId`: `string` \| `null`; `tableId`: `string`; `tallyVisible`: `boolean`; `updatedAt`: `string`; \}
+> **Form** = \{ `audience`: [`Audience`](Audience.md); `branding`: [`FormBranding`](FormBranding.md); `closesAt`: `string` \| `null`; `confirmationMessage`: `string`; `createdAt`: `string`; `databaseId`: `string`; `description`: `string`; `id`: `string`; `isHiddenInDrive`: `boolean`; `name`: `string`; `ownerId`: `string`; `projectId`: `string` \| `null`; `respondentColumnId`: `string` \| `null`; `status`: [`FormStatus`](FormStatus.md); `submittedColumnId`: `string` \| `null`; `tableId`: `string`; `tallyVisible`: `boolean`; `updatedAt`: `string`; \}
A form: a view of one database table whose rows are its responses.
@@ -19,6 +19,7 @@ A form: a view of one database table whose rows are its responses.
| <a id="property-ishiddenindrive"></a> `isHiddenInDrive` | `boolean` | Whether Drive leaves it, and the database behind it, out of its listings, as for a channel poll. |
| <a id="property-name"></a> `name` | `string` | Its display name. A standalone form follows the database it created; a form attached to an existing table has its own name. |
| <a id="property-ownerid"></a> `ownerId` | `string` | Its owner. |
+| <a id="property-projectid"></a> `projectId` | `string` \| `null` | The folder it is filed in; `null` at the root. |
| <a id="property-respondentcolumnid"></a> `respondentColumnId` | `string` \| `null` | The person column each signed-in submission names its respondent in; `null` once deleted. |
| <a id="property-status"></a> `status` | [`FormStatus`](FormStatus.md) | Whether its owner closed it. |
| <a id="property-submittedcolumnid"></a> `submittedColumnId` | `string` \| `null` | The date column each submission stamps; `null` once deleted. |
diff --git a/packages/sdk/generated/storage/types.gen.ts b/packages/sdk/generated/storage/types.gen.ts
index b1cf29ab41..b3fdcee35e 100644
--- a/packages/sdk/generated/storage/types.gen.ts
+++ b/packages/sdk/generated/storage/types.gen.ts
@@ -5079,6 +5079,10 @@ export type Database = {
* Owning user.
*/
owner_id: string;
+ /**
+ * The folder it is filed in; `null` at the root.
+ */
+ project_id: string | null;
/**
* Set when trashed.
*/
@@ -7798,6 +7802,10 @@ export type Form = {
* Its owner.
*/
ownerId: string;
+ /**
+ * The folder it is filed in; `null` at the root.
+ */
+ projectId: string | null;
/**
* The person column each signed-in submission names its respondent in;
* `null` once deleted.
diff --git a/packages/sdk/specs/storage.json b/packages/sdk/specs/storage.json
index 68e746afb8..ad0f0759b7 100644
--- a/packages/sdk/specs/storage.json
+++ b/packages/sdk/specs/storage.json
@@ -27026,7 +27026,14 @@
"Database": {
"type": "object",
"description": "A database: a named collection of tables, owned and shared as one entity.",
- "required": ["id", "name", "owner_id", "created_at", "trashed_at"],
+ "required": [
+ "id",
+ "name",
+ "owner_id",
+ "created_at",
+ "trashed_at",
+ "project_id"
+ ],
"properties": {
"created_at": {
"type": "string",
@@ -27046,6 +27053,10 @@
"type": "string",
"description": "Owning user."
},
+ "project_id": {
+ "type": ["string", "null"],
+ "description": "The folder it is filed in; `null` at the root."
+ },
"trashed_at": {
"type": ["string", "null"],
"format": "date-time",
@@ -31741,6 +31752,7 @@
"branding",
"createdAt",
"updatedAt",
+ "projectId",
"isHiddenInDrive"
],
"properties": {
@@ -31792,6 +31804,10 @@
"type": "string",
"description": "Its owner."
},
+ "projectId": {
+ "type": ["string", "null"],
+ "description": "The folder it is filed in; `null` at the root."
+ },
"respondentColumnId": {
"type": ["string", "null"],
"format": "uuid",
diff --git a/packages/sdk/tests/databases.test.ts b/packages/sdk/tests/databases.test.ts
index 7bd155ab5d..8f3179cb2f 100644
--- a/packages/sdk/tests/databases.test.ts
+++ b/packages/sdk/tests/databases.test.ts
@@ -33,6 +33,7 @@ const support: DatabaseDetail = {
owner_id: 'owner',
created_at: '2026-10-01T00:00:00Z',
trashed_at: null,
+ project_id: null,
},
grant: 'owner',
tables: [
diff --git a/services/document_storage_service/src/service/entity_mutation.rs b/services/document_storage_service/src/service/entity_mutation.rs
index 8e83b639f4..508a813b27 100644
--- a/services/document_storage_service/src/service/entity_mutation.rs
+++ b/services/document_storage_service/src/service/entity_mutation.rs
@@ -237,9 +237,14 @@ where
+ RestoreEntity
+ DeleteEntityPermanently
+ PurgeOwnedEntity,
- Databases:
- DatabasesService + RenameEntity + TrashEntity + RestoreEntity + DeleteEntityPermanently,
+ Databases: DatabasesService
+ + RenameEntity
+ + MoveEntity
+ + TrashEntity
+ + RestoreEntity
+ + DeleteEntityPermanently,
Forms: RenameEntity
+ + MoveEntity
+ TrashEntity
+ RestoreEntity
+ DeleteEntityPermanently
@@ -481,6 +486,14 @@ where
self.move_with(&*self.projects, actor, &requested, project_id)
.await
}
+ EntityType::Database => {
+ self.move_with(&*self.databases, actor, &requested, project_id)
+ .await
+ }
+ EntityType::Form => {
+ self.move_with(&*self.forms, actor, &requested, project_id)
+ .await
+ }
EntityType::User
| EntityType::Team
| EntityType::Channel
@@ -497,11 +510,7 @@ where
| EntityType::AgentSession
| EntityType::ScheduledAction
| EntityType::Initiative
- // A database is not filed into a project, so there is nowhere to
- // move it to (`EntityType::is_valid_entity_access_entity`).
- | EntityType::Database
| EntityType::ExternalChat
- | EntityType::Form
| EntityType::DatabaseRow => {
return unsupported(requested, "move");
}
@@ -852,9 +861,14 @@ where
+ RestoreEntity
+ DeleteEntityPermanently
+ PurgeOwnedEntity,
- Databases:
- DatabasesService + RenameEntity + TrashEntity + RestoreEntity + DeleteEntityPermanently,
+ Databases: DatabasesService
+ + RenameEntity
+ + MoveEntity
+ + TrashEntity
+ + RestoreEntity
+ + DeleteEntityPermanently,
Forms: RenameEntity
+ + MoveEntity
+ TrashEntity
+ RestoreEntity
+ DeleteEntityPermanently