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
//! # Passing parameters to statement
//!
//! ## In a nutshell
//!
//! * `()` -> No parameter
//! * `&a` -> Single input parameter
//! * `InOut(&mut a)` -> Input Output parameter
//! * `Out(&mut a)` -> Output parameter
//! * `(a,b,c)` -> Fixed number of parameters
//! * `&[a]` -> Arbitrary number of parameters
//! * `&mut BlobParam` -> Stream long input parameters.
//! * `Box<dyn InputParameter>` -> Aribtrary input parameter
//! * `&[Box<dyn InputParameter>]` -> Aribtrary number of arbitrary input parameters
//! * `a.into_parameter()` -> Convert idiomatic Rust type into something bindable by ODBC.
//!
//! ## Passing a single parameter
//!
//! ODBC allows you to bind parameters to positional placeholders. In the simples case it looks like
//! this:
//!
//! ```no_run
//! use odbc_api::Environment;
//!
//! let env = Environment::new()?;
//!
//! let mut conn = env.connect("YourDatabase", "SA", "My@Test@Password1")?;
//! let year = 1980;
//! if let Some(cursor) = conn.execute("SELECT year, name FROM Birthdays WHERE year > ?;", &year)? {
//!     // Use cursor to process query results.
//! }
//! # Ok::<(), odbc_api::Error>(())
//! ```
//!
//! All types implementing the `Parameter` trait can be used.
//!
//! ## Annotating a parameter with an explicit SQL DataType
//!
//! In the last example we used a bit of domain knowledge about the query and provided it with an
//! `i32`. Each `Parameter` type comes with a default SQL Type as which it is bound. In the last
//! example this spared us from specifing that we bind `year` as an SQL `INTEGER` (because `INTEGER`
//! is default for `i32`). If we want to, we can specify the SQL type independent from the Rust type
//! we are binding, by wrapping it in `WithDataType`.
//!
//! ```no_run
//! use odbc_api::{Environment, parameter::WithDataType, DataType};
//!
//! let env = Environment::new()?;
//!
//! let mut conn = env.connect("YourDatabase", "SA", "My@Test@Password1")?;
//! let year = WithDataType{
//!    value: 1980,
//!    data_type: DataType::Varchar {length: 4}
//! };
//! if let Some(cursor) = conn.execute("SELECT year, name FROM Birthdays WHERE year > ?;", &year)? {
//!     // Use cursor to process query results.
//! }
//! # Ok::<(), odbc_api::Error>(())
//! ```
//!
//! In that case it is likely that the driver manager converts our annotated year into a string
//! which is most likely being converted back into an integer by the driver. All this converting can
//! be confusing, but it is helpful if we do not know what types the parameters actually have (i.e.
//! the query could have been entered by the user on the command line.). There is also an option to
//! query the parameter types beforehand, but my advice is not trust the information blindly if you
//! cannot test this with your driver beforehand.
//!
//! ## Passing a fixed number of parameters
//!
//! To pass multiple but a fixed number of parameters to a query you can use tuples.
//!
//! ```no_run
//! use odbc_api::Environment;
//!
//! let env = Environment::new()?;
//!
//! let mut conn = env.connect("YourDatabase", "SA", "My@Test@Password1")?;
//! let too_old = 1980;
//! let too_young = 2000;
//! if let Some(cursor) = conn.execute(
//!     "SELECT year, name FROM Birthdays WHERE ? < year < ?;",
//!     (&too_old, &too_young),
//! )? {
//!     // Use cursor to congratulate only persons in the right age group...
//! }
//! # Ok::<(), odbc_api::Error>(())
//! ```
//!
//! ## Passing an arbitrary number of parameters
//!
//! Not always do we know the number of required parameters at compile time. This might be the case
//! if the query itself is generated from user input. Luckily slices of parameters are supported, too.
//!
//! ```no_run
//! use odbc_api::Environment;
//!
//! let env = Environment::new()?;
//!
//! let mut conn = env.connect("YourDatabase", "SA", "My@Test@Password1")?;
//! let params = [1980, 2000];
//! if let Some(cursor) = conn.execute(
//!     "SELECT year, name FROM Birthdays WHERE ? < year < ?;",
//!     &params[..])?
//! {
//!     // Use cursor to process query results.
//! }
//! # Ok::<(), odbc_api::Error>(())
//! ```
//!
//! ## Passing an input parameters parsed from the command line
//!
//! In case you want to read parameters from the command line you can also let ODBC do the work of
//! converting the text input into something more suitable.
//!
//! ```
//! use odbc_api::{Connection, IntoParameter, Error, parameter::VarCharSlice};
//!
//! fn execute_arbitrary_command(connection: &Connection, query: &str, parameters: &[&str])
//!     -> Result<(), Error>
//! {
//!     // Convert all strings to `VarCharSlice` and bind them as `VarChar`. Let ODBC convert them
//!     // into something better matching the types required be the query.
//!     let params: Vec<_> = parameters
//!         .iter()
//!         .map(|param| param.into_parameter())
//!         .collect();
//!
//!     // Execute the query as a one off, and pass the parameters. String parameters are parsed and
//!     // converted into something more suitable by the data source itself.
//!     connection.execute(&query, params.as_slice())?;
//!     Ok(())
//! }
//! ```
//!
//! Should you have more type information the type available, but only at runtime can also bind an
//! array of `[Box<dyn InputParameter]`.
//!
//! ## Output and Input/Output parameters
//!
//! Mutable references are treated as input/output parameters. To use a parameter purely as an
//! output parameter you may wrapt it into out. Consider a Mircosoft SQL Server with the following
//! stored procedure:
//!
//! ```mssql
//! CREATE PROCEDURE TestParam
//! @OutParm int OUTPUT
//! AS
//! SELECT @OutParm = @OutParm + 5
//! RETURN 99
//! GO
//! ```
//!
//! We bind the return value as the first output parameter. The second parameter is an input/output
//! bound as a mutable reference.
//!
//! ```no_run
//! use odbc_api::{Environment, Out, InOut, Nullable};
//!
//! let env = Environment::new()?;
//!
//! let mut conn = env.connect("YourDatabase", "SA", "My@Test@Password1")?;
//!
//! let mut ret = Nullable::<i32>::null();
//! let mut param = Nullable::<i32>::new(7);
//!
//! conn.execute(
//!     "{? = call TestParam(?)}",
//!     (Out(&mut ret), InOut(&mut param)))?;
//!
//! assert_eq!(Some(99), ret.into_opt());
//! assert_eq!(Some(7 + 5), param.into_opt());
//!
//! # Ok::<(), odbc_api::Error>(())
//! ```
//!
//! ## Sending long data
//!
//! Many ODBC drivers have size limits of how big parameters can be. Apart from that you may not
//! want to allocate really large buffers in your application in order to keep a small memory
//! footprint. Luckily ODBC also supports streaming data to the database batch by batch at statement
//! execution time. To support this, this crate offers the [`BlobParam`], which can be bound as a
//! mutable reference. An instance of [`BlobParam`] is usually created by calling
//! [`Blob::as_blob_param`] from a wrapper implenting [`Blob`].
//!
//! ### Inserting long binary data from a file.
//!
//! [`BlobRead::from_path`] is the most convinient way to turn a file path into a [`Blob`]
//! parameter. The following example also demonstrates that the streamed blob parameter can be
//! combined with reqular input parmeters like `id`.
//!
//! ```
//! use std::{error::Error, path::Path};
//! use odbc_api::{Connection, parameter::{Blob, BlobRead}, IntoParameter};
//!
//! fn insert_image_to_db(
//!     conn: &Connection<'_>,
//!     id: &str,
//!     image_path: &Path) -> Result<(), Box<dyn Error>>
//! {
//!     let mut blob = BlobRead::from_path(&image_path)?;
//!
//!     let sql = "INSERT INTO Images (id, image_data) VALUES (?, ?)";
//!     let parameters = (&id.into_parameter(), &mut blob.as_blob_param());
//!     conn.execute(sql, parameters)?;
//!     Ok(())
//! }
//! ```
//!
//! ### Inserting long binary data from any `io::BufRead`.
//!
//! This is more flexible than inserting just from files. Note however that files provide metadata
//! about the length of the data, which `io::BufRead` does not. This is not an issue for most
//! drivers, but some can perform optimization if they know the size in advance. In the tests
//! SQLite has shown a bug to only insert empty data if no size hint has been provided.
//!
//! ```
//! use std::io::BufRead;
//! use odbc_api::{Connection, parameter::{Blob, BlobRead}, IntoParameter, Error};
//!
//! fn insert_image_to_db(
//!     conn: &Connection<'_>,
//!     id: &str,
//!     image_data: impl BufRead) -> Result<(), Error>
//! {
//!     const MAX_IMAGE_SIZE: usize = 4 * 1024 * 1024;
//!     let mut blob = BlobRead::with_upper_bound(image_data, MAX_IMAGE_SIZE);
//!
//!     let sql = "INSERT INTO Images (id, image_data) VALUES (?, ?)";
//!     let parameters = (&id.into_parameter(), &mut blob.as_blob_param());
//!     conn.execute(sql, parameters)?;
//!     Ok(())
//! }
//! ```
//!
//! ### Inserting long strings
//!
//! This example insert `title` as a normal input parameter but streams the potentially much longer
//! `String` in `text` to the database as a large text blob. This allows to circumvent the size
//! restrictions for `String` arguments of many drivers (usually around 4 or 8 KiB).
//!
//! ```
//! use odbc_api::{Connection, parameter::{Blob, BlobSlice}, IntoParameter, Error};
//!
//! fn insert_book(
//!     conn: &Connection<'_>,
//!     title: &str,
//!     text: &str
//! ) -> Result<(), Error>
//! {
//!     let mut blob = BlobSlice::from_text(text);
//!
//!     let insert = "INSERT INTO Books (title, text) VALUES (?,?)";
//!     let parameters = (&title.into_parameter(), &mut blob.as_blob_param());
//!     conn.execute(&insert, parameters)?;
//!     Ok(())
//! }
//! ```
//!
//! ### Inserting long binary data from `&[u8]`.
//!
//! ```
//! use odbc_api::{Connection, parameter::{Blob, BlobSlice}, IntoParameter, Error};
//!
//! fn insert_image(
//!     conn: &Connection<'_>,
//!     id: &str,
//!     image_data: &[u8]
//! ) -> Result<(), Error>
//! {
//!     let mut blob = BlobSlice::from_byte_slice(image_data);
//!
//!     let insert = "INSERT INTO Images (id, image_data) VALUES (?,?)";
//!     let parameters = (&id.into_parameter(), &mut blob.as_blob_param());
//!     conn.execute(&insert, parameters)?;
//!     Ok(())
//! }
//! ```
//!
//! ## Passing the type you absolutely think should work, but does not.
//!
//! Sadly not every type can be safely bound as something the ODBC C-API understands. Most prominent
//! among those is a Rust string slice (`&str`).
//!
//! ```no_run
//! use odbc_api::Environment;
//!
//! let env = Environment::new()?;
//!
//! let mut conn = env.connect("YourDatabase", "SA", "My@Test@Password1")?;
//! // conn.execute("SELECT year FROM Birthdays WHERE name=?;", "Bernd")?; // <- compiler error.
//! # Ok::<(), odbc_api::Error>(())
//! ```
//!
//! Alas, not all is lost. We can still make use of the [`crate::IntoParameter`] trait to convert it
//! into something that works.
//!
//! ```no_run
//! use odbc_api::{Environment, IntoParameter};
//!
//! let env = Environment::new()?;
//!
//! let mut conn = env.connect("YourDatabase", "SA", "My@Test@Password1")?;
//! if let Some(cursor) = conn.execute(
//!     "SELECT year FROM Birthdays WHERE name=?;",
//!     &"Bernd".into_parameter())?
//! {
//!     // Use cursor to process query results.
//! };
//! # Ok::<(), odbc_api::Error>(())
//! ```
//!
//! Conversion for `&str` is not too expensive either. Just an integer more on the stack. Wait, the
//! type you wanted to use, but that I have conveniently not chosen in this example still does not
//! work? Well, in that case please open an issue or a pull request. [`crate::IntoParameter`] can usually be
//! implemented entirely in safe code, and is a suitable spot to enable support for your custom
//! types.
mod blob;
mod c_string;
mod varbin;
mod varchar;

pub use self::{
    blob::{Blob, BlobParam, BlobRead, BlobSlice},
    varbin::{VarBinary, VarBinaryArray, VarBinaryBox, VarBinarySlice, VarBinarySliceMut},
    varchar::{VarChar, VarCharArray, VarCharBox, VarCharSlice, VarCharSliceMut},
};

use std::ffi::c_void;

use odbc_sys::CDataType;

use crate::{
    handles::{CData, CDataMut, HasDataType, Statement},
    DataType, Error,
};

/// Use implementations of this type as arguments to SQL Statements.
///
/// # Safety
///
/// Considerations for implementers
///
/// Extend the [`crate::handles::HasDataType`] trait with the guarantee, that the bound parameter
/// buffer contains at least one element.
///
/// Since the indicator provided by implementation is used to indicate the length of the value in
/// the buffer, care must be taken to prevent out of bounds access in case the implementation also
/// is used as an output parameter, and contains truncated values (i.e. the indicator is longer than
/// the buffer and the value within).
pub unsafe trait InputParameter: HasDataType + CData {}

/// # Safety
///
/// Guarantees that there is space in the output buffer for at least one element.
pub unsafe trait OutputParameter: CDataMut + HasDataType {}

/// Implementers of this trait can be used as individual parameters of in a
/// [`crate::ParameterRefCollection`]. They can be bound as either input parameters, output
/// parameters or both.
///
/// # Safety
///
/// Parameters bound to the statement must remain valid for the lifetime of the instance.
pub unsafe trait ParameterRef {
    /// Bind the parameter in question to a specific `parameter_number`.
    ///
    /// # Safety
    ///
    /// Since the parameter is now bound to `stmt` callers must take care that it is ensured that
    /// the parameter remains valid while it is used. If the parameter is bound as an output
    /// parameter it must also be ensured that it is exclusively referenced by statement.
    unsafe fn bind_to(
        &mut self,
        parameter_number: u16,
        stmt: &mut impl Statement,
    ) -> Result<(), Error>;
}

/// Bind immutable references as input parameters.
unsafe impl<T: ?Sized> ParameterRef for &T
where
    T: InputParameter,
{
    unsafe fn bind_to(
        &mut self,
        parameter_number: u16,
        stmt: &mut impl Statement,
    ) -> Result<(), Error> {
        stmt.bind_input_parameter(parameter_number, *self)
            .into_result(stmt)
    }
}

/// Bind mutable references as input parameters.
unsafe impl<T: ?Sized> ParameterRef for &mut T
where
    T: InputParameter,
{
    unsafe fn bind_to(
        &mut self,
        parameter_number: u16,
        stmt: &mut impl Statement,
    ) -> Result<(), Error> {
        stmt.bind_input_parameter(parameter_number, *self)
            .into_result(stmt)
    }
}

/// Bind immutable references as input parameters.
unsafe impl<T: ?Sized> ParameterRef for Box<T>
where
    T: InputParameter,
{
    unsafe fn bind_to(
        &mut self,
        parameter_number: u16,
        stmt: &mut impl Statement,
    ) -> Result<(), Error> {
        stmt.bind_input_parameter(parameter_number, self.as_ref())
            .into_result(stmt)
    }
}

/// Bind mutable references as input/output parameter.
unsafe impl<'a, T> ParameterRef for InOut<'a, T>
where
    T: OutputParameter,
{
    unsafe fn bind_to(
        &mut self,
        parameter_number: u16,
        stmt: &mut impl Statement,
    ) -> Result<(), Error> {
        stmt.bind_parameter(parameter_number, odbc_sys::ParamType::InputOutput, self.0)
            .into_result(stmt)
    }
}

/// Wraps a mutable reference. Use this wrapper in order to indicate that a mutable reference should
/// be bound as an input / output parameter.
///
/// # Example
///
/// ```no_run
/// use odbc_api::{Environment, Out, InOut, Nullable};
///
/// let env = Environment::new()?;
///
/// let mut conn = env.connect("YourDatabase", "SA", "My@Test@Password1")?;
///
/// let mut ret = Nullable::<i32>::null();
/// let mut param = Nullable::new(7);
///
/// conn.execute(
///     "{? = call TestParam(?)}",
///     (Out(&mut ret), InOut(&mut param)))?;
///
/// # Ok::<(), odbc_api::Error>(())
/// ```
pub struct InOut<'a, T>(pub &'a mut T);

/// Wraps a mutable reference. Use this wrapper in order to indicate that a mutable reference should
/// be bound as an output parameter only.
///
/// # Example
///
/// ```no_run
/// use odbc_api::{Environment, Out, InOut, Nullable};
///
/// let env = Environment::new()?;
///
/// let mut conn = env.connect("YourDatabase", "SA", "My@Test@Password1")?;
///
/// let mut ret = Nullable::<i32>::null();
/// let mut param = Nullable::new(7);
///
/// conn.execute(
///     "{? = call TestParam(?)}",
///     (Out(&mut ret), InOut(&mut param)))?;
///
/// # Ok::<(), odbc_api::Error>(())
/// ```
pub struct Out<'a, T>(pub &'a mut T);

/// Mutable references wrapped in `Out` are bound as output parameters.
unsafe impl<'a, T> ParameterRef for Out<'a, T>
where
    T: OutputParameter,
{
    unsafe fn bind_to(
        &mut self,
        parameter_number: u16,
        stmt: &mut impl Statement,
    ) -> Result<(), Error> {
        stmt.bind_parameter(parameter_number, odbc_sys::ParamType::Output, self.0)
            .into_result(stmt)
    }
}

/// Annotates an instance of an inner type with an SQL Data type in order to indicate how it should
/// be bound as a parameter to an SQL Statement.
///
/// # Example
///
/// ```no_run
/// use odbc_api::{Environment, parameter::WithDataType, DataType};
///
/// let env = Environment::new()?;
///
/// let mut conn = env.connect("YourDatabase", "SA", "My@Test@Password1")?;
/// // Bind year as VARCHAR(4) rather than integer.
/// let year = WithDataType{
///    value: 1980,
///    data_type: DataType::Varchar {length: 4}
/// };
/// if let Some(cursor) = conn.execute("SELECT year, name FROM Birthdays WHERE year > ?;", &year)? {
///     // Use cursor to process query results.
/// }
/// # Ok::<(), odbc_api::Error>(())
/// ```
pub struct WithDataType<T> {
    /// Value to wrap with a Data Type. Should implement [`crate::handles::CData`], to be useful.
    pub value: T,
    /// The SQL type this value is supposed to map onto. What exactly happens with this information
    /// is up to the ODBC driver in use.
    pub data_type: DataType,
}

unsafe impl<T> CData for WithDataType<T>
where
    T: CData,
{
    fn cdata_type(&self) -> CDataType {
        self.value.cdata_type()
    }

    fn indicator_ptr(&self) -> *const isize {
        self.value.indicator_ptr()
    }

    fn value_ptr(&self) -> *const c_void {
        self.value.value_ptr()
    }

    fn buffer_length(&self) -> isize {
        self.value.buffer_length()
    }
}

unsafe impl<T> CDataMut for WithDataType<T>
where
    T: CDataMut,
{
    fn mut_indicator_ptr(&mut self) -> *mut isize {
        self.value.mut_indicator_ptr()
    }

    fn mut_value_ptr(&mut self) -> *mut c_void {
        self.value.mut_value_ptr()
    }
}

impl<T> HasDataType for WithDataType<T>
where
    T: HasDataType,
{
    fn data_type(&self) -> DataType {
        self.data_type
    }
}

unsafe impl<T> InputParameter for WithDataType<T> where T: InputParameter {}

// Allow for input parameters whose type is only known at runtime.
unsafe impl CData for Box<dyn InputParameter> {
    fn cdata_type(&self) -> CDataType {
        self.as_ref().cdata_type()
    }

    fn indicator_ptr(&self) -> *const isize {
        self.as_ref().indicator_ptr()
    }

    fn value_ptr(&self) -> *const c_void {
        self.as_ref().value_ptr()
    }

    fn buffer_length(&self) -> isize {
        self.as_ref().buffer_length()
    }
}

impl HasDataType for Box<dyn InputParameter> {
    fn data_type(&self) -> DataType {
        self.as_ref().data_type()
    }
}

unsafe impl InputParameter for Box<dyn InputParameter> {}

/// # Safety
///
/// A subclass of CData those value pointer or indicator pointer can not be changed through a
/// mutable reference. The values these pointers point to, may change however. Used to determine,
/// that the value has not to be rebound between multiple calls to execute.
pub unsafe trait StableCData: CData {}