hyperdb-api 0.1.1

Pure Rust API for Hyper database
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 (c) 2026, Salesforce, Inc. All rights reserved.
// SPDX-License-Identifier: Apache-2.0 OR MIT

//! Parameter encoding for parameterized queries.
//!
//! This module provides the [`ToSqlParam`] trait for type-safe parameter encoding
//! in parameterized SQL queries, preventing SQL injection attacks.
//!
//! # SQL Injection Prevention
//!
//! Using parameterized queries is the safest way to include user input in SQL:
//!
//! ```no_run
//! # use hyperdb_api::{Connection, Result};
//! # fn example(conn: &Connection, user_input: &str) -> Result<()> {
//! // DANGEROUS - vulnerable to SQL injection:
//! let query = format!("SELECT * FROM users WHERE name = '{}'", user_input);
//!
//! // SAFE - parameterized query:
//! let result = conn.query_params("SELECT * FROM users WHERE name = $1", &[&user_input])?;
//! # Ok(())
//! # }
//! ```
//!
//! # Supported Types
//!
//! The following types implement [`ToSqlParam`]:
//!
//! - Integers: `i16`, `i32`, `i64`
//! - Floats: `f32`, `f64`
//! - `bool`
//! - `&str`, `String`
//! - `Option<T>` where `T: ToSqlParam` (for nullable parameters)
//! - Date/time types: `Date`, `Time`, `Timestamp`, `OffsetTimestamp`
//!
//! # Example
//!
//! ```no_run
//! use hyperdb_api::{Connection, CreateMode, ToSqlParam, Result};
//!
//! fn find_user(conn: &Connection, user_id: i32, name: &str) -> Result<()> {
//!     // Multiple parameters with different types
//!     let result = conn.query_params(
//!         "SELECT * FROM users WHERE id = $1 AND name = $2",
//!         &[&user_id, &name],
//!     )?;
//!     Ok(())
//! }
//! ```

use hyperdb_api_core::types::{oids, Date, OffsetTimestamp, Oid, Time, Timestamp};

/// Trait for types that can be used as parameters in parameterized SQL queries.
///
/// This trait enables type-safe parameter encoding for use with
/// [`Connection::query_params`](crate::Connection::query_params) and
/// [`Connection::command_params`](crate::Connection::command_params).
///
/// # Implementing for Custom Types
///
/// You can implement this trait for custom types:
///
/// ```no_run
/// # use hyperdb_api::ToSqlParam;
/// # struct MyType;
/// # impl MyType { fn to_bytes(&self) -> Vec<u8> { vec![] } }
/// # impl ToString for MyType { fn to_string(&self) -> String { String::new() } }
/// impl ToSqlParam for MyType {
///     fn encode_param(&self) -> Option<Vec<u8>> {
///         Some(self.to_bytes())
///     }
///
///     fn to_sql_literal(&self) -> String {
///         format!("'{}'", self.to_string().replace('\'', "''"))
///     }
/// }
/// ```
pub trait ToSqlParam: Send + Sync {
    /// Encodes this value as binary bytes for use in parameterized queries.
    ///
    /// Returns `None` to represent a SQL NULL value.
    /// Returns `Some(bytes)` with the binary-encoded value otherwise.
    fn encode_param(&self) -> Option<Vec<u8>>;

    /// Returns the SQL type OID this parameter should bind as.
    ///
    /// The default returns `Oid(0)` (unspecified) which asks the server
    /// to infer the type from surrounding SQL context. That works for
    /// clauses like `WHERE column = $1` where the column type is known,
    /// but not for `INSERT INTO t VALUES ($1, $2)` — those require the
    /// caller (or the trait impl) to return a concrete OID.
    ///
    /// All built-in `ToSqlParam` impls override this with a concrete
    /// value from [`hyperdb_api_core::types::oids`].
    fn sql_oid(&self) -> Oid {
        Oid::new(0)
    }

    /// Returns the SQL literal representation of this value.
    ///
    /// Retained for building DDL statement strings that cannot use
    /// parameterized queries (e.g. `escape_sql_path` in catalog code).
    /// The parameterized-query path in
    /// [`Connection::query_params`](crate::Connection::query_params)
    /// no longer uses this method — parameters travel as binary bytes
    /// via `encode_param`.
    fn to_sql_literal(&self) -> String;
}

// =============================================================================
// Integer implementations
// =============================================================================

impl ToSqlParam for i16 {
    fn encode_param(&self) -> Option<Vec<u8>> {
        // PostgreSQL wire-protocol Bind uses big-endian for numeric
        // binary parameters. (Results come back as little-endian
        // HyperBinary because we request format code 2 for results;
        // params use format code 1 = standard PG binary = BE.)
        Some(self.to_be_bytes().to_vec())
    }

    fn sql_oid(&self) -> Oid {
        oids::SMALL_INT
    }

    fn to_sql_literal(&self) -> String {
        self.to_string()
    }
}

impl ToSqlParam for i32 {
    fn encode_param(&self) -> Option<Vec<u8>> {
        Some(self.to_be_bytes().to_vec())
    }

    fn sql_oid(&self) -> Oid {
        oids::INT
    }

    fn to_sql_literal(&self) -> String {
        self.to_string()
    }
}

impl ToSqlParam for i64 {
    fn encode_param(&self) -> Option<Vec<u8>> {
        Some(self.to_be_bytes().to_vec())
    }

    fn sql_oid(&self) -> Oid {
        oids::BIG_INT
    }

    fn to_sql_literal(&self) -> String {
        self.to_string()
    }
}

// =============================================================================
// Float implementations
// =============================================================================

impl ToSqlParam for f32 {
    fn encode_param(&self) -> Option<Vec<u8>> {
        Some(self.to_be_bytes().to_vec())
    }

    fn sql_oid(&self) -> Oid {
        oids::FLOAT
    }

    fn to_sql_literal(&self) -> String {
        // Handle special float values
        if self.is_nan() {
            "'NaN'".to_string()
        } else if self.is_infinite() {
            if *self > 0.0 {
                "'Infinity'".to_string()
            } else {
                "'-Infinity'".to_string()
            }
        } else {
            self.to_string()
        }
    }
}

impl ToSqlParam for f64 {
    fn encode_param(&self) -> Option<Vec<u8>> {
        Some(self.to_be_bytes().to_vec())
    }

    fn sql_oid(&self) -> Oid {
        oids::DOUBLE
    }

    fn to_sql_literal(&self) -> String {
        // Handle special float values
        if self.is_nan() {
            "'NaN'".to_string()
        } else if self.is_infinite() {
            if *self > 0.0 {
                "'Infinity'".to_string()
            } else {
                "'-Infinity'".to_string()
            }
        } else {
            self.to_string()
        }
    }
}

// =============================================================================
// Boolean implementation
// =============================================================================

impl ToSqlParam for bool {
    fn encode_param(&self) -> Option<Vec<u8>> {
        Some(vec![u8::from(*self)])
    }

    fn sql_oid(&self) -> Oid {
        oids::BOOL
    }

    fn to_sql_literal(&self) -> String {
        if *self { "TRUE" } else { "FALSE" }.to_string()
    }
}

// =============================================================================
// String implementations
// =============================================================================

impl ToSqlParam for str {
    fn encode_param(&self) -> Option<Vec<u8>> {
        Some(self.as_bytes().to_vec())
    }

    fn sql_oid(&self) -> Oid {
        oids::TEXT
    }

    fn to_sql_literal(&self) -> String {
        // Escape single quotes by doubling them
        format!("'{}'", self.replace('\'', "''"))
    }
}

impl ToSqlParam for String {
    fn encode_param(&self) -> Option<Vec<u8>> {
        Some(self.as_bytes().to_vec())
    }

    fn sql_oid(&self) -> Oid {
        oids::TEXT
    }

    fn to_sql_literal(&self) -> String {
        format!("'{}'", self.replace('\'', "''"))
    }
}

impl ToSqlParam for &str {
    fn encode_param(&self) -> Option<Vec<u8>> {
        Some(self.as_bytes().to_vec())
    }

    fn sql_oid(&self) -> Oid {
        oids::TEXT
    }

    fn to_sql_literal(&self) -> String {
        format!("'{}'", self.replace('\'', "''"))
    }
}

// =============================================================================
// Reference implementations
// =============================================================================

impl<T: ToSqlParam> ToSqlParam for &T {
    fn encode_param(&self) -> Option<Vec<u8>> {
        (*self).encode_param()
    }

    fn sql_oid(&self) -> Oid {
        (*self).sql_oid()
    }

    fn to_sql_literal(&self) -> String {
        (*self).to_sql_literal()
    }
}

// =============================================================================
// Option implementation (for nullable parameters)
// =============================================================================

impl<T: ToSqlParam> ToSqlParam for Option<T> {
    fn encode_param(&self) -> Option<Vec<u8>> {
        match self {
            Some(value) => value.encode_param(),
            None => None, // SQL NULL
        }
    }

    fn sql_oid(&self) -> Oid {
        match self {
            Some(value) => value.sql_oid(),
            // For NULL we leave the OID unspecified — server infers
            // from context, which is the correct behavior for `WHERE
            // col = $1` with a NULL binding.
            None => Oid::new(0),
        }
    }

    fn to_sql_literal(&self) -> String {
        match self {
            Some(value) => value.to_sql_literal(),
            None => "NULL".to_string(),
        }
    }
}

// =============================================================================
// Date/Time implementations
// =============================================================================

impl ToSqlParam for Date {
    fn encode_param(&self) -> Option<Vec<u8>> {
        // Date is stored as i32 Julian day offset from 2000-01-01.
        // Big-endian per the PG Bind protocol (format code 1).
        Some(self.to_julian_day().to_be_bytes().to_vec())
    }

    fn sql_oid(&self) -> Oid {
        oids::DATE
    }

    fn to_sql_literal(&self) -> String {
        format!("DATE '{self}'")
    }
}

impl ToSqlParam for Time {
    fn encode_param(&self) -> Option<Vec<u8>> {
        // Time is stored as i64 microseconds since midnight.
        Some(self.to_microseconds().to_be_bytes().to_vec())
    }

    fn sql_oid(&self) -> Oid {
        oids::TIME
    }

    fn to_sql_literal(&self) -> String {
        format!("TIME '{self}'")
    }
}

impl ToSqlParam for Timestamp {
    fn encode_param(&self) -> Option<Vec<u8>> {
        // Timestamp is stored as i64 microseconds since 2000-01-01.
        Some(self.to_microseconds().to_be_bytes().to_vec())
    }

    fn sql_oid(&self) -> Oid {
        oids::TIMESTAMP
    }

    fn to_sql_literal(&self) -> String {
        format!("TIMESTAMP '{self}'")
    }
}

impl ToSqlParam for OffsetTimestamp {
    fn encode_param(&self) -> Option<Vec<u8>> {
        // OffsetTimestamp is stored as i64 microseconds UTC since 2000-01-01.
        Some(self.to_microseconds_utc().to_be_bytes().to_vec())
    }

    fn sql_oid(&self) -> Oid {
        oids::TIMESTAMP_TZ
    }

    fn to_sql_literal(&self) -> String {
        format!("TIMESTAMPTZ '{self}'")
    }
}

// =============================================================================
// Bytes implementation
// =============================================================================

impl ToSqlParam for [u8] {
    fn encode_param(&self) -> Option<Vec<u8>> {
        Some(self.to_vec())
    }

    fn sql_oid(&self) -> Oid {
        oids::BYTE_A
    }

    #[expect(
        clippy::format_collect,
        reason = "readable hex/string formatting loop; refactoring to fold! obscures intent"
    )]
    fn to_sql_literal(&self) -> String {
        // Encode as hex bytea literal
        let hex_str: String = self.iter().map(|b| format!("{b:02x}")).collect();
        format!("E'\\\\x{hex_str}'")
    }
}

impl ToSqlParam for Vec<u8> {
    fn encode_param(&self) -> Option<Vec<u8>> {
        Some(self.clone())
    }

    fn sql_oid(&self) -> Oid {
        oids::BYTE_A
    }

    #[expect(
        clippy::format_collect,
        reason = "readable hex/string formatting loop; refactoring to fold! obscures intent"
    )]
    fn to_sql_literal(&self) -> String {
        let hex_str: String = self.iter().map(|b| format!("{b:02x}")).collect();
        format!("E'\\\\x{hex_str}'")
    }
}

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

    #[test]
    fn test_i32_encoding() {
        // Big-endian per PG Bind format code 1.
        assert_eq!(42i32.encode_param(), Some(vec![0, 0, 0, 42]));
        assert_eq!((-1i32).encode_param(), Some(vec![255, 255, 255, 255]));
    }

    #[test]
    fn test_i64_encoding() {
        assert_eq!(42i64.encode_param(), Some(vec![0, 0, 0, 0, 0, 0, 0, 42]));
    }

    #[test]
    fn test_string_encoding() {
        assert_eq!("hello".encode_param(), Some(b"hello".to_vec()));
        assert_eq!(
            String::from("world").encode_param(),
            Some(b"world".to_vec())
        );
    }

    #[test]
    fn test_bool_encoding() {
        assert_eq!(true.encode_param(), Some(vec![1]));
        assert_eq!(false.encode_param(), Some(vec![0]));
    }

    #[test]
    fn test_option_encoding() {
        // Big-endian per PG Bind format code 1.
        assert_eq!(Some(42i32).encode_param(), Some(vec![0, 0, 0, 42]));
        assert_eq!(None::<i32>.encode_param(), None);
    }

    #[test]
    fn test_reference_encoding() {
        let value = 42i32;
        assert_eq!(value.encode_param(), Some(vec![0, 0, 0, 42]));
        assert_eq!((&&value).encode_param(), Some(vec![0, 0, 0, 42]));
    }
}