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
//! # Microsoft SQL Server Demo Example
//!
//! This example demonstrates real database connectivity with SQL Server
//! using the Prax ORM MSSQL driver.
//!
//! ## Prerequisites
//!
//! Start SQL Server using docker compose:
//! ```bash
//! docker compose up -d mssql
//! ```
//!
//! Wait for SQL Server to be ready (about 30 seconds), then run the init script:
//! ```bash
//! docker exec -it prax-mssql /opt/mssql-tools18/bin/sqlcmd -S localhost -U sa \
//! -P 'Prax_Test_Password123!' -C -i /docker-entrypoint-initdb.d/init.sql
//! ```
//!
//! ## Running this example
//!
//! ```bash
//! cargo run --example mssql_demo
//! ```
use prax_mssql::{MssqlConnection, MssqlEngine, MssqlPool, Row};
use prax_query::traits::QueryEngine;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Initialize tracing for query logging
tracing_subscriber::fmt()
.with_env_filter("prax_mssql=debug,mssql_demo=info")
.init();
println!("🚀 Prax Microsoft SQL Server Demo\n");
println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n");
// =========================================================================
// STEP 1: Create connection pool
// =========================================================================
println!("📦 Creating connection pool...");
let pool: MssqlPool = MssqlPool::builder()
.host("localhost")
.port(1433)
.database("prax_test")
.username("sa")
.password("Prax_Test_Password123!")
.trust_cert(true)
.max_connections(10)
.build()
.await?;
println!(" ✓ Connection pool created\n");
// =========================================================================
// STEP 2: Create the MSSQL engine
// =========================================================================
println!("⚙️ Creating Prax MSSQL engine...");
let engine: MssqlEngine = MssqlEngine::new(pool.clone());
println!(" ✓ Engine created and ready\n");
// =========================================================================
// STEP 3: Verify database connection
// =========================================================================
println!("🔌 Verifying database connection...");
// Check if pool is healthy
if pool.is_healthy().await {
println!(" ✓ Connection pool is healthy\n");
} else {
println!(" ✗ Connection pool is not healthy\n");
return Err("Failed to connect to SQL Server".into());
}
// =========================================================================
// STEP 4: Check existing tables using raw connection
// =========================================================================
println!("📊 Checking database schema...");
{
let mut conn: MssqlConnection<'_> = pool.get().await?;
let tables: Vec<Row> = conn
.query(
"SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' ORDER BY TABLE_NAME",
&[],
)
.await?;
println!(" ✓ Found {} tables\n", tables.len());
println!(" Tables:");
for table in &tables {
let name: Option<&str> = table.get(0);
println!(" • {}", name.unwrap_or("unknown"));
}
println!();
}
// =========================================================================
// STEP 5: Count existing users via engine
// =========================================================================
println!("📝 Querying data via Prax engine...\n");
let count: u64 = engine.count("SELECT COUNT(*) FROM users", vec![]).await?;
println!(" Current user count: {}", count);
// =========================================================================
// STEP 6: Insert a test user
// =========================================================================
println!(" Inserting test user...");
{
let mut conn: MssqlConnection<'_> = pool.get().await?;
// Check if user exists first
let existing: Option<Row> = conn
.query_opt(
"SELECT id FROM users WHERE email = @P1",
&[&"demo@prax.dev"],
)
.await?;
if existing.is_none() {
conn.execute(
r#"
INSERT INTO users (email, name, role, active, created_at, updated_at)
VALUES (@P1, @P2, @P3, 1, GETUTCDATE(), GETUTCDATE())
"#,
&[&"demo@prax.dev", &"Prax Demo User", &"Admin"],
)
.await?;
println!(" ✓ Created demo user");
} else {
println!(" ✓ Demo user already exists");
}
}
let new_count: u64 = engine.count("SELECT COUNT(*) FROM users", vec![]).await?;
println!(" New user count: {}\n", new_count);
// =========================================================================
// STEP 7: Query users with filters
// =========================================================================
println!("🔍 Querying with filters...\n");
{
let mut conn: MssqlConnection<'_> = pool.get().await?;
let active_users: Vec<Row> = conn
.query(
"SELECT TOP 5 id, email, name, role FROM users WHERE active = 1 ORDER BY id",
&[],
)
.await?;
println!(" Active users (first 5):");
for user in &active_users {
let id: i32 = user.get(0).unwrap_or(0);
let email: Option<&str> = user.get(1);
let name: Option<&str> = user.get(2);
let role: Option<&str> = user.get(3);
println!(
" • [{}] {} - {} ({})",
id,
email.unwrap_or("unknown"),
name.unwrap_or("unknown"),
role.unwrap_or("unknown")
);
}
println!();
}
// =========================================================================
// STEP 8: Update a user
// =========================================================================
println!("✏️ Updating user...\n");
{
let mut conn: MssqlConnection<'_> = pool.get().await?;
let affected: u64 = conn
.execute(
"UPDATE users SET updated_at = GETUTCDATE() WHERE email = @P1",
&[&"demo@prax.dev"],
)
.await?;
println!(" ✓ Updated {} row(s)\n", affected);
}
// =========================================================================
// STEP 9: Aggregation query
// =========================================================================
println!("📈 Running aggregation query...\n");
{
let mut conn: MssqlConnection<'_> = pool.get().await?;
let stats: Vec<Row> = conn
.query(
"SELECT role, COUNT(*) as count FROM users GROUP BY role ORDER BY count DESC",
&[],
)
.await?;
println!(" User statistics by role:");
for stat in &stats {
let role: Option<&str> = stat.get(0);
let count: i32 = stat.get(1).unwrap_or(0);
println!(" • {}: {} users", role.unwrap_or("unknown"), count);
}
println!();
}
// =========================================================================
// STEP 10: Session context (RLS support)
// =========================================================================
println!("🔐 Testing session context (RLS support)...\n");
{
let mut conn: MssqlConnection<'_> = pool.get().await?;
conn.set_session_context("tenant_id", "tenant_123").await?;
let tenant_id: Option<String> = conn.get_session_context("tenant_id").await?;
println!(
" ✓ Session context 'tenant_id' = {}\n",
tenant_id.as_deref().unwrap_or("(not set)")
);
}
// =========================================================================
// STEP 11: Transaction example
// =========================================================================
println!("💾 Testing transaction...\n");
{
let mut conn: MssqlConnection<'_> = pool.get().await?;
conn.begin_transaction().await?;
// Create a savepoint
conn.savepoint("before_update").await?;
// Make some changes
let updated: u64 = conn
.execute(
"UPDATE users SET name = @P1 WHERE email = @P2",
&[&"Prax Demo (Updated)", &"demo@prax.dev"],
)
.await?;
println!(" ✓ Updated {} row(s) within transaction", updated);
// Rollback to savepoint
conn.rollback_to("before_update").await?;
println!(" ✓ Rolled back to savepoint");
// Commit the transaction (no changes since we rolled back)
conn.commit().await?;
println!(" ✓ Transaction committed\n");
}
// =========================================================================
// STEP 12: Pool statistics
// =========================================================================
println!("🏊 Connection pool statistics...\n");
let status = pool.status();
println!(" Connections: {}", status.connections);
println!(" Idle connections: {}", status.idle_connections);
println!(" Max size: {}", status.max_size);
println!();
// =========================================================================
// DONE
// =========================================================================
println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n");
println!("✅ MSSQL Demo completed successfully!\n");
println!("📋 Summary:");
println!(" • Connected to SQL Server with connection pooling");
println!(" • Queried and filtered data");
println!(" • Demonstrated transactions with savepoints");
println!(" • Used session context for RLS support");
println!("\n🔗 Next steps:");
println!(" • Try 'cargo run --example mysql_demo' for MySQL");
println!(" • Try 'cargo run --example mongodb_demo' for MongoDB");
println!(" • Check prax_mssql::rls module for Row-Level Security");
Ok(())
}