mssql-client 0.8.0

High-level async SQL Server client with type-state connection 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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
//! Azure SQL Database specific integration tests.
//!
//! These tests are designed to validate Azure SQL-specific functionality.
//! All tests marked with `#[ignore]` require a live Azure SQL Database.
//!
//! Run with:
//!   AZURE_SQL_HOST=myserver.database.windows.net \
//!   AZURE_SQL_DATABASE=mydb \
//!   AZURE_SQL_USER=admin \
//!   AZURE_SQL_PASSWORD=... \
//!   cargo test --test azure_sql -- --ignored --nocapture

#![allow(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::panic,
    clippy::approx_constant
)]

use mssql_client::{Config, Error};

// =============================================================================
// Configuration Helpers
// =============================================================================

fn get_azure_config() -> Option<Config> {
    let host = std::env::var("AZURE_SQL_HOST").ok()?;
    let database = std::env::var("AZURE_SQL_DATABASE").ok()?;
    let user = std::env::var("AZURE_SQL_USER").ok()?;
    let password = std::env::var("AZURE_SQL_PASSWORD").ok()?;

    let conn_str = format!(
        "Server={host};Database={database};User Id={user};Password={password};Encrypt=true;TrustServerCertificate=false"
    );

    Config::from_connection_string(&conn_str).ok()
}

fn get_azure_config_strict() -> Option<Config> {
    let host = std::env::var("AZURE_SQL_HOST").ok()?;
    let database = std::env::var("AZURE_SQL_DATABASE").ok()?;
    let user = std::env::var("AZURE_SQL_USER").ok()?;
    let password = std::env::var("AZURE_SQL_PASSWORD").ok()?;

    let conn_str = format!(
        "Server={host};Database={database};User Id={user};Password={password};Encrypt=strict"
    );

    Config::from_connection_string(&conn_str).ok()
}

// =============================================================================
// Azure Connection String Format Tests
// =============================================================================

#[test]
fn test_azure_connection_string_format() {
    let conn_str = "Server=myserver.database.windows.net;Database=mydb;\
                    User Id=admin@myserver;Password=Password123!;Encrypt=strict";

    let result = Config::from_connection_string(conn_str);
    assert!(result.is_ok(), "Azure connection string should parse");
}

#[test]
fn test_azure_connection_string_with_port() {
    // Azure SQL default port
    let conn_str = "Server=myserver.database.windows.net,1433;Database=mydb;\
                    User Id=admin;Password=Password123!;Encrypt=true";

    let result = Config::from_connection_string(conn_str);
    assert!(
        result.is_ok(),
        "Azure connection string with port should parse"
    );
}

#[test]
fn test_azure_connection_string_with_options() {
    // Full Azure SQL connection string with all options
    let conn_str = "Server=myserver.database.windows.net;Database=mydb;\
                    User Id=admin@myserver;Password=Password123!;\
                    Encrypt=strict;TrustServerCertificate=false;\
                    Connect Timeout=30;Command Timeout=60;\
                    Application Name=TestApp;MultiSubnetFailover=true";

    let result = Config::from_connection_string(conn_str);
    assert!(
        result.is_ok(),
        "Azure connection string with full options should parse"
    );
}

#[test]
fn test_azure_managed_instance_format() {
    // Azure SQL Managed Instance format
    let conn_str = "Server=mi-instance.abc123.database.windows.net;Database=mydb;\
                    User Id=admin;Password=Password123!;Encrypt=true";

    let result = Config::from_connection_string(conn_str);
    assert!(
        result.is_ok(),
        "Azure Managed Instance connection string should parse"
    );
}

// =============================================================================
// Encryption Mode Tests
// =============================================================================

#[test]
fn test_encrypt_strict_config() {
    // Use connection string with strict mode
    let config = Config::from_connection_string(
        "Server=myserver.database.windows.net;Database=mydb;User Id=admin;Password=password;Encrypt=strict",
    )
    .expect("Valid connection string");

    // strict_mode should be set
    assert!(config.strict_mode);
}

#[test]
fn test_encrypt_true_vs_strict() {
    // Encrypt=true (TDS 7.4)
    let config_true = Config::from_connection_string(
        "Server=test.database.windows.net;Database=db;User Id=u;Password=p;Encrypt=true",
    )
    .unwrap();

    // Encrypt=strict (TDS 8.0)
    let config_strict = Config::from_connection_string(
        "Server=test.database.windows.net;Database=db;User Id=u;Password=p;Encrypt=strict",
    )
    .unwrap();

    // Both should parse successfully
    let _ = (config_true, config_strict);
}

// =============================================================================
// Azure SQL Error Handling Tests
// =============================================================================

#[test]
fn test_azure_transient_error_detection() {
    // Error 40501: Service busy
    let err = Error::Server {
        number: 40501,
        class: 16,
        state: 1,
        message: "The service is currently busy".into(),
        server: Some("myserver.database.windows.net".into()),
        procedure: None,
        line: 0,
    };
    assert!(err.is_transient(), "40501 should be transient");

    // Error 40613: Database unavailable
    let err = Error::Server {
        number: 40613,
        class: 16,
        state: 1,
        message: "Database is not currently available".into(),
        server: Some("myserver.database.windows.net".into()),
        procedure: None,
        line: 0,
    };
    assert!(err.is_transient(), "40613 should be transient");

    // Error 10928: Resource limit
    let err = Error::Server {
        number: 10928,
        class: 16,
        state: 1,
        message: "Resource ID exceeded".into(),
        server: Some("myserver.database.windows.net".into()),
        procedure: None,
        line: 0,
    };
    assert!(err.is_transient(), "10928 should be transient");

    // Error 49918: Cannot process request
    let err = Error::Server {
        number: 49918,
        class: 16,
        state: 1,
        message: "Cannot process request".into(),
        server: Some("myserver.database.windows.net".into()),
        procedure: None,
        line: 0,
    };
    assert!(err.is_transient(), "49918 should be transient");
}

#[test]
fn test_azure_redirect_error() {
    let err = Error::Routing {
        host: "prod-replica.database.windows.net".into(),
        port: 11000,
    };

    assert!(err.is_transient(), "Routing should be transient");
    assert!(!err.is_terminal(), "Routing should not be terminal");
}

#[test]
fn test_azure_too_many_redirects() {
    let err = Error::TooManyRedirects { max: 3 };
    let msg = err.to_string();

    assert!(msg.contains("redirects"));
    assert!(msg.contains("3"));
}

// =============================================================================
// Live Azure SQL Tests
// =============================================================================

#[tokio::test]
#[ignore = "Requires Azure SQL Database"]
async fn test_azure_basic_connection() {
    use mssql_client::Client;

    let config = get_azure_config().expect("Azure SQL config required");
    let client = Client::connect(config).await.expect("Connection failed");

    client.close().await.expect("Close failed");
}

#[tokio::test]
#[ignore = "Requires Azure SQL Database with TDS 8.0 support"]
async fn test_azure_strict_mode_connection() {
    use mssql_client::Client;

    let config = get_azure_config_strict().expect("Azure SQL config required");
    let result = Client::connect(config).await;

    // May fail if Azure SQL doesn't support strict mode yet
    match result {
        Ok(client) => {
            client.close().await.expect("Close failed");
        }
        Err(e) => {
            // Strict mode might not be supported yet
            println!("Strict mode connection failed (may not be supported): {e}");
        }
    }
}

#[tokio::test]
#[ignore = "Requires Azure SQL Database"]
async fn test_azure_query_execution() {
    use mssql_client::Client;

    let config = get_azure_config().expect("Azure SQL config required");
    let mut client = Client::connect(config).await.expect("Connection failed");

    // Test basic query
    let rows = client
        .query("SELECT @@VERSION AS version", &[])
        .await
        .expect("Query failed");

    let mut found = false;
    for row_result in rows {
        let row = row_result.expect("Row error");
        let version: String = row.get(0).expect("Get version failed");
        println!("Azure SQL Version: {version}");
        assert!(
            version.contains("Azure") || version.contains("SQL"),
            "Version should mention Azure or SQL"
        );
        found = true;
    }
    assert!(found, "Should have at least one row");

    client.close().await.expect("Close failed");
}

#[tokio::test]
#[ignore = "Requires Azure SQL Database"]
async fn test_azure_database_properties() {
    use mssql_client::Client;

    let config = get_azure_config().expect("Azure SQL config required");
    let mut client = Client::connect(config).await.expect("Connection failed");

    // Query database edition and service objective
    let rows = client
        .query(
            "SELECT DB_NAME() AS db_name, \
             DATABASEPROPERTYEX(DB_NAME(), 'Edition') AS edition, \
             DATABASEPROPERTYEX(DB_NAME(), 'ServiceObjective') AS service_tier",
            &[],
        )
        .await
        .expect("Query failed");

    for row_result in rows {
        let row = row_result.expect("Row error");
        let db_name: String = row.get(0).expect("Get db_name failed");
        let edition: Option<String> = row.get(1).ok();
        let tier: Option<String> = row.get(2).ok();

        println!("Database: {db_name}, Edition: {edition:?}, Tier: {tier:?}");
    }

    client.close().await.expect("Close failed");
}

#[tokio::test]
#[ignore = "Requires Azure SQL Database"]
async fn test_azure_connection_with_timeout() {
    use mssql_client::Client;

    // Use connection string with timeout settings
    let host = std::env::var("AZURE_SQL_HOST").expect("AZURE_SQL_HOST required");
    let database = std::env::var("AZURE_SQL_DATABASE").expect("AZURE_SQL_DATABASE required");
    let user = std::env::var("AZURE_SQL_USER").expect("AZURE_SQL_USER required");
    let password = std::env::var("AZURE_SQL_PASSWORD").expect("AZURE_SQL_PASSWORD required");

    let conn_str = format!(
        "Server={host};Database={database};User Id={user};Password={password};Encrypt=true;\
         TrustServerCertificate=false;Connect Timeout=30;Command Timeout=60"
    );

    let config = Config::from_connection_string(&conn_str).expect("Valid connection string");
    let mut client = Client::connect(config).await.expect("Connection failed");

    // Quick query to verify connection
    let rows = client
        .query("SELECT 1 AS num", &[])
        .await
        .expect("Query failed");
    for _ in rows {}

    client.close().await.expect("Close failed");
}

#[tokio::test]
#[ignore = "Requires Azure SQL Database"]
async fn test_azure_transaction() {
    use mssql_client::Client;

    let config = get_azure_config().expect("Azure SQL config required");
    let mut client = Client::connect(config).await.expect("Connection failed");

    // Create temp table
    client
        .execute(
            "IF OBJECT_ID('tempdb..#azure_test') IS NOT NULL DROP TABLE #azure_test",
            &[],
        )
        .await
        .ok();

    client
        .execute("CREATE TABLE #azure_test (id INT, name NVARCHAR(50))", &[])
        .await
        .expect("Create table failed");

    // Transaction with rollback - type-state pattern: begin_transaction consumes client
    let mut tx = client.begin_transaction().await.expect("Begin failed");
    tx.execute(
        "INSERT INTO #azure_test (id, name) VALUES (1, N'Test')",
        &[],
    )
    .await
    .expect("Insert failed");

    // Rollback returns the client in Ready state
    let mut client = tx.rollback().await.expect("Rollback failed");

    // Verify rollback
    let rows = client
        .query("SELECT COUNT(*) FROM #azure_test", &[])
        .await
        .expect("Query failed");

    for row_result in rows {
        let row = row_result.expect("Row error");
        let count: i32 = row.get(0).expect("Get count failed");
        assert_eq!(count, 0, "Rollback should have removed the row");
    }

    client.close().await.expect("Close failed");
}

// Note: test_azure_pool moved to mssql-testing to break circular dev-dependency

// =============================================================================
// Azure-Specific Feature Tests
// =============================================================================

#[tokio::test]
#[ignore = "Requires Azure SQL Database with Unicode data"]
async fn test_azure_unicode_support() {
    use mssql_client::Client;

    let config = get_azure_config().expect("Azure SQL config required");
    let mut client = Client::connect(config).await.expect("Connection failed");

    // Test various Unicode strings
    let test_strings = [
        ("ASCII", "Hello World"),
        ("German", "Größe"),
        ("French", "Café"),
        ("Chinese", "你好世界"),
        ("Japanese", "こんにちは"),
        ("Korean", "안녕하세요"),
        ("Emoji", "Hello 👋🌍"),
        ("Arabic", "مرحبا"),
        ("Hebrew", "שלום"),
    ];

    for (name, value) in test_strings {
        let rows = client
            .query(&format!("SELECT N'{value}'"), &[])
            .await
            .unwrap_or_else(|_| panic!("Query for {name} failed"));

        for row_result in rows {
            let row = row_result.expect("Row error");
            let result: String = row.get(0).expect("Get failed");
            assert_eq!(result, value, "{name} string should roundtrip correctly");
        }
    }

    client.close().await.expect("Close failed");
}

#[tokio::test]
#[ignore = "Requires Azure SQL Database"]
async fn test_azure_datetime_types() {
    use mssql_client::Client;

    let config = get_azure_config().expect("Azure SQL config required");
    let mut client = Client::connect(config).await.expect("Connection failed");

    // Test various datetime functions
    let rows = client
        .query(
            "SELECT GETUTCDATE() AS utc, SYSDATETIMEOFFSET() AS dto",
            &[],
        )
        .await
        .expect("Query failed");

    for row_result in rows {
        let row = row_result.expect("Row error");
        // Just verify we can read the values
        let _utc: Option<chrono::NaiveDateTime> = row.get(0).ok();
        let _dto: Option<chrono::DateTime<chrono::FixedOffset>> = row.get(1).ok();
    }

    client.close().await.expect("Close failed");
}