prax-orm 0.13.3

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

const connectionExample = `// prax.toml configuration
[database]
provider = "mssql"
url = "mssql://user:password@localhost:1433/mydb"

# Connection pool settings
[database.pool]
max_connections = 10
min_connections = 2
acquire_timeout = "30s"

# TLS settings for Azure SQL
[database.tls]
enabled = true
trust_server_certificate = false`;

const schemaExample = `// MSSQL-specific schema features
generator client {
  provider = "prax-mssql"
  output   = "./generated"
}

datasource db {
  provider = "mssql"
  url      = env("DATABASE_URL")
}

model User {
  id        Int      @id @auto
  email     String   @unique @db.NVarChar(255)
  name      String?  @db.NVarChar(100)
  bio       String?  @db.NVarChar(Max)
  createdAt DateTime @default(now()) @db.DateTime2

  @@index([email])
  @@map("users")
}`;

const indexedViewExample = `// MSSQL Indexed Views (Materialized Views)
view OrderSummary {
  customerId   Int     @map("customer_id")
  orderCount   Int     @map("order_count")
  totalSpent   Decimal @map("total_spent")

  @@sql("""
    SELECT
      customer_id,
      COUNT_BIG(*) as order_count,
      SUM(total) as total_spent
    FROM orders WITH (NOLOCK)
    GROUP BY customer_id
  """)

  @@materialized
  @@index([customerId]) // Creates clustered index
}`;

const mergeExample = `use prax_query::upsert::{Upsert, ConflictTarget};

// MSSQL MERGE statement for upsert (values bind as @P1, @P2, …)
let upsert = Upsert::new("users")
    .columns(["email", "name", "updated_at"])
    .values(["@P1", "@P2", "@P3"])
    .on_conflict(ConflictTarget::columns(["email"]))
    .do_update(["name", "updated_at"])
    .to_mssql_sql();

// Generates:
// MERGE INTO users AS target
// USING (SELECT @P1 AS email, @P2 AS name, @P3 AS updated_at) AS source
// ON target.email = source.email
// WHEN MATCHED THEN
//   UPDATE SET name = source.name, updated_at = source.updated_at
// WHEN NOT MATCHED THEN
//   INSERT (email, name, updated_at) VALUES (source.email, source.name, source.updated_at);`;

const outputClauseExample = `use prax_query::advanced::{Returning, ReturnOperation};

// MSSQL OUTPUT clause. Returning is a SQL-fragment generator — a fluent
// .returning(...) on create/update operations is not wired up yet.
let clause = Returning::columns(ReturnOperation::Insert, ["id", "created_at"])
    .to_mssql_sql();
// OUTPUT INSERTED.id, INSERTED.created_at

// For updates
let clause = Returning::all(ReturnOperation::Update).to_mssql_sql();
// OUTPUT INSERTED.*`;

const crossApplyExample = `use prax_query::advanced::LateralJoin;

// MSSQL CROSS APPLY (equivalent to LATERAL JOIN)
let apply = LateralJoin::new(
    "SELECT TOP 3 * FROM orders WHERE customer_id = c.id ORDER BY created_at DESC",
    "recent_orders"
)
.cross() // CROSS APPLY
.build()
.to_mssql_sql();

// Generates:
// CROSS APPLY (SELECT TOP 3 * FROM orders WHERE customer_id = c.id ORDER BY created_at DESC) AS recent_orders

// .left() produces OUTER APPLY (left join semantics)
let apply = LateralJoin::new(subquery, "alias")
    .left()
    .build()
    .to_mssql_sql();`;

const lockingExample = `use prax_query::advanced::RowLock;

// Row locks go through the find operations and are held until the
// surrounding transaction ends, so run them inside a transaction.
client.transaction(|tx| async move {
    // WITH (UPDLOCK, ROWLOCK) after the table name
    let jobs = tx.job().find_many().for_update().exec().await?;

    // Claim rows other transactions have not locked: WITH (UPDLOCK, ROWLOCK, READPAST)
    let next = tx
        .job()
        .find_first()
        .lock(RowLock::for_update().skip_locked())
        .exec()
        .await?;

    // Shared lock: WITH (HOLDLOCK, ROWLOCK)
    let shared = tx.job().find_many().for_share().exec().await?;

    // Unsupported combinations return an error at exec(), before the query
    // runs: for_share().skip_locked(), FOR NO KEY UPDATE / FOR KEY SHARE,
    // and OF <tables>.
    Ok(())
}).await?;`;

const sqlAgentExample = `use prax_migrate::procedure::{SqlAgentJob, JobSchedule, Weekday};

// Create SQL Agent job for scheduled tasks
let job = SqlAgentJob::new("nightly_cleanup")
    .description("Cleanup old records nightly")
    .tsql_step(
        "delete_old_logs",
        "DELETE FROM logs WHERE created_at < DATEADD(day, -30, GETDATE())"
    )
    .tsql_step("update_statistics", "EXEC sp_updatestats")
    .schedule(
        JobSchedule::new("nightly")
            .weekly(vec![Weekday::Monday, Weekday::Wednesday, Weekday::Friday])
            .at("02:00:00")
    );

// generator.create_sql_agent_job(&job) renders the
// sp_add_job / sp_add_jobstep / sp_add_schedule script`;

const alwaysOnExample = `use prax_query::replication::{
    lag_queries, ConnectionRouter, QueryType, ReadPreference, ReplicaSetConfig,
};
use prax_query::sql::DatabaseType;

// Configure AlwaysOn Availability Groups
let config = ReplicaSetConfig::new("production")
    .primary("primary-1", "primary.sql.example.com:1433")
    .secondary("secondary-1", "secondary1.sql.example.com:1433")
    .secondary("secondary-2", "secondary2.sql.example.com:1433")
    .read_preference(ReadPreference::SecondaryPreferred)
    .build();

// Route reads to secondaries
let router = ConnectionRouter::new(config);
let replica = router.route(QueryType::Read, Some(&ReadPreference::SecondaryPreferred))?;

// Check replica lag
let lag_sql = lag_queries::check_lag_sql(DatabaseType::MSSQL);
// query against sys.dm_hadr_database_replica_states`;
---

<DocsLayout title="Microsoft SQL Server - 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">Microsoft SQL Server</h1>
      <p class="text-xl text-muted">
        Full MSSQL support with Tiberius driver, including Azure SQL, indexed views, MERGE statements, and SQL Agent jobs.
      </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 comprehensive Microsoft SQL Server support through the Tiberius async driver.
          This includes Azure SQL Database, Azure SQL Managed Instance, and on-premises SQL Server instances.
        </p>
        <div class="grid md:grid-cols-3 gap-4">
          <div class="p-4 rounded-xl bg-surface border border-border">
            <div class="text-2xl mb-2">🔒</div>
            <h4 class="font-semibold mb-1">Azure Ready</h4>
            <p class="text-muted text-sm">Full Azure SQL support with TLS and AAD authentication</p>
          </div>
          <div class="p-4 rounded-xl bg-surface border border-border">
            <div class="text-2xl mb-2">⚡</div>
            <h4 class="font-semibold mb-1">MERGE & OUTPUT</h4>
            <p class="text-muted text-sm">Native upsert with MERGE and RETURNING via OUTPUT</p>
          </div>
          <div class="p-4 rounded-xl bg-surface border border-border">
            <div class="text-2xl mb-2">📊</div>
            <h4 class="font-semibold mb-1">SQL Agent</h4>
            <p class="text-muted text-sm">Scheduled jobs via SQL Server Agent integration</p>
          </div>
        </div>
      </section>

      <!-- Connection -->
      <section>
        <h2 class="text-2xl font-semibold mb-4">Connection Configuration</h2>
        <p class="text-muted mb-4">
          Configure your MSSQL connection in <code class="px-2 py-1 bg-surface-elevated rounded">prax.toml</code>.
          Supports both SQL authentication and Windows/Azure AD authentication.
        </p>
        <CodeBlock code={connectionExample} lang="toml" filename="prax.toml" />
      </section>

      <!-- Schema -->
      <section>
        <h2 class="text-2xl font-semibold mb-4">Schema Definition</h2>
        <p class="text-muted mb-4">
          Use MSSQL-specific data types with the <code class="px-2 py-1 bg-surface-elevated rounded">&#64;db.</code> attribute.
        </p>
        <CodeBlock code={schemaExample} lang="prax" filename="prax/schema.prax" />
        <div class="mt-4 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">Prax Type</th>
                <th class="text-left py-3 px-4 font-semibold">MSSQL Type</th>
                <th class="text-left py-3 px-4 font-semibold">Notes</th>
              </tr>
            </thead>
            <tbody class="text-muted">
              <tr class="border-b border-border">
                <td class="py-3 px-4"><code>String</code></td>
                <td class="py-3 px-4"><code>NVARCHAR(255)</code></td>
                <td class="py-3 px-4">Use &#64;db.NVarChar(Max) for unlimited</td>
              </tr>
              <tr class="border-b border-border">
                <td class="py-3 px-4"><code>Int</code></td>
                <td class="py-3 px-4"><code>INT</code></td>
                <td class="py-3 px-4">&#64;db.BigInt for larger values</td>
              </tr>
              <tr class="border-b border-border">
                <td class="py-3 px-4"><code>DateTime</code></td>
                <td class="py-3 px-4"><code>DATETIME2</code></td>
                <td class="py-3 px-4">Higher precision than DATETIME</td>
              </tr>
              <tr class="border-b border-border">
                <td class="py-3 px-4"><code>Decimal</code></td>
                <td class="py-3 px-4"><code>DECIMAL(18,2)</code></td>
                <td class="py-3 px-4">Configurable precision/scale</td>
              </tr>
              <tr class="border-b border-border">
                <td class="py-3 px-4"><code>Bytes</code></td>
                <td class="py-3 px-4"><code>VARBINARY(MAX)</code></td>
                <td class="py-3 px-4">Binary data storage</td>
              </tr>
            </tbody>
          </table>
        </div>
      </section>

      <!-- Indexed Views -->
      <section>
        <h2 class="text-2xl font-semibold mb-4">Indexed Views (Materialized Views)</h2>
        <p class="text-muted mb-4">
          MSSQL supports indexed views, which are materialized views with a clustered index.
          They're automatically updated when base tables change.
        </p>
        <CodeBlock code={indexedViewExample} lang="prax" filename="prax/schema.prax" />
        <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> Indexed views require <code>SCHEMABINDING</code> and have restrictions on
            the types of queries they can contain. Prax automatically handles these requirements.
          </p>
        </div>
      </section>

      <!-- MERGE Statement -->
      <section>
        <h2 class="text-2xl font-semibold mb-4">MERGE Statement (Upsert)</h2>
        <p class="text-muted mb-4">
          MSSQL uses the <code class="px-2 py-1 bg-surface-elevated rounded">MERGE</code> statement for upsert operations,
          providing atomic insert-or-update functionality.
        </p>
        <CodeBlock code={mergeExample} lang="rust" filename="src/main.rs" />
      </section>

      <!-- OUTPUT Clause -->
      <section>
        <h2 class="text-2xl font-semibold mb-4">OUTPUT Clause (RETURNING)</h2>
        <p class="text-muted mb-4">
          Get inserted/updated/deleted values back from DML statements using the OUTPUT clause.
        </p>
        <CodeBlock code={outputClauseExample} lang="rust" filename="src/main.rs" />
      </section>

      <!-- CROSS APPLY -->
      <section>
        <h2 class="text-2xl font-semibold mb-4">CROSS APPLY (LATERAL Joins)</h2>
        <p class="text-muted mb-4">
          MSSQL's CROSS APPLY and OUTER APPLY are equivalent to LATERAL joins in PostgreSQL.
        </p>
        <CodeBlock code={crossApplyExample} lang="rust" filename="src/main.rs" />
      </section>

      <!-- Locking -->
      <section>
        <h2 class="text-2xl font-semibold mb-4">Table Hints & Locking</h2>
        <p class="text-muted mb-4">
          Lock rows with <code>.lock(RowLock::...)</code>, <code>.for_update()</code> or
          <code>.for_share()</code> on <code>find_many</code>, <code>find_first</code> and
          <code>find_unique</code>. Prax renders the matching MSSQL table hint and holds the lock
          until the surrounding transaction ends. Combinations SQL Server cannot express return an
          error before the query runs.
        </p>
        <CodeBlock code={lockingExample} lang="rust" filename="src/main.rs" />
        <div class="overflow-x-auto mt-6">
          <table class="w-full text-sm border border-border rounded-lg">
            <thead class="bg-muted/50">
              <tr>
                <th class="px-4 py-3 text-left font-medium">Database</th>
                <th class="px-4 py-3 text-left font-medium">Strengths</th>
                <th class="px-4 py-3 text-left font-medium">NOWAIT / SKIP LOCKED</th>
                <th class="px-4 py-3 text-left font-medium">OF tables</th>
                <th class="px-4 py-3 text-left font-medium">Rendered as</th>
              </tr>
            </thead>
            <tbody>
              <tr class="border-t border-border">
                <td class="px-4 py-3 font-mono text-primary">PostgreSQL</td>
                <td class="px-4 py-3 text-muted">UPDATE, NO KEY UPDATE, SHARE, KEY SHARE</td>
                <td class="px-4 py-3 text-muted">Both</td>
                <td class="px-4 py-3 text-muted">Yes (plain identifiers; must match the FROM table name)</td>
                <td class="px-4 py-3 text-muted">Trailing <code>FOR ...</code> clause</td>
              </tr>
              <tr class="border-t border-border">
                <td class="px-4 py-3 font-mono text-primary">MySQL 8+</td>
                <td class="px-4 py-3 text-muted">UPDATE, SHARE</td>
                <td class="px-4 py-3 text-muted">Both</td>
                <td class="px-4 py-3 text-muted">No</td>
                <td class="px-4 py-3 text-muted">Trailing <code>FOR ...</code> clause</td>
              </tr>
              <tr class="border-t border-border">
                <td class="px-4 py-3 font-mono text-primary">SQL Server</td>
                <td class="px-4 py-3 text-muted">UPDATE, SHARE</td>
                <td class="px-4 py-3 text-muted">NOWAIT; SKIP LOCKED (READPAST) with UPDATE only</td>
                <td class="px-4 py-3 text-muted">No</td>
                <td class="px-4 py-3 text-muted">Table hint after the table name</td>
              </tr>
              <tr class="border-t border-border">
                <td class="px-4 py-3 font-mono text-primary">SQLite, DuckDB, MongoDB, CQL</td>
                <td class="px-4 py-3 text-muted" colspan="4">Not supported (<code>.lock(..)</code> does not compile)</td>
              </tr>
            </tbody>
          </table>
        </div>
      </section>

      <!-- SQL Agent -->
      <section>
        <h2 class="text-2xl font-semibold mb-4">SQL Server Agent Jobs</h2>
        <p class="text-muted mb-4">
          Define and manage scheduled jobs that run on SQL Server Agent.
        </p>
        <CodeBlock code={sqlAgentExample} lang="rust" filename="migrations/jobs.rs" />
      </section>

      <!-- AlwaysOn -->
      <section>
        <h2 class="text-2xl font-semibold mb-4">AlwaysOn Availability Groups</h2>
        <p class="text-muted mb-4">
          Configure read replicas and automatic failover with AlwaysOn.
        </p>
        <CodeBlock code={alwaysOnExample} lang="rust" filename="src/config.rs" />
      </section>

      <!-- Feature Support -->
      <section>
        <h2 class="text-2xl font-semibold mb-4">MSSQL Feature Support</h2>
        <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">Status</th>
                <th class="text-left py-3 px-4 font-semibold">Notes</th>
              </tr>
            </thead>
            <tbody class="text-muted">
              <tr class="border-b border-border">
                <td class="py-3 px-4">Indexed Views</td>
                <td class="py-3 px-4"><span class="text-success-400">✅</span></td>
                <td class="py-3 px-4">Automatic maintenance</td>
              </tr>
              <tr class="border-b border-border">
                <td class="py-3 px-4">MERGE Statement</td>
                <td class="py-3 px-4"><span class="text-success-400">✅</span></td>
                <td class="py-3 px-4">Full upsert support</td>
              </tr>
              <tr class="border-b border-border">
                <td class="py-3 px-4">OUTPUT Clause</td>
                <td class="py-3 px-4"><span class="text-success-400">✅</span></td>
                <td class="py-3 px-4">INSERTED/DELETED access</td>
              </tr>
              <tr class="border-b border-border">
                <td class="py-3 px-4">CROSS/OUTER APPLY</td>
                <td class="py-3 px-4"><span class="text-success-400">✅</span></td>
                <td class="py-3 px-4">Lateral join equivalent</td>
              </tr>
              <tr class="border-b border-border">
                <td class="py-3 px-4">SQL Agent Jobs</td>
                <td class="py-3 px-4"><span class="text-success-400">✅</span></td>
                <td class="py-3 px-4">Scheduled tasks</td>
              </tr>
              <tr class="border-b border-border">
                <td class="py-3 px-4">AlwaysOn</td>
                <td class="py-3 px-4"><span class="text-success-400">✅</span></td>
                <td class="py-3 px-4">HA and read replicas</td>
              </tr>
              <tr class="border-b border-border">
                <td class="py-3 px-4">Row-Level Security</td>
                <td class="py-3 px-4"><span class="text-success-400">✅</span></td>
                <td class="py-3 px-4">Security predicates</td>
              </tr>
              <tr class="border-b border-border">
                <td class="py-3 px-4">Dynamic Data Masking</td>
                <td class="py-3 px-4"><span class="text-success-400">✅</span></td>
                <td class="py-3 px-4">Column masking</td>
              </tr>
            </tbody>
          </table>
        </div>
      </section>
    </div>
  </article>
</DocsLayout>