ignis-db 0.2.0

A comprehensive PostgreSQL ORM with macro-driven schema management
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
//! Common utilities for SQL name generation and other shared functionality

use anyhow::{Context, Result};
use std::collections::HashSet;

/// Generate a qualified table/view name with proper escaping
pub fn qualified_name(schema: Option<&str>, name: &str) -> String {
    match schema {
        Some(schema) => format!("\"{}\".\"{}\"", schema, name),
        None => format!("\"{}\"", name),
    }
}

/// Generate a qualified column name with proper escaping
pub fn qualified_column_name(
    table_schema: Option<&str>,
    table_name: &str,
    column_name: &str,
) -> String {
    let qualified_table = qualified_name(table_schema, table_name);
    format!("{}.\"{}\"", qualified_table, escape_identifier(column_name))
}

/// Escape a SQL identifier with double quotes
/// This prevents SQL injection by properly escaping special characters
pub fn escape_identifier(identifier: &str) -> String {
    // Remove any existing quotes to prevent double-escaping
    let clean_id = identifier.trim_matches('"');

    // Escape any double quotes within the identifier by doubling them
    let escaped = clean_id.replace("\"", "\"\"");

    format!("\"{}\"", escaped)
}

/// Join multiple identifiers with proper escaping
pub fn join_identifiers(identifiers: &[&str]) -> String {
    identifiers
        .iter()
        .map(|&id| escape_identifier(id))
        .collect::<Vec<_>>()
        .join(", ")
}

/// Validate and sanitize a SQL identifier
/// Returns None if the identifier is invalid
pub fn validate_identifier(identifier: &str) -> Option<String> {
    if identifier.is_empty() {
        return None;
    }

    // Check for SQL keywords that could cause issues
    if is_sql_keyword(identifier) {
        return None;
    }

    // Check for dangerous characters that could lead to injection
    if contains_dangerous_chars(identifier) {
        return None;
    }

    // Return the escaped identifier for safe use
    Some(escape_identifier(identifier))
}

/// Check if a string is a SQL keyword
pub fn is_sql_keyword(word: &str) -> bool {
    let keywords: HashSet<&str> = [
        "SELECT",
        "FROM",
        "WHERE",
        "INSERT",
        "UPDATE",
        "DELETE",
        "CREATE",
        "DROP",
        "ALTER",
        "TABLE",
        "VIEW",
        "INDEX",
        "SCHEMA",
        "DATABASE",
        "USER",
        "GRANT",
        "REVOKE",
        "COMMIT",
        "ROLLBACK",
        "BEGIN",
        "TRANSACTION",
        "UNION",
        "JOIN",
        "GROUP",
        "ORDER",
        "HAVING",
        "LIMIT",
        "OFFSET",
        "DISTINCT",
        "AS",
        "ON",
        "IN",
        "EXISTS",
        "BETWEEN",
        "LIKE",
        "ILIKE",
        "IS",
        "NULL",
        "NOT",
        "AND",
        "OR",
        "XOR",
        "CASE",
        "WHEN",
        "THEN",
        "ELSE",
        "END",
        "CAST",
        "CONVERT",
        "FUNCTION",
        "PROCEDURE",
        "TRIGGER",
        "CONSTRAINT",
        "PRIMARY",
        "FOREIGN",
        "KEY",
        "UNIQUE",
        "CHECK",
        "DEFAULT",
        "REFERENCES",
        "CASCADE",
        "RESTRICT",
        "SET",
        "NULL",
        "NOTNULL",
        "AUTO_INCREMENT",
        "SERIAL",
        "BIGSERIAL",
        "SMALLSERIAL",
        "UUID",
        "TIMESTAMP",
        "TIMESTAMPTZ",
        "DATE",
        "TIME",
        "INTERVAL",
        "TEXT",
        "VARCHAR",
        "CHAR",
        "INTEGER",
        "INT",
        "BIGINT",
        "SMALLINT",
        "DECIMAL",
        "NUMERIC",
        "REAL",
        "DOUBLE",
        "FLOAT",
        "BOOLEAN",
        "BOOL",
        "JSON",
        "JSONB",
        "ARRAY",
        "BLOB",
        "BYTEA",
        "MONEY",
        "BIT",
        "VARBIT",
        "XML",
        "POINT",
        "LINE",
        "CIRCLE",
        "BOX",
        "PATH",
        "POLYGON",
    ]
    .iter()
    .cloned()
    .collect();

    keywords.contains(&word.to_uppercase().as_str())
}

/// Check if a string contains dangerous characters that could lead to injection
pub fn contains_dangerous_chars(s: &str) -> bool {
    // Check for dangerous control characters
    if s.chars().any(|c| {
        matches!(
            c,
            ';' | '='
                | '/'
                | '\\'
                | '`'
                | '\''
                | '\0'
                | '\x01'
                | '\x02'
                | '\x03'
                | '\x04'
                | '\x05'
                | '\x06'
                | '\x07'
                | '\x08'
                | '\x0B'
                | '\x0C'
                | '\x0E'
                | '\x0F'
                | '\x10'
                | '\x11'
                | '\x12'
                | '\x13'
                | '\x14'
                | '\x15'
                | '\x16'
                | '\x17'
                | '\x18'
                | '\x19'
                | '\x1A'
                | '\x1B'
                | '\x1C'
                | '\x1D'
                | '\x1E'
                | '\x1F'
        )
    }) {
        return true;
    }

    // Check for dangerous SQL patterns - only exact matches or patterns that could be exploited
    let upper = s.to_uppercase();
    if upper == "UNION"
        || upper == "DROP"
        || upper == "INSERT"
        || upper == "UPDATE"
        || upper == "DELETE"
        || upper == "CREATE"
        || upper == "ALTER"
        || upper == "EXEC"
        || upper == "EXECUTE"
        || upper.starts_with("UNION ")
        || upper.starts_with("DROP ")
        || upper.starts_with("INSERT ")
        || upper.starts_with("UPDATE ")
        || upper.starts_with("DELETE ")
        || upper.starts_with("CREATE ")
        || upper.starts_with("ALTER ")
        || upper.starts_with("EXEC ")
        || upper.starts_with("EXECUTE ")
    {
        return true;
    }

    false
}

/// Safely construct a SQL statement with proper escaping
/// This is the main function for building safe SQL statements
pub fn safe_sql_statement(
    statement_type: &str,
    table_name: &str,
    columns: &[&str],
) -> Result<String> {
    // Validate the statement type
    let valid_types = [
        "SELECT", "INSERT", "UPDATE", "DELETE", "CREATE", "DROP", "ALTER",
    ];
    if !valid_types.contains(&statement_type.to_uppercase().as_str()) {
        return Err(anyhow::anyhow!(
            "Invalid SQL statement type: {}",
            statement_type
        ));
    }

    // Validate table name
    let safe_table = validate_identifier(table_name)
        .with_context(|| format!("Invalid table name: '{}'", table_name))?;

    // Validate and escape column names
    let safe_columns: Result<Vec<String>> = columns
        .iter()
        .map(|&col| {
            validate_identifier(col).with_context(|| format!("Invalid column name: '{}'", col))
        })
        .collect();

    let safe_columns = safe_columns?;

    // Construct the safe SQL statement
    let sql = match statement_type.to_uppercase().as_str() {
        "SELECT" => format!(
            "SELECT {} FROM {}",
            safe_columns
                .iter()
                .map(|c| escape_identifier(c))
                .collect::<Vec<_>>()
                .join(", "),
            escape_identifier(&safe_table)
        ),
        "INSERT" => format!(
            "INSERT INTO {} ({}) VALUES ({})",
            escape_identifier(&safe_table),
            safe_columns
                .iter()
                .map(|c| escape_identifier(c))
                .collect::<Vec<_>>()
                .join(", "),
            safe_columns
                .iter()
                .map(|_| "?")
                .collect::<Vec<_>>()
                .join(", ")
        ),
        "UPDATE" => format!(
            "UPDATE {} SET {}",
            escape_identifier(&safe_table),
            safe_columns
                .iter()
                .map(|c| format!("{} = ?", escape_identifier(c)))
                .collect::<Vec<_>>()
                .join(", ")
        ),
        "DELETE" => format!("DELETE FROM {}", escape_identifier(&safe_table)),
        _ => {
            return Err(anyhow::anyhow!(
                "Unsupported statement type: {}",
                statement_type
            ))
        }
    };

    Ok(sql)
}

/// Escape a SQL string literal to prevent injection
pub fn escape_string_literal(s: &str) -> String {
    // Replace single quotes with two single quotes (SQL standard)
    let escaped = s.replace("'", "''");
    format!("'{}'", escaped)
}

/// Validate a SQL string literal
pub fn validate_string_literal(s: &str) -> Option<String> {
    if s.is_empty() {
        return Some("''".to_string());
    }

    // Check for null bytes and other dangerous characters
    if s.chars().any(|c| c == '\0') {
        return None;
    }

    Some(escape_string_literal(s))
}

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

    #[test]
    fn test_escape_identifier() {
        assert_eq!(escape_identifier("normal_name"), "\"normal_name\"");
        assert_eq!(
            escape_identifier("name with spaces"),
            "\"name with spaces\""
        );
        assert_eq!(
            escape_identifier("name\"with\"quotes"),
            "\"name\"\"with\"\"quotes\""
        );
        assert_eq!(
            escape_identifier("\"already_quoted\""),
            "\"already_quoted\""
        );
    }

    #[test]
    fn test_validate_identifier() {
        assert_eq!(
            validate_identifier("valid_name"),
            Some("\"valid_name\"".to_string())
        );
        assert_eq!(validate_identifier(""), None);
        assert_eq!(validate_identifier("SELECT"), None); // SQL keyword
        assert_eq!(validate_identifier("name;"), None); // Dangerous char
    }

    #[test]
    fn test_safe_sql_statement() {
        let result = safe_sql_statement("SELECT", "users", &["id", "name"]);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "SELECT \"id\", \"name\" FROM \"users\"");

        let result = safe_sql_statement("INSERT", "users", &["id", "name"]);
        assert!(result.is_ok());
        assert_eq!(
            result.unwrap(),
            "INSERT INTO \"users\" (\"id\", \"name\") VALUES (?, ?)"
        );
    }

    #[test]
    fn test_escape_string_literal() {
        assert_eq!(escape_string_literal("normal"), "'normal'");
        assert_eq!(escape_string_literal("O'Reilly"), "'O''Reilly'");
        assert_eq!(escape_string_literal(""), "''");
    }
}