ctb_storage/models/
graph_impl.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Database query implementation for graph structures and node relationships.
21
22use crate::db::{authorize_db_access, get_connection, validate_and_get_user};
23#[allow(
24    unused_imports,
25    clippy::wildcard_imports,
26    reason = "Standard workspace module prelude"
27)]
28use crate::utilities::*;
29use anyhow::{Context, Result, anyhow};
30use sea_query::{
31    Alias, Asterisk, ConditionalStatement, Expr, ExprTrait, Iden,
32    OrderedStatement, Query, QueryStatementWriter, SchemaStatementBuilder,
33    SqliteQueryBuilder, ValueType,
34};
35use turso::{Connection, Value};
36
37#[derive(sea_query::Iden)]
38#[iden(rename = "nodes")]
39enum Nodes {
40    Table,
41    #[iden(rename = "id")]
42    Id,
43    #[iden(rename = "graph_id")]
44    GraphId,
45    #[iden(rename = "type")]
46    Type,
47    #[iden(rename = "data")]
48    Data,
49    #[iden(rename = "checksum")]
50    Checksum,
51    #[iden(rename = "timestamp")]
52    Timestamp,
53}
54
55#[derive(sea_query::Iden)]
56#[iden(rename = "database_sections")]
57enum DatabaseSections {
58    Table,
59    #[iden(rename = "path")]
60    Path,
61}
62
63async fn allocate_next_system_id_internal(conn: &Connection) -> Result<u128> {
64    let block = crate::global_graph_layout::get_block("System")
65        .ok_or_else(|| anyhow::anyhow!("System block layout not found"))?;
66    let start_id = block.first_id;
67    let end_id = block.last_id;
68
69    let start_id_blob = start_id.to_be_bytes().to_vec();
70    let end_id_blob = end_id.to_be_bytes().to_vec();
71    let graph_id_blob = 0u128.to_be_bytes().to_vec();
72
73    let (sql, values) = Query::select()
74        .column(Nodes::Id)
75        .from(Nodes::Table)
76        .and_where(Expr::col(Nodes::GraphId).eq(graph_id_blob))
77        .and_where(Expr::col(Nodes::Id).gte(start_id_blob))
78        .and_where(Expr::col(Nodes::Id).lte(end_id_blob))
79        .order_by(Nodes::Id, sea_query::Order::Desc)
80        .limit(1)
81        .build(SqliteQueryBuilder);
82
83    let params = crate::db::sea_values_to_turso(values)?;
84    let mut stmt = conn.prepare(&sql).await?;
85    let mut rows = stmt.query(params).await?;
86    let mut max_id = None;
87    if let Some(row) = rows.next().await? {
88        if let Ok(Value::Blob(b)) = row.get_value(0) {
89            max_id = Some(u128::from_be_bytes(
90                b.as_slice()
91                    .try_into()
92                    .context("Graph max_id blob did not fit into 16 bytes")?,
93            ));
94        }
95    }
96
97    let next_id = match max_id {
98        Some(max) => max.saturating_add(1),
99        None => start_id,
100    };
101
102    if next_id > end_id {
103        anyhow::bail!("System allocation block is full.");
104    }
105
106    Ok(next_id)
107}
108
109/// Allocate the next system ID in the global graph layout.
110#[ipc_method]
111pub async fn allocate_next_system_id(session_token: String) -> Result<u128> {
112    let user = validate_and_get_user(&session_token).await?;
113    let global_user_id =
114        crate::models::user_impl::get_user_by_name("global".to_string())
115            .await?
116            .ok_or_else(|| anyhow!("Global user not found"))?
117            .id;
118    let global_db_name = format!("graphs/{global_user_id}/user_data");
119    let conn = get_connection(&global_db_name).await?;
120
121    // Only administrators or the system layout allocator can request new IDs.
122    if !user.is_admin() {
123        anyhow::bail!("Admin privileges are required to allocate system IDs.");
124    }
125
126    allocate_next_system_id_internal(&conn).await
127}
128
129/// Publish a packaged node to the global graph.
130#[ipc_method]
131pub async fn publish_packaged_node_to_global(
132    session_token: String,
133    package: Vec<u8>,
134    target_id: Option<u128>,
135) -> Result<u128> {
136    let user = validate_and_get_user(&session_token).await?;
137
138    if !user.is_admin() {
139        anyhow::bail!(
140            "Admin privileges are required to publish nodes to the global graph."
141        );
142    }
143
144    // Deserialize the packaged node
145    let pkg = crate::packaged_node::deserialize_packaged_node(&package)
146        .context("Failed to deserialize packaged node")?;
147
148    // Get global database connection
149    let global_user_id =
150        crate::models::user_impl::get_user_by_name("global".to_string())
151            .await?
152            .ok_or_else(|| anyhow!("Global user not found"))?
153            .id;
154    let global_db_name = format!("graphs/{global_user_id}/user_data");
155    let global_conn = get_connection(&global_db_name).await?;
156    crate::models::node_impl::ensure_statement_does_not_revise_data_nodes(
157        &global_conn,
158        0,
159        pkg.node_type,
160        &pkg.body,
161    )
162    .await?;
163
164    let allocated_id = if let Some(tid) = target_id {
165        // Disallow Unicode range
166        let block = crate::global_graph_layout::get_block_name_for_id(tid)?;
167        if block == "Unicode" {
168            anyhow::bail!(
169                "Publishing nodes to the Unicode range is disallowed."
170            );
171        }
172
173        // Verify no node exists in global database using SeaQuery
174        let (sql, values) = Query::select()
175            .column(Nodes::Id)
176            .from(Nodes::Table)
177            .and_where(
178                Expr::col(Nodes::GraphId).eq(0u128.to_be_bytes().to_vec()),
179            )
180            .and_where(Expr::col(Nodes::Id).eq(tid.to_be_bytes().to_vec()))
181            .build(SqliteQueryBuilder);
182
183        let params = crate::db::sea_values_to_turso(values)?;
184        let mut stmt = global_conn.prepare(&sql).await?;
185        let mut rows = stmt.query(params).await?;
186        if rows.next().await?.is_some() {
187            anyhow::bail!(
188                "Node with ID {tid} already exists in the global graph."
189            );
190        }
191        tid
192    } else {
193        // Allocate next ID in the System block
194        allocate_next_system_id_internal(&global_conn).await?
195    };
196
197    // Insert into global graph (graph_id = 0)
198    let (sql, values) = Query::insert()
199        .into_table(Nodes::Table)
200        .columns([
201            Nodes::Id,
202            Nodes::GraphId,
203            Nodes::Type,
204            Nodes::Data,
205            Nodes::Checksum,
206            Nodes::Timestamp,
207        ])
208        .values_panic([
209            allocated_id.to_be_bytes().to_vec().into(),
210            0u128.to_be_bytes().to_vec().into(),
211            u32::from(pkg.node_type).into(),
212            pkg.body.into(),
213            pkg.checksum.to_vec().into(),
214            pkg.timestamp.to_be_bytes().to_vec().into(),
215        ])
216        .build(SqliteQueryBuilder);
217
218    let params = crate::db::sea_values_to_turso(values)?;
219    let mut stmt = global_conn.prepare(&sql).await?;
220    stmt.execute(params).await?;
221
222    Ok(allocated_id)
223}
224
225/// List all database names/paths available to the user.
226#[ipc_method]
227pub async fn list_databases(session_token: String) -> Result<Vec<String>> {
228    let user = validate_and_get_user(&session_token).await?;
229    let user_id = user.local_id();
230    let mut list = Vec::new();
231    list.push("users".to_string());
232
233    let main_db_name = format!("graphs/{user_id}/user_data");
234    list.push(main_db_name.clone());
235
236    // Try to read other sections from the database_sections table in the first database
237    if let Ok(conn) = get_connection(&main_db_name).await {
238        let check_sql = "SELECT name FROM sqlite_master WHERE type='table' AND name='database_sections'";
239        let mut check_found = false;
240        if let Ok(mut stmt) = conn.prepare(check_sql).await {
241            if let Ok(mut rows) = stmt.query(()).await {
242                if let Ok(Some(_)) = rows.next().await {
243                    check_found = true;
244                }
245            }
246        }
247        if check_found {
248            let (sql, values) = Query::select()
249                .column(DatabaseSections::Path)
250                .from(DatabaseSections::Table)
251                .build(SqliteQueryBuilder);
252            if let Ok(params) = crate::db::sea_values_to_turso(values) {
253                if let Ok(mut data_stmt) = conn.prepare(&sql).await {
254                    if let Ok(mut data_rows) = data_stmt.query(params).await {
255                        while let Ok(Some(row)) = data_rows.next().await {
256                            if let Ok(Value::Text(p)) = row.get_value(0) {
257                                let resolved = p
258                                    .replace("{user_id}", &user_id.to_string());
259                                if !list.contains(&resolved) {
260                                    list.push(resolved);
261                                }
262                            }
263                        }
264                    }
265                }
266            }
267        }
268    }
269
270    Ok(list)
271}
272
273/// List all table names in the specified database.
274#[ipc_method]
275pub async fn list_tables(
276    session_token: String,
277    db_name: String,
278) -> Result<Vec<String>> {
279    let user = validate_and_get_user(&session_token).await?;
280    let user_id = user.local_id();
281    authorize_db_access(user_id, &db_name)?;
282    let conn = get_connection(&db_name).await?;
283    let mut stmt = conn.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'").await?;
284    let mut rows = stmt.query(()).await?;
285    let mut tables = Vec::new();
286    while let Some(row) = rows.next().await? {
287        if let Ok(Value::Text(name)) = row.get_value(0) {
288            tables.push(name);
289        }
290    }
291    Ok(tables)
292}
293
294/// Get raw columns and row values for a table, formatted specifically for display
295/// in the Web UI (e.g. converting node IDs/checksums to string, handling blobs,
296/// and truncation).
297///
298/// This is used by the Web UI.
299#[ipc_method]
300pub async fn get_formatted_table_data(
301    session_token: String,
302    db_name: String,
303    table_name: String,
304    page: u32,
305) -> Result<::ctb_utilities::ipc::service_traits::storage::TableRow> {
306    let user = validate_and_get_user(&session_token).await?;
307    let user_id = user.local_id();
308    authorize_db_access(user_id, &db_name)?;
309    let conn = get_connection(&db_name).await?;
310
311    // Basic validation to prevent SQL injection since table name cannot be parameterized
312    if !table_name.chars().all(|c| c.is_alphanumeric() || c == '_') {
313        anyhow::bail!("Invalid table name");
314    }
315
316    // Get total rows using SeaQuery
317    let (count_sql, count_values) = Query::select()
318        .expr(sea_query::Func::count(Expr::col(Asterisk)))
319        .from(Alias::new(&table_name))
320        .build(SqliteQueryBuilder);
321
322    let count_params = crate::db::sea_values_to_turso(count_values)?;
323    let mut count_stmt = conn.prepare(&count_sql).await?;
324    let mut count_rows = count_stmt.query(count_params).await?;
325    let mut total_rows = 0u32;
326    if let Some(row) = count_rows.next().await? {
327        if let Ok(Value::Integer(v)) = row.get_value(0) {
328            total_rows = <u32 as TryFrom<_>>::try_from(v)
329                .context("Row count integer did not fit into u32")?;
330        }
331    }
332
333    let limit = 50u32;
334    let total_pages = total_rows
335        .saturating_add(limit)
336        .saturating_sub(1)
337        .checked_div(limit)
338        .context("division by limit failed")?;
339    let current_page = std::cmp::max(1, page);
340    let offset = current_page.saturating_sub(1).saturating_mul(limit);
341
342    // Select row data using SeaQuery
343    let (query_sql, query_values) = Query::select()
344        .column(Asterisk)
345        .from(Alias::new(&table_name))
346        .limit(u64::from(limit))
347        .offset(u64::from(offset))
348        .build(SqliteQueryBuilder);
349
350    let query_params = crate::db::sea_values_to_turso(query_values)?;
351    let mut stmt = conn.prepare(&query_sql).await?;
352    let mut rows = stmt.query(query_params).await?;
353
354    let columns = rows.column_names();
355    let column_count = rows.column_count();
356
357    let id_col_idx = columns.iter().position(|c| c == "id");
358    let graph_id_col_idx = columns.iter().position(|c| c == "graph_id");
359    let type_col_idx = columns.iter().position(|c| c == "type");
360    let data_col_idx = columns.iter().position(|c| c == "data");
361    let checksum_col_idx = columns.iter().position(|c| c == "checksum");
362
363    let mut values = Vec::new();
364    while let Some(row) = rows.next().await? {
365        let mut row_values = Vec::new();
366        let mut node_type_val = None;
367        if table_name == "nodes" {
368            if let Some(idx) = type_col_idx {
369                if let Ok(Value::Integer(v)) = row.get_value(idx) {
370                    node_type_val = <u32 as TryFrom<_>>::try_from(v).ok();
371                }
372            }
373        }
374
375        for i in 0..column_count {
376            let val = match row.get_value(i) {
377                Ok(Value::Null) => "NULL".to_string(),
378                Ok(Value::Integer(v)) => v.to_string(),
379                Ok(Value::Real(v)) => v.to_string(),
380                Ok(Value::Text(v)) => v,
381                Ok(Value::Blob(v)) => {
382                    if table_name == "nodes"
383                        && (Some(i) == id_col_idx
384                            || Some(i) == graph_id_col_idx)
385                        && v.len() == 16
386                    {
387                        if let Ok(bytes) = <[u8; 16]>::try_from(v.clone()) {
388                            u128::from_be_bytes(bytes).to_string()
389                        } else {
390                            format!("0x{}", bin2hex(&v))
391                        }
392                    } else if table_name == "nodes"
393                        && Some(i) == checksum_col_idx
394                    {
395                        bin2hex(&v)
396                    } else {
397                        let is_dctext = if table_name == "nodes"
398                            && Some(i) == data_col_idx
399                        {
400                            if let Some(t_val) = node_type_val {
401                                if let Ok(nt) =
402                                    crate::models::node::NodeType::try_from(
403                                        t_val,
404                                    )
405                                {
406                                    nt == crate::models::node::NodeType::Statements || nt == crate::models::node::NodeType::System
407                                } else {
408                                    false
409                                }
410                            } else {
411                                false
412                            }
413                        } else {
414                            false
415                        };
416                        ctb_formats_dcstring::dctext::format_blob_preview(
417                            &v, is_dctext,
418                        )
419                    }
420                }
421                Err(_) => "ERROR".to_string(),
422            };
423            row_values.push(val);
424        }
425        values.push(row_values);
426    }
427
428    Ok(::ctb_utilities::ipc::service_traits::storage::TableRow {
429        columns,
430        values,
431        page: current_page,
432        total_pages: std::cmp::max(1, total_pages),
433        total_rows,
434    })
435}