what-core 1.7.1

Core framework for What - an HTML-first web framework powered by Rust
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
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
//! Database Adapter — unified interface for SQLite, Cloudflare D1, and Supabase backends
//!
//! Configured via `[database]` in `what.toml`. Defaults to SQLite when no config is present.

use serde_json::Value;
use std::collections::HashMap;

use crate::Result;

mod sqlite;
pub use sqlite::SqliteDatabase;

pub mod d1;
pub use d1::D1Database;

pub mod supabase;
pub use supabase::SupabaseDatabase;

/// Query options for collection retrieval
#[derive(Debug, Default, Clone)]
pub struct CollectionQuery {
    /// Sort expression: "field:asc" or "field:desc"
    pub sort: Option<String>,
    /// Filter expression: "field=value", "field>N", joined by "&" (AND) or "," (OR)
    pub filter: Option<String>,
    /// Full-text search term
    pub search: Option<String>,
    /// Fields to search in (comma-separated)
    pub search_fields: Option<String>,
    /// Max items to return
    pub limit: Option<usize>,
    /// Items to skip
    pub offset: Option<usize>,
    /// Mandatory scope filters AND-ed into every query regardless of the
    /// user-supplied `filter`. Set by authorization policies (owner/tenant
    /// scoping) — the user cannot widen past these. Each string uses the same
    /// mini-language as `filter` (comma = OR, `&` = AND).
    pub forced_filters: Vec<String>,
}

/// Unified database adapter — dispatches to SQLite, D1, or Supabase
#[derive(Clone)]
pub enum DatabaseAdapter {
    Sqlite(SqliteDatabase),
    D1(D1Database),
    Supabase(SupabaseDatabase),
}

impl DatabaseAdapter {
    /// Get all items from a collection (with optional query parameters)
    pub async fn get_collection(&self, name: &str) -> Option<Vec<Value>> {
        match self {
            Self::Sqlite(db) => db
                .get_collection(name)
                .await
                .map_err(|e| {
                    tracing::warn!("SQLite get_collection '{}' error: {}", name, e);
                    e
                })
                .ok(),
            Self::D1(db) => db
                .get_collection(name)
                .await
                .map_err(|e| {
                    tracing::warn!("D1 get_collection '{}' error: {}", name, e);
                    e
                })
                .ok(),
            Self::Supabase(db) => db
                .get_collection(name)
                .await
                .map_err(|e| {
                    tracing::warn!("Supabase get_collection '{}' error: {}", name, e);
                    e
                })
                .ok(),
        }
    }

    /// Get items with query options (sort, filter, search, limit, offset)
    pub async fn query_collection(
        &self,
        name: &str,
        query: &CollectionQuery,
    ) -> Option<Vec<Value>> {
        match self {
            Self::Sqlite(db) => db
                .query_collection(name, query)
                .await
                .map_err(|e| {
                    tracing::warn!("SQLite query_collection '{}' error: {}", name, e);
                    e
                })
                .ok(),
            Self::D1(db) => db
                .query_collection(name, query)
                .await
                .map_err(|e| {
                    tracing::warn!("D1 query_collection '{}' error: {}", name, e);
                    e
                })
                .ok(),
            Self::Supabase(db) => db
                .query_collection(name, query)
                .await
                .map_err(|e| {
                    tracing::warn!("Supabase query_collection '{}' error: {}", name, e);
                    e
                })
                .ok(),
        }
    }

    /// Find items by a field value
    pub async fn find_by(&self, collection: &str, field: &str, value: &Value) -> Vec<Value> {
        match self {
            Self::Sqlite(db) => db
                .find_by(collection, field, value)
                .await
                .unwrap_or_else(|e| {
                    tracing::warn!("SQLite find_by '{}.{}' error: {}", collection, field, e);
                    Vec::new()
                }),
            Self::D1(db) => db
                .find_by(collection, field, value)
                .await
                .unwrap_or_else(|e| {
                    tracing::warn!("D1 find_by '{}.{}' error: {}", collection, field, e);
                    Vec::new()
                }),
            Self::Supabase(db) => db
                .find_by(collection, field, value)
                .await
                .unwrap_or_else(|e| {
                    tracing::warn!("Supabase find_by '{}.{}' error: {}", collection, field, e);
                    Vec::new()
                }),
        }
    }

    /// Find a single item by field value
    pub async fn find_one_by(&self, collection: &str, field: &str, value: &Value) -> Option<Value> {
        match self {
            Self::Sqlite(db) => db
                .find_one_by(collection, field, value)
                .await
                .map_err(|e| {
                    tracing::warn!("SQLite find_one_by '{}.{}' error: {}", collection, field, e);
                    e
                })
                .ok()
                .flatten(),
            Self::D1(db) => db
                .find_one_by(collection, field, value)
                .await
                .map_err(|e| {
                    tracing::warn!("D1 find_one_by '{}.{}' error: {}", collection, field, e);
                    e
                })
                .ok()
                .flatten(),
            Self::Supabase(db) => db
                .find_one_by(collection, field, value)
                .await
                .map_err(|e| {
                    tracing::warn!(
                        "Supabase find_one_by '{}.{}' error: {}",
                        collection,
                        field,
                        e
                    );
                    e
                })
                .ok()
                .flatten(),
        }
    }

    /// Create an item in a collection
    pub async fn create(&self, collection: &str, item: Value) -> Result<Value> {
        match self {
            Self::Sqlite(db) => db.create(collection, item).await,
            Self::D1(db) => db.create(collection, item).await,
            Self::Supabase(db) => db.create(collection, item).await,
        }
    }

    /// Update an item by ID
    pub async fn update(
        &self,
        collection: &str,
        id: &Value,
        updates: Value,
    ) -> Result<Option<Value>> {
        match self {
            Self::Sqlite(db) => db.update(collection, id, updates).await,
            Self::D1(db) => db.update(collection, id, updates).await,
            Self::Supabase(db) => db.update(collection, id, updates).await,
        }
    }

    /// Delete an item by ID
    pub async fn delete(&self, collection: &str, id: &Value) -> Result<bool> {
        match self {
            Self::Sqlite(db) => db.delete(collection, id).await,
            Self::D1(db) => db.delete(collection, id).await,
            Self::Supabase(db) => db.delete(collection, id).await,
        }
    }

    /// Set a key-value pair
    pub async fn set(&self, key: &str, value: Value) -> Result<()> {
        match self {
            Self::Sqlite(db) => db.set(key, value).await,
            Self::D1(db) => db.set(key, value).await,
            Self::Supabase(db) => db.set(key, value).await,
        }
    }

    /// Get a value by key
    pub async fn get(&self, key: &str) -> Option<Value> {
        match self {
            Self::Sqlite(db) => db
                .get(key)
                .await
                .map_err(|e| {
                    tracing::warn!("SQLite get '{}' error: {}", key, e);
                    e
                })
                .ok()
                .flatten(),
            Self::D1(db) => db
                .get(key)
                .await
                .map_err(|e| {
                    tracing::warn!("D1 get '{}' error: {}", key, e);
                    e
                })
                .ok()
                .flatten(),
            Self::Supabase(db) => db
                .get(key)
                .await
                .map_err(|e| {
                    tracing::warn!("Supabase get '{}' error: {}", key, e);
                    e
                })
                .ok()
                .flatten(),
        }
    }

    /// Get all data as a template context
    pub async fn as_context(&self) -> HashMap<String, Value> {
        match self {
            Self::Sqlite(db) => db.as_context().await.unwrap_or_else(|e| {
                tracing::warn!("SQLite as_context error: {}", e);
                HashMap::new()
            }),
            Self::D1(db) => db.as_context().await.unwrap_or_else(|e| {
                tracing::warn!("D1 as_context error: {}", e);
                HashMap::new()
            }),
            Self::Supabase(db) => db.as_context().await.unwrap_or_else(|e| {
                tracing::warn!("Supabase as_context error: {}", e);
                HashMap::new()
            }),
        }
    }

    /// Replace an entire collection
    pub async fn set_collection(&self, name: &str, items: Vec<Value>) -> Result<()> {
        match self {
            Self::Sqlite(db) => db.set_collection(name, items).await,
            Self::D1(db) => db.set_collection(name, items).await,
            Self::Supabase(db) => db.set_collection(name, items).await,
        }
    }

    /// Load collection from a file path (no-op for database backends)
    pub async fn load_collection(
        &self,
        _name: &str,
        _path: impl AsRef<std::path::Path>,
    ) -> Result<()> {
        Ok(())
    }

    /// Atomically modify a key-value
    pub async fn atomic_modify<F>(&self, key: &str, f: F) -> Result<Value>
    where
        F: FnOnce(Option<&Value>) -> Value + Send + 'static,
    {
        match self {
            Self::Sqlite(db) => db.atomic_modify(key, f).await,
            Self::D1(db) => db.atomic_modify(key, f).await,
            Self::Supabase(db) => db.atomic_modify(key, f).await,
        }
    }

    /// Delete a key-value pair
    pub async fn remove(&self, key: &str) -> Result<Option<Value>> {
        match self {
            Self::Sqlite(db) => db.remove(key).await,
            Self::D1(db) => db.remove(key).await,
            Self::Supabase(db) => db.remove(key).await,
        }
    }
}

// ---------------------------------------------------------------------------
// In-memory query helpers (used by tests)
// ---------------------------------------------------------------------------

#[cfg(test)]
fn apply_query_in_memory(mut items: Vec<Value>, query: &CollectionQuery) -> Vec<Value> {
    // Filter
    if let Some(ref filter_expr) = query.filter {
        items = apply_filter(&items, filter_expr);
    }

    // Search
    if let Some(ref search_term) = query.search {
        if !search_term.is_empty() {
            let fields: Vec<&str> = query
                .search_fields
                .as_deref()
                .map(|s| s.split(',').collect())
                .unwrap_or_default();
            let term_lower = search_term.to_lowercase();
            items.retain(|item| {
                if fields.is_empty() {
                    // Search all string fields
                    if let Value::Object(map) = item {
                        map.values().any(|v| {
                            v.as_str()
                                .map(|s| s.to_lowercase().contains(&term_lower))
                                .unwrap_or(false)
                        })
                    } else {
                        false
                    }
                } else {
                    fields.iter().any(|field| {
                        item.get(field.trim())
                            .and_then(|v| v.as_str())
                            .map(|s| s.to_lowercase().contains(&term_lower))
                            .unwrap_or(false)
                    })
                }
            });
        }
    }

    // Sort
    if let Some(ref sort_expr) = query.sort {
        let (field, descending) = parse_sort_expr(sort_expr);
        items.sort_by(|a, b| {
            let va = a.get(&field);
            let vb = b.get(&field);
            let cmp = compare_json_values(va, vb);
            if descending { cmp.reverse() } else { cmp }
        });
    }

    // Offset
    if let Some(offset) = query.offset {
        if offset < items.len() {
            items = items[offset..].to_vec();
        } else {
            items.clear();
        }
    }

    // Limit
    if let Some(limit) = query.limit {
        items.truncate(limit);
    }

    items
}

#[cfg(test)]
fn parse_sort_expr(expr: &str) -> (String, bool) {
    if let Some((field, dir)) = expr.rsplit_once(':') {
        (field.to_string(), dir.eq_ignore_ascii_case("desc"))
    } else {
        (expr.to_string(), false)
    }
}

#[cfg(test)]
fn compare_json_values(a: Option<&Value>, b: Option<&Value>) -> std::cmp::Ordering {
    match (a, b) {
        (None, None) => std::cmp::Ordering::Equal,
        (None, Some(_)) => std::cmp::Ordering::Less,
        (Some(_), None) => std::cmp::Ordering::Greater,
        (Some(a), Some(b)) => {
            // Try numeric comparison first
            if let (Some(na), Some(nb)) = (a.as_f64(), b.as_f64()) {
                return na.partial_cmp(&nb).unwrap_or(std::cmp::Ordering::Equal);
            }
            // Fall back to string comparison
            let sa = a.as_str().unwrap_or("");
            let sb = b.as_str().unwrap_or("");
            sa.cmp(sb)
        }
    }
}

#[cfg(test)]
fn apply_filter(items: &[Value], filter_expr: &str) -> Vec<Value> {
    // Support OR (comma) at top level, AND (&) within groups
    let or_groups: Vec<&str> = filter_expr.split(',').collect();

    items
        .iter()
        .filter(|item| {
            or_groups.iter().any(|group| {
                let and_conditions: Vec<&str> = group.split('&').collect();
                and_conditions.iter().all(|cond| {
                    let cond = cond.trim();
                    evaluate_condition(item, cond)
                })
            })
        })
        .cloned()
        .collect()
}

#[cfg(test)]
fn evaluate_condition(item: &Value, cond: &str) -> bool {
    if let Some((field, val)) = cond.split_once(">=") {
        let field = field.trim();
        let val = val.trim();
        item.get(field)
            .map(|v| {
                if let (Some(n), Ok(target)) = (v.as_f64(), val.parse::<f64>()) {
                    n >= target
                } else {
                    v.as_str().unwrap_or("") >= val
                }
            })
            .unwrap_or(false)
    } else if let Some((field, val)) = cond.split_once("<=") {
        let field = field.trim();
        let val = val.trim();
        item.get(field)
            .map(|v| {
                if let (Some(n), Ok(target)) = (v.as_f64(), val.parse::<f64>()) {
                    n <= target
                } else {
                    v.as_str().unwrap_or("") <= val
                }
            })
            .unwrap_or(false)
    } else if let Some((field, val)) = cond.split_once('>') {
        let field = field.trim();
        let val = val.trim();
        item.get(field)
            .map(|v| {
                if let (Some(n), Ok(target)) = (v.as_f64(), val.parse::<f64>()) {
                    n > target
                } else {
                    v.as_str().unwrap_or("") > val
                }
            })
            .unwrap_or(false)
    } else if let Some((field, val)) = cond.split_once('<') {
        let field = field.trim();
        let val = val.trim();
        item.get(field)
            .map(|v| {
                if let (Some(n), Ok(target)) = (v.as_f64(), val.parse::<f64>()) {
                    n < target
                } else {
                    v.as_str().unwrap_or("") < val
                }
            })
            .unwrap_or(false)
    } else if let Some((field, val)) = cond.split_once('=') {
        let field = field.trim();
        let val = val.trim();
        item.get(field)
            .map(|v| match v {
                Value::String(s) => s == val,
                Value::Number(n) => n.to_string() == val,
                Value::Bool(b) => b.to_string() == val,
                _ => false,
            })
            .unwrap_or(false)
    } else {
        true // Unknown condition format — don't filter
    }
}

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

    #[test]
    fn test_sort_asc() {
        let items = vec![
            json!({"name": "Charlie", "age": 30}),
            json!({"name": "Alice", "age": 25}),
            json!({"name": "Bob", "age": 28}),
        ];
        let query = CollectionQuery {
            sort: Some("name:asc".to_string()),
            ..Default::default()
        };
        let result = apply_query_in_memory(items, &query);
        assert_eq!(result[0]["name"], "Alice");
        assert_eq!(result[1]["name"], "Bob");
        assert_eq!(result[2]["name"], "Charlie");
    }

    #[test]
    fn test_sort_desc() {
        let items = vec![
            json!({"name": "Alice", "age": 25}),
            json!({"name": "Bob", "age": 28}),
            json!({"name": "Charlie", "age": 30}),
        ];
        let query = CollectionQuery {
            sort: Some("age:desc".to_string()),
            ..Default::default()
        };
        let result = apply_query_in_memory(items, &query);
        assert_eq!(result[0]["age"], 30);
        assert_eq!(result[1]["age"], 28);
        assert_eq!(result[2]["age"], 25);
    }

    #[test]
    fn test_filter_exact() {
        let items = vec![
            json!({"status": "published", "title": "A"}),
            json!({"status": "draft", "title": "B"}),
            json!({"status": "published", "title": "C"}),
        ];
        let query = CollectionQuery {
            filter: Some("status=published".to_string()),
            ..Default::default()
        };
        let result = apply_query_in_memory(items, &query);
        assert_eq!(result.len(), 2);
    }

    #[test]
    fn test_filter_comparison() {
        let items = vec![
            json!({"price": 10}),
            json!({"price": 25}),
            json!({"price": 50}),
        ];
        let query = CollectionQuery {
            filter: Some("price>20".to_string()),
            ..Default::default()
        };
        let result = apply_query_in_memory(items, &query);
        assert_eq!(result.len(), 2);
    }

    #[test]
    fn test_filter_and() {
        let items = vec![
            json!({"status": "published", "category": "tech"}),
            json!({"status": "published", "category": "food"}),
            json!({"status": "draft", "category": "tech"}),
        ];
        let query = CollectionQuery {
            filter: Some("status=published&category=tech".to_string()),
            ..Default::default()
        };
        let result = apply_query_in_memory(items, &query);
        assert_eq!(result.len(), 1);
    }

    #[test]
    fn test_filter_or() {
        let items = vec![
            json!({"status": "published"}),
            json!({"status": "draft"}),
            json!({"status": "archived"}),
        ];
        let query = CollectionQuery {
            filter: Some("status=published,status=draft".to_string()),
            ..Default::default()
        };
        let result = apply_query_in_memory(items, &query);
        assert_eq!(result.len(), 2);
    }

    #[test]
    fn test_search() {
        let items = vec![
            json!({"title": "Rust Programming", "content": "Learn Rust"}),
            json!({"title": "Python Basics", "content": "Learn Python"}),
            json!({"title": "Rust Web Dev", "content": "Build web apps"}),
        ];
        let query = CollectionQuery {
            search: Some("rust".to_string()),
            search_fields: Some("title,content".to_string()),
            ..Default::default()
        };
        let result = apply_query_in_memory(items, &query);
        assert_eq!(result.len(), 2);
    }

    #[test]
    fn test_limit_offset() {
        let items: Vec<Value> = (1..=10).map(|i| json!({"n": i})).collect();
        let query = CollectionQuery {
            offset: Some(3),
            limit: Some(2),
            ..Default::default()
        };
        let result = apply_query_in_memory(items, &query);
        assert_eq!(result.len(), 2);
        assert_eq!(result[0]["n"], 4);
        assert_eq!(result[1]["n"], 5);
    }

    #[test]
    fn test_combined_query() {
        let items = vec![
            json!({"title": "Rust A", "views": 100, "status": "published"}),
            json!({"title": "Rust B", "views": 50, "status": "draft"}),
            json!({"title": "Python", "views": 200, "status": "published"}),
            json!({"title": "Rust C", "views": 150, "status": "published"}),
        ];
        let query = CollectionQuery {
            filter: Some("status=published".to_string()),
            sort: Some("views:desc".to_string()),
            limit: Some(2),
            ..Default::default()
        };
        let result = apply_query_in_memory(items, &query);
        assert_eq!(result.len(), 2);
        assert_eq!(result[0]["title"], "Python");
        assert_eq!(result[1]["title"], "Rust C");
    }
}