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
use std::cell::RefCell;
use std::ptr;
use std::fmt;
use std::rc::Rc;
#[allow(unused_imports, deprecated)]
use std::ascii::AsciiExt;
use binding::*;
use Connection;
use Error;
use FromSql;
use OracleType;
use Result;
use ResultSet;
use Row;
use RowValue;
use SqlValue;
use ToSql;
use sql_value::BufferRowIndex;
use new_odpi_str;
use to_odpi_str;
use to_rust_str;
use private;
#[derive(Debug, Clone, PartialEq)]
pub enum StmtParam {
FetchArraySize(u32),
Tag(String),
Scrollable,
}
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum StatementType {
Select,
Insert,
Update,
Delete,
Merge,
Create,
Alter,
Drop,
Begin,
Declare,
Commit,
Rollback,
ExplainPlan,
Call,
Unknown,
}
impl StatementType {
pub(crate) fn from_enum(num: dpiStatementType) -> StatementType {
match num as u32 {
DPI_STMT_TYPE_SELECT => StatementType::Select,
DPI_STMT_TYPE_INSERT => StatementType::Insert,
DPI_STMT_TYPE_UPDATE => StatementType::Update,
DPI_STMT_TYPE_DELETE => StatementType::Delete,
DPI_STMT_TYPE_MERGE => StatementType::Merge,
DPI_STMT_TYPE_CREATE => StatementType::Create,
DPI_STMT_TYPE_ALTER => StatementType::Alter,
DPI_STMT_TYPE_DROP => StatementType::Drop,
DPI_STMT_TYPE_BEGIN => StatementType::Begin,
DPI_STMT_TYPE_DECLARE => StatementType::Declare,
DPI_STMT_TYPE_COMMIT => StatementType::Commit,
DPI_STMT_TYPE_ROLLBACK => StatementType::Rollback,
DPI_STMT_TYPE_EXPLAIN_PLAN => StatementType::ExplainPlan,
DPI_STMT_TYPE_CALL => StatementType::Call,
_ => StatementType::Unknown,
}
}
}
impl fmt::Display for StatementType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
&StatementType::Select => write!(f, "select"),
&StatementType::Insert => write!(f, "insert"),
&StatementType::Update => write!(f, "update"),
&StatementType::Delete => write!(f, "delete"),
&StatementType::Merge => write!(f, "merge"),
&StatementType::Create => write!(f, "create"),
&StatementType::Alter => write!(f, "alter"),
&StatementType::Drop => write!(f, "drop"),
&StatementType::Begin => write!(f, "PL/SQL(begin)"),
&StatementType::Declare => write!(f, "PL/SQL(declare)"),
&StatementType::Commit => write!(f, "commit"),
&StatementType::Rollback => write!(f, "rollback"),
&StatementType::ExplainPlan => write!(f, "explain plan"),
&StatementType::Call => write!(f, "call"),
&StatementType::Unknown => write!(f, "unknown"),
}
}
}
pub struct Statement<'conn> {
pub(crate) conn: &'conn Connection,
handle: *mut dpiStmt,
pub(crate) column_info: Vec<ColumnInfo>,
pub(crate) row: Option<Row>,
shared_buffer_row_index: Rc<RefCell<u32>>,
statement_type: StatementType,
is_returning: bool,
bind_count: usize,
bind_names: Vec<String>,
bind_values: Vec<SqlValue>,
fetch_array_size: u32,
}
impl<'conn> Statement<'conn> {
pub(crate) fn new(conn: &'conn Connection, sql: &str, params: &[StmtParam]) -> Result<Statement<'conn>> {
let sql = to_odpi_str(sql);
let mut fetch_array_size = DPI_DEFAULT_FETCH_ARRAY_SIZE;
let mut scrollable = 0;
let mut tag = new_odpi_str();
for param in params {
match param {
&StmtParam::FetchArraySize(size) => {
fetch_array_size = size;
},
&StmtParam::Scrollable => {
scrollable = 1;
},
&StmtParam::Tag(ref name) => {
tag = to_odpi_str(name);
},
}
}
let mut handle: *mut dpiStmt = ptr::null_mut();
chkerr!(conn.ctxt,
dpiConn_prepareStmt(conn.handle, scrollable, sql.ptr, sql.len,
tag.ptr, tag.len, &mut handle));
let mut info: dpiStmtInfo = Default::default();
chkerr!(conn.ctxt,
dpiStmt_getInfo(handle, &mut info),
unsafe { dpiStmt_release(handle); });
let mut num = 0;
chkerr!(conn.ctxt,
dpiStmt_getBindCount(handle, &mut num),
unsafe { dpiStmt_release(handle); });
let bind_count = num as usize;
let mut bind_names = Vec::with_capacity(bind_count);
let mut bind_values = Vec::with_capacity(bind_count);
if bind_count > 0 {
let mut names: Vec<*const i8> = vec![ptr::null_mut(); bind_count];
let mut lengths = vec![0; bind_count];
chkerr!(conn.ctxt,
dpiStmt_getBindNames(handle, &mut num,
names.as_mut_ptr(), lengths.as_mut_ptr()),
unsafe { dpiStmt_release(handle); });
bind_names = Vec::with_capacity(num as usize);
for i in 0..(num as usize) {
bind_names.push(to_rust_str(names[i], lengths[i]));
bind_values.push(SqlValue::new(conn.ctxt));
}
};
Ok(Statement {
conn: conn,
handle: handle,
column_info: Vec::new(),
row: None,
shared_buffer_row_index: Rc::new(RefCell::new(0)),
statement_type: StatementType::from_enum(info.statementType),
is_returning: info.isReturning != 0,
bind_count: bind_count,
bind_names: bind_names,
bind_values: bind_values,
fetch_array_size: fetch_array_size,
})
}
pub fn close(&mut self) -> Result<()> {
self.close_internal("")
}
fn close_internal(&mut self, tag: &str) -> Result<()> {
let tag = to_odpi_str(tag);
chkerr!(self.conn.ctxt,
dpiStmt_close(self.handle, tag.ptr, tag.len));
self.handle = ptr::null_mut();
Ok(())
}
pub fn query(&mut self, params: &[&ToSql]) -> Result<ResultSet<Row>> {
self.exec(params, true, "query")?;
Ok(ResultSet::<Row>::new(self))
}
pub fn query_named(&mut self, params: &[(&str, &ToSql)]) -> Result<ResultSet<Row>> {
self.exec_named(params, true, "query_named")?;
Ok(ResultSet::<Row>::new(self))
}
pub fn query_as<'a, T>(&'a mut self, params: &[&ToSql]) -> Result<ResultSet<'a, T>>
where T: RowValue
{
self.exec(params, true, "query_as")?;
Ok(ResultSet::new(self))
}
pub fn query_as_named<'a, T>(&'a mut self, params: &[(&str, &ToSql)]) -> Result<ResultSet<'a, T>>
where T: RowValue
{
self.exec_named(params, true, "query_as_named")?;
Ok(ResultSet::new(self))
}
pub fn query_row(&mut self, params: &[&ToSql]) -> Result<Row> {
let rows = self.query(params)?;
(&rows).next().unwrap_or(Err(Error::NoDataFound))
}
pub fn query_row_named(&mut self, params: &[(&str, &ToSql)]) -> Result<Row> {
let rows = self.query_named(params)?;
(&rows).next().unwrap_or(Err(Error::NoDataFound))
}
pub fn query_row_as<T>(&mut self, params: &[&ToSql]) -> Result<<T>::Item> where T: RowValue {
let rows = self.query_as::<T>(params)?;
(&rows).next().unwrap_or(Err(Error::NoDataFound))
}
pub fn query_row_as_named<T>(&mut self, params: &[(&str, &ToSql)]) -> Result<<T>::Item> where T: RowValue {
let rows = self.query_as_named::<T>(params)?;
(&rows).next().unwrap_or(Err(Error::NoDataFound))
}
pub fn execute(&mut self, params: &[&ToSql]) -> Result<()> {
self.exec(params, false, "execute")
}
pub fn execute_named(&mut self, params: &[(&str, &ToSql)]) -> Result<()> {
self.exec_named(params, false, "execute_named")
}
fn check_stmt_type(&self, must_be_query: bool, method_name: &str) -> Result<()> {
if must_be_query {
if self.statement_type == StatementType::Select {
Ok(())
} else {
Err(Error::InvalidOperation(format!("Could not use the `{}` method for non-select statements", method_name)))
}
} else {
if self.statement_type != StatementType::Select {
Ok(())
} else {
Err(Error::InvalidOperation(format!("Could not use the `{}` method for select statements", method_name)))
}
}
}
pub(crate) fn exec(&mut self, params: &[&ToSql], must_be_query: bool, method_name: &str) -> Result<()> {
self.check_stmt_type(must_be_query, method_name)?;
for i in 0..params.len() {
self.bind(i + 1, params[i])?;
}
self.exec_common()
}
pub(crate) fn exec_named(&mut self, params: &[(&str, &ToSql)], must_be_query: bool, method_name: &str) -> Result<()> {
self.check_stmt_type(must_be_query, method_name)?;
for i in 0..params.len() {
self.bind(params[i].0, params[i].1)?;
}
self.exec_common()
}
fn exec_common(&mut self) -> Result<()> {
let mut num_query_columns = 0;
let mut exec_mode = DPI_MODE_EXEC_DEFAULT;
if self.conn.autocommit {
exec_mode |= DPI_MODE_EXEC_COMMIT_ON_SUCCESS;
}
chkerr!(self.conn.ctxt,
dpiStmt_setFetchArraySize(self.handle, self.fetch_array_size));
chkerr!(self.conn.ctxt,
dpiStmt_execute(self.handle, exec_mode, &mut num_query_columns));
if self.statement_type == StatementType::Select {
if self.row.is_none() {
let num_cols = num_query_columns as usize;
let mut column_names = Vec::with_capacity(num_cols);
let mut column_values = Vec::with_capacity(num_cols);
self.column_info = Vec::with_capacity(num_cols);
for i in 0..num_cols {
let ci = ColumnInfo::new(self, i)?;
column_names.push(ci.name.clone());
self.column_info.push(ci);
let mut val = SqlValue::new(self.conn.ctxt);
val.buffer_row_index = BufferRowIndex::Shared(self.shared_buffer_row_index.clone());
let oratype = self.column_info[i].oracle_type();
let oratype_i64 = OracleType::Int64;
let oratype = match *oratype {
OracleType::Number(prec, 0) if 0 < prec && prec < DPI_MAX_INT64_PRECISION as u8 =>
&oratype_i64,
_ =>
oratype,
};
val.init_handle(self.conn.handle, oratype, self.fetch_array_size)?;
chkerr!(self.conn.ctxt,
dpiStmt_define(self.handle, (i + 1) as u32, val.handle));
column_values.push(val);
}
self.row = Some(Row::new(self.conn, column_names, column_values)?);
}
}
if self.is_returning {
for mut val in self.bind_values.iter_mut() {
val.fix_internal_data()?;
}
}
Ok(())
}
pub fn bind_count(&self) -> usize {
self.bind_count
}
pub fn bind_names(&self) -> Vec<&str> {
self.bind_names.iter().map(|name| name.as_str()).collect()
}
pub fn bind<I>(&mut self, bindidx: I, value: &ToSql) -> Result<()> where I: BindIndex {
let pos = bindidx.idx(&self)?;
if self.bind_values[pos].init_handle(self.conn.handle, &value.oratype()?, 1)? {
chkerr!(self.conn.ctxt,
bindidx.bind(self.handle, self.bind_values[pos].handle));
}
self.bind_values[pos].set(value)
}
pub fn bind_value<I, T>(&self, bindidx: I) -> Result<T> where I: BindIndex, T: FromSql {
let pos = bindidx.idx(&self)?;
self.bind_values[pos].get()
}
pub fn returned_values<I, T>(&self, bindidx: I) -> Result<Vec<T>> where I: BindIndex, T: FromSql {
let mut rows = 0;
chkerr!(self.conn.ctxt,
dpiStmt_getRowCount(self.handle, &mut rows));
if rows == 0 {
return Ok(vec![]);
}
let mut sqlval = self.bind_values[bindidx.idx(&self)?].unsafely_clone();
if rows > sqlval.array_size as u64 {
rows = sqlval.array_size as u64;
}
let mut vec = Vec::with_capacity(rows as usize);
for i in 0..rows {
sqlval.buffer_row_index = BufferRowIndex::Owned(i as u32);
vec.push(sqlval.get()?);
}
Ok(vec)
}
pub(crate) fn next(&self) -> Option<Result<&Row>> {
let mut found = 0;
let mut buffer_row_index = 0;
if unsafe { dpiStmt_fetch(self.handle, &mut found, &mut buffer_row_index) } == 0 {
if found != 0 {
*self.shared_buffer_row_index.borrow_mut() = buffer_row_index;
Some(Ok(self.row.as_ref().unwrap()))
} else {
None
}
} else {
Some(Err(::error::error_from_context(self.conn.ctxt)))
}
}
pub fn row_count(&self) -> Result<u64> {
let mut count = 0;
chkerr!(self.conn.ctxt,
dpiStmt_getRowCount(self.handle, &mut count));
Ok(count)
}
pub fn statement_type(&self) -> StatementType {
self.statement_type
}
pub fn is_query(&self) -> bool {
self.statement_type == StatementType::Select
}
pub fn is_plsql(&self) -> bool {
match self.statement_type {
StatementType::Begin |
StatementType::Declare |
StatementType::Call => true,
_ => false,
}
}
pub fn is_ddl(&self) -> bool {
match self.statement_type {
StatementType::Create |
StatementType::Drop |
StatementType::Alter => true,
_ => false,
}
}
pub fn is_dml(&self) -> bool {
match self.statement_type {
StatementType::Insert |
StatementType::Update |
StatementType::Delete |
StatementType::Merge => true,
_ => false,
}
}
pub fn is_returning(&self) -> bool {
self.is_returning
}
}
impl<'conn> Drop for Statement<'conn> {
fn drop(&mut self) {
unsafe { dpiStmt_release(self.handle) };
}
}
impl<'conn> fmt::Debug for Statement<'conn> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Statement {{ handle: {:?}, conn: {:?}, stmt_type: {}",
self.handle, self.conn, self.statement_type())?;
if self.column_info.len() != 0 {
write!(f, ", colum_info: [")?;
for (idx, colinfo) in (&self.column_info).iter().enumerate() {
if idx != 0 {
write!(f, ", ")?;
}
write!(f, "{} {}{}", colinfo.name(), colinfo.oracle_type(),
if colinfo.nullable() {""} else {" NOT NULL"})?;
}
write!(f, "], fetch_array_size: {}", self.fetch_array_size)?;
}
if self.bind_count != 0 {
write!(f, ", bind_count: {}, bind_names: {:?}, bind_values: {:?}",
self.bind_count, self.bind_names, self.bind_values)?;
}
if self.is_returning {
write!(f, ", is_returning: true")?;
}
write!(f, " }}")
}
}
#[derive(Debug, Clone)]
pub struct ColumnInfo {
name: String,
oracle_type: OracleType,
nullable: bool,
}
impl ColumnInfo {
fn new(stmt: &Statement, idx: usize) -> Result<ColumnInfo> {
let mut info = Default::default();
chkerr!(stmt.conn.ctxt,
dpiStmt_getQueryInfo(stmt.handle, (idx + 1) as u32, &mut info));
Ok(ColumnInfo {
name: to_rust_str(info.name, info.nameLength),
oracle_type: OracleType::from_type_info(stmt.conn.ctxt, &info.typeInfo)?,
nullable: info.nullOk != 0,
})
}
pub fn name(&self) -> &str {
&self.name
}
pub fn oracle_type(&self) -> &OracleType {
&self.oracle_type
}
pub fn nullable(&self) -> bool {
self.nullable
}
}
impl fmt::Display for ColumnInfo {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.nullable {
write!(f, "{} {}", self.name, self.oracle_type)
} else {
write!(f, "{} {} NOT NULL", self.name, self.oracle_type)
}
}
}
pub trait BindIndex: private::Sealed {
#[doc(hidden)]
fn idx(&self, stmt: &Statement) -> Result<usize>;
#[doc(hidden)]
unsafe fn bind(&self, stmt_handle: *mut dpiStmt, var_handle: *mut dpiVar) -> i32;
}
impl BindIndex for usize {
fn idx(&self, stmt: &Statement) -> Result<usize> {
let num = stmt.bind_count();
if 0 < num && *self <= num {
Ok(*self - 1)
} else {
Err(Error::InvalidBindIndex(*self))
}
}
unsafe fn bind(&self, stmt_handle: *mut dpiStmt, var_handle: *mut dpiVar) -> i32 {
dpiStmt_bindByPos(stmt_handle, *self as u32, var_handle)
}
}
impl<'a> BindIndex for &'a str {
fn idx(&self, stmt: &Statement) -> Result<usize> {
let bindname = self.to_uppercase();
stmt.bind_names().iter().position(|&name| name == bindname)
.ok_or_else(|| Error::InvalidBindName((*self).to_string()))
}
unsafe fn bind(&self, stmt_handle: *mut dpiStmt, var_handle: *mut dpiVar) -> i32 {
let s = to_odpi_str(*self);
dpiStmt_bindByName(stmt_handle, s.ptr, s.len, var_handle)
}
}
pub trait ColumnIndex: private::Sealed {
#[doc(hidden)]
fn idx(&self, column_names: &Vec<String>) -> Result<usize>;
}
impl ColumnIndex for usize {
fn idx(&self, column_names: &Vec<String>) -> Result<usize> {
let ncols = column_names.len();
if *self < ncols {
Ok(*self)
} else {
Err(Error::InvalidColumnIndex(*self))
}
}
}
impl<'a> ColumnIndex for &'a str {
fn idx(&self, column_names: &Vec<String>) -> Result<usize> {
for (idx, colname) in column_names.iter().enumerate() {
if colname.as_str().eq_ignore_ascii_case(*self) {
return Ok(idx);
}
}
Err(Error::InvalidColumnName((*self).to_string()))
}
}