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
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
// Copyright 2025 Stoolap Contributors
//
// 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.
//! Fast-path execution for simple PK-based UPDATE and DELETE operations
//!
//! This module provides optimized execution paths for simple DML like:
//! - `UPDATE table SET col = val WHERE pk = $1`
//! - `DELETE FROM table WHERE pk = $1`
//!
//! By detecting these patterns early and bypassing the full executor overhead
//! (subquery checking, memory filter setup, expression compilation), we can
//! reduce per-operation overhead significantly.
use std::sync::RwLock;
use crate::common::{CompactArc, SmartString};
use crate::core::{Result, Row, Schema, Value};
use crate::parser::ast::{DeleteStatement, Expression, UpdateStatement};
use crate::storage::expression::{ComparisonExpr, Expression as StorageExpression};
use crate::storage::traits::{Engine, QueryResult};
use super::context::{
invalidate_in_subquery_cache_for_table, invalidate_scalar_subquery_cache_for_table,
invalidate_semi_join_cache_for_table, ExecutionContext,
};
use super::query_cache::{
CompiledExecution, CompiledPkDelete, CompiledPkUpdate, CompiledUpdateColumn, PkValueSource,
UpdateValueSource,
};
use super::result::ExecResult;
use super::Executor;
impl Executor {
/// Try to execute an UPDATE using pre-compiled state
pub(crate) fn try_fast_pk_update_compiled(
&self,
stmt: &UpdateStatement,
ctx: &ExecutionContext,
compiled: &RwLock<CompiledExecution>,
) -> Option<Result<Box<dyn QueryResult>>> {
// Quick reject: explicit transaction (use try_lock for fast rejection)
{
let active_tx = match self.active_transaction.try_lock() {
Ok(guard) => guard,
Err(_) => return None, // Lock contention - fall back to normal path
};
if active_tx.is_some() {
return None;
}
}
// Try read lock first - check if already compiled
{
let compiled_guard = match compiled.read() {
Ok(guard) => guard,
Err(_) => return None,
};
match &*compiled_guard {
CompiledExecution::NotOptimizable(epoch)
if self.engine.schema_epoch() == *epoch =>
{
return None
}
CompiledExecution::PkUpdate(update) => {
// Fast validation using schema epoch (~1ns vs ~7ns for HashMap lookup)
if self.engine.schema_epoch() == update.cached_epoch {
// Fast path: extract PK value and execute
let pk_value =
self.extract_pk_value_from_source(&update.pk_value_source, ctx)?;
return Some(self.execute_compiled_pk_update(update, pk_value, ctx));
}
// Epoch changed - fall through to recompile
}
CompiledExecution::NotOptimizable(_) | CompiledExecution::Unknown => {} // Epoch changed or first run - fall through to recompile
_ => return None, // Different type of compiled execution
}
}
// First execution or schema changed - compile and cache
self.compile_and_execute_pk_update(stmt, ctx, compiled)
}
/// Try to execute a DELETE using pre-compiled state
pub(crate) fn try_fast_pk_delete_compiled(
&self,
stmt: &DeleteStatement,
ctx: &ExecutionContext,
compiled: &RwLock<CompiledExecution>,
) -> Option<Result<Box<dyn QueryResult>>> {
// Quick reject: explicit transaction (use try_lock for fast rejection)
{
let active_tx = match self.active_transaction.try_lock() {
Ok(guard) => guard,
Err(_) => return None, // Lock contention - fall back to normal path
};
if active_tx.is_some() {
return None;
}
}
// Try read lock first - check if already compiled
{
let compiled_guard = match compiled.read() {
Ok(guard) => guard,
Err(_) => return None,
};
match &*compiled_guard {
CompiledExecution::NotOptimizable(epoch)
if self.engine.schema_epoch() == *epoch =>
{
return None
}
CompiledExecution::PkDelete(delete) => {
// Fast validation using schema epoch (~1ns vs ~7ns for HashMap lookup)
if self.engine.schema_epoch() == delete.cached_epoch {
// Fast path: extract PK value and execute
let pk_value =
self.extract_pk_value_from_source(&delete.pk_value_source, ctx)?;
return Some(self.execute_compiled_pk_delete(delete, pk_value));
}
// Epoch changed - fall through to recompile
}
CompiledExecution::NotOptimizable(_) | CompiledExecution::Unknown => {} // Epoch changed or first run - fall through to recompile
_ => return None, // Different type of compiled execution
}
}
// First execution or schema changed - compile and cache
self.compile_and_execute_pk_delete(stmt, ctx, compiled)
}
// ============================================================================
// HELPER METHODS
// ============================================================================
/// Extract PK equality value from WHERE clause
/// Returns (pk_value, pk_source) if WHERE is `pk_col = literal` or `pk_col = $param`
fn extract_pk_equality_value(
&self,
expr: &Expression,
pk_column: &str,
ctx: &ExecutionContext,
) -> Option<(i64, PkValueSource)> {
match expr {
Expression::Infix(infix) => {
if infix.operator != "=" {
return None;
}
// Try column = value pattern
if let Some((col, val, source)) =
self.extract_col_eq_val_dml(&infix.left, &infix.right, ctx)
{
if col.eq_ignore_ascii_case(pk_column) {
return Some((val, source));
}
}
// Try value = column pattern
if let Some((col, val, source)) =
self.extract_col_eq_val_dml(&infix.right, &infix.left, ctx)
{
if col.eq_ignore_ascii_case(pk_column) {
return Some((val, source));
}
}
None
}
_ => None,
}
}
/// Extract column name, integer value, and value source from col = val pattern
fn extract_col_eq_val_dml(
&self,
col_expr: &Expression,
val_expr: &Expression,
ctx: &ExecutionContext,
) -> Option<(String, i64, PkValueSource)> {
// Get column name
let col_name = match col_expr {
Expression::Identifier(id) => id.value.to_string(),
Expression::QualifiedIdentifier(q) => q.name.value.to_string(),
_ => return None,
};
// Get integer value and source
let (pk_value, pk_value_source) = match val_expr {
Expression::IntegerLiteral(lit) => (lit.value, PkValueSource::Literal(lit.value)),
Expression::FloatLiteral(lit) => {
let v = lit.value as i64;
(v, PkValueSource::Literal(v))
}
Expression::Parameter(param) => {
// Named parameters (e.g., :name) resolve via get_named_param() at execution time
// Positional parameters ($1, $2, ...) are 1-indexed, array is 0-indexed
if param.name.starts_with(':') {
let name = ¶m.name[1..];
let value = ctx.get_named_param(name)?;
let pk_value = match value {
Value::Integer(i) => *i,
Value::Float(f) => *f as i64,
_ => return None,
};
(
pk_value,
PkValueSource::NamedParameter(SmartString::new(name)),
)
} else {
let params = ctx.params();
let param_idx = if param.index > 0 {
param.index - 1
} else {
return None;
};
if param_idx >= params.len() {
return None;
}
let pk_value = match ¶ms[param_idx] {
Value::Integer(i) => *i,
Value::Float(f) => *f as i64,
_ => return None,
};
(pk_value, PkValueSource::Parameter(param_idx))
}
}
_ => return None,
};
Some((col_name, pk_value, pk_value_source))
}
/// Extract PK value from pre-compiled source
fn extract_pk_value_from_source(
&self,
source: &PkValueSource,
ctx: &ExecutionContext,
) -> Option<i64> {
match source {
PkValueSource::NamedParameter(name) => match ctx.get_named_param(name)? {
Value::Integer(i) => Some(*i),
Value::Float(f) => Some(*f as i64),
_ => None,
},
_ => Self::extract_pk_value_from_params(source, ctx.params()),
}
}
/// Extract PK value from params slice directly (avoids ExecutionContext overhead)
#[inline]
fn extract_pk_value_from_params(source: &PkValueSource, params: &[Value]) -> Option<i64> {
match source {
PkValueSource::Literal(v) => Some(*v),
PkValueSource::Parameter(idx) => {
if *idx >= params.len() {
return None;
}
match ¶ms[*idx] {
Value::Integer(i) => Some(*i),
Value::Float(f) => Some(*f as i64),
_ => None,
}
}
PkValueSource::NamedParameter(_) => None, // No ctx available in slice path
}
}
/// Extract update value from params slice directly
#[inline]
fn extract_update_value_from_slice(
source: &UpdateValueSource,
params: &[Value],
) -> Option<Value> {
match source {
UpdateValueSource::Literal(v) => Some(v.clone()),
UpdateValueSource::Parameter(idx) => params.get(*idx).cloned(),
UpdateValueSource::NamedParameter(_) => None, // No ctx available in slice path
}
}
/// Try fast PK update with borrowed params slice (avoids Arc allocation)
pub(crate) fn try_fast_pk_update_with_params(
&self,
_stmt: &UpdateStatement,
params: &[Value],
compiled: &RwLock<CompiledExecution>,
) -> Option<Result<Box<dyn QueryResult>>> {
// Try read lock first - check if already compiled
let compiled_guard = compiled.read().ok()?;
match &*compiled_guard {
CompiledExecution::NotOptimizable(_) => None,
CompiledExecution::PkUpdate(update) => {
// Fast validation using schema epoch
if self.engine.schema_epoch() == update.cached_epoch {
let pk_value =
Self::extract_pk_value_from_params(&update.pk_value_source, params)?;
// Extract update values
let mut updates = Vec::with_capacity(update.updates.len());
for u in &update.updates {
let value = Self::extract_update_value_from_slice(&u.value_source, params)?;
updates.push((u.column_idx, value.coerce_to_type(u.column_type)));
}
// Clone only what we need (cheap: SmartString + Arc)
let table_name = update.table_name.clone();
let pk_column_name = update.pk_column_name.clone();
let schema = update.schema.clone();
drop(compiled_guard);
return Some(self.execute_pk_update_minimal(
&table_name,
&pk_column_name,
&schema,
pk_value,
updates,
));
}
None // Epoch changed, use normal path
}
CompiledExecution::Unknown => None,
_ => None,
}
}
/// Try fast PK delete with borrowed params slice (avoids Arc allocation)
pub(crate) fn try_fast_pk_delete_with_params(
&self,
_stmt: &DeleteStatement,
params: &[Value],
compiled: &RwLock<CompiledExecution>,
) -> Option<Result<Box<dyn QueryResult>>> {
// Try read lock first - check if already compiled
let compiled_guard = compiled.read().ok()?;
match &*compiled_guard {
CompiledExecution::NotOptimizable(_) => None,
CompiledExecution::PkDelete(delete) => {
// Fast validation using schema epoch
if self.engine.schema_epoch() == delete.cached_epoch {
let pk_value =
Self::extract_pk_value_from_params(&delete.pk_value_source, params)?;
// Clone only what we need (cheap: SmartString + Arc)
let table_name = delete.table_name.clone();
let pk_column_name = delete.pk_column_name.clone();
let schema = delete.schema.clone();
drop(compiled_guard);
return Some(self.execute_pk_delete_minimal(
&table_name,
&pk_column_name,
&schema,
pk_value,
));
}
None // Epoch changed, use normal path
}
CompiledExecution::Unknown => None,
_ => None,
}
}
/// Execute PK update with minimal data (avoids cloning CompiledPkUpdate)
fn execute_pk_update_minimal(
&self,
table_name: &str,
pk_column_name: &str,
schema: &CompactArc<Schema>,
pk_value: i64,
updates: Vec<(usize, Value)>,
) -> Result<Box<dyn QueryResult>> {
// Create auto-commit transaction
let tx = self.engine.begin_transaction()?;
let mut table = tx.get_table(table_name)?;
// Build WHERE expression for PK lookup
let mut pk_expr = ComparisonExpr::new(
pk_column_name,
crate::core::Operator::Eq,
Value::Integer(pk_value),
);
pk_expr.prepare_for_schema(schema);
// Execute update with simple setter
let mut setter = |mut row: Row| -> Result<(Row, bool)> {
for (idx, new_value) in &updates {
let _ = row.set(*idx, new_value.clone());
}
Ok((row, true))
};
let rows_affected = table.update(Some(&pk_expr), &mut setter)?;
// Invalidate caches
if rows_affected > 0 {
self.semantic_cache.invalidate_table(table_name);
invalidate_semi_join_cache_for_table(table_name);
invalidate_scalar_subquery_cache_for_table(table_name);
invalidate_in_subquery_cache_for_table(table_name);
}
// Commit
drop(table);
let mut tx = tx;
tx.commit()?;
Ok(Box::new(ExecResult::with_rows_affected(
rows_affected as i64,
)))
}
/// Execute PK delete with minimal data (avoids cloning CompiledPkDelete)
fn execute_pk_delete_minimal(
&self,
table_name: &str,
pk_column_name: &str,
schema: &CompactArc<Schema>,
pk_value: i64,
) -> Result<Box<dyn QueryResult>> {
// Create auto-commit transaction
let tx = self.engine.begin_transaction()?;
let mut table = tx.get_table(table_name)?;
// Build WHERE expression for PK lookup
let mut pk_expr = ComparisonExpr::new(
pk_column_name,
crate::core::Operator::Eq,
Value::Integer(pk_value),
);
pk_expr.prepare_for_schema(schema);
// Execute delete
let rows_affected = table.delete(Some(&pk_expr))?;
// Invalidate caches
if rows_affected > 0 {
self.semantic_cache.invalidate_table(table_name);
invalidate_semi_join_cache_for_table(table_name);
invalidate_scalar_subquery_cache_for_table(table_name);
invalidate_in_subquery_cache_for_table(table_name);
}
// Commit
drop(table);
let mut tx = tx;
tx.commit()?;
Ok(Box::new(ExecResult::with_rows_affected(
rows_affected as i64,
)))
}
// ============================================================================
// EXECUTION METHODS
// ============================================================================
/// Execute a compiled PK update (extracts values from ctx then delegates to core impl)
fn execute_compiled_pk_update(
&self,
compiled: &CompiledPkUpdate,
pk_value: i64,
ctx: &ExecutionContext,
) -> Result<Box<dyn QueryResult>> {
// Extract values from compiled sources
let mut updates = Vec::with_capacity(compiled.updates.len());
for u in &compiled.updates {
let value = match &u.value_source {
UpdateValueSource::Literal(v) => v.clone(),
UpdateValueSource::Parameter(idx) => {
let params = ctx.params();
match params.get(*idx) {
Some(v) => v.clone(),
None => continue,
}
}
UpdateValueSource::NamedParameter(name) => match ctx.get_named_param(name) {
Some(v) => v.clone(),
None => continue,
},
};
updates.push((u.column_idx, value.coerce_to_type(u.column_type)));
}
self.execute_pk_update_minimal(
&compiled.table_name,
&compiled.pk_column_name,
&compiled.schema,
pk_value,
updates,
)
}
/// Execute a compiled PK delete (delegates to core impl)
fn execute_compiled_pk_delete(
&self,
compiled: &CompiledPkDelete,
pk_value: i64,
) -> Result<Box<dyn QueryResult>> {
self.execute_pk_delete_minimal(
&compiled.table_name,
&compiled.pk_column_name,
&compiled.schema,
pk_value,
)
}
// ============================================================================
// COMPILE AND EXECUTE METHODS
// ============================================================================
/// Compile and execute a PK update, caching the compiled state
fn compile_and_execute_pk_update(
&self,
stmt: &UpdateStatement,
ctx: &ExecutionContext,
compiled: &RwLock<CompiledExecution>,
) -> Option<Result<Box<dyn QueryResult>>> {
// Acquire write lock
let mut compiled_guard = match compiled.write() {
Ok(guard) => guard,
Err(_) => return None,
};
// Double-check after acquiring lock
match &*compiled_guard {
CompiledExecution::NotOptimizable(epoch) if self.engine.schema_epoch() == *epoch => {
return None
}
CompiledExecution::PkUpdate(update) => {
let pk_value = self.extract_pk_value_from_source(&update.pk_value_source, ctx)?;
return Some(self.execute_compiled_pk_update(update, pk_value, ctx));
}
CompiledExecution::NotOptimizable(_) | CompiledExecution::Unknown => {} // Epoch changed or first run - recompile
_ => return None,
}
// Validate pattern
let where_clause = stmt.where_clause.as_ref()?;
if !stmt.returning.is_empty() {
*compiled_guard = CompiledExecution::NotOptimizable(self.engine.schema_epoch());
return None;
}
let table_name = &stmt.table_name.value_lower;
let schema = match self.engine.get_table_schema(table_name) {
Ok(s) => s,
Err(_) => {
*compiled_guard = CompiledExecution::NotOptimizable(self.engine.schema_epoch());
return None;
}
};
let pk_indices = schema.primary_key_indices();
if pk_indices.len() != 1 {
*compiled_guard = CompiledExecution::NotOptimizable(self.engine.schema_epoch());
return None;
}
let pk_idx = pk_indices[0];
let pk_column = &schema.columns[pk_idx].name;
// Reject UPDATE on primary key column (row_id == pk_value invariant)
{
let col_map = schema.column_index_map();
for col_name in stmt.updates.keys() {
let col_lower = col_name.to_lowercase();
if col_map.get(col_lower.as_str()).copied() == Some(pk_idx) {
return Some(Err(crate::core::Error::invalid_argument(format!(
"cannot UPDATE primary key column '{}'. Use DELETE + INSERT instead",
pk_column
))));
}
}
}
// Bail if table has FK constraints (child table) or is referenced by other tables (parent table)
// FK enforcement requires cross-table lookups — fall back to normal path
if !schema.foreign_keys.is_empty()
|| !super::foreign_key::find_referencing_fks(&self.engine, table_name).is_empty()
{
*compiled_guard = CompiledExecution::NotOptimizable(self.engine.schema_epoch());
return None;
}
// Bail if any column being updated has a CHECK constraint
// CHECK validation requires expression evaluation — fall back to normal path
{
let col_map = schema.column_index_map();
for col_name in stmt.updates.keys() {
let col_lower = col_name.to_lowercase();
if let Some(&idx) = col_map.get(col_lower.as_str()) {
if schema.columns[idx].check_expr.is_some() {
*compiled_guard =
CompiledExecution::NotOptimizable(self.engine.schema_epoch());
return None;
}
}
}
}
// Extract PK value source
let (pk_value, pk_source) =
match self.extract_pk_equality_value(where_clause, pk_column, ctx) {
Some(v) => v,
None => {
*compiled_guard = CompiledExecution::NotOptimizable(self.engine.schema_epoch());
return None;
}
};
// Extract update value sources
let col_map = schema.column_index_map();
let mut compiled_updates = Vec::with_capacity(stmt.updates.len());
for (col_name, expr) in &stmt.updates {
let col_lower = col_name.to_lowercase();
let col_idx = match col_map.get(col_lower.as_str()) {
Some(&idx) => idx,
None => {
*compiled_guard = CompiledExecution::NotOptimizable(self.engine.schema_epoch());
return None;
}
};
let col_type = schema.columns[col_idx].data_type;
let value_source = match self.extract_value_source(expr) {
Some(s) => s,
None => {
*compiled_guard = CompiledExecution::NotOptimizable(self.engine.schema_epoch());
return None;
}
};
compiled_updates.push(CompiledUpdateColumn {
column_idx: col_idx,
column_type: col_type,
value_source,
});
}
// Build compiled state
let compiled_update = CompiledPkUpdate {
table_name: SmartString::new(table_name),
schema: CompactArc::new((*schema).clone()),
pk_column_name: SmartString::new(pk_column),
pk_value_source: pk_source,
updates: compiled_updates,
cached_epoch: self.engine.schema_epoch(),
};
*compiled_guard = CompiledExecution::PkUpdate(compiled_update.clone());
drop(compiled_guard);
// Execute
Some(self.execute_compiled_pk_update(&compiled_update, pk_value, ctx))
}
/// Compile and execute a PK delete, caching the compiled state
fn compile_and_execute_pk_delete(
&self,
stmt: &DeleteStatement,
ctx: &ExecutionContext,
compiled: &RwLock<CompiledExecution>,
) -> Option<Result<Box<dyn QueryResult>>> {
// Acquire write lock
let mut compiled_guard = match compiled.write() {
Ok(guard) => guard,
Err(_) => return None,
};
// Double-check after acquiring lock
match &*compiled_guard {
CompiledExecution::NotOptimizable(epoch) if self.engine.schema_epoch() == *epoch => {
return None
}
CompiledExecution::PkDelete(delete) => {
let pk_value = self.extract_pk_value_from_source(&delete.pk_value_source, ctx)?;
return Some(self.execute_compiled_pk_delete(delete, pk_value));
}
CompiledExecution::NotOptimizable(_) | CompiledExecution::Unknown => {} // Epoch changed or first run - recompile
_ => return None,
}
// Validate pattern
let where_clause = stmt.where_clause.as_ref()?;
if !stmt.returning.is_empty() {
*compiled_guard = CompiledExecution::NotOptimizable(self.engine.schema_epoch());
return None;
}
let table_name = &stmt.table_name.value_lower;
let schema = match self.engine.get_table_schema(table_name) {
Ok(s) => s,
Err(_) => {
*compiled_guard = CompiledExecution::NotOptimizable(self.engine.schema_epoch());
return None;
}
};
let pk_indices = schema.primary_key_indices();
if pk_indices.len() != 1 {
*compiled_guard = CompiledExecution::NotOptimizable(self.engine.schema_epoch());
return None;
}
let pk_idx = pk_indices[0];
let pk_column = &schema.columns[pk_idx].name;
// Bail if this table is referenced by child tables (FK enforcement needed)
if !super::foreign_key::find_referencing_fks(&self.engine, table_name).is_empty() {
*compiled_guard = CompiledExecution::NotOptimizable(self.engine.schema_epoch());
return None;
}
// Extract PK value source
let (pk_value, pk_source) =
match self.extract_pk_equality_value(where_clause, pk_column, ctx) {
Some(v) => v,
None => {
*compiled_guard = CompiledExecution::NotOptimizable(self.engine.schema_epoch());
return None;
}
};
// Build compiled state
let compiled_delete = CompiledPkDelete {
table_name: SmartString::new(table_name),
schema: CompactArc::new((*schema).clone()),
pk_column_name: SmartString::new(pk_column),
pk_value_source: pk_source,
cached_epoch: self.engine.schema_epoch(),
};
*compiled_guard = CompiledExecution::PkDelete(compiled_delete.clone());
drop(compiled_guard);
// Execute
Some(self.execute_compiled_pk_delete(&compiled_delete, pk_value))
}
/// Extract value source (literal or parameter) from expression
fn extract_value_source(&self, expr: &Expression) -> Option<UpdateValueSource> {
match expr {
Expression::IntegerLiteral(lit) => {
Some(UpdateValueSource::Literal(Value::Integer(lit.value)))
}
Expression::FloatLiteral(lit) => {
Some(UpdateValueSource::Literal(Value::Float(lit.value)))
}
Expression::StringLiteral(lit) => {
Some(UpdateValueSource::Literal(Value::text(lit.value.as_str())))
}
Expression::BooleanLiteral(lit) => {
Some(UpdateValueSource::Literal(Value::Boolean(lit.value)))
}
Expression::NullLiteral(_) => Some(UpdateValueSource::Literal(Value::null_unknown())),
Expression::Prefix(prefix) if prefix.operator == "-" => match prefix.right.as_ref() {
Expression::IntegerLiteral(lit) => {
Some(UpdateValueSource::Literal(Value::Integer(-lit.value)))
}
Expression::FloatLiteral(lit) => {
Some(UpdateValueSource::Literal(Value::Float(-lit.value)))
}
_ => None,
},
Expression::Parameter(param) => {
if param.name.starts_with(':') {
let name = ¶m.name[1..];
Some(UpdateValueSource::NamedParameter(SmartString::new(name)))
} else {
let param_idx = if param.index > 0 {
param.index - 1
} else {
return None;
};
Some(UpdateValueSource::Parameter(param_idx))
}
}
_ => None, // Complex expression
}
}
}