sibyl 0.7.0

An OCI-based (synchronous or asynchronous) interface between Rust applications and Oracle databases
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
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
//! Rows (result set) of a query (Statement) or a cursor.

#[cfg(feature="blocking")]
#[cfg_attr(docsrs, doc(cfg(feature="blocking")))]
mod blocking;

#[cfg(feature="nonblocking")]
#[cfg_attr(docsrs, doc(cfg(feature="nonblocking")))]
mod nonblocking;

use std::sync::atomic::{AtomicI32, Ordering};

use super::{cols::Columns, data::FromSql, Position};
use crate::{Cursor, Error, Result, RowID, Statement, oci::{*, attr}, types::Ctx, Session};
use parking_lot::{RwLockReadGuard, RwLockWriteGuard};

pub(crate) enum DataSource<'a> {
    Statement(&'a Statement<'a>),
    Cursor(&'a Cursor<'a>)
}

macro_rules! impl_as_ref_for_data_source {
    ($($tname:ty),+) => {
        $(
            impl AsRef<$tname> for DataSource<'_> {
                fn as_ref(&self) -> &$tname {
                    match self {
                        &Self::Statement(stmt) => stmt.as_ref(),
                        &Self::Cursor(cursor)  => cursor.as_ref(),
                    }
                }
            }
        )+
    };
}

impl_as_ref_for_data_source!(OCIEnv, OCIError, OCISvcCtx, OCIStmt);

impl Ctx for DataSource<'_> {
    fn try_as_session(&self) -> Option<&OCISession> {
        match self {
            &Self::Statement(stmt) => stmt.try_as_session(),
            &Self::Cursor(cursor)  => cursor.try_as_session(),
        }
    }
}

impl DataSource<'_> {
    pub(crate) fn read_columns(&self) -> RwLockReadGuard<'_, Columns> {
        match self {
            &Self::Statement(stmt) => stmt.read_columns(),
            &Self::Cursor(cursor)  => cursor.read_columns(),
        }
    }

    pub(crate) fn write_columns(&self) -> RwLockWriteGuard<'_, Columns> {
        match self {
            &Self::Statement(stmt) => stmt.write_columns(),
            &Self::Cursor(cursor)  => cursor.write_columns(),
        }
    }

    pub(crate) fn session(&self) -> &Session<'_> {
        match self {
            &Self::Statement(stmt) => stmt.session(),
            &Self::Cursor(cursor)  => cursor.session(),
        }
    }
}

/// Result set of a query
pub struct Rows<'a> {
    rset: DataSource<'a>,
    last_result: AtomicI32,
}

impl<'a> Rows<'a> {
    pub(crate) fn from_query(query_result: i32, stmt: &'a Statement<'a>) -> Self {
        Self { rset: DataSource::Statement(stmt), last_result: AtomicI32::new(query_result) }
    }

    pub(crate) fn from_cursor(query_result: i32, cursor: &'a Cursor<'a>) -> Self {
        Self { rset: DataSource::Cursor(cursor), last_result: AtomicI32::new(query_result) }
    }

    fn src(self) -> DataSource<'a> {
        self.rset
    }

    /**
    Returns `true` if the result set has been completely consumed and the next call to
    [`Rows::next()`] will return [`None`].

    # Example

    ## Blocking
    ```
    # #[cfg(feature="blocking")]
    # fn main() -> sibyl::Result<()> {
    # let session = sibyl::test_env::get_session()?;
    let stmt = session.prepare("
        SELECT employee_id, first_name, last_name, commission_pct
          FROM hr.employees
         WHERE manager_id = :id
           AND commission_pct IS NOT NULL
         ORDER BY commission_pct
    ")?;
    let rows = stmt.query(100)?;

    assert!(!rows.is_done(), "There are 5 rows in this result set");

    if let Some(row) = rows.next()? {
        let emp_id: u32 = row.get(0)?;
        assert_eq!(emp_id, 149);
    }
    assert!(!rows.is_done(), "There are still 4 remaining rows");

    while let Some(_row) = rows.next()? {
    }
    assert!(rows.is_done());
    # Ok(())
    # }
    # #[cfg(feature="nonblocking")]
    # fn main() {}
    ```

    ## Nonblocking

    ```
    # #[cfg(feature="nonblocking")]
    # fn main() -> sibyl::Result<()> {
    # sibyl::block_on(async {
    # let session = sibyl::test_env::get_session().await?;
    let stmt = session.prepare("
        SELECT employee_id, first_name, last_name, commission_pct
          FROM hr.employees
         WHERE manager_id = :id
           AND commission_pct IS NOT NULL
         ORDER BY commission_pct
    ").await?;
    let rows = stmt.query(100).await?;

    assert!(!rows.is_done(), "There are 5 rows in this result set");

    if let Some(row) = rows.next().await? {
        let emp_id: u32 = row.get(0)?;
        assert_eq!(emp_id, 149);
    }
    assert!(!rows.is_done(), "There are still 4 remaining rows");

    while let Some(_row) = rows.next().await? {
    }
    assert!(rows.is_done());
    # Ok(()) })
    # }
    # #[cfg(feature="blocking")]
    # fn main() {}
    ```
    */
    pub fn is_done(&self) -> bool {
        self.last_result.load(Ordering::Relaxed) == OCI_NO_DATA
    }
}

enum RowSource<'a> {
    Single(DataSource<'a>),
    Multi(&'a DataSource<'a>)
}

impl RowSource<'_> {
    fn rset(&self) -> &DataSource<'_> {
        match self {
            Self::Single(ds) => ds,
            &Self::Multi(ds) => ds,
        }
    }
}

macro_rules! impl_as_ref_for_row_source {
    ($($tname:ty),+) => {
        $(
            impl AsRef<$tname> for RowSource<'_> {
                fn as_ref(&self) -> &$tname {
                    match self {
                        Self::Single(ds) => ds.as_ref(),
                        &Self::Multi(ds) => ds.as_ref(),
                    }
                }
            }
        )+
    };
}

impl_as_ref_for_row_source!(OCIEnv, OCIError, OCISvcCtx, OCIStmt);


/// A row in the returned result set
pub struct Row<'a> {
    src: RowSource<'a>,
}

macro_rules! impl_as_ref_for_row {
    ($($tname:ty),+) => {
        $(
            impl AsRef<$tname> for Row<'_> {
                fn as_ref(&self) -> &$tname {
                    self.src.as_ref()
                }
            }
        )+
    };
}

impl_as_ref_for_row!(OCIEnv, OCIError, OCISvcCtx, OCIStmt);

impl Ctx for Row<'_> {
    fn try_as_session(&self) -> Option<&OCISession> {
        self.src.rset().try_as_session()
    }
}

impl<'a> Row<'a> {
    fn new(rows: &'a Rows) -> Self {
        Self { src: RowSource::Multi(&rows.rset) }
    }

    fn single(rows: Rows<'a>) -> Self {
        Self { src: RowSource::Single(rows.src()) }
    }

    pub(crate) fn session(&self) -> &Session<'_> {
        self.src.rset().session()
    }

    // `get` helper to ensure that the read lock is released when we have the index
    fn col_index(&self, pos: &impl Position) -> Option<usize> {
        let cols = self.src.rset().read_columns();
        pos.name().and_then(|name| cols.col_index(name)).or(pos.index())
    }

    /**
    Returns `true` if the value in the specified column is NULL.

    # Parameters

    * `pos` - column name or a zero-based column index

    # Example

    ## Blocking

    ```
    # #[cfg(feature="blocking")]
    # fn main() -> sibyl::Result<()> {
    # let session = sibyl::test_env::get_session()?;
    let stmt = session.prepare("
        SELECT MAX(commission_pct)
          FROM hr.employees
         WHERE manager_id = :id
    ")?;
    let row = stmt.query_single(120)?.unwrap();
    let commission_exists = !row.is_null(0);

    assert!(!commission_exists);
    # Ok(())
    # }
    # #[cfg(feature="nonblocking")]
    # fn main() {}
    ```

    ## Nonblocking

    ```
    # #[cfg(feature="nonblocking")]
    # fn main() -> sibyl::Result<()> {
    # sibyl::block_on(async {
    # let session = sibyl::test_env::get_session().await?;
    let stmt = session.prepare("
        SELECT MAX(commission_pct)
          FROM hr.employees
         WHERE manager_id = :id
    ").await?;
    let row = stmt.query_single(120).await?.unwrap();
    let commission_exists = !row.is_null(0);

    assert!(!commission_exists);
    # Ok(()) })
    # }
    # #[cfg(feature="blocking")]
    # fn main() {}
    ```

    ## Note

    This method considers the out of bounds or unknown/misnamed "columns" to be NULL.
    */
    pub fn is_null(&self, pos: impl Position) -> bool {
        let cols = self.src.rset().read_columns();
        pos.name().and_then(|name| cols.col_index(name)).or(pos.index())
            .map(|ix| cols.is_null(ix))
            .unwrap_or(true)
    }

    /**
    Returns value of the specified column in the row.

    The column can be specified either by its numeric index in the row, or by its column name.

    To fetch data from NULL-able columns save the returned data into `Option` of the approrpriate
    type. If the value in the column was NULL, then the saved value will be `None`.

    # Parameters

    * `pos` - column name or a zero-based column index

    # Failures

    * `Column does not exist` - the column as specified was not found
    * `Column is null` - method was used to fetch data from a NULL-able column **and**
        the column's value was NULL **and** the type of the returned value is not an `Option`

    # Example

    ## Blocking

    ```
    # #[cfg(feature="blocking")]
    # fn main() -> sibyl::Result<()> {
    # let session = sibyl::test_env::get_session()?;
    let stmt = session.prepare("
        SELECT postal_code, country_id
          FROM hr.locations
         WHERE location_id = :id
    ")?;
    let row = stmt.query_single(2400)?.unwrap();

    // Either a 0-based column position...
    let postal_code : Option<&str> = row.get(0)?;
    assert!(postal_code.is_none());
    let country_id  : Option<&str> = row.get(1)?;
    assert!(country_id.is_some());
    let country_id = country_id.unwrap();
    assert_eq!(country_id, "UK");

    // Or the column name can be used to get the data
    let postal_code : Option<&str> = row.get("POSTAL_CODE")?;
    assert!(postal_code.is_none());
    let country_id  : Option<&str> = row.get("COUNTRY_ID")?;
    assert!(country_id.is_some());
    let country_id = country_id.unwrap();
    assert_eq!(country_id, "UK");
    # Ok(())
    # }
    # #[cfg(feature="nonblocking")]
    # fn main() {}
    ```

    ## Nonblocking

    ```
    # #[cfg(feature="nonblocking")]
    # fn main() -> sibyl::Result<()> {
    # sibyl::block_on(async {
    # let session = sibyl::test_env::get_session().await?;
    let stmt = session.prepare("
        SELECT postal_code, country_id
          FROM hr.locations
         WHERE location_id = :id
    ").await?;
    let row = stmt.query_single(2400).await?.unwrap();
    let postal_code : Option<&str> = row.get(0)?;
    assert!(postal_code.is_none());
    let country_id  : Option<&str> = row.get(1)?;
    assert!(country_id.is_some());
    let country_id = country_id.unwrap();
    assert_eq!(country_id, "UK");

    let postal_code : Option<&str> = row.get("POSTAL_CODE")?;
    assert!(postal_code.is_none());
    let country_id  : Option<&str> = row.get("COUNTRY_ID")?;
    assert!(country_id.is_some());
    let country_id = country_id.unwrap();
    assert_eq!(country_id, "UK");
    # Ok(()) })
    # }
    # #[cfg(feature="blocking")]
    # fn main() {}
    ```
    */
    pub fn get<T: FromSql<'a>, P: Position>(&'a self, pos: P) -> Result<T> {
        match self.col_index(&pos) {
            None => Err(Error::msg(format!("Column {} does not exist", pos))),
            Some(index) => {
                if let Some(result) = self.src.rset().write_columns().col_mut(index).map(|col| FromSql::value(self, col)) {
                    result
                } else {
                    Err(Error::msg(format!("Column {} cannot be found", pos)))
                }
            }
        }
    }

    /**
    Returns value of the specified column in the current row.

    # Deprecated

    This method used to provides a friendlier alternative to [`Row::get()`] to fetch data
    from `NOT NULL` columns at the time when `get` was always returning an `Option`.

    # Parameters

    * `pos` - column name or a zero-based column index

    # Failures

    * `Column does not exist` - the column as specified was not found
    * `Column is null` - method was used to fetch data from a NULL-able column **and**
        the column's value was NULL.

    # Example

    ## Blocking

    ```
    # #[cfg(feature="blocking")]
    # fn main() -> sibyl::Result<()> {
    # let session = sibyl::test_env::get_session()?;
    let stmt = session.prepare("
        SELECT postal_code, city, state_province, country_id
          FROM hr.locations
         WHERE location_id = :id
    ")?;
    let row = stmt.query_single(2400)?.unwrap();

    // CITY is NOT NULL
    let city : &str = row.get("CITY")?;

    assert_eq!(city, "London");

    // POSTAL_CODE, STATE_PROVINCE and COUNTRY_ID are all NULL-able
    let postal_code    : Option<&str> = row.get("POSTAL_CODE")?;
    let state_province : Option<&str> = row.get("STATE_PROVINCE")?;
    let country_id     : Option<&str> = row.get("COUNTRY_ID")?;

    assert!(postal_code.is_none());     // this one is NULL
    assert!(state_province.is_none());  // also NULL
    assert!(country_id.is_some());      // not NULL then
    let country_id = country_id.unwrap();
    assert_eq!(country_id, "UK");

    // We could have used `get` without `Option` to get `COUNTRY_ID`
    // even if it is NULL-able provided we had a posteriori knowledge
    // that all country IDs have values despite column being NOT NULL:

    let country_id : &str = row.get("COUNTRY_ID")?;

    assert_eq!(country_id, "UK");
    # Ok(())
    # }
    # #[cfg(feature="nonblocking")]
    # fn main() {}
    ```

    ## Nonblocking

    ```
    # #[cfg(feature="nonblocking")]
    # fn main() -> sibyl::Result<()> {
    # sibyl::block_on(async {
    # let session = sibyl::test_env::get_session().await?;
    let stmt = session.prepare("
        SELECT postal_code, city, state_province, country_id
          FROM hr.locations
         WHERE location_id = :id
    ").await?;
    let row = stmt.query_single(2400).await?.unwrap();
    let city : &str = row.get("CITY")?;
    assert_eq!(city, "London");

    let postal_code    : Option<&str> = row.get("POSTAL_CODE")?;
    let state_province : Option<&str> = row.get("STATE_PROVINCE")?;
    let country_id     : Option<&str> = row.get("COUNTRY_ID")?;

    assert!(postal_code.is_none());
    assert!(state_province.is_none());
    assert!(country_id.is_some());

    let country_id = country_id.unwrap();
    assert_eq!(country_id, "UK");

    let country_id : &str = row.get("COUNTRY_ID")?;
    assert_eq!(country_id, "UK");
    # Ok(()) })
    # }
    # #[cfg(feature="blocking")]
    # fn main() {}
    ```
    */
    #[deprecated = "Use [`Row::get()`] instead."]
    pub fn get_not_null<T: FromSql<'a>, P: Position>(&'a self, pos: P) -> Result<T> {
        self.get(pos)
    }

    /**
    Returns the implicitily returned `RowID` of the current row in the SELECT...FOR UPDATE results.
    The returned `RowID` can be used in a later UPDATE or DELETE statement.

    # Notes

    This method is only valid for the SELECT...FOR UPDATE results as only those return ROWIDs implicitly.
    For all others the returned `RowID` will be empty (one might think about it as NULL).

    # Example

    ## Blocking

    ```
    # #[cfg(feature="blocking")]
    # fn main() -> sibyl::Result<()> {
    # let session = sibyl::test_env::get_session()?;
    let stmt = session.prepare("
        SELECT manager_id
          FROM hr.employees
         WHERE employee_id = :id
           FOR UPDATE
    ")?;
    let row = stmt.query_single(107)?.unwrap();
    let manager_id: u32 = row.get(0)?;
    assert_eq!(manager_id, 103);

    let rowid = row.rowid()?;

    let stmt = session.prepare("
        UPDATE hr.employees
           SET manager_id = :mgr_id
         WHERE rowid = :row_id
    ")?;
    let num_updated = stmt.execute((
        (":MGR_ID", 103),
        (":ROW_ID", &rowid),
    ))?;
    assert_eq!(num_updated, 1);
    # session.rollback()?;
    # Ok(())
    # }
    # #[cfg(feature="nonblocking")]
    # fn main() {}
    ```

    ## Nonblocking

    ```
    # #[cfg(feature="nonblocking")]
    # fn main() -> sibyl::Result<()> {
    # sibyl::block_on(async {
    # let session = sibyl::test_env::get_session().await?;
    let stmt = session.prepare("
        SELECT manager_id
          FROM hr.employees
         WHERE employee_id = :id
           FOR UPDATE
    ").await?;
    let row = stmt.query_single(107).await?.unwrap();
    let manager_id: u32 = row.get(0)?;
    assert_eq!(manager_id, 103);

    let rowid = row.rowid()?;

    let stmt = session.prepare("
        UPDATE hr.employees
           SET manager_id = :mgr_id
         WHERE rowid = :row_id
    ").await?;
    let num_updated = stmt.execute((
        (":MGR_ID", 103),
        (":ROW_ID", &rowid),
    )).await?;

    assert_eq!(num_updated, 1);
    # session.rollback().await?;
    # Ok(()) })
    # }
    # #[cfg(feature="blocking")]
    # fn main() {}
    ```
    */
    pub fn rowid(&self) -> Result<RowID> {
        let mut rowid = RowID::new(self)?;
        let stmt : &OCIStmt = self.as_ref();
        attr::get_into(OCI_ATTR_ROWID, &mut rowid, OCI_HTYPE_STMT, stmt, self.as_ref())?;
        Ok( rowid )
    }
}

#[cfg(all(test,feature="blocking"))]
mod tests {
    use crate::*;

    #[test]
    fn get_null() -> Result<()> {
        let session = crate::test_env::get_session()?;

        let stmt = session.prepare("
            SELECT postal_code, city, state_province, country_id
              FROM hr.locations
             WHERE location_id = :id
        ")?;
        let row = stmt.query_single(2400)?.unwrap();

        assert!(row.is_null("POSTAL_CODE"));
        assert!(!row.is_null("CITY"));
        assert!(row.is_null("STATE_PROVINCE"));
        assert!(!row.is_null("COUNTRY_ID"));

        let postal_code : Option<&str> = row.get("POSTAL_CODE")?;
        assert!(postal_code.is_none());
        let state_province : Option<&str> = row.get("STATE_PROVINCE")?;
        assert!(state_province.is_none());

        let city : &str = row.get("CITY")?;
        assert_eq!(city, "London");
        let country_id : &str = row.get("COUNTRY_ID")?;
        assert_eq!(country_id, "UK");

        let res : Result<&str> = row.get("POSTAL_CODE");
        assert!(res.is_err());
        match res {
            Err(Error::Interface(msg)) => assert_eq!(msg, "Column POSTAL_CODE is null"),
            _ => panic!("unexpected result {:?}", res),
        }

        Ok(())
    }

    #[test]
    fn column_indexing() -> Result<()> {
        use std::fmt::Display;

        let session = crate::test_env::get_session()?;

        let stmt = session.prepare("
            SELECT postal_code, city, state_province, country_id
              FROM hr.locations
             WHERE location_id = :id
        ")?;
        let row = stmt.query_single(2400)?.unwrap();

        #[derive(Clone,Copy)]
        enum Col {
            PostalCode, City, StateProvince, CountryId
        }
        impl Position for Col {
            fn index(&self) -> Option<usize> { Some(*self as _) }
        }
        impl Display for Col {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                static COLS : [&str;4] = ["POSTAL_CODE", "CITY", "STATE_PROVINCE", "COUNTRY_ID"];
                let i = *self as usize;
                f.write_str(COLS[i])
            }
        }

        assert!(row.is_null(Col::PostalCode));
        assert!(!row.is_null(Col::City));
        assert!(row.is_null(Col::StateProvince));
        assert!(!row.is_null(Col::CountryId));

        let postal_code : Option<&str> = row.get(Col::PostalCode)?;
        assert!(postal_code.is_none());
        let state_province : Option<&str> = row.get(Col::StateProvince)?;
        assert!(state_province.is_none());

        let city : &str = row.get(Col::City)?;
        assert_eq!(city, "London");
        let country_id : &str = row.get(Col::CountryId)?;
        assert_eq!(country_id, "UK");

        let res : Result<&str> = row.get(Col::PostalCode);
        assert!(res.is_err());
        match res {
            Err(Error::Interface(msg)) => assert_eq!(msg, "Column POSTAL_CODE is null"),
            _ => panic!("unexpected result {:?}", res),
        }

        Ok(())
    }
}