kstone-core 0.1.0

Core storage engine for KeystoneDB - LSM tree, WAL, and DynamoDB-compatible API
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
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
/// Translates PartiQL AST to KeystoneDB operations
///
/// Maps SELECT to Query/Scan, INSERT to Put, UPDATE to Update, DELETE to Delete.

use crate::partiql::ast::*;
use crate::partiql::validator::{DynamoDBValidator, QueryType};
use crate::{Error, Key, Result};
use bytes::Bytes;

/// PartiQL to KeystoneDB translator
pub struct PartiQLTranslator;

impl PartiQLTranslator {
    /// Translate SELECT statement to Query or Scan parameters
    pub fn translate_select(stmt: &SelectStatement) -> Result<SelectTranslation> {
        // Validate and determine query type
        let query_type = DynamoDBValidator::validate_select(stmt)?;

        match query_type {
            QueryType::Query { pk_condition, sk_condition } => {
                // Translate to Query
                let (pk_bytes, multiple_pks) = Self::extract_pk_bytes(&pk_condition)?;

                if multiple_pks {
                    // IN clause with multiple PKs - need to execute multiple gets
                    Ok(SelectTranslation::MultiGet {
                        keys: pk_bytes,
                        index_name: stmt.index_name.clone(),
                    })
                } else {
                    // Single PK - regular Query
                    let pk = pk_bytes.into_iter().next().unwrap();
                    let sk_condition_translated = sk_condition
                        .as_ref()
                        .map(Self::translate_sk_condition)
                        .transpose()?;

                    Ok(SelectTranslation::Query {
                        pk,
                        sk_condition: sk_condition_translated,
                        index_name: stmt.index_name.clone(),
                        forward: stmt.order_by.as_ref().map_or(true, |o| o.ascending),
                    })
                }
            }
            QueryType::Scan => {
                // Translate to Scan
                Ok(SelectTranslation::Scan {
                    filter_conditions: stmt
                        .where_clause
                        .as_ref()
                        .map(|wc| wc.conditions.clone())
                        .unwrap_or_default(),
                })
            }
        }
    }

    /// Extract partition key bytes from condition
    fn extract_pk_bytes(condition: &Condition) -> Result<(Vec<Bytes>, bool)> {
        match &condition.operator {
            CompareOp::Equal => {
                let bytes = Self::value_to_bytes(&condition.value)?;
                Ok((vec![bytes], false))
            }
            CompareOp::In => {
                // IN clause - extract all values
                match &condition.value {
                    SqlValue::List(values) => {
                        let bytes_vec: Result<Vec<Bytes>> = values
                            .iter()
                            .map(Self::value_to_bytes)
                            .collect();
                        Ok((bytes_vec?, true))
                    }
                    _ => Err(Error::InvalidQuery("IN value must be a list".into())),
                }
            }
            _ => Err(Error::InvalidQuery(
                "Partition key must use = or IN operator".into(),
            )),
        }
    }

    /// Convert SqlValue to Bytes for key
    fn value_to_bytes(value: &SqlValue) -> Result<Bytes> {
        match value {
            SqlValue::String(s) => Ok(Bytes::copy_from_slice(s.as_bytes())),
            SqlValue::Number(n) => Ok(Bytes::copy_from_slice(n.as_bytes())),
            _ => Err(Error::InvalidQuery(format!(
                "Unsupported key value type: {:?}",
                value
            ))),
        }
    }

    /// Translate sort key condition to KeystoneDB SortKeyCondition
    fn translate_sk_condition(condition: &Condition) -> Result<SortKeyConditionType> {
        let sk_bytes = Self::value_to_bytes(&condition.value)?;

        match condition.operator {
            CompareOp::Equal => Ok(SortKeyConditionType::Equal(sk_bytes)),
            CompareOp::LessThan => Ok(SortKeyConditionType::LessThan(sk_bytes)),
            CompareOp::LessThanOrEqual => Ok(SortKeyConditionType::LessThanOrEqual(sk_bytes)),
            CompareOp::GreaterThan => Ok(SortKeyConditionType::GreaterThan(sk_bytes)),
            CompareOp::GreaterThanOrEqual => Ok(SortKeyConditionType::GreaterThanOrEqual(sk_bytes)),
            CompareOp::Between => {
                match &condition.value {
                    SqlValue::List(values) if values.len() == 2 => {
                        let low = Self::value_to_bytes(&values[0])?;
                        let high = Self::value_to_bytes(&values[1])?;
                        Ok(SortKeyConditionType::Between(low, high))
                    }
                    _ => Err(Error::InvalidQuery("BETWEEN requires exactly 2 values".into())),
                }
            }
            _ => Err(Error::InvalidQuery(format!(
                "Unsupported sort key operator: {:?}",
                condition.operator
            ))),
        }
    }

    /// Translate INSERT statement
    pub fn translate_insert(stmt: &InsertStatement) -> Result<InsertTranslation> {
        // Validate
        DynamoDBValidator::validate_insert(stmt)?;

        // Extract key and item from value map
        let value_map = match &stmt.value {
            SqlValue::Map(map) => map,
            _ => return Err(Error::InvalidQuery("INSERT value must be a map".into())),
        };

        // Extract pk
        let pk_value = value_map
            .get("pk")
            .ok_or_else(|| Error::InvalidQuery("INSERT value must contain 'pk'".into()))?;
        let pk_bytes = Self::value_to_bytes(pk_value)?;

        // Extract optional sk
        let sk_bytes = value_map
            .get("sk")
            .map(Self::value_to_bytes)
            .transpose()?;

        // Build key
        let key = if let Some(sk) = sk_bytes {
            Key::with_sk(pk_bytes.to_vec(), sk.to_vec())
        } else {
            Key::new(pk_bytes.to_vec())
        };

        // Convert remaining attributes to Item
        let mut item = std::collections::HashMap::new();
        for (attr_name, attr_value) in value_map {
            if attr_name != "pk" && attr_name != "sk" {
                item.insert(attr_name.clone(), attr_value.to_kstone_value());
            }
        }

        Ok(InsertTranslation { key, item })
    }

    /// Translate UPDATE statement
    pub fn translate_update(stmt: &UpdateStatement) -> Result<UpdateTranslation> {
        // Validate
        DynamoDBValidator::validate_update(stmt)?;

        // Extract key from WHERE clause
        let pk_cond = stmt
            .where_clause
            .get_condition("pk")
            .ok_or_else(|| Error::InvalidQuery("UPDATE must specify pk in WHERE clause".into()))?;
        let pk_bytes = Self::value_to_bytes(&pk_cond.value)?;

        let sk_bytes = stmt
            .where_clause
            .get_condition("sk")
            .map(|c| Self::value_to_bytes(&c.value))
            .transpose()?;

        let key = if let Some(sk) = sk_bytes {
            Key::with_sk(pk_bytes.to_vec(), sk.to_vec())
        } else {
            Key::new(pk_bytes.to_vec())
        };

        // Build UPDATE expression and values map
        let mut expression_parts = Vec::new();
        let mut values = std::collections::HashMap::new();
        let mut value_counter = 1;

        // Process SET assignments
        if !stmt.set_assignments.is_empty() {
            let mut set_exprs = Vec::new();
            for assignment in &stmt.set_assignments {
                match &assignment.value {
                    SetValue::Literal(sql_value) => {
                        // SET attr = :v1
                        let placeholder = format!(":v{}", value_counter);
                        set_exprs.push(format!("{} = {}", assignment.attribute, placeholder));
                        values.insert(placeholder, sql_value.to_kstone_value());
                        value_counter += 1;
                    }
                    SetValue::Add { attribute, value } => {
                        // SET attr = attr + :v1
                        let placeholder = format!(":v{}", value_counter);
                        set_exprs.push(format!(
                            "{} = {} + {}",
                            assignment.attribute, attribute, placeholder
                        ));
                        values.insert(placeholder, value.to_kstone_value());
                        value_counter += 1;
                    }
                    SetValue::Subtract { attribute, value } => {
                        // SET attr = attr - :v1
                        let placeholder = format!(":v{}", value_counter);
                        set_exprs.push(format!(
                            "{} = {} - {}",
                            assignment.attribute, attribute, placeholder
                        ));
                        values.insert(placeholder, value.to_kstone_value());
                        value_counter += 1;
                    }
                }
            }
            expression_parts.push(format!("SET {}", set_exprs.join(", ")));
        }

        // Process REMOVE attributes
        if !stmt.remove_attributes.is_empty() {
            expression_parts.push(format!("REMOVE {}", stmt.remove_attributes.join(", ")));
        }

        let expression = expression_parts.join(" ");

        Ok(UpdateTranslation {
            key,
            expression,
            values,
        })
    }

    /// Translate DELETE statement
    pub fn translate_delete(stmt: &DeleteStatement) -> Result<DeleteTranslation> {
        // Validate
        DynamoDBValidator::validate_delete(stmt)?;

        // Extract key from WHERE clause
        let pk_cond = stmt
            .where_clause
            .get_condition("pk")
            .ok_or_else(|| Error::InvalidQuery("DELETE must specify pk in WHERE clause".into()))?;
        let pk_bytes = Self::value_to_bytes(&pk_cond.value)?;

        let sk_bytes = stmt
            .where_clause
            .get_condition("sk")
            .map(|c| Self::value_to_bytes(&c.value))
            .transpose()?;

        let key = if let Some(sk) = sk_bytes {
            Key::with_sk(pk_bytes.to_vec(), sk.to_vec())
        } else {
            Key::new(pk_bytes.to_vec())
        };

        Ok(DeleteTranslation { key })
    }
}

/// SELECT statement translation result
#[derive(Debug)]
pub enum SelectTranslation {
    /// Query operation (single partition)
    Query {
        pk: Bytes,
        sk_condition: Option<SortKeyConditionType>,
        index_name: Option<String>,
        forward: bool,
    },
    /// Multiple get operations (IN clause on pk)
    MultiGet {
        keys: Vec<Bytes>,
        index_name: Option<String>,
    },
    /// Scan operation (full table scan)
    Scan {
        filter_conditions: Vec<Condition>,
    },
}

/// Sort key condition type
#[derive(Debug, Clone)]
pub enum SortKeyConditionType {
    Equal(Bytes),
    LessThan(Bytes),
    LessThanOrEqual(Bytes),
    GreaterThan(Bytes),
    GreaterThanOrEqual(Bytes),
    Between(Bytes, Bytes),
}

/// INSERT translation result
#[derive(Debug)]
pub struct InsertTranslation {
    pub key: Key,
    pub item: crate::Item,
}

/// UPDATE translation result
#[derive(Debug)]
pub struct UpdateTranslation {
    pub key: Key,
    pub expression: String,
    pub values: std::collections::HashMap<String, crate::Value>,
}

/// DELETE translation result
#[derive(Debug)]
pub struct DeleteTranslation {
    pub key: Key,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_translate_select_query() {
        let stmt = SelectStatement {
            table_name: "users".to_string(),
            index_name: None,
            select_list: SelectList::All,
            where_clause: Some(WhereClause {
                conditions: vec![Condition {
                    attribute: "pk".to_string(),
                    operator: CompareOp::Equal,
                    value: SqlValue::String("user#123".to_string()),
                }],
            }),
            order_by: None,
            limit: None,
            offset: None,
        };

        let translation = PartiQLTranslator::translate_select(&stmt).unwrap();
        match translation {
            SelectTranslation::Query { pk, .. } => {
                assert_eq!(pk, Bytes::from("user#123"));
            }
            _ => panic!("Expected Query translation"),
        }
    }

    #[test]
    fn test_translate_select_scan() {
        let stmt = SelectStatement {
            table_name: "users".to_string(),
            index_name: None,
            select_list: SelectList::All,
            where_clause: None,
            order_by: None,
            limit: None,
            offset: None,
        };

        let translation = PartiQLTranslator::translate_select(&stmt).unwrap();
        match translation {
            SelectTranslation::Scan { .. } => {}
            _ => panic!("Expected Scan translation"),
        }
    }

    #[test]
    fn test_translate_insert() {
        let mut map = std::collections::HashMap::new();
        map.insert("pk".to_string(), SqlValue::String("user#123".to_string()));
        map.insert("name".to_string(), SqlValue::String("Alice".to_string()));
        map.insert("age".to_string(), SqlValue::Number("30".to_string()));

        let stmt = InsertStatement {
            table_name: "users".to_string(),
            value: SqlValue::Map(map),
        };

        let translation = PartiQLTranslator::translate_insert(&stmt).unwrap();
        assert_eq!(translation.key.pk.as_ref(), "user#123".as_bytes());
        assert_eq!(translation.item.len(), 2); // name and age (pk/sk excluded)
    }

    #[test]
    fn test_translate_delete() {
        let stmt = DeleteStatement {
            table_name: "users".to_string(),
            where_clause: WhereClause {
                conditions: vec![Condition {
                    attribute: "pk".to_string(),
                    operator: CompareOp::Equal,
                    value: SqlValue::String("user#123".to_string()),
                }],
            },
        };

        let translation = PartiQLTranslator::translate_delete(&stmt).unwrap();
        assert_eq!(translation.key.pk.as_ref(), "user#123".as_bytes());
    }

    #[test]
    fn test_translate_update_simple() {
        let stmt = UpdateStatement {
            table_name: "users".to_string(),
            where_clause: WhereClause {
                conditions: vec![Condition {
                    attribute: "pk".to_string(),
                    operator: CompareOp::Equal,
                    value: SqlValue::String("user#123".to_string()),
                }],
            },
            set_assignments: vec![
                SetAssignment {
                    attribute: "name".to_string(),
                    value: SetValue::Literal(SqlValue::String("Alice".to_string())),
                },
                SetAssignment {
                    attribute: "age".to_string(),
                    value: SetValue::Literal(SqlValue::Number("30".to_string())),
                },
            ],
            remove_attributes: vec![],
        };

        let translation = PartiQLTranslator::translate_update(&stmt).unwrap();
        assert_eq!(translation.key.pk.as_ref(), "user#123".as_bytes());
        assert!(translation.expression.contains("SET"));
        assert_eq!(translation.values.len(), 2); // :v1 and :v2
    }

    #[test]
    fn test_translate_update_with_arithmetic() {
        let stmt = UpdateStatement {
            table_name: "users".to_string(),
            where_clause: WhereClause {
                conditions: vec![Condition {
                    attribute: "pk".to_string(),
                    operator: CompareOp::Equal,
                    value: SqlValue::String("user#123".to_string()),
                }],
            },
            set_assignments: vec![
                SetAssignment {
                    attribute: "age".to_string(),
                    value: SetValue::Add {
                        attribute: "age".to_string(),
                        value: SqlValue::Number("1".to_string()),
                    },
                },
                SetAssignment {
                    attribute: "count".to_string(),
                    value: SetValue::Subtract {
                        attribute: "count".to_string(),
                        value: SqlValue::Number("5".to_string()),
                    },
                },
            ],
            remove_attributes: vec![],
        };

        let translation = PartiQLTranslator::translate_update(&stmt).unwrap();
        assert!(translation.expression.contains("age = age + :v1"));
        assert!(translation.expression.contains("count = count - :v2"));
        assert_eq!(translation.values.len(), 2);
    }

    #[test]
    fn test_translate_update_with_remove() {
        let stmt = UpdateStatement {
            table_name: "users".to_string(),
            where_clause: WhereClause {
                conditions: vec![Condition {
                    attribute: "pk".to_string(),
                    operator: CompareOp::Equal,
                    value: SqlValue::String("user#123".to_string()),
                }],
            },
            set_assignments: vec![SetAssignment {
                attribute: "name".to_string(),
                value: SetValue::Literal(SqlValue::String("Alice".to_string())),
            }],
            remove_attributes: vec!["tags".to_string(), "metadata".to_string()],
        };

        let translation = PartiQLTranslator::translate_update(&stmt).unwrap();
        assert!(translation.expression.contains("SET"));
        assert!(translation.expression.contains("REMOVE tags, metadata"));
        assert_eq!(translation.values.len(), 1); // :v1 for name
    }

    #[test]
    fn test_translate_update_remove_only() {
        let stmt = UpdateStatement {
            table_name: "users".to_string(),
            where_clause: WhereClause {
                conditions: vec![
                    Condition {
                        attribute: "pk".to_string(),
                        operator: CompareOp::Equal,
                        value: SqlValue::String("user#123".to_string()),
                    },
                    Condition {
                        attribute: "sk".to_string(),
                        operator: CompareOp::Equal,
                        value: SqlValue::String("profile".to_string()),
                    },
                ],
            },
            set_assignments: vec![],
            remove_attributes: vec!["tags".to_string(), "metadata".to_string()],
        };

        let translation = PartiQLTranslator::translate_update(&stmt).unwrap();
        assert_eq!(translation.key.pk.as_ref(), "user#123".as_bytes());
        assert_eq!(translation.key.sk.as_ref().map(|b| b.as_ref()), Some("profile".as_bytes()));
        assert_eq!(translation.expression, "REMOVE tags, metadata");
        assert_eq!(translation.values.len(), 0); // No placeholders needed
    }
}