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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
// Rust-oracle - Rust binding for Oracle database
//
// URL: https://github.com/kubo/rust-oracle
//
//-----------------------------------------------------------------------------
// Copyright (c) 2017-2018 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::fmt;
use std::mem;
use std::ptr;

use Version;
use Statement;

use binding::*;
use Context;
use ObjectType;
use Result;
use ResultSet;
use Row;
use RowValue;
use StmtParam;
use ToSql;

use new_odpi_str;
use to_odpi_str;
use to_rust_str;

/// Database startup mode
///
/// See [Connection.startup_database](struct.Connection.html#method.startup_database).
#[derive(Debug, Copy, Clone, PartialEq)]
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](struct.Connection.html#method.shutdown_database).
#[derive(Debug, Copy, Clone, PartialEq)]
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 [shutdown_database](struct.Connection.html#method.shutdown_database) after the database is closed and dismounted.
    Final,
}

/// Parameters to create Connection passed to [Connection::connect][].
///
/// [Connection::connect]: struct.Connection.html#method.connect
#[derive(Debug, Clone, PartialEq)]
pub enum ConnParam {
    /// Connects as [SYSDBA](https://docs.oracle.com/database/122/ADMQS/administering-user-accounts-and-security.htm#GUID-2033E766-8FE6-4FBA-97E0-2607B083FA2C)
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use oracle::*; fn try_main() -> Result<()> {
    /// let conn = Connection::connect("system", "manager", "", &[ConnParam::Sysdba])?;
    /// # Ok(())} fn main() { try_main().unwrap(); }
    /// ```
    Sysdba,

    /// Connects as [SYSOPER](https://docs.oracle.com/database/122/ADMQS/administering-user-accounts-and-security.htm#GUID-2033E766-8FE6-4FBA-97E0-2607B083FA2C)
    ///
    /// See [`Examples`](#examples) in the Sysdba variant.
    Sysoper,

    /// Connects as [SYSASM](https://docs.oracle.com/database/122/OSTMG/authenticate-access-asm-instance.htm#OSTMG02600) (Oracle 12c or later)
    ///
    /// See [`Examples`](#examples) in the Sysdba variant.
    Sysasm,

    /// Connects as [SYSBACKUP](https://docs.oracle.com/database/122/DBSEG/configuring-privilege-and-role-authorization.htm#DBSEG785) (Oracle 12c or later)
    ///
    /// See [`Examples`](#examples) in the Sysdba variant.
    Sysbackup,

    /// Connects as [SYSDG](https://docs.oracle.com/database/122/DBSEG/configuring-privilege-and-role-authorization.htm#GUID-5798F976-85B2-4973-92F7-DB3F6BC9D497) (Oracle 12c or later)
    ///
    /// See [`Examples`](#examples) in the Sysdba variant.
    Sysdg,

    /// Connects as [SYSKM](https://docs.oracle.com/database/122/DBSEG/configuring-privilege-and-role-authorization.htm#GUID-573B5831-E106-4D8C-9101-CF9C1B74A39C) (Oracle 12c or later)
    ///
    /// See [`Examples`](#examples) in the Sysdba variant.
    Syskm,

    /// Connects as [SYSRAC](https://docs.oracle.com/database/122/DBSEG/configuring-privilege-and-role-authorization.htm#DBSEG-GUID-69D0614C-D24E-4EC1-958A-79D7CCA3FA3A) (Oracle 12c R2 or later)
    ///
    /// See [`Examples`](#examples) in the Sysdba variant.
    Sysrac,

    /// Uses external authentication such as [OS authentication][].
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use oracle::*; fn try_main() -> Result<()> {
    /// let conn = Connection::connect("", "", "", &[ConnParam::ExternalAuth])?;
    /// # Ok(())} fn main() { try_main().unwrap(); }
    /// ```
    ///
    /// [OS authentication]: https://docs.oracle.com/en/database/oracle/oracle-database/12.2/dbseg/configuring-authentication.html#GUID-37BECE32-58D5-43BF-A098-97936D66968F
    ExternalAuth,

    /// Sets prelim auth mode to connect to an idle instance.
    ///
    /// See [starting up a database](struct.Connection.html#method.startup_database).
    PrelimAuth,

    /// 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::*; fn try_main() -> Result<()> {
    /// let conn = match Connection::connect("scott", "tiger", "", &[]) {
    ///     Ok(conn) => conn,
    ///     Err(Error::OciError(ref dberr)) if dberr.code() == 28001 => {
    ///         // ORA-28001: the password has expired
    ///         let params = [ConnParam::NewPassword("jaguar".into())];
    ///         Connection::connect("scott", "tiger", "", &params)?
    ///     },
    ///     Err(err) => panic!(err.to_string()),
    /// };
    /// # Ok(())} fn main() { try_main().unwrap(); }
    /// ```
    NewPassword(String),

    /// Uses a new session in [DRCP][] pooled sessions.
    ///
    /// See [here][] for more detail.
    ///
    /// [DRCP]: https://docs.oracle.com/en/database/oracle/oracle-database/12.2/adfns/performance-and-scalability.html#GUID-0B0DC596-17FF-4EEE-BAA1-9F428710C1AC
    /// [here]: https://docs.oracle.com/en/database/oracle/oracle-database/12.2/adfns/performance-and-scalability.html#GUID-12410EEC-FE79-42E2-8F6B-EAA9EDA59665
    PurityNew,

    /// Reuses a pooled session in [DRCP][] pooled sessions.
    ///
    /// See [here][] for more detail.
    ///
    /// [DRCP]: https://docs.oracle.com/en/database/oracle/oracle-database/12.2/adfns/performance-and-scalability.html#GUID-0B0DC596-17FF-4EEE-BAA1-9F428710C1AC
    /// [here]: https://docs.oracle.com/en/database/oracle/oracle-database/12.2/adfns/performance-and-scalability.html#GUID-12410EEC-FE79-42E2-8F6B-EAA9EDA59665
    PuritySelf,

    /// Sets a connection class to restrict sharing [DRCP][] pooled sessions.
    ///
    /// See [here][] for more detail.
    ///
    /// [DRCP]: https://docs.oracle.com/en/database/oracle/oracle-database/12.2/adfns/performance-and-scalability.html#GUID-0B0DC596-17FF-4EEE-BAA1-9F428710C1AC
    /// [here]: https://docs.oracle.com/en/database/oracle/oracle-database/12.2/adfns/performance-and-scalability.html#GUID-EC3DEE61-512C-4CBB-A431-91894D0E1E37
    ConnectionClass(String),

    /// Sets an application context.
    ///
    /// See [Oracle manual](https://docs.oracle.com/database/122/DBSEG/using-application-contexts-to-retrieve-user-information.htm#DBSEG165)
    ///
    /// This is same with [DBMS_SESSION.SET_CONTEXT][] but this can set application contexts before a connection is established.
    ///
    /// [DBMS_SESSION.SET_CONTEXT]: https://docs.oracle.com/database/122/ARPLS/DBMS_SESSION.htm#GUID-395C622C-ED79-44CC-9157-6A320934F2A9
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use oracle::*; fn try_main() -> Result<()> {
    /// let params = [
    ///     ConnParam::AppContext("CLIENTCONTEXT".into(), "foo".into(), "bar".into()),
    ///     ConnParam::AppContext("CLIENTCONTEXT".into(), "baz".into(), "qux".into()),
    /// ];
    /// let conn = Connection::connect("scott", "tiger", "", &params)?;
    /// let val = conn.query_row_as::<String>("select sys_context('CLIENTCONTEXT', 'baz') from dual", &[])?;
    /// assert_eq!(val, "qux");
    /// # Ok(())} fn main() { try_main().unwrap(); }
    /// ```
    AppContext(String, String, String),

    /// Reserved for when connection pooling is supported.
    Tag(String),

    /// Reserved for when connection pooling is supported.
    MatchAnyTag,

    /// Reserved for when advanced queuing (AQ) or continuous query
    /// notification (CQN) is supported.
    Events,

    /// Specifies edition of [Edition-Based Redefinition][].
    ///
    /// [Edition-Based Redefinition]: https://docs.oracle.com/database/122/ADFNS/editions.htm#ADFNS020
    Edition(String),

    /// 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://docs.oracle.com/database/122/REFRN/V-SESSION_CONNECT_INFO.htm
    DriverName(String),
}

/// Connection to an Oracle database
pub struct Connection {
    pub(crate) ctxt: &'static Context,
    pub(crate) handle: *mut dpiConn,
    tag: String,
    tag_found: bool,
    pub(crate) autocommit: bool,
}

impl Connection {

    /// Connects to an Oracle server
    ///
    /// # Examples
    /// Connect to a local database.
    ///
    /// ```no_run
    /// # use oracle::*; fn try_main() -> Result<()> {
    /// let conn = Connection::connect("scott", "tiger", "", &[])?;
    /// # Ok(())} fn main() { try_main().unwrap(); }
    /// ```
    ///
    /// Connect to a remote database specified by easy connect naming.
    ///
    /// ```no_run
    /// # use oracle::*; fn try_main() -> Result<()> {
    /// let conn = Connection::connect("scott", "tiger",
    ///                                "server_name:1521/service_name", &[])?;
    /// # Ok(())} fn main() { try_main().unwrap(); }
    /// ```
    ///
    /// Connect as sysdba.
    ///
    /// ```no_run
    /// # use oracle::*; fn try_main() -> Result<()> {
    /// let conn = Connection::connect("system", "manager", "",
    ///                                &[ConnParam::Sysdba])?;
    /// # Ok(())} fn main() { try_main().unwrap(); }
    /// ```
    ///
    pub fn connect(username: &str, password: &str, connect_string: &str, params: &[ConnParam]) -> Result<Connection> {
        let ctxt = Context::get()?;
        Connection::connect_internal(ctxt, username, password, connect_string, params, ptr::null_mut())
    }

    #[deprecated(since="0.0.6", note="use `Connection::connect()` instead")]
    #[doc(hidden)]
    pub fn new(username: &str, password: &str, connect_string: &str) -> Result<Connection> {
        Connection::connect(username, password, connect_string, &[])
    }

    pub(crate) fn connect_internal(ctxt: &'static Context, username: &str, password: &str, connect_string: &str, params: &[ConnParam], pool: *mut dpiPool) -> Result<Connection> {
        let mut common_params = ctxt.common_create_params;
        let mut conn_params = ctxt.conn_create_params;

        let mut num_app_context = 0;
        for param in params {
            if let &ConnParam::AppContext(_, _, _) = param {
                num_app_context += 1;
            }
        }
        let mut app_context = Vec::with_capacity(num_app_context);

        for param in params {
            match param {
                &ConnParam::Sysdba => {
                    conn_params.authMode |= DPI_MODE_AUTH_SYSDBA;
                },
                &ConnParam::Sysoper => {
                    conn_params.authMode |= DPI_MODE_AUTH_SYSOPER;
                },
                &ConnParam::Sysasm => {
                    conn_params.authMode |= DPI_MODE_AUTH_SYSASM;
                },
                &ConnParam::Sysbackup => {
                    conn_params.authMode |= DPI_MODE_AUTH_SYSBKP;
                },
                &ConnParam::Sysdg => {
                    conn_params.authMode |= DPI_MODE_AUTH_SYSDGD;
                },
                &ConnParam::Syskm => {
                    conn_params.authMode |= DPI_MODE_AUTH_SYSKMT;
                },
                &ConnParam::Sysrac => {
                    conn_params.authMode |= DPI_MODE_AUTH_SYSRAC;
                },
                &ConnParam::ExternalAuth => {
                    conn_params.externalAuth = 1;
                },
                &ConnParam::PrelimAuth => {
                    conn_params.authMode |= DPI_MODE_AUTH_PRELIM;
                },
                &ConnParam::NewPassword(ref password) => {
                    let s = to_odpi_str(password);
                    conn_params.newPassword = s.ptr;
                    conn_params.newPasswordLength = s.len;
                },
                &ConnParam::PurityNew => {
                    conn_params.purity = DPI_PURITY_NEW;
                },
                &ConnParam::PuritySelf => {
                    conn_params.purity = DPI_PURITY_SELF;
                },
                &ConnParam::ConnectionClass(ref name) => {
                    let s = to_odpi_str(name);
                    conn_params.connectionClass = s.ptr;
                    conn_params.connectionClassLength = s.len;
                },
                &ConnParam::AppContext(ref namespace, ref name, ref value) => {
                    let namespace = to_odpi_str(namespace);
                    let name = to_odpi_str(name);
                    let value = to_odpi_str(value);
                    app_context.push(
                        dpiAppContext {
                            namespaceName: namespace.ptr,
                            namespaceNameLength: namespace.len,
                            name: name.ptr,
                            nameLength: name.len,
                            value: value.ptr,
                            valueLength: value.len,
                        });
                },
                &ConnParam::Tag(ref tag) => {
                    let s = to_odpi_str(tag);
                    conn_params.tag = s.ptr;
                    conn_params.tagLength = s.len;
                },
                &ConnParam::MatchAnyTag => {
                    conn_params.matchAnyTag = 1;
                },
                &ConnParam::Events => {
                    common_params.createMode |= DPI_MODE_CREATE_EVENTS;
                },
                &ConnParam::Edition(ref edition) => {
                    let s = to_odpi_str(edition);
                    common_params.edition = s.ptr;
                    common_params.editionLength = s.len;
                },
                &ConnParam::DriverName(ref driver_name) => {
                    let s = to_odpi_str(driver_name);
                    common_params.driverName = s.ptr;
                    common_params.driverNameLength = s.len;
                },
            }
        }
        if app_context.len() != 0 {
            conn_params.appContext = app_context.as_mut_ptr();
            conn_params.numAppContext = app_context.len() as u32;
        }
        conn_params.pool = pool;

        let username = to_odpi_str(username);
        let password = to_odpi_str(password);
        let connect_string = to_odpi_str(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));
        Ok(Connection{
            ctxt: ctxt,
            handle: handle,
            tag: to_rust_str(conn_params.outTag, conn_params.outTagLength),
            tag_found: conn_params.outTagFound != 0,
            autocommit: false,
        })
    }

    /// Closes the connection before the end of lifetime.
    ///
    /// This fails when open statements or LOBs exist.
    pub fn close(&self) -> Result<()> {
        self.close_internal(DPI_MODE_CONN_CLOSE_DEFAULT, "")
    }

    /// Prepares a statement
    ///
    /// # Examples
    ///
    /// Executes a SQL statement with different parameters.
    ///
    /// ```no_run
    /// # use oracle::*; fn try_main() -> Result<()> {
    /// # let conn = Connection::connect("scott", "tiger", "", &[])?;
    /// let mut stmt = conn.prepare("insert into emp(empno, ename) values (:id, :name)", &[])?;
    ///
    /// 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(())} fn main() { try_main().unwrap(); }
    /// ```
    ///
    /// 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 `StmtParam::FetchArraySize(u32)`
    /// to customize it.
    ///
    /// ```no_run
    /// # use oracle::*; fn try_main() -> Result<()> {
    /// # let conn = Connection::connect("scott", "tiger", "", &[])?;
    /// // fetch top 10 rows.
    /// let mut stmt = conn.prepare("select * from (select empno, ename from emp order by empno) where rownum <= 10",
    ///                             &[StmtParam::FetchArraySize(10)])?;
    /// for row_result in &stmt.query_as::<(i32, String)>(&[])? {
    ///     let (empno, ename) = row_result?;
    ///     println!("empno: {}, ename: {}", empno, ename);
    /// }
    /// # Ok(())} fn main() { try_main().unwrap(); }
    /// ```
    ///
    pub fn prepare(&self, sql: &str, params: &[StmtParam]) -> Result<Statement> {
        Statement::new(self, sql, params)
    }

    /// Executes a select statement and returns a result set containing [Row][]s.
    ///
    /// See [Query Methods][].
    ///
    /// [Row]: struct.Row.html
    /// [Query Methods]: https://github.com/kubo/rust-oracle/blob/master/docs/query-methods.md
    pub fn query(&self, sql: &str, params: &[&ToSql]) -> Result<ResultSet<Row>> {
        let mut rs = ResultSet::<Row>::from_conn(self, sql)?;
        rs.stmt_boxed.as_mut().unwrap().exec(params, true, "query")?;
        Ok(rs)
    }

    /// Executes a select statement using named parameters and returns a result set containing [Row][]s.
    ///
    /// See [Query Methods][].
    ///
    /// [Row]: struct.Row.html
    /// [Query Methods]: https://github.com/kubo/rust-oracle/blob/master/docs/query-methods.md
    pub fn query_named(&self, sql: &str, params: &[(&str, &ToSql)]) -> Result<ResultSet<Row>> {
        let mut rs = ResultSet::<Row>::from_conn(self, sql)?;
        rs.stmt_boxed.as_mut().unwrap().exec_named(params, true, "query_named")?;
        Ok(rs)
    }

    /// Executes a select statement and returns a result set containing [RowValue][]s.
    ///
    /// See [Query Methods][].
    ///
    /// [RowValue]: struct.RowValue.html
    /// [Query Methods]: https://github.com/kubo/rust-oracle/blob/master/docs/query-methods.md
    pub fn query_as<T>(&self, sql: &str, params: &[&ToSql]) -> Result<ResultSet<T>> where T: RowValue {
        let mut rs = ResultSet::from_conn(self, sql)?;
        rs.stmt_boxed.as_mut().unwrap().exec(params, true, "query_as")?;
        Ok(rs)
    }

    /// Executes a select statement using named parameters and returns a result set containing [RowValue][]s.
    ///
    /// See [Query Methods][].
    ///
    /// [RowValue]: struct.RowValue.html
    /// [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, &ToSql)]) -> Result<ResultSet<T>> where T: RowValue {
        let mut rs = ResultSet::from_conn(self, sql)?;
        rs.stmt_boxed.as_mut().unwrap().exec_named(params, true, "query_as_named")?;
        Ok(rs)
    }

    /// 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: &[&ToSql]) -> Result<Row> {
        let mut stmt = self.prepare(sql, &[StmtParam::FetchArraySize(1)])?;
        if let Err(err) = stmt.query_row(params) {
            return Err(err)
        };
        Ok(mem::replace(&mut stmt.row, None).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, &ToSql)]) -> Result<Row> {
        let mut stmt = self.prepare(sql, &[StmtParam::FetchArraySize(1)])?;
        if let Err(err) = stmt.query_row_named(params) {
            return Err(err)
        };
        Ok(mem::replace(&mut stmt.row, None).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: &[&ToSql]) -> Result<<T>::Item> where T: RowValue {
        let mut stmt = self.prepare(sql, &[StmtParam::FetchArraySize(1)])?;
        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, &ToSql)]) -> Result<<T>::Item> where T: RowValue {
        let mut stmt = self.prepare(sql, &[StmtParam::FetchArraySize(1)])?;
        stmt.query_row_as_named::<T>(params)
    }

    /// Prepares 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::*; fn try_main() -> Result<()> {
    /// 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(())} fn main() { try_main().unwrap(); }
    /// ```
    pub fn execute(&self, sql: &str, params: &[&ToSql])-> Result<Statement> {
        let mut stmt = self.prepare(sql, &[])?;
        stmt.execute(params)?;
        Ok(stmt)
    }

    /// Prepares 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::*; fn try_main() -> Result<()> {
    /// 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(())} fn main() { try_main().unwrap(); }
    /// ```
    pub fn execute_named(&self, sql: &str, params: &[(&str, &ToSql)])-> Result<Statement> {
        let mut stmt = self.prepare(sql, &[])?;
        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.autocommit
    }

    /// Enables or disables autocommit mode.
    /// It is disabled by default.
    pub fn set_autocommit(&mut self, autocommit: bool) {
        self.autocommit = autocommit;
    }

    /// Cancels execution of running statements in the connection
    pub fn break_execution(&self) -> Result<()> {
        chkerr!(self.ctxt,
                dpiConn_breakExecution(self.handle));
        Ok(())
    }

    /// Gets an object type information from name
    ///
    /// ```no_run
    /// # use oracle::*; fn try_main() -> Result<()> {
    /// let conn = Connection::connect("scott", "tiger", "", &[])?;
    /// let objtype = conn.object_type("MDSYS.SDO_GEOMETRY");
    /// # Ok(())} fn main() { try_main().unwrap(); }
    /// ```
    pub fn object_type(&self, name: &str) -> Result<ObjectType> {
        let name = to_odpi_str(name);
        let mut handle = ptr::null_mut();
        chkerr!(self.ctxt,
                dpiConn_getObjectType(self.handle, name.ptr, name.len, &mut handle));
        let res = ObjectType::from_dpiObjectType(self.ctxt, handle);
        unsafe { dpiObjectType_release(handle); }
        res
    }

    /// Gets information about the server version
    ///
    /// NOTE: if you connect to Oracle Database 18 or higher with
    /// Oracle client libraries 12.2 or lower, it gets the base
    /// version (such as 18.0.0.0.0) instead of the full version
    /// (such as 18.3.0.0.0).
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use oracle::*; fn try_main() -> Result<()> {
    /// let conn = Connection::connect("scott", "tiger", "", &[])?;
    /// let (version, banner) = conn.server_version()?;
    /// println!("Oracle Version: {}", version);
    /// println!("--- Version Banner ---");
    /// println!("{}", banner);
    /// println!("---------------------");
    /// # Ok(())} fn main() { try_main().unwrap(); }
    /// ```
    pub fn server_version(&self) -> Result<(Version, String)> {
        let mut s = new_odpi_str();
        let mut dpi_ver = Default::default();
        chkerr!(self.ctxt,
                dpiConn_getServerVersion(self.handle, &mut s.ptr, &mut s.len,
                                         &mut dpi_ver));
        Ok((Version::new_from_dpi_ver(dpi_ver), s.to_string()))
    }

    /// Changes the password for the specified user
    pub fn change_password(&self, username: &str, old_password: &str, new_password: &str) -> Result<()> {
        let username = to_odpi_str(username);
        let old_password = to_odpi_str(old_password);
        let new_password = to_odpi_str(new_password);
        chkerr!(self.ctxt,
                dpiConn_changePassword(self.handle,
                                       username.ptr, username.len,
                                       old_password.ptr, old_password.len,
                                       new_password.ptr, new_password.len));
        Ok(())
    }

    /// Pings the connection to see if it is still alive
    pub fn ping(&self) -> Result<()> {
        chkerr!(self.ctxt,
                dpiConn_ping(self.handle));
        Ok(())
    }

    /// Gets the statement cache size
    pub fn stmt_cache_size(&self) -> Result<u32> {
        let mut size = 0u32;
        chkerr!(self.ctxt,
                dpiConn_getStmtCacheSize(self.handle, &mut size));
        Ok(size)
    }

    /// Sets the statement cache size
    pub fn set_stmt_cache_size(&self, size: u32) -> Result<()> {
        chkerr!(self.ctxt,
                dpiConn_setStmtCacheSize(self.handle, size));
        Ok(())
    }

    /// Gets current schema associated with the connection
    pub fn current_schema(&self) -> Result<String> {
        let mut s = new_odpi_str();
        chkerr!(self.ctxt,
                dpiConn_getCurrentSchema(self.handle, &mut s.ptr, &mut s.len));
        Ok(s.to_string())
    }

    /// Sets current schema associated with the connection
    pub fn set_current_schema(&self, current_schema: &str) -> Result<()> {
        let s = to_odpi_str(current_schema);
        chkerr!(self.ctxt,
                dpiConn_setCurrentSchema(self.handle, s.ptr, s.len));
        Ok(())
    }

    /// Gets edition associated with the connection
    pub fn edition(&self) -> Result<String> {
        let mut s = new_odpi_str();
        chkerr!(self.ctxt,
                dpiConn_getEdition(self.handle, &mut s.ptr, &mut s.len));
        Ok(s.to_string())
    }

    /// Gets external name associated with the connection
    pub fn external_name(&self) -> Result<String> {
        let mut s = new_odpi_str();
        chkerr!(self.ctxt,
                dpiConn_getExternalName(self.handle, &mut s.ptr, &mut s.len));
        Ok(s.to_string())
    }

    /// Sets external name associated with the connection
    pub fn set_external_name(&self, external_name: &str) -> Result<()> {
        let s = to_odpi_str(external_name);
        chkerr!(self.ctxt,
                dpiConn_setExternalName(self.handle, s.ptr, s.len));
        Ok(())
    }

    /// Gets internal name associated with the connection
    pub fn internal_name(&self) -> Result<String> {
        let mut s = new_odpi_str();
        chkerr!(self.ctxt,
                dpiConn_getInternalName(self.handle, &mut s.ptr, &mut s.len));
        Ok(s.to_string())
    }

    /// Sets internal name associated with the connection
    pub fn set_internal_name(&self, internal_name: &str) -> Result<()> {
        let s = to_odpi_str(internal_name);
        chkerr!(self.ctxt,
                dpiConn_setInternalName(self.handle, s.ptr, s.len));
        Ok(())
    }

    /// Sets module associated with the connection
    ///
    /// This is same with calling [DBMS_APPLICATION_INFO.SET_MODULE][] but
    /// without executing a statement. The module name is piggybacked
    /// to the server with the next network round-trip.
    ///
    /// [DBMS_APPLICATION_INFO.SET_MODULE]: https://docs.oracle.com/database/122/ARPLS/DBMS_APPLICATION_INFO.htm#GUID-B2E2BD20-D91D-40DB-A3F6-37A853384F30
    pub fn set_module(&self, module: &str) -> Result<()> {
        let s = to_odpi_str(module);
        chkerr!(self.ctxt,
                dpiConn_setModule(self.handle, s.ptr, s.len));
        Ok(())
    }

    /// Sets action associated with the connection
    ///
    /// This is same with calling [DBMS_APPLICATION_INFO.SET_ACTION][] but
    /// without executing a statement. The action name is piggybacked
    /// to the server with the next network round-trip.
    ///
    /// [DBMS_APPLICATION_INFO.SET_ACTION]: https://docs.oracle.com/database/122/ARPLS/DBMS_APPLICATION_INFO.htm#GUID-90DA860F-BFBE-4539-BA00-2279B02B8F26
    pub fn set_action(&self, action: &str) -> Result<()> {
        let s = to_odpi_str(action);
        chkerr!(self.ctxt,
                dpiConn_setAction(self.handle, s.ptr, s.len));
        Ok(())
    }

    /// Sets client info associated with the connection
    ///
    /// This is same with calling [DBMS_APPLICATION_INFO.SET_CLIENT_INFO][] but
    /// without executing a statement. The client info is piggybacked
    /// to the server with the next network round-trip.
    ///
    /// [DBMS_APPLICATION_INFO.SET_CLIENT_INFO]: https://docs.oracle.com/database/122/ARPLS/DBMS_APPLICATION_INFO.htm#GUID-68A3DF04-BE91-46CC-8D2B-97BA0E89956F
    pub fn set_client_info(&self, client_info: &str) -> Result<()> {
        let s = to_odpi_str(client_info);
        chkerr!(self.ctxt,
                dpiConn_setClientInfo(self.handle, s.ptr, s.len));
        Ok(())
    }

    /// Sets client identifier associated with the connection
    ///
    /// This is same with calling [DBMS_SESSION.SET_IDENTIFIER][] but
    /// without executing a statement. The client identifier is piggybacked
    /// to the server with the next network round-trip.
    ///
    /// [DBMS_SESSION.SET_IDENTIFIER]: https://docs.oracle.com/database/122/ARPLS/DBMS_SESSION.htm#GUID-988EA930-BDFE-4205-A806-E54F05333562
    pub fn set_client_identifier(&self, client_identifier: &str) -> Result<()> {
        let s = to_odpi_str(client_identifier);
        chkerr!(self.ctxt,
                dpiConn_setClientIdentifier(self.handle, s.ptr, s.len));
        Ok(())
    }

    /// Sets name of the database operation to be monitored in the database.
    /// Sets to `''` if you want to end monitoring the current running database operation.
    ///
    /// This is same with calling [DBMS_SQL_MONITOR.BEGIN_OPERATION][] but
    /// without executing a statement. The database operation name is piggybacked
    /// to the server with the next network round-trip.
    ///
    /// See [Monitoring Database Operations][] in Oracle Database SQL Tuning Guide
    ///
    /// [db_op]: https://docs.oracle.com/database/121/TGSQL/glossary.htm#GUID-EB7D5D0A-0439-4336-8DC3-2DA24072977F
    /// [DBMS_SQL_MONITOR.BEGIN_OPERATION]: https://docs.oracle.com/database/122/ARPLS/DBMS_SQL_MONITOR.htm#ARPLS74785
    /// [Monitoring Database Operations]: https://docs.oracle.com/database/122/TGSQL/monitoring-database-operations.htm#TGSQL-GUID-C941CE9D-97E1-42F8-91ED-4949B2B710BF
    pub fn set_db_op(&self, db_op: &str) -> Result<()> {
        let s = to_odpi_str(db_op);
        chkerr!(self.ctxt,
                dpiConn_setDbOp(self.handle, s.ptr, s.len));
        Ok(())
    }

    /// Starts up a database
    ///
    /// This corresponds to sqlplus command `startup nomount`.
    /// You need to connect the databas as system privilege in prelim_auth
    /// mode in advance.
    /// After this method is executed, you need to reconnect the server
    /// as system privilege *without* prelim_auth and executes
    /// `alter database mount` and then `alter database open`.
    ///
    /// # Examples
    ///
    /// Connect to an idle instance as sysdba and start up a database
    ///
    /// ```no_run
    /// # use oracle::*; fn try_main() -> Result<()> {
    /// // connect as sysdba with prelim_auth mode
    /// let conn = Connection::connect("sys", "change_on_install", "",
    ///                                 &[ConnParam::Sysdba,
    ///                                   ConnParam::PrelimAuth,
    ///                                   ])?;
    ///
    /// // start the instance
    /// conn.startup_database(&[])?;
    /// conn.close()?;
    ///
    /// // connect again without prelim_auth
    /// let conn = Connection::connect("sys", "change_on_install", "",
    ///                                 &[ConnParam::Sysdba,
    ///                                   ])?;
    ///
    /// // mount and open a database
    /// conn.execute("alter database mount", &[])?;
    /// conn.execute("alter database open", &[])?;
    /// # Ok(())} fn main() { try_main().unwrap(); }
    /// ```
    ///
    /// Start up a database in restricted mode
    ///
    /// ```ignore
    /// ...
    /// conn.startup_database(&[StartupMode::Restrict])?;
    /// ...
    /// ```
    ///
    /// If the database is running, shut it down with mode ABORT and then
    /// start up in restricted mode
    ///
    /// ```ignore
    /// ...
    /// conn.startup_database(&[StartupMode::Force, StartupMode::Restrict])?;
    /// ...
    /// ```
    pub fn startup_database(&self, modes: &[StartupMode]) -> Result<()> {
        let mut mode_num = 0;
        for mode in modes {
            mode_num |= match *mode {
                StartupMode::Force => DPI_MODE_STARTUP_FORCE,
                StartupMode::Restrict => DPI_MODE_STARTUP_RESTRICT,
            };
        }
        chkerr!(self.ctxt,
                dpiConn_startupDatabase(self.handle, mode_num));
        Ok(())
    }

    /// Shuts down a database
    ///
    /// When this method is called with [ShutdownMode::Default][],
    /// [ShutdownMode::Transactional][], [ShutdownMode::TransactionalLocal][]
    /// or [ShutdownMode::Immediate], execute "alter database close normal"
    /// and "alter database dismount" and call this method again with
    /// [ShutdownMode::Final].
    ///
    /// When this method is called with [ShutdownMode::Abort][],
    /// the database is aborted immediately.
    ///
    /// [ShutdownMode::Default]: enum.ShutdownMode.html#variant.Default
    /// [ShutdownMode::Transactional]: enum.ShutdownMode.html#variant.Transactional
    /// [ShutdownMode::TransactionalLocal]: enum.ShutdownMode.html#variant.TransactionalLocal
    /// [ShutdownMode::Immediate]: enum.ShutdownMode.html#variant.Immediate
    /// [ShutdownMode::Abort]: enum.ShutdownMode.html#variant.Abort
    /// [ShutdownMode::Final]: enum.ShutdownMode.html#variant.Final
    ///
    /// # Examples
    ///
    /// Same with `shutdown immediate` on sqlplus.
    ///
    /// ```no_run
    /// # use oracle::*; fn try_main() -> Result<()> {
    /// // connect as sysdba
    /// let conn = Connection::connect("sys", "change_on_install", "",
    ///                                &[ConnParam::Sysdba])?;
    ///
    /// // begin 'shutdown immediate'
    /// conn.shutdown_database(ShutdownMode::Immediate)?;
    ///
    /// // close and dismount the database
    /// conn.execute("alter database close normal", &[])?;
    /// conn.execute("alter database dismount", &[])?;
    ///
    /// // finish shutdown
    /// conn.shutdown_database(ShutdownMode::Final)?;
    /// # Ok(())} fn main() { try_main().unwrap(); }
    /// ```
    ///
    /// Same with `shutdown abort` on sqlplus.
    ///
    /// ```no_run
    /// # use oracle::*; fn try_main() -> Result<()> {
    /// // connect as sysdba
    /// let conn = Connection::connect("sys", "change_on_install", "",
    ///                                &[ConnParam::Sysdba])?;
    ///
    /// // 'shutdown abort'
    /// conn.shutdown_database(ShutdownMode::Abort)?;
    ///
    /// // The database is aborted here.
    /// # Ok(())} fn main() { try_main().unwrap(); }
    /// ```
    pub fn shutdown_database(&self, mode: ShutdownMode) -> Result<()> {
        let mode = match mode {
            ShutdownMode::Default => DPI_MODE_SHUTDOWN_DEFAULT,
            ShutdownMode::Transactional => DPI_MODE_SHUTDOWN_TRANSACTIONAL,
            ShutdownMode::TransactionalLocal => DPI_MODE_SHUTDOWN_TRANSACTIONAL_LOCAL,
            ShutdownMode::Immediate => DPI_MODE_SHUTDOWN_IMMEDIATE,
            ShutdownMode::Abort => DPI_MODE_SHUTDOWN_ABORT,
            ShutdownMode::Final => DPI_MODE_SHUTDOWN_FINAL,
        };
        chkerr!(self.ctxt,
                dpiConn_shutdownDatabase(self.handle, mode));
        Ok(())
    }

    #[doc(hidden)] // hiden until connection pooling is supported.
    pub fn tag(&self) -> &str {
        &self.tag
    }

    #[doc(hidden)] // hiden until connection pooling is supported.
    pub fn tag_found(&self) -> bool {
        self.tag_found
    }

    fn close_internal(&self, mode: dpiConnCloseMode, tag: &str) -> Result<()> {
        let tag = to_odpi_str(tag);
        chkerr!(self.ctxt,
                dpiConn_close(self.handle, mode, tag.ptr, tag.len));
        Ok(())
    }
}

impl Drop for Connection {
    fn drop(&mut self) {
        unsafe { dpiConn_release(self.handle) };
    }
}

impl fmt::Debug for Connection {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Connection {{ handle: {:?}", self.handle)?;
        if self.tag.len() != 0 {
            write!(f, ", tag: {:?}", self.tag)?;
        }
        if self.tag_found {
            write!(f, ", tag_found: {:?}", self.tag_found)?;
        }
        write!(f, ", autocommit: {:?} }}", self.autocommit)
    }
}