-
Notifications
You must be signed in to change notification settings - Fork 44
/
connection.rs
1801 lines (1689 loc) · 62.1 KB
/
connection.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
// Rust-oracle - Rust binding for Oracle database
//
// URL: https://github.com/kubo/rust-oracle
//
//-----------------------------------------------------------------------------
// Copyright (c) 2017-2024 Kubo Takehiro <kubo@jiubao.org>. All rights reserved.
// This program is free software: you can modify it and/or redistribute it
// under the terms of:
//
// (i) the Universal Permissive License v 1.0 or at your option, any
// later version (http://oss.oracle.com/licenses/upl); and/or
//
// (ii) the Apache License v 2.0. (http://www.apache.org/licenses/LICENSE-2.0)
//-----------------------------------------------------------------------------
use std::borrow::ToOwned;
use std::collections::HashMap;
use std::fmt;
use std::mem::MaybeUninit;
use std::ptr;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::sync::Mutex;
use std::time::Duration;
use crate::binding::*;
use crate::chkerr;
use crate::conn::{CloseMode, Info, Purity};
use crate::error::DPI_ERR_NOT_CONNECTED;
use crate::oci_attr::data_type::{AttrValue, DataType};
use crate::oci_attr::handle::ConnHandle;
use crate::oci_attr::handle::Server;
use crate::oci_attr::mode::Read;
use crate::oci_attr::mode::{ReadMode, WriteMode};
use crate::oci_attr::OciAttr;
#[cfg(doc)]
use crate::pool::PoolOptions;
use crate::sql_type::ObjectType;
use crate::sql_type::ObjectTypeInternal;
use crate::sql_type::ToSql;
use crate::to_rust_str;
use crate::AssertSend;
use crate::AssertSync;
#[cfg(doc)]
use crate::Batch;
use crate::BatchBuilder;
use crate::Context;
use crate::DpiConn;
use crate::DpiObjectType;
use crate::Error;
use crate::OdpiStr;
use crate::Result;
use crate::ResultSet;
use crate::Row;
use crate::RowValue;
use crate::Statement;
use crate::StatementBuilder;
use crate::Version;
struct ServerStatus;
const OCI_ATTR_SERVER_STATUS: u32 = 143;
const OCI_SERVER_NOT_CONNECTED: u32 = 0;
const OCI_SERVER_NORMAL: u32 = 1;
unsafe impl OciAttr for ServerStatus {
type HandleType = Server;
type Mode = Read;
type DataType = u32;
const ATTR_NUM: u32 = OCI_ATTR_SERVER_STATUS;
}
/// Database startup mode
///
/// See [`Connection::startup_database`]
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum StartupMode {
/// Shuts down a running instance (if there is any) using ABORT before
/// starting a new one. This mode should be used only in unusual circumstances.
Force,
/// Allows database access only to users with both the CREATE SESSION
/// and RESTRICTED SESSION privileges (normally, the DBA).
Restrict,
}
/// Database shutdown mode
///
/// See [`Connection::shutdown_database`].
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum ShutdownMode {
/// Further connects are prohibited. Waits for users to disconnect from
/// the database.
Default,
/// Further connects are prohibited and no new transactions are allowed.
/// Waits for active transactions to complete.
Transactional,
/// Further connects are prohibited and no new transactions are allowed.
/// Waits only for local transactions to complete.
TransactionalLocal,
/// Does not wait for current calls to complete or users to disconnect
/// from the database. All uncommitted transactions are terminated and
/// rolled back.
Immediate,
/// Does not wait for current calls to complete or users to disconnect
/// from the database. All uncommitted transactions are terminated and
/// are not rolled back. This is the fastest possible way to shut down
/// the database, but the next database startup may require instance
/// recovery. Therefore, this option should be used only in unusual
/// circumstances; for example, if a background process terminates abnormally.
Abort,
/// Shuts down the database. Should be used only in the second call
/// to [`Connection::shutdown_database`] after the database is closed and dismounted.
Final,
}
/// [Administrative privilege](https://www.oracle.com/pls/topic/lookup?ctx=dblatest&id=GUID-633842B8-4B19-4F96-A757-783BF62825A7)
///
/// See [`Connector::privilege`].
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum Privilege {
/// Connects as [SYSDBA](https://www.oracle.com/pls/topic/lookup?ctx=dblatest&id=GUID-BD5D39D1-DBFF-400A-8645-355F8FB9CD31).
///
Sysdba,
/// Connects as [SYSOPER](https://www.oracle.com/pls/topic/lookup?ctx=dblatest&id=GUID-BD5D39D1-DBFF-400A-8645-355F8FB9CD31).
Sysoper,
/// Connects as [SYSASM](https://www.oracle.com/pls/topic/lookup?ctx=dblatest&id=GUID-7396FD18-628B-4026-AA55-79C6D6205EAE) (Oracle 12c or later)
Sysasm,
/// Connects as [SYSBACKUP](https://www.oracle.com/pls/topic/lookup?ctx=dblatest&id=GUID-BF12E37F-4606-42BB-B8B6-4CDC5A870EE7)
Sysbackup,
/// Connects as [SYSDG](https://www.oracle.com/pls/topic/lookup?ctx=dblatest&id=GUID-5798F976-85B2-4973-92F7-DB3F6BC9D497) (Oracle 12c or later)
Sysdg,
/// Connects as [SYSKM](https://www.oracle.com/pls/topic/lookup?ctx=dblatest&id=GUID-573B5831-E106-4D8C-9101-CF9C1B74A39C) (Oracle 12c or later)
Syskm,
/// Connects as [SYSRAC](https://www.oracle.com/pls/topic/lookup?ctx=dblatest&id=GUID-69D0614C-D24E-4EC1-958A-79D7CCA3FA3A) (Oracle 12c R2 or later)
Sysrac,
}
impl Privilege {
pub(crate) fn to_dpi(self) -> dpiAuthMode {
match self {
Privilege::Sysdba => DPI_MODE_AUTH_SYSDBA,
Privilege::Sysoper => DPI_MODE_AUTH_SYSOPER,
Privilege::Sysasm => DPI_MODE_AUTH_SYSASM,
Privilege::Sysbackup => DPI_MODE_AUTH_SYSBKP,
Privilege::Sysdg => DPI_MODE_AUTH_SYSDGD,
Privilege::Syskm => DPI_MODE_AUTH_SYSKMT,
Privilege::Sysrac => DPI_MODE_AUTH_SYSRAC,
}
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
/// Connection status
pub enum ConnStatus {
/// The connection is alive. See [`Connection::status`] for details.
Normal,
/// The connection has been terminated. See [`Connection::status`] for details.
NotConnected,
/// The connection has been closed by [`Connection::close`].
Closed,
}
#[derive(Debug, Default, Clone, PartialEq)]
pub(crate) struct CommonCreateParamsBuilder {
events: bool,
edition: Option<String>,
driver_name: Option<String>,
stmt_cache_size: Option<u32>,
}
impl CommonCreateParamsBuilder {
pub fn events(&mut self, b: bool) {
self.events = b;
}
pub fn edition<S>(&mut self, edition: S)
where
S: Into<String>,
{
self.edition = Some(edition.into());
}
pub fn driver_name<S>(&mut self, driver_name: S)
where
S: Into<String>,
{
self.driver_name = Some(driver_name.into());
}
pub fn stmt_cache_size(&mut self, size: u32) {
self.stmt_cache_size = Some(size);
}
pub fn build(&self, ctxt: &Context) -> dpiCommonCreateParams {
let mut common_params = ctxt.common_create_params();
if self.events {
common_params.createMode |= DPI_MODE_CREATE_EVENTS;
}
if let Some(ref s) = self.edition {
let s = OdpiStr::new(s);
common_params.edition = s.ptr;
common_params.editionLength = s.len;
}
if let Some(ref s) = self.driver_name {
let s = OdpiStr::new(s);
common_params.driverName = s.ptr;
common_params.driverNameLength = s.len;
}
if let Some(s) = self.stmt_cache_size {
common_params.stmtCacheSize = s;
}
common_params
}
}
/// Builder data type to create Connection.
///
/// When a connection can be established only with username, password
/// and connect string, use [`Connection::connect`] instead.
#[derive(Debug, Clone, PartialEq)]
pub struct Connector {
username: String,
password: String,
connect_string: String,
privilege: Option<Privilege>,
external_auth: bool,
prelim_auth: bool,
new_password: String,
purity: Option<Purity>,
connection_class: String,
app_context: Vec<(String, String, String)>,
common_params: CommonCreateParamsBuilder,
}
impl Connector {
/// Create a connector
pub fn new<U, P, C>(username: U, password: P, connect_string: C) -> Connector
where
U: Into<String>,
P: Into<String>,
C: Into<String>,
{
Connector {
username: username.into(),
password: password.into(),
connect_string: connect_string.into(),
privilege: None,
external_auth: false,
prelim_auth: false,
new_password: "".into(),
purity: None,
connection_class: "".into(),
app_context: vec![],
common_params: Default::default(),
}
}
/// Set [administrative privilege](https://www.oracle.com/pls/topic/lookup?ctx=dblatest&id=GUID-633842B8-4B19-4F96-A757-783BF62825A7).
///
/// # Examples
///
/// ```no_run
/// # use oracle::*;
/// // connect system/manager as sysdba
/// let conn = Connector::new("system", "manager", "")
/// .privilege(Privilege::Sysdba)
/// .connect()?;
/// # Ok::<(), Error>(())
/// ```
pub fn privilege(&mut self, privilege: Privilege) -> &mut Connector {
self.privilege = Some(privilege);
self
}
/// Uses external authentication such as [OS authentication][].
///
/// # Examples
///
/// ```no_run
/// # use oracle::*;
/// let conn = Connector::new("", "", "")
/// .external_auth(true)
/// .connect()?;
/// # Ok::<(), Error>(())
/// ```
///
/// [OS authentication]: https://www.oracle.com/pls/topic/lookup?ctx=dblatest&id=GUID-37BECE32-58D5-43BF-A098-97936D66968F
pub fn external_auth(&mut self, b: bool) -> &mut Connector {
self.external_auth = b;
self
}
/// Sets prelim auth mode to connect to an idle instance.
///
/// See [starting up a database](Connection::startup_database).
pub fn prelim_auth(&mut self, b: bool) -> &mut Connector {
self.prelim_auth = b;
self
}
/// Sets new password during establishing a connection.
///
/// When a password is expired, you cannot connect to the user.
/// A new password must be set by other user or set during establishing
/// a connection.
///
/// # Examples
///
/// Connect to user `scott` with password `tiger`. If the password
/// is expired, set a new password `jaguar`.
///
/// ```no_run
/// # use oracle::*;
/// let conn = match Connection::connect("scott", "tiger", "") {
/// Ok(conn) => conn,
/// Err(Error::OciError(dberr)) if dberr.code() == 28001 => {
/// // ORA-28001: the password has expired
/// Connector::new("scott", "tiger", "")
/// .new_password("jaguar")
/// .connect()?
/// }
/// Err(err) => return Err(err),
/// };
/// # Ok::<(), Error>(())
/// ```
pub fn new_password<P>(&mut self, password: P) -> &mut Connector
where
P: Into<String>,
{
self.new_password = password.into();
self
}
/// Sets session purity specifying whether an application can reuse a pooled session (`Purity::Self_`) or must use a new session (`Purity::New`) from [DRCP][] pooled sessions.
///
/// [DRCP]: https://www.oracle.com/pls/topic/lookup?ctx=dblatest&id=GUID-015CA8C1-2386-4626-855D-CC546DDC1086
pub fn purity(&mut self, purity: Purity) -> &mut Connector {
self.purity = Some(purity);
self
}
/// Sets a connection class to restrict sharing [DRCP][] pooled sessions.
///
/// See [here][] for more detail.
///
/// [DRCP]: https://www.oracle.com/pls/topic/lookup?ctx=dblatest&id=GUID-015CA8C1-2386-4626-855D-CC546DDC1086
/// [here]: https://www.oracle.com/pls/topic/lookup?ctx=dblatest&id=GUID-EC3DEE61-512C-4CBB-A431-91894D0E1E37
pub fn connection_class<S>(&mut self, connection_class: S) -> &mut Connector
where
S: Into<String>,
{
self.connection_class = connection_class.into();
self
}
/// Appends an application context.
///
/// See [Oracle manual](https://www.oracle.com/pls/topic/lookup?ctx=dblatest&id=GUID-5841261E-988F-4A56-A2B4-71114AB3D51D)
///
/// This is same with [DBMS_SESSION.SET_CONTEXT][] but this can set application contexts before a connection is established.
///
/// [DBMS_SESSION.SET_CONTEXT]: https://www.oracle.com/pls/topic/lookup?ctx=dblatest&id=GUID-395C622C-ED79-44CC-9157-6A320934F2A9
///
/// # Examples
///
/// ```
/// # use oracle::{Connector, Error};
/// # use oracle::test_util;
/// # let username = test_util::main_user();
/// # let password = test_util::main_password();
/// # let connect_string = test_util::connect_string();
/// let conn = Connector::new(username, password, connect_string)
/// .app_context("CLIENTCONTEXT", "foo", "bar")
/// .app_context("CLIENTCONTEXT", "baz", "qux")
/// .connect()?;
/// let val = conn.query_row_as::<String>("select sys_context('CLIENTCONTEXT', 'foo') from dual", &[])?;
/// assert_eq!(val, "bar");
/// let val = conn.query_row_as::<String>("select sys_context('CLIENTCONTEXT', 'baz') from dual", &[])?;
/// assert_eq!(val, "qux");
/// # Ok::<(), Error>(())
/// ```
pub fn app_context<T1, T2, T3>(&mut self, namespace: T1, name: T2, value: T3) -> &mut Connector
where
T1: Into<String>,
T2: Into<String>,
T3: Into<String>,
{
self.app_context
.push((namespace.into(), name.into(), value.into()));
self
}
// Remove later
#[doc(hidden)]
pub fn tag<S>(&mut self, _tag: S) -> &mut Connector
where
S: Into<String>,
{
self
}
// Remove later
#[doc(hidden)]
pub fn match_any_tag(&mut self, _b: bool) -> &mut Connector {
self
}
/// Reserved for when advanced queuing (AQ) or continuous query
/// notification (CQN) is supported.
pub fn events(&mut self, b: bool) -> &mut Connector {
self.common_params.events(b);
self
}
/// Specifies edition of [Edition-Based Redefinition][].
///
/// [Edition-Based Redefinition]: https://www.oracle.com/pls/topic/lookup?ctx=dblatest&id=GUID-58DE05A0-5DEF-4791-8FA8-F04D11964906
pub fn edition<S>(&mut self, edition: S) -> &mut Connector
where
S: Into<String>,
{
self.common_params.edition(edition);
self
}
/// Sets the driver name displayed in [V$SESSION_CONNECT_INFO.CLIENT_DRIVER][].
///
/// The default value is "rust-oracle : version number". Only the first 8
/// chracters "rust-ora" are displayed when the Oracle server version is
/// lower than 12.0.1.2.
///
/// [V$SESSION_CONNECT_INFO.CLIENT_DRIVER]: https://www.oracle.com/pls/topic/lookup?ctx=dblatest&id=GUID-9F0DCAEA-A67E-4183-89E7-B1555DC591CE
pub fn driver_name<S>(&mut self, driver_name: S) -> &mut Connector
where
S: Into<String>,
{
self.common_params.driver_name(driver_name);
self
}
/// Specifies the number of statements to retain in the statement cache. Use a
/// value of 0 to disable the statement cache completely.
///
/// The default value is 20.
///
/// See also [`Connection::stmt_cache_size`] and [`Connection::set_stmt_cache_size`]
pub fn stmt_cache_size(&mut self, size: u32) -> &mut Connector {
self.common_params.stmt_cache_size(size);
self
}
/// Connect an Oracle server using specified parameters
pub fn connect(&self) -> Result<Connection> {
let ctxt = Context::new()?;
let common_params = self.common_params.build(&ctxt);
let (conn_params, _app_contexts) = self.to_dpi_conn_create_params(&ctxt);
Connection::connect_internal(
ctxt,
&self.username,
&self.password,
&self.connect_string,
common_params,
conn_params,
)
}
fn to_dpi_conn_create_params(
&self,
ctxt: &Context,
) -> (dpiConnCreateParams, Vec<dpiAppContext>) {
let mut conn_params = ctxt.conn_create_params();
if let Some(ref privilege) = self.privilege {
conn_params.authMode |= privilege.to_dpi();
}
if self.external_auth {
conn_params.externalAuth = 1;
}
if self.prelim_auth {
conn_params.authMode |= DPI_MODE_AUTH_PRELIM;
}
let s = OdpiStr::new(&self.new_password);
conn_params.newPassword = s.ptr;
conn_params.newPasswordLength = s.len;
if let Some(purity) = self.purity {
conn_params.purity = purity.to_dpi();
}
let s = OdpiStr::new(&self.connection_class);
conn_params.connectionClass = s.ptr;
conn_params.connectionClassLength = s.len;
let mut app_context = Vec::with_capacity(self.app_context.len());
for ac in &self.app_context {
let namespace = OdpiStr::new(&ac.0);
let name = OdpiStr::new(&ac.1);
let value = OdpiStr::new(&ac.2);
app_context.push(dpiAppContext {
namespaceName: namespace.ptr,
namespaceNameLength: namespace.len,
name: name.ptr,
nameLength: name.len,
value: value.ptr,
valueLength: value.len,
});
}
if !app_context.is_empty() {
conn_params.appContext = app_context.as_mut_ptr();
conn_params.numAppContext = app_context.len() as u32;
}
(conn_params, app_context)
}
}
pub(crate) type Conn = Arc<InnerConn>;
pub(crate) struct InnerConn {
ctxt: Context,
pub(crate) handle: DpiConn,
pub(crate) autocommit: AtomicBool,
pub(crate) objtype_cache: Mutex<HashMap<String, Arc<ObjectTypeInternal>>>,
tag: String,
tag_found: bool,
is_new_connection: bool,
}
impl InnerConn {
pub fn new(
ctxt: Context,
handle: *mut dpiConn,
conn_params: &dpiConnCreateParams,
) -> InnerConn {
InnerConn {
ctxt,
handle: DpiConn::new(handle),
autocommit: AtomicBool::new(false),
objtype_cache: Mutex::new(HashMap::new()),
tag: to_rust_str(conn_params.outTag, conn_params.outTagLength),
tag_found: conn_params.outTagFound != 0,
is_new_connection: conn_params.outNewSession != 0,
}
}
pub(crate) fn ctxt(&self) -> &Context {
&self.ctxt
}
pub fn autocommit(&self) -> bool {
self.autocommit.load(Ordering::Relaxed)
}
pub fn clear_object_type_cache(&self) -> Result<()> {
self.objtype_cache.lock()?.clear();
Ok(())
}
}
impl fmt::Debug for InnerConn {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"Conn {{ handle: {:?}, autocommit: {:?}",
self.handle.raw(),
self.autocommit,
)?;
if !self.tag.is_empty() {
write!(f, ", tag: {:?}", self.tag)?;
}
if self.tag_found {
write!(f, ", tag_found: {:?}", self.tag_found)?;
}
write!(f, " }}")
}
}
/// Connection to an Oracle database
pub struct Connection {
pub(crate) conn: Conn,
}
impl AssertSync for Connection {}
impl AssertSend for Connection {}
impl Connection {
/// Connects to an Oracle server using username, password and connect string.
///
/// If you need to connect the server with additional parameters
/// such as SYSDBA privilege, use [`Connector`] instead.
///
/// # Examples
///
/// Connect to a local database.
///
/// ```no_run
/// # use oracle::*;
/// let conn = Connection::connect("scott", "tiger", "")?;
/// # Ok::<(), Error>(())
/// ```
///
/// Connect to a remote database specified by easy connect naming.
///
/// ```no_run
/// # use oracle::*;
/// let conn = Connection::connect("scott", "tiger",
/// "server_name:1521/service_name")?;
/// # Ok::<(), Error>(())
/// ```
pub fn connect<U, P, C>(username: U, password: P, connect_string: C) -> Result<Connection>
where
U: AsRef<str>,
P: AsRef<str>,
C: AsRef<str>,
{
let ctxt = Context::new()?;
let common_params = ctxt.common_create_params();
let conn_params = ctxt.conn_create_params();
Connection::connect_internal(
ctxt,
username.as_ref(),
password.as_ref(),
connect_string.as_ref(),
common_params,
conn_params,
)
}
fn connect_internal(
ctxt: Context,
username: &str,
password: &str,
connect_string: &str,
common_params: dpiCommonCreateParams,
mut conn_params: dpiConnCreateParams,
) -> Result<Connection> {
let username = OdpiStr::new(username);
let password = OdpiStr::new(password);
let connect_string = OdpiStr::new(connect_string);
let mut handle = ptr::null_mut();
chkerr!(
&ctxt,
dpiConn_create(
ctxt.context,
username.ptr,
username.len,
password.ptr,
password.len,
connect_string.ptr,
connect_string.len,
&common_params,
&mut conn_params,
&mut handle
)
);
ctxt.set_warning();
conn_params.outNewSession = 1;
Ok(Connection::from_dpi_handle(ctxt, handle, &conn_params))
}
pub(crate) fn from_conn(conn: Conn) -> Connection {
Connection { conn }
}
pub(crate) fn from_dpi_handle(
ctxt: Context,
handle: *mut dpiConn,
params: &dpiConnCreateParams,
) -> Connection {
Connection {
conn: Arc::new(InnerConn::new(ctxt, handle, params)),
}
}
pub(crate) fn ctxt(&self) -> &Context {
&self.conn.ctxt
}
pub(crate) fn handle(&self) -> *mut dpiConn {
self.conn.handle.raw()
}
/// Closes the connection before the end of lifetime.
///
/// This fails when open statements or LOBs exist.
pub fn close(&self) -> Result<()> {
self.close_with_mode(CloseMode::Default)
}
pub fn close_with_mode(&self, mode: CloseMode) -> Result<()> {
let (mode, tag) = match mode {
CloseMode::Default => (DPI_MODE_CONN_CLOSE_DEFAULT, ""),
CloseMode::Drop => (DPI_MODE_CONN_CLOSE_DROP, ""),
CloseMode::Retag(tag) => (DPI_MODE_CONN_CLOSE_RETAG, tag),
};
let tag = OdpiStr::new(tag);
chkerr!(
self.ctxt(),
dpiConn_close(self.handle(), mode, tag.ptr, tag.len)
);
Ok(())
}
/// Creates [`StatementBuilder`][] to create a [`Statement`][]
///
/// # Examples
///
/// Executes a SQL statement with different parameters.
///
/// ```no_run
/// # use oracle::*;
/// # let conn = Connection::connect("scott", "tiger", "")?;
/// let mut stmt = conn.statement("insert into emp(empno, ename) values (:id, :name)").build()?;
///
/// let emp_list = [
/// (7369, "Smith"),
/// (7499, "Allen"),
/// (7521, "Ward"),
/// ];
///
/// // insert rows using positional parameters
/// for emp in &emp_list {
/// stmt.execute(&[&emp.0, &emp.1])?;
/// }
///
/// let emp_list = [
/// (7566, "Jones"),
/// (7654, "Martin"),
/// (7698, "Blake"),
/// ];
///
/// // insert rows using named parameters
/// for emp in &emp_list {
/// stmt.execute_named(&[("id", &emp.0), ("name", &emp.1)])?;
/// }
/// # Ok::<(), Error>(())
/// ```
///
/// Query methods in Connection allocate memory for 100 rows by default
/// to reduce the number of network round trips in case that many rows are
/// fetched. When 100 isn't preferable, use [`StatementBuilder::fetch_array_size`]
/// to customize it.
///
/// ```no_run
/// # use oracle::*;
/// # let conn = Connection::connect("scott", "tiger", "")?;
/// // fetch top 10 rows.
/// let mut stmt = conn
/// .statement("select empno, ename from emp order by empno fetch first 10 rows only")
/// .fetch_array_size(10)
/// .build()?;
/// for row_result in stmt.query_as::<(i32, String)>(&[])? {
/// let (empno, ename) = row_result?;
/// println!("empno: {}, ename: {}", empno, ename);
/// }
/// # Ok::<(), Error>(())
/// ```
///
/// By default, a maximum of 2 rows are returned when the query is first
/// executed. To modify this, use [`StatementBuilder::prefetch_rows`] to customize
/// it. For more information on the difference between this and `fetch_array_size`,
/// see [this writeup](https://blog.dbi-services.com/arraysize-or-rowprefetch-in-sqlplus/)
/// or [this description](https://oracle.github.io/node-oracledb/doc/api.html#rowfetching).
///
/// ```no_run
/// # use oracle::*;
/// # let conn = Connection::connect("scott", "tiger", "")?;
/// // fetch top 10 rows.
/// let mut stmt = conn
/// .statement("select empno, ename from emp order by empno fetch first 10 rows only")
/// .prefetch_rows(11) // add one to avoid a round-trip to check for end-of-fetch
/// .build()?;
/// for row_result in stmt.query_as::<(i32, String)>(&[])? {
/// let (empno, ename) = row_result?;
/// println!("empno: {}, ename: {}", empno, ename);
/// }
/// # Ok::<(), Error>(())
/// ```
pub fn statement<'conn, 'sql>(&'conn self, sql: &'sql str) -> StatementBuilder<'conn, 'sql> {
StatementBuilder::new(self, sql)
}
/// Creates [BatchBuilder][]
///
/// See [`Batch`].
pub fn batch<'conn, 'sql>(
&'conn self,
sql: &'sql str,
max_batch_size: usize,
) -> BatchBuilder<'conn, 'sql> {
BatchBuilder::new(self, sql, max_batch_size)
}
/// Executes a select statement and returns a result set containing [`Row`]s.
///
/// See [Query Methods][].
///
/// [Query Methods]: https://github.com/kubo/rust-oracle/blob/master/docs/query-methods.md
pub fn query(&self, sql: &str, params: &[&dyn ToSql]) -> Result<ResultSet<'static, Row>> {
let mut stmt = self.statement(sql).build()?;
stmt.exec(params, true, "query")?;
Ok(ResultSet::<Row>::from_stmt(stmt.stmt))
}
/// Executes a select statement using named parameters and returns a result set containing [`Row`]s.
///
/// See [Query Methods][].
///
/// [Query Methods]: https://github.com/kubo/rust-oracle/blob/master/docs/query-methods.md
pub fn query_named(
&self,
sql: &str,
params: &[(&str, &dyn ToSql)],
) -> Result<ResultSet<'static, Row>> {
let mut stmt = self.statement(sql).build()?;
stmt.exec_named(params, true, "query_named")?;
Ok(ResultSet::<Row>::from_stmt(stmt.stmt))
}
/// Executes a select statement and returns a result set containing [`RowValue`]s.
///
/// See [Query Methods][].
///
/// [Query Methods]: https://github.com/kubo/rust-oracle/blob/master/docs/query-methods.md
pub fn query_as<T>(&self, sql: &str, params: &[&dyn ToSql]) -> Result<ResultSet<'static, T>>
where
T: RowValue,
{
let mut stmt = self.statement(sql).build()?;
stmt.exec(params, true, "query_as")?;
Ok(ResultSet::<T>::from_stmt(stmt.stmt))
}
/// Executes a select statement using named parameters and returns a result set containing [`RowValue`]s.
///
/// See [Query Methods][].
///
/// [Query Methods]: https://github.com/kubo/rust-oracle/blob/master/docs/query-methods.md
pub fn query_as_named<T>(
&self,
sql: &str,
params: &[(&str, &dyn ToSql)],
) -> Result<ResultSet<'static, T>>
where
T: RowValue,
{
let mut stmt = self.statement(sql).build()?;
stmt.exec_named(params, true, "query_as_named")?;
Ok(ResultSet::<T>::from_stmt(stmt.stmt))
}
/// Gets one row from a query using positoinal bind parameters.
///
/// See [Query Methods][].
///
/// [Query Methods]: https://github.com/kubo/rust-oracle/blob/master/docs/query-methods.md
pub fn query_row(&self, sql: &str, params: &[&dyn ToSql]) -> Result<Row> {
let mut stmt = self.statement(sql).fetch_array_size(1).build()?;
stmt.query_row(params)?;
Ok(stmt.stmt.row.take().unwrap())
}
/// Gets one row from a query using named bind parameters.
///
/// See [Query Methods][].
///
/// [Query Methods]: https://github.com/kubo/rust-oracle/blob/master/docs/query-methods.md
pub fn query_row_named(&self, sql: &str, params: &[(&str, &dyn ToSql)]) -> Result<Row> {
let mut stmt = self.statement(sql).fetch_array_size(1).build()?;
stmt.query_row_named(params)?;
Ok(stmt.stmt.row.take().unwrap())
}
/// Gets one row from a query as specified type.
///
/// See [Query Methods][].
///
/// [Query Methods]: https://github.com/kubo/rust-oracle/blob/master/docs/query-methods.md
pub fn query_row_as<T>(&self, sql: &str, params: &[&dyn ToSql]) -> Result<T>
where
T: RowValue,
{
let mut stmt = self.statement(sql).fetch_array_size(1).build()?;
stmt.query_row_as::<T>(params)
}
/// Gets one row from a query with named bind parameters as specified type.
///
/// See [Query Methods][].
///
/// [Query Methods]: https://github.com/kubo/rust-oracle/blob/master/docs/query-methods.md
pub fn query_row_as_named<T>(&self, sql: &str, params: &[(&str, &dyn ToSql)]) -> Result<T>
where
T: RowValue,
{
let mut stmt = self.statement(sql).fetch_array_size(1).build()?;
stmt.query_row_as_named::<T>(params)
}
/// Creates a statement, binds values by position and executes it in one call.
/// It will retunrs `Err` when the statemnet is a select statement.
///
/// # Examples
///
/// ```no_run
/// # use oracle::*;
/// let conn = Connection::connect("scott", "tiger", "")?;
///
/// // execute a statement without bind parameters
/// conn.execute("insert into emp(empno, ename) values (113, 'John')", &[])?;
///
/// // execute a statement with binding parameters by position
/// conn.execute("insert into emp(empno, ename) values (:1, :2)", &[&114, &"Smith"])?;
///
/// # Ok::<(), Error>(())
/// ```
pub fn execute(&self, sql: &str, params: &[&dyn ToSql]) -> Result<Statement> {
let mut stmt = self.statement(sql).build()?;
stmt.execute(params)?;
Ok(stmt)
}
/// Creates a statement, binds values by name and executes it in one call.
/// It will retunrs `Err` when the statemnet is a select statement.
///
/// The bind variable names are compared case-insensitively.
///
/// # Examples
///
/// ```no_run
/// # use oracle::*;
/// let conn = Connection::connect("scott", "tiger", "")?;
///
/// // execute a statement with binding parameters by name
/// conn.execute_named("insert into emp(empno, ename) values (:id, :name)",
/// &[("id", &114),
/// ("name", &"Smith")])?;
///
/// # Ok::<(), Error>(())
/// ```
pub fn execute_named(&self, sql: &str, params: &[(&str, &dyn ToSql)]) -> Result<Statement> {
let mut stmt = self.statement(sql).build()?;
stmt.execute_named(params)?;
Ok(stmt)
}
/// Commits the current active transaction
pub fn commit(&self) -> Result<()> {
chkerr!(self.ctxt(), dpiConn_commit(self.handle()));
Ok(())
}
/// Rolls back the current active transaction
pub fn rollback(&self) -> Result<()> {
chkerr!(self.ctxt(), dpiConn_rollback(self.handle()));
Ok(())
}
/// Gets autocommit mode.
/// It is false by default.
pub fn autocommit(&self) -> bool {
self.conn.autocommit()
}
/// Enables or disables autocommit mode.
/// It is disabled by default.
pub fn set_autocommit(&mut self, autocommit: bool) {
self.conn.autocommit.store(autocommit, Ordering::Relaxed)
}
/// Cancels execution of running statements in the connection
///
/// # Examples
///
/// ```
/// # use oracle::Error;
/// # use oracle::test_util;
/// # use std::sync::Arc;
/// # use std::thread::{self, sleep};
/// # use std::time::{Duration, Instant};
/// # let conn = test_util::connect()?;
///
/// // Wrap conn with Arc to be share it with threads.
/// let conn = Arc::new(conn);
///
/// let now = Instant::now();
/// let range = Duration::from_secs(3)..=Duration::from_secs(20);
///
/// // Start a thread to cancel a query
/// let cloned_conn = conn.clone();
/// let join_handle = thread::spawn(move || {
/// sleep(Duration::from_secs(3));
/// cloned_conn.break_execution()
/// });