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
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
use ignis_db::builders::FunctionBuilder;
use ignis_db::builders::{ConditionalBuilder, InspectableBuilder, SchemaBuilder};
use ignis_db::schema::{FunctionSecurity, FunctionVolatility, ProcedureLanguage};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    println!("=== FunctionBuilder Demo ===\n");

    // 1. Basic functions
    println!("1. Basic Functions:");
    println!("---------------------");

    let add_function = FunctionBuilder::new()
        .name("add_numbers")
        .parameter("a", "INTEGER")
        .parameter("b", "INTEGER")
        .returns("INTEGER")
        .language(ProcedureLanguage::Sql)
        .body("SELECT a + b")
        .build()?;

    println!("Add Function: {:?}", add_function);

    let multiply_function = FunctionBuilder::new()
        .name("multiply_numbers")
        .parameters(vec![("x", "NUMERIC(10,2)"), ("y", "NUMERIC(10,2)")])
        .returns("NUMERIC(10,2)")
        .body("SELECT x * y")
        .build()?;

    println!("Multiply Function: {:?}", multiply_function);

    // 2. PL/pgSQL functions
    println!("\n2. PL/pgSQL Functions:");
    println!("-------------------------");

    let user_count_function = FunctionBuilder::plpgsql()
        .name("get_user_count")
        .returns("INTEGER")
        .body("SELECT COUNT(*) FROM users")
        .build()?;

    println!("User Count Function: {:?}", user_count_function);

    let create_user_function = FunctionBuilder::plpgsql()
        .name("create_user")
        .parameters(vec![
            ("name", "VARCHAR(255)"),
            ("email", "VARCHAR(255)"),
            ("age", "INTEGER"),
        ])
        .returns("INTEGER")
        .body("INSERT INTO users (name, email, age) VALUES (name, email, age) RETURNING id")
        .build()?;

    println!("Create User Function: {:?}", create_user_function);

    // 3. Functions with different volatility
    println!("\n3. Functions with Different Volatility:");
    println!("----------------------------------------");

    let constant_function = FunctionBuilder::immutable()
        .name("get_constant")
        .returns("TEXT")
        .body("SELECT 'constant_value'")
        .build()?;

    println!("Immutable Function: {:?}", constant_function);

    let current_time_function = FunctionBuilder::stable()
        .name("get_current_time")
        .returns("TIMESTAMPTZ")
        .body("SELECT NOW()")
        .build()?;

    println!("Stable Function: {:?}", current_time_function);

    let random_function = FunctionBuilder::volatile()
        .name("get_random_number")
        .returns("INTEGER")
        .body("SELECT floor(random() * 100)::INTEGER")
        .build()?;

    println!("Volatile Function: {:?}", random_function);

    // 4. Functions with security settings
    println!("\n4. Functions with Security Settings:");
    println!("-------------------------------------");

    let invoker_function = FunctionBuilder::invoker()
        .name("get_user_info")
        .parameter("user_id", "INTEGER")
        .returns("TEXT")
        .body("SELECT name FROM users WHERE id = user_id")
        .build()?;

    println!("Invoker Security Function: {:?}", invoker_function);

    let definer_function = FunctionBuilder::definer()
        .name("admin_operation")
        .parameter("operation", "TEXT")
        .returns("BOOLEAN")
        .body("SELECT true")
        .build()?;

    println!("Definer Security Function: {:?}", definer_function);

    // 5. Specialized function types
    println!("\n5. Specialized Function Types:");
    println!("--------------------------------");

    let math_function = FunctionBuilder::math()
        .name("calculate_area")
        .parameter("radius", "DOUBLE PRECISION")
        .returns("DOUBLE PRECISION")
        .body("SELECT PI() * radius * radius")
        .build()?;

    println!("Math Function: {:?}", math_function);

    let utility_function = FunctionBuilder::utility()
        .name("get_database_info")
        .returns("JSONB")
        .body("SELECT jsonb_build_object('version', version(), 'current_database', current_database())")
        .build()?;

    println!("Utility Function: {:?}", utility_function);

    let trigger_function = FunctionBuilder::trigger()
        .name("audit_changes")
        .body("RETURN NEW")
        .build()?;

    println!("Trigger Function: {:?}", trigger_function);

    // 6. Functions with schema
    println!("\n6. Functions with Schema:");
    println!("---------------------------");

    let geometry_function = FunctionBuilder::new()
        .name("calculate_distance")
        .in_schema("geometry")
        .parameters(vec![
            ("x1", "DOUBLE PRECISION"),
            ("y1", "DOUBLE PRECISION"),
            ("x2", "DOUBLE PRECISION"),
            ("y2", "DOUBLE PRECISION"),
        ])
        .returns("DOUBLE PRECISION")
        .language(ProcedureLanguage::Sql)
        .body("SELECT SQRT(POWER(x2 - x1, 2) + POWER(y2 - y1, 2))")
        .build()?;

    println!("Geometry Function: {:?}", geometry_function);

    let finance_function = FunctionBuilder::new()
        .name("calculate_interest")
        .in_schema("finance")
        .parameters(vec![
            ("principal", "NUMERIC(19,4)"),
            ("rate", "NUMERIC(5,4)"),
            ("time", "NUMERIC(5,2)"),
        ])
        .returns("NUMERIC(19,4)")
        .language(ProcedureLanguage::PlPgSql)
        .body("RETURN principal * POWER(1 + rate, time)")
        .build()?;

    println!("Finance Function: {:?}", finance_function);

    // 7. Complex functions
    println!("\n7. Complex Functions:");
    println!("----------------------");

    let search_function = FunctionBuilder::new()
        .name("search_users")
        .parameters(vec![
            ("search_term", "TEXT"),
            ("limit_count", "INTEGER"),
            ("offset_count", "INTEGER"),
        ])
        .returns("TABLE(id INTEGER, name TEXT, email TEXT, relevance_score NUMERIC(5,4))")
        .language(ProcedureLanguage::PlPgSql)
        .body(
            "
            RETURN QUERY
            SELECT 
                u.id,
                u.name,
                u.email,
                CASE 
                    WHEN u.name ILIKE '%' || search_term || '%' THEN 1.0
                    WHEN u.email ILIKE '%' || search_term || '%' THEN 0.8
                    ELSE 0.5
                END as relevance_score
            FROM users u
            WHERE u.name ILIKE '%' || search_term || '%' 
               OR u.email ILIKE '%' || search_term || '%'
            ORDER BY relevance_score DESC, u.name
            LIMIT limit_count
            OFFSET offset_count;
        ",
        )
        .build()?;

    println!("Search Function: {:?}", search_function);

    let aggregation_function = FunctionBuilder::new()
        .name("get_user_statistics")
        .parameter("date_from", "DATE")
        .parameter("date_to", "DATE")
        .returns("TABLE(metric_name TEXT, metric_value NUMERIC(10,2))")
        .language(ProcedureLanguage::PlPgSql)
        .body(
            "
            RETURN QUERY
            SELECT 'total_users'::TEXT, COUNT(*)::NUMERIC(10,2)
            FROM users
            WHERE created_at BETWEEN date_from AND date_to
            
            UNION ALL
            
            SELECT 'active_users'::TEXT, COUNT(*)::NUMERIC(10,2)
            FROM users
            WHERE created_at BETWEEN date_from AND date_to
              AND is_active = true;
        ",
        )
        .build()?;

    println!("Aggregation Function: {:?}", aggregation_function);

    // 8. Conditional function building
    println!("\n8. Conditional Function Building:");
    println!("----------------------------------");

    let is_production = std::env::var("ENV").unwrap_or_default() == "production";

    let conditional_function = FunctionBuilder::new()
        .when(is_production, |f| {
            f.set_name("prod_get_user_data");
            f.add_parameter("user_id", "INTEGER");
            f.add_parameter("include_sensitive", "BOOLEAN");
            f.set_body("SELECT id, name, email FROM users WHERE id = user_id");
        })
        .when(!is_production, |f| {
            f.set_name("dev_get_user_data");
            f.add_parameter("user_id", "INTEGER");
            f.add_parameter("include_sensitive", "BOOLEAN");
            f.add_parameter("debug_mode", "BOOLEAN");
            f.set_body(
                "SELECT id, name, email, created_at, last_login FROM users WHERE id = user_id",
            );
        })
        .returns("TABLE(id INTEGER, name TEXT, email TEXT)")
        .build()?;

    println!("Conditional Function: {:?}", conditional_function);

    // 9. Function validation
    println!("\n9. Function Validation:");
    println!("------------------------");

    // This should fail validation
    let invalid_result = FunctionBuilder::new().name("test").build();
    match invalid_result {
        Ok(_) => println!("❌ Unexpected success for invalid function"),
        Err(e) => println!("✅ Correctly caught validation error: {}", e),
    }

    // This should pass validation
    let valid_result = FunctionBuilder::new()
        .name("valid_function")
        .parameter("param1", "TEXT")
        .body("SELECT param1")
        .build();

    match valid_result {
        Ok(_) => println!("✅ Valid function built successfully"),
        Err(e) => println!("❌ Unexpected error for valid function: {}", e),
    }

    // 10. Function inspection
    println!("\n10. Function Inspection:");
    println!("--------------------------");

    let builder = FunctionBuilder::new()
        .name("inspect_function")
        .in_schema("public")
        .parameters(vec![("col1", "TEXT"), ("col2", "INTEGER")])
        .returns("BOOLEAN")
        .language(ProcedureLanguage::PlPgSql)
        .volatility(FunctionVolatility::Stable)
        .security(FunctionSecurity::Invoker)
        .body("RETURN col1 IS NOT NULL AND col2 > 0")
        .comment("This is a test function");

    println!("Debug info: {}", builder.debug_info());
    println!("Summary: {}", builder.summary());
    println!("Parameter count: {}", builder.parameter_count());
    println!("Has parameter 'col1': {}", builder.has_parameter("col1"));
    println!(
        "Has parameter 'nonexistent': {}",
        builder.has_parameter("nonexistent")
    );
    println!("Has name: {}", builder.has_name());
    println!("Has schema: {}", builder.has_schema());
    println!("Has parameters: {}", builder.has_parameters());
    println!("Has return type: {}", builder.has_return_type());
    println!("Has language: {}", builder.has_language());
    println!("Has volatility: {}", builder.has_volatility());
    println!("Has security: {}", builder.has_security());
    println!("Has body: {}", builder.has_body());
    println!("Has comment: {}", builder.has_comment());

    let param = builder.get_parameter("col1");
    assert!(param.is_some());
    println!("Parameter 'col1' type: {}", param.unwrap().data_type);

    // 11. Advanced function patterns
    println!("\n11. Advanced Function Patterns:");
    println!("--------------------------------");

    let window_function = FunctionBuilder::new()
        .name("get_user_rankings")
        .parameter("category", "TEXT")
        .returns(
            "TABLE(user_id INTEGER, user_name TEXT, score NUMERIC(10,2), rank_position INTEGER)",
        )
        .language(ProcedureLanguage::PlPgSql)
        .body(
            "
            RETURN QUERY
            SELECT 
                u.id,
                u.name,
                s.score,
                ROW_NUMBER() OVER (ORDER BY s.score DESC) as rank_position
            FROM users u
            JOIN user_scores s ON u.id = s.user_id
            WHERE s.category = get_user_rankings.category
            ORDER BY s.score DESC;
        ",
        )
        .build()?;

    println!("Window Function: {:?}", window_function);

    let recursive_function = FunctionBuilder::new()
        .name("get_ancestors")
        .parameter("node_id", "INTEGER")
        .parameter("max_depth", "INTEGER")
        .returns("TABLE(ancestor_id INTEGER, ancestor_name TEXT, depth_level INTEGER)")
        .language(ProcedureLanguage::PlPgSql)
        .body(
            "
            RETURN QUERY
            WITH RECURSIVE ancestors AS (
                SELECT id, name, 0 as depth
                FROM nodes
                WHERE id = node_id
                
                UNION ALL
                
                SELECT n.id, n.name, a.depth + 1
                FROM nodes n
                JOIN ancestors a ON n.id = a.parent_id
                WHERE a.depth < max_depth
            )
            SELECT id, name, depth
            FROM ancestors
            WHERE depth > 0
            ORDER BY depth;
        ",
        )
        .build()?;

    println!("Recursive Function: {:?}", recursive_function);

    // 12. Performance optimization functions
    println!("\n12. Performance Optimization Functions:");
    println!("---------------------------------------");

    let cached_function = FunctionBuilder::new()
        .name("get_user_profile_cached")
        .parameter("user_id", "INTEGER")
        .returns("JSONB")
        .language(ProcedureLanguage::PlPgSql)
        .volatility(FunctionVolatility::Stable)
        .body(
            "
            -- This function is designed to be cached
            SELECT jsonb_build_object(
                'id', u.id,
                'name', u.name,
                'email', u.email,
                'profile_data', u.profile_data
            )
            FROM users u
            WHERE u.id = get_user_profile_cached.user_id;
        ",
        )
        .build()?;

    println!("Cached Function: {:?}", cached_function);

    let batch_function = FunctionBuilder::new()
        .name("batch_update_users")
        .parameter("user_ids", "INTEGER[]")
        .parameter("updates", "JSONB")
        .returns("INTEGER")
        .language(ProcedureLanguage::PlPgSql)
        .body(
            "
            -- Batch update for performance
            UPDATE users 
            SET 
                name = COALESCE(updates->>'name', name),
                email = COALESCE(updates->>'email', email),
                updated_at = NOW()
            WHERE id = ANY(user_ids);
            
            RETURN array_length(user_ids, 1);
        ",
        )
        .build()?;

    println!("Batch Function: {:?}", batch_function);

    println!("\n=== FunctionBuilder Demo Complete ===");

    Ok(())
}