prax-query 0.9.0

Type-safe query builder for the Prax ORM
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
//! Query context for middleware.

use crate::filter::FilterValue;
use std::collections::HashMap;
use std::time::Instant;

/// The type of query being executed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum QueryType {
    /// SELECT query.
    Select,
    /// INSERT query.
    Insert,
    /// UPDATE query.
    Update,
    /// DELETE query.
    Delete,
    /// COUNT query.
    Count,
    /// Raw SQL query.
    Raw,
    /// Transaction begin.
    TransactionBegin,
    /// Transaction commit.
    TransactionCommit,
    /// Transaction rollback.
    TransactionRollback,
    /// Unknown query type.
    Unknown,
}

impl QueryType {
    /// Detect query type from SQL string.
    pub fn from_sql(sql: &str) -> Self {
        let sql = sql.trim().to_uppercase();
        if sql.starts_with("SELECT") {
            // Check if it's a COUNT query
            if sql.contains("COUNT(") {
                Self::Count
            } else {
                Self::Select
            }
        } else if sql.starts_with("INSERT") {
            Self::Insert
        } else if sql.starts_with("UPDATE") {
            Self::Update
        } else if sql.starts_with("DELETE") {
            Self::Delete
        } else if sql.starts_with("BEGIN") || sql.starts_with("START TRANSACTION") {
            Self::TransactionBegin
        } else if sql.starts_with("COMMIT") {
            Self::TransactionCommit
        } else if sql.starts_with("ROLLBACK") {
            Self::TransactionRollback
        } else {
            Self::Unknown
        }
    }

    /// Check if this is a read operation.
    pub fn is_read(&self) -> bool {
        matches!(self, Self::Select | Self::Count)
    }

    /// Check if this is a write operation.
    pub fn is_write(&self) -> bool {
        matches!(self, Self::Insert | Self::Update | Self::Delete)
    }

    /// Check if this is a transaction operation.
    pub fn is_transaction(&self) -> bool {
        matches!(
            self,
            Self::TransactionBegin | Self::TransactionCommit | Self::TransactionRollback
        )
    }
}

/// The current phase of query execution.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum QueryPhase {
    /// Before the query is executed.
    Before,
    /// During query execution.
    During,
    /// After the query has completed successfully.
    AfterSuccess,
    /// After the query has failed.
    AfterError,
}

/// Metadata about a query.
#[derive(Debug, Clone)]
pub struct QueryMetadata {
    /// The model being queried (if known).
    pub model: Option<String>,
    /// The operation name (e.g., "findMany", "create").
    pub operation: Option<String>,
    /// Request ID for tracing.
    pub request_id: Option<String>,
    /// User ID for auditing.
    pub user_id: Option<String>,
    /// Tenant ID for multi-tenancy.
    pub tenant_id: Option<String>,
    /// Schema override for multi-tenancy.
    pub schema_override: Option<String>,
    /// Custom tags for filtering.
    pub tags: HashMap<String, String>,
    /// Custom attributes.
    pub attributes: HashMap<String, serde_json::Value>,
}

impl Default for QueryMetadata {
    fn default() -> Self {
        Self::new()
    }
}

impl QueryMetadata {
    /// Create new empty metadata.
    pub fn new() -> Self {
        Self {
            model: None,
            operation: None,
            request_id: None,
            user_id: None,
            tenant_id: None,
            schema_override: None,
            tags: HashMap::new(),
            attributes: HashMap::new(),
        }
    }

    /// Set the model name.
    pub fn with_model(mut self, model: impl Into<String>) -> Self {
        self.model = Some(model.into());
        self
    }

    /// Set the operation name.
    pub fn with_operation(mut self, operation: impl Into<String>) -> Self {
        self.operation = Some(operation.into());
        self
    }

    /// Set the request ID.
    pub fn with_request_id(mut self, id: impl Into<String>) -> Self {
        self.request_id = Some(id.into());
        self
    }

    /// Set the user ID.
    pub fn with_user_id(mut self, id: impl Into<String>) -> Self {
        self.user_id = Some(id.into());
        self
    }

    /// Set the tenant ID.
    pub fn with_tenant_id(mut self, id: impl Into<String>) -> Self {
        self.tenant_id = Some(id.into());
        self
    }

    /// Add a tag.
    pub fn with_tag(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.tags.insert(key.into(), value.into());
        self
    }

    /// Add an attribute.
    pub fn with_attribute(mut self, key: impl Into<String>, value: serde_json::Value) -> Self {
        self.attributes.insert(key.into(), value);
        self
    }

    /// Set the schema override for multi-tenancy.
    pub fn set_schema_override(&mut self, schema: Option<String>) {
        self.schema_override = schema;
    }

    /// Get the schema override.
    pub fn schema_override(&self) -> Option<&str> {
        self.schema_override.as_deref()
    }
}

/// Context passed through the middleware chain.
#[derive(Debug, Clone)]
pub struct QueryContext {
    /// The SQL query string.
    sql: String,
    /// Query parameters.
    params: Vec<FilterValue>,
    /// Query type.
    query_type: QueryType,
    /// Query metadata.
    metadata: QueryMetadata,
    /// When the query started.
    started_at: Instant,
    /// Current execution phase.
    phase: QueryPhase,
    /// Whether the query should be skipped (e.g., cache hit).
    skip_execution: bool,
    /// Cached response (if skipping execution).
    cached_response: Option<serde_json::Value>,
}

impl QueryContext {
    /// Create a new query context.
    pub fn new(sql: impl Into<String>, params: Vec<FilterValue>) -> Self {
        let sql = sql.into();
        let query_type = QueryType::from_sql(&sql);
        Self {
            sql,
            params,
            query_type,
            metadata: QueryMetadata::new(),
            started_at: Instant::now(),
            phase: QueryPhase::Before,
            skip_execution: false,
            cached_response: None,
        }
    }

    /// Get the SQL string.
    pub fn sql(&self) -> &str {
        &self.sql
    }

    /// Get mutable SQL string (for query modification).
    pub fn sql_mut(&mut self) -> &mut String {
        &mut self.sql
    }

    /// Set a new SQL string.
    pub fn set_sql(&mut self, sql: impl Into<String>) {
        self.sql = sql.into();
        self.query_type = QueryType::from_sql(&self.sql);
    }

    /// Set a new SQL string (builder pattern).
    pub fn with_sql(mut self, sql: impl Into<String>) -> Self {
        self.set_sql(sql);
        self
    }

    /// Get the query parameters.
    pub fn params(&self) -> &[FilterValue] {
        &self.params
    }

    /// Get mutable parameters.
    pub fn params_mut(&mut self) -> &mut Vec<FilterValue> {
        &mut self.params
    }

    /// Get the query type.
    pub fn query_type(&self) -> QueryType {
        self.query_type
    }

    /// Get the metadata.
    pub fn metadata(&self) -> &QueryMetadata {
        &self.metadata
    }

    /// Get mutable metadata.
    pub fn metadata_mut(&mut self) -> &mut QueryMetadata {
        &mut self.metadata
    }

    /// Set metadata.
    pub fn with_metadata(mut self, metadata: QueryMetadata) -> Self {
        self.metadata = metadata;
        self
    }

    /// Get elapsed time since query started.
    pub fn elapsed(&self) -> std::time::Duration {
        self.started_at.elapsed()
    }

    /// Get elapsed time in microseconds.
    pub fn elapsed_us(&self) -> u64 {
        self.started_at.elapsed().as_micros() as u64
    }

    /// Get the current phase.
    pub fn phase(&self) -> QueryPhase {
        self.phase
    }

    /// Set the current phase.
    pub fn set_phase(&mut self, phase: QueryPhase) {
        self.phase = phase;
    }

    /// Check if execution should be skipped.
    pub fn should_skip(&self) -> bool {
        self.skip_execution
    }

    /// Mark query to skip execution (e.g., for cache hit).
    pub fn skip_with_response(&mut self, response: serde_json::Value) {
        self.skip_execution = true;
        self.cached_response = Some(response);
    }

    /// Get the cached response if skipping.
    pub fn cached_response(&self) -> Option<&serde_json::Value> {
        self.cached_response.as_ref()
    }

    /// Check if this is a read query.
    pub fn is_read(&self) -> bool {
        self.query_type.is_read()
    }

    /// Check if this is a write query.
    pub fn is_write(&self) -> bool {
        self.query_type.is_write()
    }
}

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

    #[test]
    fn test_query_type_detection() {
        assert_eq!(
            QueryType::from_sql("SELECT * FROM users"),
            QueryType::Select
        );
        assert_eq!(
            QueryType::from_sql("INSERT INTO users VALUES (1)"),
            QueryType::Insert
        );
        assert_eq!(
            QueryType::from_sql("UPDATE users SET name = 'test'"),
            QueryType::Update
        );
        assert_eq!(
            QueryType::from_sql("DELETE FROM users WHERE id = 1"),
            QueryType::Delete
        );
        assert_eq!(
            QueryType::from_sql("SELECT COUNT(*) FROM users"),
            QueryType::Count
        );
        assert_eq!(QueryType::from_sql("BEGIN"), QueryType::TransactionBegin);
        assert_eq!(QueryType::from_sql("COMMIT"), QueryType::TransactionCommit);
        assert_eq!(
            QueryType::from_sql("ROLLBACK"),
            QueryType::TransactionRollback
        );
    }

    #[test]
    fn test_query_type_categories() {
        assert!(QueryType::Select.is_read());
        assert!(QueryType::Count.is_read());
        assert!(!QueryType::Insert.is_read());

        assert!(QueryType::Insert.is_write());
        assert!(QueryType::Update.is_write());
        assert!(QueryType::Delete.is_write());
        assert!(!QueryType::Select.is_write());

        assert!(QueryType::TransactionBegin.is_transaction());
        assert!(QueryType::TransactionCommit.is_transaction());
        assert!(QueryType::TransactionRollback.is_transaction());
    }

    #[test]
    fn test_query_context() {
        let ctx = QueryContext::new("SELECT * FROM users", vec![]);
        assert_eq!(ctx.sql(), "SELECT * FROM users");
        assert_eq!(ctx.query_type(), QueryType::Select);
        assert!(ctx.is_read());
        assert!(!ctx.is_write());
    }

    #[test]
    fn test_query_metadata() {
        let metadata = QueryMetadata::new()
            .with_model("User")
            .with_operation("findMany")
            .with_request_id("req-123")
            .with_tag("env", "production");

        assert_eq!(metadata.model, Some("User".to_string()));
        assert_eq!(metadata.operation, Some("findMany".to_string()));
        assert_eq!(metadata.tags.get("env"), Some(&"production".to_string()));
    }

    #[test]
    fn test_context_skip_execution() {
        let mut ctx = QueryContext::new("SELECT * FROM users", vec![]);
        assert!(!ctx.should_skip());

        ctx.skip_with_response(serde_json::json!({"cached": true}));
        assert!(ctx.should_skip());
        assert!(ctx.cached_response().is_some());
    }
}