prax-orm 0.11.0

A next-generation, type-safe ORM for Rust inspired by Prisma
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
---
import DocsLayout from '../../layouts/DocsLayout.astro';
import CodeBlock from '../../components/CodeBlock.astro';

const basicCall = `use prax::procedure::{ProcedureCall, Parameter, ParameterMode};

// Call a stored procedure
let result = ProcedureCall::new("get_user_orders")
    .param("user_id", 123)
    .param("status", "completed")
    .exec(&client)
    .await?;

// Access result sets
for row in result.rows() {
    let order_id: i32 = row.get("order_id")?;
    let total: Decimal = row.get("total")?;
    println!("Order {}: \${}", order_id, total);
}`;

const outParameters = `use prax::procedure::{ProcedureCall, Parameter, ParameterMode, ProcedureResult};

// Procedure with OUT parameters
let result = ProcedureCall::new("calculate_totals")
    .param(Parameter::new("order_id", 123).mode(ParameterMode::In))
    .param(Parameter::new("subtotal", 0.0).mode(ParameterMode::Out))
    .param(Parameter::new("tax", 0.0).mode(ParameterMode::Out))
    .param(Parameter::new("total", 0.0).mode(ParameterMode::Out))
    .exec(&client)
    .await?;

// Access output values
let subtotal: f64 = result.output("subtotal")?;
let tax: f64 = result.output("tax")?;
let total: f64 = result.output("total")?;

println!("Subtotal: \${}, Tax: \${}, Total: \${}", subtotal, tax, total);

// INOUT parameters (value modified in-place)
let result = ProcedureCall::new("increment_counter")
    .param(Parameter::new("counter", 10).mode(ParameterMode::InOut))
    .exec(&client)
    .await?;

let new_value: i32 = result.output("counter")?;`;

const functionCall = `use prax::procedure::ProcedureCall;

// Call a user-defined function
let distance = ProcedureCall::function("calculate_distance")
    .param("lat1", 40.7128)
    .param("lon1", -74.0060)
    .param("lat2", 34.0522)
    .param("lon2", -118.2437)
    .exec(&client)
    .await?
    .scalar::<f64>()?;

println!("Distance: {} km", distance);

// Table-valued function (PostgreSQL/MSSQL)
let nearby = ProcedureCall::table_function("find_nearby_stores")
    .param("lat", 40.7128)
    .param("lon", -74.0060)
    .param("radius_km", 10.0)
    .exec(&client)
    .await?;

for store in nearby.rows() {
    let name: String = store.get("name")?;
    let distance: f64 = store.get("distance")?;
    println!("{}: {} km away", name, distance);
}`;

const sqliteUdf = `use prax::procedure::sqlite_udf::{ScalarUdf, AggregateUdf, WindowUdf};

// Register a scalar UDF in SQLite
let levenshtein = ScalarUdf::new("levenshtein")
    .args(2)  // Two string arguments
    .deterministic(true)
    .handler(|args| {
        let s1: &str = args.get(0)?;
        let s2: &str = args.get(1)?;
        Ok(levenshtein_distance(s1, s2) as i64)
    });

client.register_function(levenshtein)?;

// Use in queries
let similar = client.raw_query(
    "SELECT * FROM products WHERE levenshtein(name, ?) < 3",
    ["headphones"]
).await?;

// Register an aggregate UDF
let median = AggregateUdf::new("median")
    .init(|| Vec::new())
    .step(|state: &mut Vec<f64>, value: f64| {
        state.push(value);
    })
    .finalize(|mut state: Vec<f64>| {
        state.sort_by(|a, b| a.partial_cmp(b).unwrap());
        let mid = state.len() / 2;
        if state.len() % 2 == 0 {
            (state[mid - 1] + state[mid]) / 2.0
        } else {
            state[mid]
        }
    });

client.register_aggregate(median)?;

// Window UDF
let running_avg = WindowUdf::new("running_avg")
    .value_handler(|partition, current_row| {
        let sum: f64 = partition[..=current_row].iter().sum();
        sum / (current_row + 1) as f64
    });`;

const mongoFunction = `use prax::procedure::mongodb::{MongoFunction, MongoAccumulator};

// MongoDB $function (JavaScript UDF)
let custom_fn = MongoFunction::new("calculateScore")
    .args(["score", "multiplier", "bonus"])
    .body(r#"
        function(score, multiplier, bonus) {
            return (score * multiplier) + bonus;
        }
    "#)
    .lang("js");

// Use in aggregation pipeline
let pipeline = vec![
    doc! {
        "$addFields": {
            "finalScore": custom_fn.to_bson()
        }
    }
];

// MongoDB $accumulator (custom aggregation)
let weighted_avg = MongoAccumulator::new("weightedAverage")
    .init_args(["weights"])
    .init(r#"
        function(weights) {
            return { sum: 0, weightSum: 0, weights: weights };
        }
    "#)
    .accumulate_args(["state", "value", "index"])
    .accumulate(r#"
        function(state, value, index) {
            const weight = state.weights[index] || 1;
            state.sum += value * weight;
            state.weightSum += weight;
            return state;
        }
    "#)
    .merge(r#"
        function(state1, state2) {
            return {
                sum: state1.sum + state2.sum,
                weightSum: state1.weightSum + state2.weightSum,
                weights: state1.weights
            };
        }
    "#)
    .finalize(r#"
        function(state) {
            return state.sum / state.weightSum;
        }
    "#);`;

const procedureMigration = `use prax_migrate::procedure::{
    ProcedureDefinition, ProcedureParameter, ProcedureLanguage,
    ProcedureVolatility, ProcedureSecurity, ProcedureDiffer, ProcedureSqlGenerator
};

// Define a stored procedure for migration
let procedure = ProcedureDefinition::new("get_user_orders")
    .language(ProcedureLanguage::PlPgSql)
    .param(ProcedureParameter::new("p_user_id", "INT").mode(ParameterMode::In))
    .param(ProcedureParameter::new("p_status", "VARCHAR(50)").mode(ParameterMode::In))
    .returns("TABLE(order_id INT, total DECIMAL, created_at TIMESTAMP)")
    .volatility(ProcedureVolatility::Stable)
    .security(ProcedureSecurity::Definer)
    .body(r#"
        BEGIN
            RETURN QUERY
            SELECT o.id, o.total, o.created_at
            FROM orders o
            WHERE o.user_id = p_user_id
              AND (p_status IS NULL OR o.status = p_status)
            ORDER BY o.created_at DESC;
        END;
    "#);

// Generate SQL for different databases
let postgres_sql = ProcedureSqlGenerator::new(DatabaseType::PostgreSQL)
    .create_procedure(&procedure);

let mysql_sql = ProcedureSqlGenerator::new(DatabaseType::MySQL)
    .create_procedure(&procedure);

// Diff procedures for migrations
let differ = ProcedureDiffer::new();
let changes = differ.diff(&old_procedures, &new_procedures);

for change in changes {
    match change {
        ProcedureChange::Added(proc) => {
            println!("CREATE: {}", proc.name);
        }
        ProcedureChange::Modified { old, new } => {
            println!("ALTER: {}", new.name);
        }
        ProcedureChange::Removed(proc) => {
            println!("DROP: {}", proc.name);
        }
    }
}`;

const databaseComparison = `// PostgreSQL procedure
CREATE OR REPLACE FUNCTION get_user_orders(
    p_user_id INT,
    p_status VARCHAR(50) DEFAULT NULL
) RETURNS TABLE(order_id INT, total DECIMAL, created_at TIMESTAMP)
LANGUAGE plpgsql STABLE SECURITY DEFINER
AS $$
BEGIN
    RETURN QUERY SELECT ...;
END;
$$;

-- MySQL procedure
DELIMITER //
CREATE PROCEDURE get_user_orders(
    IN p_user_id INT,
    IN p_status VARCHAR(50)
)
BEGIN
    SELECT o.id, o.total, o.created_at
    FROM orders o
    WHERE o.user_id = p_user_id
      AND (p_status IS NULL OR o.status = p_status);
END //
DELIMITER ;

-- MSSQL procedure
CREATE OR ALTER PROCEDURE get_user_orders
    @p_user_id INT,
    @p_status VARCHAR(50) = NULL
AS
BEGIN
    SELECT o.id, o.total, o.created_at
    FROM orders o
    WHERE o.user_id = @p_user_id
      AND (@p_status IS NULL OR o.status = @p_status);
END;`;
---

<DocsLayout title="Stored Procedures & Functions - Prax ORM">
  <article class="max-w-4xl mx-auto px-6 py-12">
    <header class="mb-12">
      <h1 class="text-4xl font-bold mb-4">Stored Procedures & Functions</h1>
      <p class="text-xl text-muted">
        Call stored procedures and user-defined functions across all supported databases with type-safe parameter handling.
      </p>
    </header>

    <div class="space-y-12">
      <!-- Introduction -->
      <section>
        <h2 class="text-2xl font-semibold mb-4">Overview</h2>
        <p class="text-muted mb-4">
          Prax provides a unified API for calling stored procedures and functions across PostgreSQL, MySQL, MSSQL, and SQLite.
          Support includes IN/OUT/INOUT parameters, table-valued functions, and custom aggregates.
        </p>
        <div class="overflow-x-auto">
          <table class="w-full text-sm">
            <thead>
              <tr class="border-b border-border">
                <th class="text-left py-3 px-4 font-semibold">Feature</th>
                <th class="text-left py-3 px-4 font-semibold">PostgreSQL</th>
                <th class="text-left py-3 px-4 font-semibold">MySQL</th>
                <th class="text-left py-3 px-4 font-semibold">SQLite</th>
                <th class="text-left py-3 px-4 font-semibold">MSSQL</th>
                <th class="text-left py-3 px-4 font-semibold">MongoDB</th>
              </tr>
            </thead>
            <tbody class="text-muted">
              <tr class="border-b border-border">
                <td class="py-3 px-4">Stored Procedures</td>
                <td class="py-3 px-4"><span class="text-success-400">✅</span></td>
                <td class="py-3 px-4"><span class="text-success-400">✅</span></td>
                <td class="py-3 px-4"><span class="text-muted">❌</span></td>
                <td class="py-3 px-4"><span class="text-success-400">✅</span></td>
                <td class="py-3 px-4"><span class="text-muted">❌</span></td>
              </tr>
              <tr class="border-b border-border">
                <td class="py-3 px-4">User-Defined Functions</td>
                <td class="py-3 px-4"><span class="text-success-400">✅</span></td>
                <td class="py-3 px-4"><span class="text-success-400">✅</span></td>
                <td class="py-3 px-4"><span class="text-success-400">✅</span> Rust</td>
                <td class="py-3 px-4"><span class="text-success-400">✅</span></td>
                <td class="py-3 px-4"><span class="text-success-400">✅</span> $function</td>
              </tr>
              <tr class="border-b border-border">
                <td class="py-3 px-4">Table-Valued Functions</td>
                <td class="py-3 px-4"><span class="text-success-400">✅</span></td>
                <td class="py-3 px-4"><span class="text-muted">❌</span></td>
                <td class="py-3 px-4"><span class="text-muted">❌</span></td>
                <td class="py-3 px-4"><span class="text-success-400">✅</span></td>
                <td class="py-3 px-4"><span class="text-muted">❌</span></td>
              </tr>
              <tr class="border-b border-border">
                <td class="py-3 px-4">Aggregate Functions</td>
                <td class="py-3 px-4"><span class="text-success-400">✅</span></td>
                <td class="py-3 px-4"><span class="text-success-400">✅</span></td>
                <td class="py-3 px-4"><span class="text-success-400">✅</span> Rust</td>
                <td class="py-3 px-4"><span class="text-success-400">✅</span></td>
                <td class="py-3 px-4"><span class="text-success-400">✅</span> $accumulator</td>
              </tr>
            </tbody>
          </table>
        </div>
      </section>

      <!-- Basic Calls -->
      <section>
        <h2 class="text-2xl font-semibold mb-4">Calling Procedures</h2>
        <p class="text-muted mb-4">
          Use <code class="px-2 py-1 bg-surface-elevated rounded">ProcedureCall</code> to invoke stored procedures
          with type-safe parameters.
        </p>
        <CodeBlock code={basicCall} lang="rust" filename="src/main.rs" />
      </section>

      <!-- OUT Parameters -->
      <section>
        <h2 class="text-2xl font-semibold mb-4">OUT and INOUT Parameters</h2>
        <p class="text-muted mb-4">
          Handle output parameters with <code class="px-2 py-1 bg-surface-elevated rounded">ParameterMode</code>.
        </p>
        <CodeBlock code={outParameters} lang="rust" filename="src/main.rs" />
      </section>

      <!-- Functions -->
      <section>
        <h2 class="text-2xl font-semibold mb-4">User-Defined Functions</h2>
        <p class="text-muted mb-4">
          Call scalar and table-valued functions with the same fluent API.
        </p>
        <CodeBlock code={functionCall} lang="rust" filename="src/main.rs" />
      </section>

      <!-- SQLite UDFs -->
      <section>
        <h2 class="text-2xl font-semibold mb-4">SQLite Rust UDFs</h2>
        <p class="text-muted mb-4">
          Since SQLite doesn't support stored procedures, register Rust functions directly with the connection.
        </p>
        <CodeBlock code={sqliteUdf} lang="rust" filename="src/main.rs" />
        <div class="mt-4 p-4 rounded-xl bg-info-500/10 border border-info-500/30">
          <p class="text-info-400 text-sm">
            <strong>Note:</strong> SQLite UDFs are registered per-connection. Use the connection pool's
            <code>after_connect</code> hook to register functions on all connections.
          </p>
        </div>
      </section>

      <!-- MongoDB Functions -->
      <section>
        <h2 class="text-2xl font-semibold mb-4">MongoDB $function & $accumulator</h2>
        <p class="text-muted mb-4">
          Define custom JavaScript functions for MongoDB aggregation pipelines.
        </p>
        <CodeBlock code={mongoFunction} lang="rust" filename="src/aggregations.rs" />
      </section>

      <!-- Migrations -->
      <section>
        <h2 class="text-2xl font-semibold mb-4">Procedure Migrations</h2>
        <p class="text-muted mb-4">
          Version control your stored procedures with Prax migrations. The differ detects changes automatically.
        </p>
        <CodeBlock code={procedureMigration} lang="rust" filename="migrations/procedures.rs" />
      </section>

      <!-- Database Comparison -->
      <section>
        <h2 class="text-2xl font-semibold mb-4">Generated SQL by Database</h2>
        <p class="text-muted mb-4">
          Prax generates the correct syntax for each database:
        </p>
        <CodeBlock code={databaseComparison} lang="sql" />
      </section>

      <!-- Best Practices -->
      <section>
        <h2 class="text-2xl font-semibold mb-4">Best Practices</h2>
        <div class="grid gap-4">
          <div class="p-4 rounded-xl bg-surface border border-border">
            <h4 class="font-semibold mb-2 text-primary-400">Use Transactions</h4>
            <p class="text-muted text-sm">
              Wrap procedure calls in transactions when they modify data.
              Some procedures handle their own transactions—check the procedure definition.
            </p>
          </div>
          <div class="p-4 rounded-xl bg-surface border border-border">
            <h4 class="font-semibold mb-2 text-primary-400">Handle Multiple Result Sets</h4>
            <p class="text-muted text-sm">
              Some procedures return multiple result sets. Use <code>result.next_result_set()</code>
              to iterate through them.
            </p>
          </div>
          <div class="p-4 rounded-xl bg-surface border border-border">
            <h4 class="font-semibold mb-2 text-primary-400">Version Control Procedures</h4>
            <p class="text-muted text-sm">
              Keep procedure definitions in migrations. Use <code>ProcedureDiffer</code> to detect
              changes and generate appropriate ALTER/DROP/CREATE statements.
            </p>
          </div>
          <div class="p-4 rounded-xl bg-surface border border-border">
            <h4 class="font-semibold mb-2 text-warning-400">Avoid N+1 with Procedures</h4>
            <p class="text-muted text-sm">
              Don't call procedures in a loop. Batch operations when possible, or design procedures
              to accept arrays/table-valued parameters.
            </p>
          </div>
        </div>
      </section>
    </div>
  </article>
</DocsLayout>