hawdb 0.34.0

An embedded Rust graph database for local data-plane workloads
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
// Copyright 2026 Nowledge
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Canonical SQL reads using existing row and declared-index identities.

use super::*;
use crate::sql::{
    Expr, ExprKind, SelectProjection, SelectStatement, SqlComparisonOp, SqlStatement, SqlValue,
};
use hawdb_relational::query_value::value_to_relational_as;
use hawdb_storage::relational::{RelationalKey, RelationalTableSchema, RelationalValue};

#[path = "relational/indexed.rs"]
mod indexed;
#[path = "relational/joined.rs"]
mod joined;

const MAX_INPUT_BYTES: usize = 64 * 1024;
const MAX_PARAMETERS: usize = 1024;
const MAX_TOKENS: usize = 4096;
const MAX_RECURSIVE_TOKENS: usize = 32;
const MAX_EXPRESSION_NODES: usize = 1024;
const MAX_EXPRESSION_DEPTH: usize = 64;
const MAX_KEY_COLUMNS: usize = 32;
const MAX_KEY_BYTES: usize = 4096;

pub(in crate::api) fn admit_transaction_input(text: &str, parameters: &[Value]) -> Result<()> {
    admit_input(text, parameters)?;
    crate::sql::admit_postgres_sql_syntax(text, MAX_INPUT_BYTES, MAX_TOKENS, MAX_RECURSIVE_TOKENS)
}

/// Capture from the transaction's current private relational view, without
/// re-executing the statement or replacing its ordinary query semantics.
pub(in crate::api) fn collect_transaction(
    text: &str,
    statement: &SqlStatement,
    parameters: &[Value],
    state: &hawdb_storage::relational::RelationalState,
    dependencies: &mut GraphReadDependencies,
) -> Result<()> {
    admit_input(text, parameters)?;
    let record = |dependencies: &mut GraphReadDependencies, key| {
        dependencies
            .record(key)
            .map_err(|error| HawDBError::Execution(error.to_string()))
    };
    match statement {
        SqlStatement::Select(select) if let Some(search) = select.text_search() => {
            // BM25 statistics depend on every indexed document, and results
            // on the hydrated source rows. Index rows change only with source
            // rows, so the source table's domain covers both; an index name
            // that does not resolve keeps the database barrier.
            let index = match &search.index {
                crate::sql::SqlValue::Literal(Value::String(index)) => Some(index.as_str()),
                crate::sql::SqlValue::Parameter(position) => position
                    .checked_sub(1)
                    .and_then(|position| parameters.get(position))
                    .and_then(|value| match value {
                        Value::String(index) => Some(index.as_str()),
                        _ => None,
                    }),
                _ => None,
            };
            let source = index
                .and_then(|index| state.table_schema(index))
                .filter(|schema| schema.search_index().is_some())
                .and_then(|schema| schema.materialized_view.as_deref())
                .map(|definition| definition.source.clone());
            match source {
                Some(source) => record(dependencies, VersionKey::ReadRelationalTableDomain(source)),
                None => record(dependencies, VersionKey::Database),
            }
        }
        SqlStatement::Select(select) => {
            qualify_expressions(select)?;
            let table = select
                .from
                .as_ref()
                .ok_or_else(|| refusal("FROM-less transaction SELECT"))?;
            transaction_schema(state, table)?;
            if system_sql::is_virtual_catalog_select(select) || select.joins.len() > MAX_KEY_COLUMNS
            {
                return Err(refusal("virtual or unbounded joined transaction SELECT"));
            }
            if !select.joins.is_empty() {
                // Private writes may change join keys. Complete table domains
                // cover both parent/child membership without querying a second
                // snapshot or guessing from the returned rows.
                for table in
                    std::iter::once(table).chain(select.joins.iter().map(|join| &join.table))
                {
                    record(
                        dependencies,
                        VersionKey::ReadRelationalTableDomain(
                            transaction_schema(state, table)?.name.clone(),
                        ),
                    )?;
                }
                return Ok(());
            }
            let schema = transaction_schema(state, table)?;
            let key = primary_key(select, schema, parameters)?;
            let key = if matches!(key, VersionKey::Database) {
                indexed::prefix_key(select, schema, parameters)?
                    .unwrap_or_else(|| VersionKey::ReadRelationalTableDomain(schema.name.clone()))
            } else {
                key
            };
            record(dependencies, key)
        }
        SqlStatement::Insert(statement) => {
            let key = VersionKey::ReadRelationalTableDomain(
                transaction_schema(state, &statement.table)?.name.clone(),
            );
            let schema = transaction_schema(state, &statement.table)?;
            if schema.columns.iter().enumerate().any(|(index, column)| {
                matches!(
                    column.default,
                    Some(
                        hawdb_storage::relational::RelationalColumnDefault::UuidV7
                            | hawdb_storage::relational::RelationalColumnDefault::CurrentTimestamp(
                                _
                            )
                    )
                ) && if statement.columns.is_empty() {
                    statement.rows.iter().any(|row| row.len() <= index)
                } else {
                    !statement.columns.contains(&column.name)
                }
            }) {
                return Err(refusal("unversioned generated UUID or clock default"));
            }
            record(dependencies, key)
        }
        SqlStatement::Update(statement) => {
            if let Some(predicate) = &statement.selection {
                qualify_expression(predicate, &mut 0, 0)?;
            }
            record(
                dependencies,
                VersionKey::ReadRelationalTableDomain(
                    transaction_schema(state, &statement.table)?.name.clone(),
                ),
            )
        }
        SqlStatement::Delete(statement) => {
            if let Some(predicate) = &statement.selection {
                qualify_expression(predicate, &mut 0, 0)?;
            }
            record(
                dependencies,
                VersionKey::ReadRelationalTableDomain(
                    transaction_schema(state, &statement.table)?.name.clone(),
                ),
            )
        }
        SqlStatement::CreateTable(_)
        | SqlStatement::CreateMaterializedView(_)
        | SqlStatement::DropMaterializedView(_)
        | SqlStatement::CreateSearchIndex(_)
        | SqlStatement::DropSearchIndex(_)
        | SqlStatement::CreateIndex(_)
        | SqlStatement::AlterTableAddColumn(_) => record(dependencies, VersionKey::Database),
        SqlStatement::Explain(_) | SqlStatement::Branch(_) => {
            Err(refusal("noncanonical transaction statement"))
        }
    }
}

fn transaction_schema<'a>(
    state: &'a hawdb_storage::relational::RelationalState,
    table: &crate::sql::SqlTableName,
) -> Result<&'a RelationalTableSchema> {
    if table.name.len() > MAX_KEY_BYTES
        || table
            .schema
            .as_deref()
            .is_some_and(|schema| schema != "public")
    {
        return Err(refusal("noncanonical or unbounded transaction table"));
    }
    state
        .table_schema(&table.name)
        .filter(|schema| schema.columns.len() <= MAX_EXPRESSION_NODES)
        .ok_or_else(|| refusal("unknown or unbounded transaction schema"))
}

impl PreparedRead {
    /// Executes a bounded canonical SELECT. Necessary complete
    /// primary-key equalities under AND use existing row stamps, including
    /// absent keys. Necessary leading equalities of declared indexes record
    /// complete prefix domains, including payload and empty-page changes.
    /// One aliased INNER JOIN to a complete parent primary key collects the
    /// child scope and parent point, including absent/filtered parents. A pinned
    /// child point query may read its join fields (at most one row / 4 KiB).
    /// Other qualified single-table reads retain a complete table domain,
    /// including empty scans and rows outside a selected page. Unsupported
    /// qualified JOIN scopes retain their existing whole-epoch fallback.
    /// Other joins, functions, catalogs, projection bindings and locking reads fail
    /// closed. Metadata admission bounds SQL plus scalar parameters to 64 KiB,
    /// 1024 parameters/expression nodes and 64 nested expression levels. A lexical
    /// preflight caps 4096 non-whitespace tokens and 32 conservative recursive
    /// tokens (keywords, operators and opening delimiters) before parsing,
    /// lowering or dropping a potentially deep upstream AST.
    pub fn query_sql_with_params(
        &mut self,
        sql: &str,
        parameters: &[Value],
    ) -> Result<QueryOutput> {
        let result = self.query_sql_inner(sql, parameters);
        self.failed |= result.is_err();
        result
    }

    fn query_sql_inner(&mut self, sql: &str, parameters: &[Value]) -> Result<QueryOutput> {
        admit_input(sql, parameters)?;
        crate::sql::admit_postgres_sql_syntax(
            sql,
            MAX_INPUT_BYTES,
            MAX_TOKENS,
            MAX_RECURSIVE_TOKENS,
        )?;
        if self.read.projection_relational.is_some() {
            return Err(refusal("projection-bound relational reads"));
        }
        let prepared = self.read.relational_plan_template_cache.prepare(sql)?;
        let SqlStatement::Select(select) = prepared.statement() else {
            return Err(refusal("non-SELECT statements"));
        };
        let Some(table) = &select.from else {
            return Err(refusal("FROM-less SELECT"));
        };
        if system_sql::is_virtual_catalog_select(select)
            || table
                .schema
                .as_deref()
                .is_some_and(|schema| schema != "public")
            || select.lock_strength.is_some()
        {
            return Err(refusal("catalog, join or locking SELECT"));
        }
        qualify_expressions(select)?;
        if !select.joins.is_empty() {
            for key in joined::keys(self, select, parameters)? {
                self.dependencies
                    .graph
                    .record(key)
                    .map_err(|error| HawDBError::Execution(error.to_string()))?;
            }
            return self
                .read
                .query_sql_with_prepared_params(sql, parameters, prepared);
        }
        let schema = self
            .read
            .store
            .relational_state()
            .table_schema(&table.name)
            .ok_or_else(|| refusal("noncanonical or unknown relational table"))?;
        let key = primary_key(select, schema, parameters)?;
        let key = if matches!(key, VersionKey::Database) {
            indexed::prefix_key(select, schema, parameters)?
                .unwrap_or_else(|| VersionKey::ReadRelationalTableDomain(schema.name.clone()))
        } else {
            key
        };
        self.dependencies
            .graph
            .record(key)
            .map_err(|error| HawDBError::Execution(error.to_string()))?;
        self.read
            .query_sql_with_prepared_params(sql, parameters, prepared)
    }
}

fn refusal(shape: &str) -> HawDBError {
    HawDBError::Execution(format!(
        "prepared SQL dependency collector does not qualify {shape}"
    ))
}

fn scalar_bytes(value: &Value) -> Result<usize> {
    match value {
        Value::String(value) => Ok(value.len()),
        Value::Decimal(_) => Ok(17),
        Value::Binary(value) => Ok(value.len()),
        Value::Vector(value) => Ok(value.encoded().len()),
        Value::Null
        | Value::Bool(_)
        | Value::Int(_)
        | Value::Float(_)
        | Value::Uuid(_)
        | Value::Date(_)
        | Value::LocalTime(_)
        | Value::LocalDateTime(_)
        | Value::DateTime(_)
        | Value::Duration(_) => Ok(16),
        Value::List(_) | Value::Map(_) => Err(refusal("compound SQL parameter values")),
    }
}

fn admit_input(sql: &str, parameters: &[Value]) -> Result<()> {
    if sql.len() > MAX_INPUT_BYTES || parameters.len() > MAX_PARAMETERS {
        return Err(refusal("SQL input exceeding metadata admission"));
    }
    let mut bytes = sql.len().saturating_add(
        parameters
            .len()
            .saturating_mul(std::mem::size_of::<Value>()),
    );
    for parameter in parameters {
        bytes = bytes.saturating_add(scalar_bytes(parameter)?);
        if bytes > MAX_INPUT_BYTES {
            return Err(refusal("SQL input exceeding metadata admission"));
        }
    }
    Ok(())
}

fn qualify_expressions(select: &SelectStatement) -> Result<()> {
    let mut nodes = 0usize;
    for projection in &select.projection {
        if let SelectProjection::Expression { expression, .. } = projection {
            qualify_expression(expression, &mut nodes, 0)?;
        }
    }
    for expression in select.joins.iter().map(|join| &join.on) {
        qualify_expression(expression, &mut nodes, 0)?;
    }
    for expression in select
        .selection
        .iter()
        .chain(select.having.iter())
        .chain(select.order_by.iter().map(|item| &item.expression))
    {
        qualify_expression(expression, &mut nodes, 0)?;
    }
    Ok(())
}

fn qualify_expression(expression: &Expr, nodes: &mut usize, depth: usize) -> Result<()> {
    *nodes = nodes.saturating_add(1);
    if *nodes > MAX_EXPRESSION_NODES || depth > MAX_EXPRESSION_DEPTH {
        return Err(refusal("expression exceeding metadata work admission"));
    }
    match &expression.kind {
        ExprKind::Value(SqlValue::Expression(expression)) => {
            qualify_expression(expression, nodes, depth + 1)
        }
        ExprKind::Column(_) | ExprKind::Value(_) | ExprKind::CurrentTimestamp(_) => Ok(()),
        ExprKind::And(left, right)
        | ExprKind::Or(left, right)
        | ExprKind::Compare { left, right, .. }
        | ExprKind::Arithmetic { left, right, .. }
        | ExprKind::Like {
            left,
            pattern: right,
            ..
        } => {
            qualify_expression(left, nodes, depth + 1)?;
            qualify_expression(right, nodes, depth + 1)
        }
        ExprKind::Not(expression)
        | ExprKind::IsNull { expression, .. }
        | ExprKind::Negate(expression)
        | ExprKind::Cast { expression, .. }
        | ExprKind::TimestampCast { expression, .. } => {
            qualify_expression(expression, nodes, depth + 1)
        }
        ExprKind::InList { left, values, .. } => {
            qualify_expression(left, nodes, depth + 1)?;
            for value in values {
                qualify_expression(value, nodes, depth + 1)?;
            }
            Ok(())
        }
        ExprKind::Function { .. } => Err(refusal("function expressions")),
    }
}

fn primary_key(
    select: &SelectStatement,
    schema: &RelationalTableSchema,
    parameters: &[Value],
) -> Result<VersionKey> {
    if schema.primary_key.is_empty() || schema.primary_key.len() > MAX_KEY_COLUMNS {
        return Ok(VersionKey::Database);
    }
    let mut bytes = std::mem::size_of::<VersionKey>()
        .saturating_add(schema.name.len())
        .saturating_add(
            schema
                .primary_key
                .len()
                .saturating_mul(std::mem::size_of::<RelationalValue>()),
        );
    let mut values = Vec::new();
    for name in &schema.primary_key {
        let Some(value) = select
            .selection
            .as_ref()
            .and_then(|predicate| necessary_equality(predicate, select, name))
        else {
            return Ok(VersionKey::Database);
        };
        let value = match value {
            SqlValue::Literal(value) => value,
            SqlValue::Expression(_) => return Ok(VersionKey::Database),
            SqlValue::Parameter(position) => {
                parameters.get(position.saturating_sub(1)).ok_or_else(|| {
                    HawDBError::Semantic(format!("missing PostgreSQL parameter ${position}"))
                })?
            }
        };
        bytes = bytes.saturating_add(scalar_bytes(value)?);
        if bytes > MAX_KEY_BYTES {
            return Ok(VersionKey::Database);
        }
        let column = schema
            .column_position(name)
            .ok_or_else(|| refusal("invalid primary-key schema"))?;
        let scalar_type = schema.columns[column].scalar_type;
        let value = value_to_relational_as(value.clone(), scalar_type)?;
        if matches!(value, RelationalValue::Null) {
            return Ok(VersionKey::Database);
        }
        if !scalar_type.same_value_domain(value.scalar_type()) {
            return Err(refusal(
                "primary-key comparison with incompatible scalar types",
            ));
        }
        values.push(value);
    }
    Ok(VersionKey::RelationalRow {
        table: schema.name.clone(),
        primary_key: RelationalKey(values),
    })
}

fn necessary_equality<'a>(
    expression: &'a Expr,
    select: &SelectStatement,
    name: &str,
) -> Option<&'a SqlValue> {
    match &expression.kind {
        ExprKind::And(left, right) => necessary_equality(left, select, name)
            .or_else(|| necessary_equality(right, select, name)),
        ExprKind::Compare {
            left,
            op: SqlComparisonOp::Eq,
            right,
        } => {
            let column = left.as_column()?;
            (column.name == name
                && (if select.joins.is_empty() {
                    column.qualifier.as_deref().is_none_or(|qualifier| {
                        qualifier == select.from_table().name
                            || Some(qualifier) == select.from_alias.as_deref()
                    })
                } else {
                    column.qualifier.as_deref() == select.from_alias.as_deref()
                }))
            .then(|| right.as_value())
            .flatten()
        }
        _ => None,
    }
}