/
integration.rs
3748 lines (3264 loc) · 132 KB
/
integration.rs
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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
mod common;
use odbc_sys::{SqlDataType, Timestamp};
use stdext::function_name;
use sys::NULL_DATA;
use tempfile::NamedTempFile;
use test_case::test_case;
use common::{cursor_to_string, Profile, SingleColumnRowSetBuffer, ENV};
use odbc_api::{
buffers::{
BufferDesc, ColumnarAnyBuffer, ColumnarBuffer, Indicator, Item, TextColumn, TextRowSet,
},
handles::{OutputStringBuffer, ParameterDescription, Statement},
parameter::InputParameter,
parameter::{
Blob, BlobRead, BlobSlice, VarBinaryArray, VarCharArray, VarCharSlice, WithDataType,
},
sys, Bit, ColumnDescription, Connection, ConnectionOptions, Cursor, DataType, Error, InOut,
IntoParameter, Nullability, Nullable, Out, ResultSetMetadata, U16Str, U16String,
};
use std::{
ffi::CString,
io::{self, Write},
iter, str, thread,
time::Duration,
};
const MSSQL_CONNECTION: &str =
"Driver={ODBC Driver 17 for SQL Server};Server=localhost;UID=SA;PWD=My@Test@Password1;";
const MSSQL: &Profile = &Profile {
connection_string: MSSQL_CONNECTION,
index_type: "int IDENTITY(1,1)",
blob_type: "Image",
};
#[cfg(target_os = "windows")]
const SQLITE_3_CONNECTION: &str = "Driver={SQLite3 ODBC Driver};Database=sqlite-test.db";
#[cfg(not(target_os = "windows"))]
const SQLITE_3_CONNECTION: &str = "Driver={SQLite3};Database=sqlite-test.db";
const SQLITE_3: &Profile = &Profile {
connection_string: SQLITE_3_CONNECTION,
index_type: "int IDENTITY(1,1)",
blob_type: "BLOB",
};
#[cfg(target_os = "windows")]
const MARIADB_CONNECTION: &str = "Driver={MariaDB ODBC 3.1 Driver};\
Server=localhost;DB=test_db;\
UID=root;PWD=my-secret-pw;\
Port=3306";
// Use 127.0.0.1 instead of localhost so the system uses the TCP/IP connector instead of the socket
// connector. Prevents error message: 'Can't connect to local MySQL server through socket'.
#[cfg(not(target_os = "windows"))]
const MARIADB_CONNECTION: &str = "Driver={MariaDB 3.1 Driver};\
Server=127.0.0.1;DB=test_db;\
UID=root;PWD=my-secret-pw;\
Port=3306";
const POSTGRES_CONNECTION: &str = "Driver={PostgreSQL UNICODE};\
Server=localhost;\
Port=5432;\
Database=test;\
Uid=test;\
Pwd=test;";
const MARIADB: &Profile = &Profile {
connection_string: MARIADB_CONNECTION,
index_type: "INTEGER AUTO_INCREMENT PRIMARY KEY",
blob_type: "BLOB",
};
const POSTGRES: &Profile = &Profile {
connection_string: POSTGRES_CONNECTION,
index_type: "SERIAL PRIMARY KEY",
blob_type: "BYTEA",
};
macro_rules! table_name {
() => {
// Make function name a valid table name
function_name!()
.replace("::", "_")
.replace(r#"_{{closure}}"#, "")
};
}
#[test]
fn bogus_connection_string() {
// When
let result = ENV.connect_with_connection_string("foobar", ConnectionOptions::default());
// Then
// We expect an error, since "foobar" is obviously not a connection string we can use to connect
// to any datasource (for starters it does not specify a driver).
assert!(result.is_err());
// We also want to be sure our error messages do not contain any Nul.
let error = result.err().unwrap();
if let Error::Diagnostics { record, function } = error {
assert_eq!("SQLDriverConnect", function);
// Make sure we remove any Nuls from the message, trailing or otherwise.
assert!(!record.message.contains(&0));
} else {
panic!("Expected Error::Diagnostics")
};
}
#[test_case(MSSQL; "Microsoft SQL Server")]
#[test_case(MARIADB; "Maria DB")]
#[test_case(SQLITE_3; "SQLite 3")]
#[test_case(POSTGRES; "PostgreSQL")]
fn connect_to_db(profile: &Profile) {
let conn = profile.connection().unwrap();
assert!(!conn.is_dead().unwrap())
}
#[test_case(MSSQL; "Microsoft SQL Server")]
fn describe_columns(profile: &Profile) {
let table_name = table_name!();
let (conn, table) = profile
.given(
&table_name,
&[
"VARCHAR(255) NOT NULL",
"INTEGER",
"BINARY(12)",
"VARBINARY(100)",
"NCHAR(10)",
"NUMERIC(3,2)",
"DATETIME2",
"TIME",
"text",
"Image",
"DOUBLE PRECISION",
],
)
.unwrap();
let sql = table.sql_all_ordered_by_id();
let mut cursor = conn.execute(&sql, ()).unwrap().unwrap();
assert_eq!(cursor.num_result_cols().unwrap(), 11);
let mut actual = ColumnDescription::default();
let kind = DataType::Varchar { length: 255 };
let expected = ColumnDescription::new("a", kind, Nullability::NoNulls);
cursor.describe_col(1, &mut actual).unwrap();
assert_eq!(expected, actual);
assert_eq!(kind, cursor.col_data_type(1).unwrap());
let kind = DataType::Integer;
let expected = ColumnDescription::new("b", kind, Nullability::Nullable);
cursor.describe_col(2, &mut actual).unwrap();
assert_eq!(expected, actual);
assert_eq!(kind, cursor.col_data_type(2).unwrap());
let kind = DataType::Binary { length: 12 };
let expected = ColumnDescription::new("c", kind, Nullability::Nullable);
cursor.describe_col(3, &mut actual).unwrap();
assert_eq!(expected, actual);
assert_eq!(kind, cursor.col_data_type(3).unwrap());
let kind = DataType::Varbinary { length: 100 };
let expected = ColumnDescription::new("d", kind, Nullability::Nullable);
cursor.describe_col(4, &mut actual).unwrap();
assert_eq!(expected, actual);
assert_eq!(kind, cursor.col_data_type(4).unwrap());
let kind = DataType::WChar { length: 10 };
let expected = ColumnDescription::new("e", kind, Nullability::Nullable);
cursor.describe_col(5, &mut actual).unwrap();
assert_eq!(expected, actual);
assert_eq!(kind, cursor.col_data_type(5).unwrap());
let kind = DataType::Numeric {
precision: 3,
scale: 2,
};
let expected = ColumnDescription::new("f", kind, Nullability::Nullable);
cursor.describe_col(6, &mut actual).unwrap();
assert_eq!(expected, actual);
assert_eq!(kind, cursor.col_data_type(6).unwrap());
let kind = DataType::Timestamp { precision: 7 };
let expected = ColumnDescription::new("g", kind, Nullability::Nullable);
cursor.describe_col(7, &mut actual).unwrap();
assert_eq!(expected, actual);
assert_eq!(kind, cursor.col_data_type(7).unwrap());
let kind = DataType::Other {
data_type: SqlDataType(-154),
column_size: 16,
decimal_digits: 7,
};
let expected = ColumnDescription::new("h", kind, Nullability::Nullable);
cursor.describe_col(8, &mut actual).unwrap();
assert_eq!(expected, actual);
assert_eq!(kind, cursor.col_data_type(8).unwrap());
let kind = DataType::LongVarchar { length: 2147483647 };
let expected = ColumnDescription::new("i", kind, Nullability::Nullable);
cursor.describe_col(9, &mut actual).unwrap();
assert_eq!(expected, actual);
assert_eq!(kind, cursor.col_data_type(9).unwrap());
let kind = DataType::LongVarbinary { length: 2147483647 };
let expected = ColumnDescription::new("j", kind, Nullability::Nullable);
cursor.describe_col(10, &mut actual).unwrap();
assert_eq!(expected, actual);
assert_eq!(kind, cursor.col_data_type(10).unwrap());
let kind = DataType::Float { precision: 53 };
let expected = ColumnDescription::new("k", kind, Nullability::Nullable);
cursor.describe_col(11, &mut actual).unwrap();
assert_eq!(expected, actual);
assert_eq!(kind, cursor.col_data_type(11).unwrap());
}
/// Fetch text from data source using the TextBuffer type
#[test_case(MSSQL; "Microsoft SQL Server")]
#[test_case(MARIADB; "Maria DB")]
#[test_case(SQLITE_3; "SQLite 3")]
#[test_case(POSTGRES; "PostgreSQL")]
fn bulk_fetch_text(profile: &Profile) {
let table_name = table_name!();
let (conn, table) = profile
.given(&table_name, &["VARCHAR(255)", "INT"])
.unwrap();
// Insert data
let insert = format!("INSERT INTO {table_name} (a,b) VALUES (?,?), (?,?),(?,?)");
conn.execute(
&insert,
(
&"Interstellar".into_parameter(),
&None::<i32>.into_parameter(),
&"2001: A Space Odyssey".into_parameter(),
&1968,
&"Jurassic Park".into_parameter(),
&1993,
),
)
.unwrap();
let query = table.sql_all_ordered_by_id();
let cursor = conn.execute(&query, ()).unwrap().unwrap();
// Cursor to string helper utilizes the text buffer
let actual = cursor_to_string(cursor);
let expected = "Interstellar,NULL\n2001: A Space Odyssey,1968\nJurassic Park,1993";
assert_eq!(expected, actual);
}
/// Into cursor should enable users to open a connection within a function and return a cursor.
#[test_case(MSSQL; "Microsoft SQL Server")]
#[test_case(MARIADB; "Maria DB")]
#[test_case(SQLITE_3; "SQLite 3")]
#[test_case(POSTGRES; "PostgreSQL")]
fn into_cursor(profile: &Profile) {
let table_name = table_name!();
let (conn, table) = profile
.given(&table_name, &["VARCHAR(255)", "INT"])
.unwrap();
// Insert data
let insert = format!("INSERT INTO {table_name} (a,b) VALUES (?,?), (?,?),(?,?)");
conn.execute(
&insert,
(
&"Interstellar".into_parameter(),
&None::<i32>.into_parameter(),
&"2001: A Space Odyssey".into_parameter(),
&1968,
&"Jurassic Park".into_parameter(),
&1993,
),
)
.unwrap();
let make_cursor = || {
let conn = profile.connection().unwrap();
let query = table.sql_all_ordered_by_id();
conn.into_cursor(&query, ()).unwrap().unwrap()
};
let cursor = make_cursor();
// Cursor to string helper utilizes the text buffer
let actual = cursor_to_string(cursor);
let expected = "Interstellar,NULL\n2001: A Space Odyssey,1968\nJurassic Park,1993";
assert_eq!(expected, actual);
}
#[test_case(MSSQL; "Microsoft SQL Server")]
#[test_case(MARIADB; "Maria DB")]
#[test_case(SQLITE_3; "SQLite 3")]
#[test_case(POSTGRES; "PostgreSQL")]
fn column_name(profile: &Profile) {
let table_name = table_name!();
let conn = profile
.setup_empty_table(&table_name, &["VARCHAR(255)", "INT"])
.unwrap();
let sql = format!("SELECT a, b FROM {table_name};");
let mut cursor = conn.execute(&sql, ()).unwrap().unwrap();
let name = cursor.col_name(1).unwrap();
assert_eq!("a", name);
let name = cursor.col_name(2).unwrap();
assert_eq!("b", name);
// Test the same using column descriptions
let mut desc = ColumnDescription::default();
cursor.describe_col(1, &mut desc).unwrap();
assert_eq!("a", desc.name_to_string().unwrap());
cursor.describe_col(2, &mut desc).unwrap();
assert_eq!("b", desc.name_to_string().unwrap());
}
#[test_case(MSSQL; "Microsoft SQL Server")]
#[test_case(MARIADB; "Maria DB")]
#[test_case(SQLITE_3; "SQLite 3")]
#[test_case(POSTGRES; "PostgreSQL")]
fn bind_wide_column_to_char(profile: &Profile) {
let table_name = table_name!();
let (conn, table) = profile.given(&table_name, &["CHAR(5)"]).unwrap();
let insert_sql = table.sql_insert();
conn.execute(&insert_sql, &"Hello".into_parameter())
.unwrap();
let sql = table.sql_all_ordered_by_id();
let cursor = conn.execute(&sql, ()).unwrap().unwrap();
let mut buf = ColumnarBuffer::new(vec![(1, TextColumn::<u16>::new(1, 5))]);
let mut row_set_cursor = cursor.bind_buffer(&mut buf).unwrap();
row_set_cursor.fetch().unwrap();
drop(row_set_cursor);
assert_eq!(
Some(U16String::from_str("Hello").as_ustr()),
buf.column(0).get(0).map(U16Str::from_slice)
);
}
/// Bind a BIT column to a Bit buffer.
#[test_case(MSSQL; "Microsoft SQL Server")]
#[test_case(MARIADB; "Maria DB")]
#[test_case(SQLITE_3; "SQLite 3")]
#[test_case(POSTGRES; "PostgreSQL")]
fn bind_bit(profile: &Profile) {
let table_name = table_name!();
let conn = profile.setup_empty_table(&table_name, &["BIT"]).unwrap();
let insert_sql = format!("INSERT INTO {table_name} (a) VALUES (?),(?);");
conn.execute(&insert_sql, (&Bit::from_bool(false), &Bit::from_bool(true)))
.unwrap();
let sql = format!("SELECT a FROM {table_name};");
let cursor = conn.execute(&sql, ()).unwrap().unwrap();
let mut buf = ColumnarBuffer::new(vec![(1, vec![Bit(0); 3])]);
let mut row_set_cursor = cursor.bind_buffer(&mut buf).unwrap();
let batch = row_set_cursor.fetch().unwrap().unwrap();
assert!(!batch.column(0)[0].as_bool());
assert!(batch.column(0)[1].as_bool());
}
/// Binds a buffer which is too short to a fixed sized character type. This provokes an indicator of
/// `NO_TOTAL` on MSSQL.
#[test_case(MSSQL; "Microsoft SQL Server")]
#[test_case(MARIADB; "Maria DB")]
#[test_case(SQLITE_3; "SQLite 3")]
#[test_case(POSTGRES; "PostgreSQL")]
fn truncate_fixed_sized(profile: &Profile) {
let table_name = table_name!();
let (conn, table) = profile.given(&table_name, &["CHAR(5)"]).unwrap();
let insert_sql = table.sql_insert();
conn.execute(&insert_sql, &"Hello".into_parameter())
.unwrap();
let cursor = conn
.execute(&table.sql_all_ordered_by_id(), ())
.unwrap()
.unwrap();
let mut buf = ColumnarBuffer::new(vec![(1, TextColumn::new(1, 3))]);
let mut row_set_cursor = cursor.bind_buffer(&mut buf).unwrap();
let batch = row_set_cursor.fetch().unwrap().unwrap();
assert_eq!(Some(&b"Hel"[..]), batch.column(0).get(0));
}
/// Bind a VARCHAR column to a char buffer.
#[test_case(MSSQL; "Microsoft SQL Server")]
#[test_case(MARIADB; "Maria DB")]
#[test_case(SQLITE_3; "SQLite 3")]
#[test_case(POSTGRES; "PostgreSQL")]
fn bind_varchar(profile: &Profile) {
let table_name = table_name!();
let conn = profile
.setup_empty_table(&table_name, &["VARCHAR(100)"])
.unwrap();
let insert_sql = format!("INSERT INTO {table_name} (a) VALUES ('Hello, World!');");
conn.execute(&insert_sql, ()).unwrap();
let sql = format!("SELECT a FROM {table_name};");
let cursor = conn.execute(&sql, ()).unwrap().unwrap();
let mut buf = TextRowSet::from_max_str_lens(1, [100]).unwrap();
// let mut buf = SingleColumnRowSetBuffer::with_text_column(1, 100);
let mut row_set_cursor = cursor.bind_buffer(&mut buf).unwrap();
row_set_cursor.fetch().unwrap();
drop(row_set_cursor);
assert_eq!(Some(&b"Hello, World!"[..]), buf.column(0).get(0));
}
/// Bind a VARCHAR column to a wchar buffer
#[test_case(MSSQL; "Microsoft SQL Server")]
#[test_case(MARIADB; "Maria DB")]
#[test_case(SQLITE_3; "SQLite 3")]
#[test_case(POSTGRES; "PostgreSQL")]
fn bind_varchar_to_wchar(profile: &Profile) {
let table_name = table_name!();
let (conn, table) = profile.given(&table_name, &["VARCHAR(100)"]).unwrap();
let insert_sql = table.sql_insert();
conn.execute(&insert_sql, &"Hello, World!".into_parameter())
.unwrap();
let sql = table.sql_all_ordered_by_id();
let cursor = conn.execute(&sql, ()).unwrap().unwrap();
let mut buf = ColumnarBuffer::new(vec![(1, TextColumn::<u16>::new(1, 100))]);
let mut row_set_cursor = cursor.bind_buffer(&mut buf).unwrap();
let batch = row_set_cursor.fetch().unwrap().unwrap();
assert_eq!(
U16String::from_str("Hello, World!").as_ustr(),
U16Str::from_slice(batch.column(0).get(0).unwrap())
);
}
/// utf16 to utf8 conversion with one character those utf-16 representation is smaller than its utf8
/// representation
#[test_case(MSSQL; "Microsoft SQL Server")]
#[test_case(MARIADB; "Maria DB")]
// #[test_case(SQLITE_3; "SQLite 3")] //Doesn't work on Linux
#[cfg(not(target_os = "windows"))] // Windows does not use UTF-8 locale by default
fn nvarchar_to_text(profile: &Profile) {
let table_name = table_name!();
let conn = profile
.setup_empty_table(&table_name, &["NVARCHAR(1)"])
.unwrap();
// Trade mark sign (`™`) is longer in utf-8 (3 Bytes) than in utf-16 (2 Bytes).
let insert_sql = format!("INSERT INTO {} (a) VALUES (?);", table_name);
conn.execute(&insert_sql, &"™".into_parameter()).unwrap();
let sql = format!("SELECT a FROM {};", table_name);
let cursor = conn.execute(&sql, ()).unwrap().unwrap();
let text = cursor_to_string(cursor);
assert_eq!("™", text);
}
#[test_case(MSSQL; "Microsoft SQL Server")]
#[test_case(MARIADB; "Maria DB")]
#[test_case(SQLITE_3; "SQLite 3")]
#[test_case(POSTGRES; "PostgreSQL")]
fn bind_numeric_to_float(profile: &Profile) {
// Setup table
let table_name = table_name!();
let conn = profile
.setup_empty_table(&table_name, &["NUMERIC(3,2)"])
.unwrap();
let insert_sql = format!("INSERT INTO {table_name} (a) VALUES (?);");
conn.execute(&insert_sql, &1.23).unwrap();
let sql = format!("SELECT a FROM {table_name}");
let cursor = conn.execute(&sql, ()).unwrap().unwrap();
let buf: SingleColumnRowSetBuffer<Vec<f64>> = SingleColumnRowSetBuffer::new(1);
let mut row_set_cursor = cursor.bind_buffer(buf).unwrap();
let actual = row_set_cursor.fetch().unwrap().unwrap().get();
assert_eq!(1, actual.len());
assert!((1.23f64 - actual[0]).abs() < f64::EPSILON);
}
#[test_case(MSSQL; "Microsoft SQL Server")]
#[test_case(MARIADB; "Maria DB")]
#[test_case(SQLITE_3; "SQLite 3")]
#[test_case(POSTGRES; "PostgreSQL")]
fn bind_numeric_to_i64(profile: &Profile) {
// Setup table
let table_name = table_name!();
let conn = profile
.setup_empty_table(&table_name, &["NUMERIC(10,0)"])
.unwrap();
let insert_sql = format!("INSERT INTO {table_name} (a) VALUES (?);");
conn.execute(&insert_sql, &1234567890i64).unwrap();
let sql = format!("SELECT a FROM {table_name}");
let cursor = conn.execute(&sql, ()).unwrap().unwrap();
let buf: SingleColumnRowSetBuffer<Vec<i64>> = SingleColumnRowSetBuffer::new(1);
let mut row_set_cursor = cursor.bind_buffer(buf).unwrap();
let actual = row_set_cursor.fetch().unwrap().unwrap().get();
assert_eq!(1, actual.len());
assert_eq!(1234567890, actual[0]);
}
/// Bind a columnar buffer to a VARBINARY(10) column and fetch data.
#[test_case(MSSQL; "Microsoft SQL Server")]
// #[test_case(MARIADB; "Maria DB")] // Convert syntax is different
// #[test_case(SQLITE_3; "SQLite 3")]
fn columnar_fetch_varbinary(profile: &Profile) {
// Setup
let table_name = table_name!();
let (conn, table) = profile.given(&table_name, &["VARBINARY(10)"]).unwrap();
let insert_sql = format!(
"INSERT INTO {table_name} (a) Values \
(CONVERT(Varbinary(10), 'Hello')),\
(CONVERT(Varbinary(10), 'World')),\
(NULL)"
);
conn.execute(&insert_sql, ()).unwrap();
// Retrieve values
let mut cursor = conn
.execute(&table.sql_all_ordered_by_id(), ())
.unwrap()
.unwrap();
let data_type = cursor.col_data_type(1).unwrap();
assert_eq!(DataType::Varbinary { length: 10 }, data_type);
let buffer_desc = BufferDesc::from_data_type(data_type, true).unwrap();
assert_eq!(BufferDesc::Binary { length: 10 }, buffer_desc);
let row_set_buffer = ColumnarAnyBuffer::try_from_descs(10, iter::once(buffer_desc)).unwrap();
let mut cursor = cursor.bind_buffer(row_set_buffer).unwrap();
let batch = cursor.fetch().unwrap().unwrap();
let mut col_it = batch.column(0).as_bin_view().unwrap().iter();
assert_eq!(Some(&b"Hello"[..]), col_it.next().unwrap());
assert_eq!(Some(&b"World"[..]), col_it.next().unwrap());
assert_eq!(Some(None), col_it.next()); // Expecting NULL
assert_eq!(None, col_it.next()); // Expecting iterator end.
}
#[test_case(MSSQL, "VARCHAR(max)"; "Microsoft SQL Server")]
#[test_case(MARIADB, "TEXT"; "Maria DB")]
#[test_case(SQLITE_3, "TEXT"; "SQLite 3")]
#[test_case(POSTGRES, "TEXT"; "PostgreSQL")]
fn upper_limit_for_varchar_max(profile: &Profile, large_text_type: &'static str) {
// Given
let table_name = table_name!();
let types = [large_text_type];
let (conn, table) = profile.given(&table_name, &types).unwrap();
conn.execute(&table.sql_insert(), &"Hello, World!".into_parameter())
.unwrap();
// When
let mut cursor = conn
.execute(&format!("SELECT a FROM {table_name}"), ())
.unwrap()
.unwrap();
let text_buffer = TextRowSet::for_cursor(10, &mut cursor, Some(50)).unwrap();
let mut cursor = cursor.bind_buffer(text_buffer).unwrap();
let batch = cursor.fetch().unwrap().unwrap();
// Then
assert_eq!(
"Hello, World!",
str::from_utf8(batch.column(0).get(0).unwrap()).unwrap()
);
}
/// Bind a columnar buffer to a BINARY(5) column and fetch data.
#[test_case(MSSQL; "Microsoft SQL Server")]
// #[test_case(MARIADB; "Maria DB")] // different convert syntax
// #[test_case(SQLITE_3; "SQLite 3")]
fn columnar_fetch_binary(profile: &Profile) {
// Setup
let conn = profile
.setup_empty_table("ColumnarFetchBinary", &["BINARY(5)"])
.unwrap();
conn.execute(
"INSERT INTO ColumnarFetchBinary (a) Values \
(CONVERT(Binary(5), 'Hello')),\
(CONVERT(Binary(5), 'World')),\
(NULL)",
(),
)
.unwrap();
// Retrieve values
let mut cursor = conn
.execute("SELECT a FROM ColumnarFetchBinary ORDER BY Id", ())
.unwrap()
.unwrap();
let data_type = cursor.col_data_type(1).unwrap();
assert_eq!(DataType::Binary { length: 5 }, data_type);
let buffer_desc = BufferDesc::from_data_type(data_type, true).unwrap();
assert_eq!(BufferDesc::Binary { length: 5 }, buffer_desc);
let row_set_buffer = ColumnarAnyBuffer::try_from_descs(10, iter::once(buffer_desc)).unwrap();
let mut cursor = cursor.bind_buffer(row_set_buffer).unwrap();
let batch = cursor.fetch().unwrap().unwrap();
let mut col_it = batch.column(0).as_bin_view().unwrap().iter();
assert_eq!(Some(&b"Hello"[..]), col_it.next().unwrap());
assert_eq!(Some(&b"World"[..]), col_it.next().unwrap());
assert_eq!(Some(None), col_it.next()); // Expecting NULL
assert_eq!(None, col_it.next()); // Expecting iterator end.
}
/// Bind a columnar buffer to a DATETIME2 column and fetch data.
#[test_case(MSSQL; "Microsoft SQL Server")]
// #[test_case(MARIADB; "Maria DB")] No DATEIME2 type
#[test_case(SQLITE_3; "SQLite 3")]
fn columnar_fetch_timestamp(profile: &Profile) {
let table_name = table_name!();
// Setup
let conn = profile
.setup_empty_table(&table_name, &["DATETIME2(3)"])
.unwrap();
conn.execute(
&format!(
"INSERT INTO {table_name} (a) Values \
({{ ts '2021-03-20 15:24:12.12' }}),\
({{ ts '2020-03-20 15:24:12' }}),\
({{ ts '1970-01-01 00:00:00' }}),\
(NULL)"
),
(),
)
.unwrap();
// Retrieve values
let mut cursor = conn
.execute(&format!("SELECT a FROM {table_name} ORDER BY Id"), ())
.unwrap()
.unwrap();
let data_type = cursor.col_data_type(1).unwrap();
assert_eq!(DataType::Timestamp { precision: 3 }, data_type);
let buffer_desc = BufferDesc::from_data_type(data_type, true).unwrap();
assert_eq!(BufferDesc::Timestamp { nullable: true }, buffer_desc);
let row_set_buffer = ColumnarAnyBuffer::try_from_descs(10, iter::once(buffer_desc)).unwrap();
let mut cursor = cursor.bind_buffer(row_set_buffer).unwrap();
let batch = cursor.fetch().unwrap().unwrap();
let mut col_it = batch.column(0).as_nullable_slice().unwrap();
assert_eq!(
Some(&Timestamp {
year: 2021,
month: 3,
day: 20,
hour: 15,
minute: 24,
second: 12,
fraction: 120_000_000,
}),
col_it.next().unwrap()
);
assert_eq!(
Some(&Timestamp {
year: 2020,
month: 3,
day: 20,
hour: 15,
minute: 24,
second: 12,
fraction: 0,
}),
col_it.next().unwrap()
);
assert_eq!(
Some(&Timestamp {
year: 1970,
month: 1,
day: 1,
hour: 0,
minute: 0,
second: 0,
fraction: 0,
}),
col_it.next().unwrap()
);
assert_eq!(Some(None), col_it.next()); // Expecting NULL
assert_eq!(None, col_it.next()); // Expecting iterator end.
}
/// Insert values into a DATETIME2 column using a columnar buffer
#[test_case(MSSQL; "Microsoft SQL Server")]
// #[test_case(MARIADB; "Maria DB")] No DATEIME2 type
// #[test_case(SQLITE_3; "SQLite 3")] default precision of 3 instead 7
fn columnar_insert_timestamp(profile: &Profile) {
let table_name = table_name!();
// Setup
let (conn, table) = profile.given(&table_name, &["DATETIME2"]).unwrap();
// Fill buffer with values
let desc = BufferDesc::Timestamp { nullable: true };
let prepared = conn.prepare(&table.sql_insert()).unwrap();
let mut prebound = prepared.into_column_inserter(10, [desc]).unwrap();
// Input values to insert. Note that the last element has > 5 chars and is going to trigger a
// reallocation of the underlying buffer.
let input = [
Some(Timestamp {
year: 2020,
month: 3,
day: 20,
hour: 16,
minute: 13,
second: 54,
fraction: 0,
}),
Some(Timestamp {
year: 2021,
month: 3,
day: 20,
hour: 16,
minute: 13,
second: 54,
fraction: 123456700,
}),
None,
];
prebound.set_num_rows(input.len());
let column = prebound.column_mut(0);
let mut writer = Timestamp::as_nullable_slice_mut(column).unwrap();
writer.write(input.iter().copied());
// Bind buffer and insert values.
prebound.execute().unwrap();
// Query values and compare with expectation
let actual = table.content_as_string(&conn);
let expected = "2020-03-20 16:13:54.0000000\n2021-03-20 16:13:54.1234567\nNULL";
assert_eq!(expected, actual);
}
/// Insert values into a i32 column using a columnar buffer's raw values
#[test_case(MSSQL; "Microsoft SQL Server")]
#[test_case(MARIADB; "Maria DB")]
#[test_case(SQLITE_3; "SQLite 3")]
#[test_case(POSTGRES; "PostgreSQL")]
fn columnar_insert_int_raw(profile: &Profile) {
let table_name = table_name!();
// Setup
let (conn, table) = profile.given(&table_name, &["INTEGER"]).unwrap();
// Fill buffer with values
let desc = BufferDesc::I32 { nullable: true };
let prepared = conn.prepare(&table.sql_insert()).unwrap();
let mut prebound = prepared.into_column_inserter(10, [desc]).unwrap();
// Input values to insert.
let input_values = [1, 0, 3];
let mask = [true, false, true];
prebound.set_num_rows(input_values.len());
let mut writer = prebound.column_mut(0).as_nullable_slice::<i32>().unwrap();
let (values, indicators) = writer.raw_values();
values[..input_values.len()].copy_from_slice(&input_values);
indicators
.iter_mut()
.zip(mask.iter())
.for_each(|(indicator, &mask)| *indicator = if mask { 0 } else { NULL_DATA });
// Bind buffer and insert values.
prebound.execute().unwrap();
// Query values and compare with expectation
let actual = table.content_as_string(&conn);
let expected = "1\nNULL\n3";
assert_eq!(expected, actual);
}
/// Insert values into a DATETIME2(3) column using a columnar buffer. Milliseconds precision is
/// different from the default precision 7 (100ns).
#[test_case(MSSQL; "Microsoft SQL Server")]
// #[test_case(MARIADB; "Maria DB")] No DATEIME2 type
#[test_case(SQLITE_3; "SQLite 3")]
fn columnar_insert_timestamp_ms(profile: &Profile) {
let table_name = table_name!();
// Setup
let conn = profile
.setup_empty_table(&table_name, &["DATETIME2(3)"])
.unwrap();
let prepared = conn
.prepare(&format!("INSERT INTO {table_name} (a) VALUES (?)"))
.unwrap();
// Fill buffer with values
let desc = BufferDesc::Timestamp { nullable: true };
let mut prebound = prepared.into_column_inserter(10, [desc]).unwrap();
// Input values to insert. Note that the last element has > 5 chars and is going to trigger a
// reallocation of the underlying buffer.
let input = [
Some(Timestamp {
year: 2020,
month: 3,
day: 20,
hour: 16,
minute: 13,
second: 54,
fraction: 0,
}),
Some(Timestamp {
year: 2021,
month: 3,
day: 20,
hour: 16,
minute: 13,
second: 54,
fraction: 123456700,
}),
None,
];
prebound.set_num_rows(input.len());
let mut writer = prebound.column_mut(0).as_nullable_slice().unwrap();
writer.write(input.iter().copied());
prebound.execute().unwrap();
// Query values and compare with expectation
let cursor = conn
.execute(&format!("SELECT a FROM {table_name} ORDER BY Id"), ())
.unwrap()
.unwrap();
let actual = cursor_to_string(cursor);
let expected = "2020-03-20 16:13:54.000\n2021-03-20 16:13:54.123\nNULL";
assert_eq!(expected, actual);
}
/// Insert values into a varbinary column using a columnar buffer
#[test_case(MSSQL; "Microsoft SQL Server")]
// #[test_case(MARIADB; "Maria DB")] different binary text representation
// #[test_case(SQLITE_3; "SQLite 3")] different binary text representation
fn columnar_insert_varbinary(profile: &Profile) {
// Setup
let conn = profile
.setup_empty_table("ColumnarInsertVarbinary", &["VARBINARY(13)"])
.unwrap();
let prepared = conn
.prepare("INSERT INTO ColumnarInsertVarbinary (a) VALUES (?)")
.unwrap();
// Fill buffer with values
let desc = BufferDesc::Binary { length: 5 };
let mut prebound = prepared.into_column_inserter(4, [desc]).unwrap();
// Input values to insert. Note that the last element has > 5 chars and is going to trigger a
// reallocation of the underlying buffer.
let input = [
Some(&b"Hello"[..]),
Some(&b"World"[..]),
None,
Some(&b"Hello, World!"[..]),
];
prebound.set_num_rows(input.len());
let mut writer = prebound.column_mut(0).as_bin_view().unwrap();
// Reset length to make room for `Hello, World!`.
writer.ensure_max_element_length(13, 0).unwrap();
writer.set_cell(0, Some("Hello".as_bytes()));
writer.set_cell(1, Some("World".as_bytes()));
writer.set_cell(2, None);
writer.set_cell(3, Some("Hello, World!".as_bytes()));
// Bind buffer and insert values.
prebound.execute().unwrap();
// Query values and compare with expectation
let cursor = conn
.execute("SELECT a FROM ColumnarInsertVarbinary ORDER BY Id", ())
.unwrap()
.unwrap();
let actual = cursor_to_string(cursor);
let expected = "48656C6C6F\n576F726C64\nNULL\n48656C6C6F2C20576F726C6421";
assert_eq!(expected, actual);
}
#[test_case(MSSQL; "Microsoft SQL Server")]
#[test_case(MARIADB; "Maria DB")]
#[test_case(SQLITE_3; "SQLite 3")]
#[test_case(POSTGRES; "PostgreSQL")]
fn columnar_insert_varchar(profile: &Profile) {
let table_name = table_name!();
// Setup
let conn = profile
.setup_empty_table(&table_name, &["VARCHAR(13)"])
.unwrap();
let prepared = conn
.prepare(&format!("INSERT INTO {table_name} (a) VALUES (?)"))
.unwrap();
let desc = BufferDesc::Text {
// Buffer size purposefully chosen too small, so we would get a panic if `set_max_len` would
// not work.
max_str_len: 5,
};
let mut prebound = prepared.into_column_inserter(4, [desc]).unwrap();
// Fill buffer with values
// Input values to insert. Note that the last element has > 5 chars and is going to trigger a
// reallocation of the underlying buffer.
let input = [
Some(&b"Hello"[..]),
Some(&b"World"[..]),
None,
Some(&b"Hello, World!"[..]),
];
prebound.set_num_rows(input.len());
let mut col_view = prebound.column_mut(0).as_text_view().unwrap();
// Reset length to make room for `Hello, World!`.
col_view.ensure_max_element_length(13, 0).unwrap();
col_view.set_cell(0, Some("Hello".as_bytes()));
col_view.set_cell(1, Some("World".as_bytes()));
col_view.set_cell(2, None);
col_view.set_cell(3, Some("Hello, World!".as_bytes()));
// Bind buffer and insert values.
prebound.execute().unwrap();
// Query values and compare with expectation
let cursor = conn
.execute(&format!("SELECT a FROM {table_name} ORDER BY Id"), ())
.unwrap()
.unwrap();
let actual = cursor_to_string(cursor);
let expected = "Hello\nWorld\nNULL\nHello, World!";
assert_eq!(expected, actual);
}
#[test_case(MSSQL; "Microsoft SQL Server")]
#[test_case(MARIADB; "Maria DB")]
#[test_case(SQLITE_3; "SQLite 3")]
#[test_case(POSTGRES; "PostgreSQL")]
fn columnar_insert_text_as_sql_integer(profile: &Profile) {
let table_name = table_name!();
// Setup
let conn = profile
.setup_empty_table(&table_name, &["INTEGER"])
.unwrap();
let prepared = conn
.prepare(&format!("INSERT INTO {table_name} (a) VALUES (?)"))
.unwrap();
let parameter_buffers = vec![WithDataType {
value: TextColumn::try_new(4, 5).unwrap(),
data_type: DataType::Integer,
}];
// Safety: all values in the buffer are safe for insertion
let mut prebound =
unsafe { prepared.unchecked_bind_columnar_array_parameters(parameter_buffers) }.unwrap();
prebound.set_num_rows(4);
let mut writer = prebound.column_mut(0);
writer.set_cell(0, Some("1".as_bytes()));
writer.set_cell(1, Some("2".as_bytes()));
writer.set_cell(2, None);
writer.set_cell(3, Some("4".as_bytes()));
// Bind buffer and insert values.
prebound.execute().unwrap();
// Query values and compare with expectation
let cursor = conn
.execute(&format!("SELECT a FROM {table_name} ORDER BY Id"), ())
.unwrap()
.unwrap();
let actual = cursor_to_string(cursor);
let expected = "1\n2\nNULL\n4";
assert_eq!(expected, actual);
}
/// Inserts a Vector of integers using a generic implementation
#[test_case(MSSQL; "Microsoft SQL Server")]
#[test_case(MARIADB; "Maria DB")]
#[test_case(SQLITE_3; "SQLite 3")]
#[test_case(POSTGRES; "PostgreSQL")]
fn insert_vec_column_using_generic_code(profile: &Profile) {
let table_name = table_name!();
let (conn, table) = profile.given(&table_name, &["INTEGER", "INTEGER"]).unwrap();
let insert_sql = table.sql_insert();
fn insert_tuple2_vec<A: Item, B: Item>(
conn: &Connection<'_>,
insert_sql: &str,
source: &[(A, B)],
) {
let mut prepared = conn.prepare(insert_sql).unwrap();
// Number of rows submitted in one round trip
let capacity = source.len();
// We do not need a nullable buffer since elements of source are not optional
let descriptions = [A::buffer_desc(false), B::buffer_desc(false)];
let mut inserter = prepared.column_inserter(capacity, descriptions).unwrap();
// We send everything in one go.
inserter.set_num_rows(source.len());
// Now let's copy the row based tuple into the columnar structure
for (index, (a, b)) in source.iter().enumerate() {
inserter.column_mut(0).as_slice::<A>().unwrap()[index] = *a;
inserter.column_mut(1).as_slice::<B>().unwrap()[index] = *b;