odbc_api/
environment.rs

1use std::{
2    cmp::max,
3    collections::HashMap,
4    ptr::null_mut,
5    sync::{Mutex, OnceLock},
6};
7
8use crate::{
9    Connection, DriverCompleteOption, Error,
10    connection::ConnectionOptions,
11    error::ExtendResult,
12    handles::{
13        self, OutputStringBuffer, SqlChar, SqlResult, SqlText, State, SzBuffer, log_diagnostics,
14        slice_to_utf8,
15    },
16};
17use log::debug;
18use odbc_sys::{AttrCpMatch, AttrOdbcVersion, FetchOrientation, HWnd};
19
20#[cfg(target_os = "windows")]
21// Currently only windows driver manager supports prompt.
22use winit::{
23    application::ApplicationHandler,
24    event::WindowEvent,
25    event_loop::{ActiveEventLoop, EventLoop},
26    platform::run_on_demand::EventLoopExtRunOnDemand,
27    window::{Window, WindowId},
28};
29
30#[cfg(not(feature = "odbc_version_3_5"))]
31const ODBC_API_VERSION: AttrOdbcVersion = AttrOdbcVersion::Odbc3_80;
32
33#[cfg(feature = "odbc_version_3_5")]
34const ODBC_API_VERSION: AttrOdbcVersion = AttrOdbcVersion::Odbc3;
35
36/// An ODBC 3.8 environment.
37///
38/// Associated with an `Environment` is any information that is global in nature, such as:
39///
40/// * The `Environment`'s state
41/// * The current environment-level diagnostics
42/// * The handles of connections currently allocated on the environment
43/// * The current stetting of each environment attribute
44///
45/// Creating the environment is the first applications do, then interacting with an ODBC driver
46/// manager. There must only be one environment in the entire process.
47#[derive(Debug)]
48pub struct Environment {
49    environment: handles::Environment,
50    /// ODBC environments use interior mutability to maintain iterator state then iterating over
51    /// driver and / or data source information. The environment is otherwise protected by interior
52    /// synchronization mechanism, yet in order to be able to access to iterate over information
53    /// using a shared reference we need to protect the interior iteration state with a mutex of its
54    /// own.
55    /// The environment is also mutable with regards to Errors, which are accessed over the handle.
56    /// If multiple fallible operations are executed in parallel, we need the mutex to ensure the
57    /// errors are fetched by the correct thread.
58    internal_state: Mutex<()>,
59}
60
61unsafe impl Sync for Environment {}
62
63impl Environment {
64    /// Enable or disable (default) connection pooling for ODBC connections. Call this function
65    /// before creating the ODBC environment for which you want to enable connection pooling.
66    ///
67    /// ODBC specifies an interface to enable the driver manager to enable connection pooling for
68    /// your application. It is off by default, but if you use ODBC to connect to your data source
69    /// instead of implementing it in your application, or importing a library you may simply enable
70    /// it in ODBC instead.
71    /// Connection Pooling is governed by two attributes. The most important one is the connection
72    /// pooling scheme which is `Off` by default. It must be set even before you create your ODBC
73    /// environment. It is global mutable state on the process level. Setting it in Rust is therefore
74    /// unsafe.
75    ///
76    /// The other one is changed via [`Self::set_connection_pooling_matching`]. It governs how a
77    /// connection is choosen from the pool. It defaults to strict which means the `Connection` you
78    /// get from the pool will have exactly the attributes specified in the connection string.
79    ///
80    /// See:
81    /// <https://docs.microsoft.com/en-us/sql/odbc/reference/develop-app/driver-manager-connection-pooling>
82    ///
83    /// # Example
84    ///
85    /// ```no_run
86    /// use odbc_api::{Environment, sys::{AttrConnectionPooling, AttrCpMatch}};
87    ///
88    /// /// Create an environment with connection pooling enabled.
89    /// let env = unsafe {
90    ///     Environment::set_connection_pooling(AttrConnectionPooling::DriverAware).unwrap();
91    ///     let mut env = Environment::new().unwrap();
92    ///     // Strict is the default, and is set here to be explicit about it.
93    ///     env.set_connection_pooling_matching(AttrCpMatch::Strict).unwrap();
94    ///     env
95    /// };
96    /// ```
97    ///
98    /// # Safety
99    ///
100    /// > An ODBC driver must be fully thread-safe, and connections must not have thread affinity to
101    /// > support connection pooling. This means the driver is able to handle a call on any thread
102    /// > at any time and is able to connect on one thread, to use the connection on another thread,
103    /// > and to disconnect on a third thread.
104    ///
105    /// Also note that this is changes global mutable state for the entire process. As such it is
106    /// vulnerable to race conditions if called from more than one place in your application. It is
107    /// recommened to call this in the beginning, before creating any connection.
108    pub unsafe fn set_connection_pooling(
109        scheme: odbc_sys::AttrConnectionPooling,
110    ) -> Result<(), Error> {
111        match unsafe { handles::Environment::set_connection_pooling(scheme) } {
112            SqlResult::Error { .. } => Err(Error::FailedSettingConnectionPooling),
113            SqlResult::Success(()) | SqlResult::SuccessWithInfo(()) => Ok(()),
114            other => {
115                panic!("Unexpected return value `{other:?}`.")
116            }
117        }
118    }
119
120    /// Determines how a connection is chosen from a connection pool. When [`Self::connect`],
121    /// [`Self::connect_with_connection_string`] or [`Self::driver_connect`] is called, the Driver
122    /// Manager determines which connection is reused from the pool. The Driver Manager tries to
123    /// match the connection options in the call and the connection attributes set by the
124    /// application to the keywords and connection attributes of the connections in the pool. The
125    /// value of this attribute determines the level of precision of the matching criteria.
126    ///
127    /// The following values are used to set the value of this attribute:
128    ///
129    /// * [`crate::sys::AttrCpMatch::Strict`] = Only connections that exactly match the connection
130    ///   options in the call and the connection attributes set by the application are reused. This
131    ///   is the default.
132    /// * [`crate::sys::AttrCpMatch::Relaxed`] = Connections with matching connection string \
133    ///   keywords can be used. Keywords must match, but not all connection attributes must match.
134    pub fn set_connection_pooling_matching(&mut self, matching: AttrCpMatch) -> Result<(), Error> {
135        self.environment
136            .set_connection_pooling_matching(matching)
137            .into_result(&self.environment)
138    }
139
140    /// Entry point into this API. Allocates a new ODBC Environment and declares to the driver
141    /// manager that the Application wants to use ODBC version 3.8.
142    ///
143    /// # Safety
144    ///
145    /// There may only be one ODBC environment in any process at any time. Take care using this
146    /// function in unit tests, as these run in parallel by default in Rust. Also no library should
147    /// probably wrap the creation of an odbc environment into a safe function call. This is because
148    /// using two of these "safe" libraries at the same time in different parts of your program may
149    /// lead to race condition thus violating Rust's safety guarantees.
150    ///
151    /// Creating one environment in your binary is safe however.
152    pub fn new() -> Result<Self, Error> {
153        let result = handles::Environment::new();
154
155        let environment = match result {
156            SqlResult::Success(env) => env,
157            SqlResult::SuccessWithInfo(env) => {
158                log_diagnostics(&env);
159                env
160            }
161            SqlResult::Error { .. } => return Err(Error::FailedAllocatingEnvironment),
162            other => panic!("Unexpected return value '{other:?}'"),
163        };
164
165        debug!("ODBC Environment created.");
166
167        debug!("Setting ODBC API version to {ODBC_API_VERSION:?}");
168        let result = environment
169            .declare_version(ODBC_API_VERSION)
170            .into_result(&environment);
171
172        // Status code S1009 has been seen with unixODBC 2.3.1. S1009 meant (among other things)
173        // invalid attribute. If we see this then we try to declare the ODBC version it is of course
174        // likely that the driver manager only knows ODBC 2.x.
175        // See: <https://learn.microsoft.com/sql/odbc/reference/develop-app/sqlstate-mappings>
176        const ODBC_2_INVALID_ATTRIBUTE: State = State(*b"S1009");
177
178        // Translate invalid attribute into a more meaningful error, provided the additional
179        // context that we know we tried to set version number.
180        result.provide_context_for_diagnostic(|record, function| match record.state {
181            // INVALID_STATE_TRANSACTION has been seen with some really old version of unixODBC on
182            // a CentOS used to build manylinux wheels, with the preinstalled ODBC version.
183            // INVALID_ATTRIBUTE_VALUE is the correct status code to emit for a driver manager if it
184            // does not know the version and has been seen with an unknown version of unixODBC on an
185            // Oracle Linux.
186            ODBC_2_INVALID_ATTRIBUTE
187            | State::INVALID_STATE_TRANSACTION
188            | State::INVALID_ATTRIBUTE_VALUE => Error::UnsupportedOdbcApiVersion(record),
189            _ => Error::Diagnostics { record, function },
190        })?;
191
192        Ok(Self {
193            environment,
194            internal_state: Mutex::new(()),
195        })
196    }
197
198    /// Allocates a connection handle and establishes connections to a driver and a data source.
199    ///
200    /// * See [Connecting with SQLConnect][1]
201    /// * See [SQLConnectFunction][2]
202    ///
203    /// # Arguments
204    ///
205    /// * `data_source_name` - Data source name. The data might be located on the same computer as
206    ///   the program, or on another computer somewhere on a network.
207    /// * `user` - User identifier.
208    /// * `pwd` - Authentication string (typically the password).
209    ///
210    /// # Example
211    ///
212    /// ```no_run
213    /// use odbc_api::{Environment, ConnectionOptions};
214    ///
215    /// let env = Environment::new()?;
216    ///
217    /// let mut conn = env.connect(
218    ///     "YourDatabase", "SA", "My@Test@Password1",
219    ///     ConnectionOptions::default()
220    /// )?;
221    /// # Ok::<(), odbc_api::Error>(())
222    /// ```
223    ///
224    /// [1]: https://docs.microsoft.com/sql/odbc/reference/syntax/sqlconnect-function
225    /// [2]: https://docs.microsoft.com/sql/odbc/reference/syntax/sqlconnect-function
226    pub fn connect(
227        &self,
228        data_source_name: &str,
229        user: &str,
230        pwd: &str,
231        options: ConnectionOptions,
232    ) -> Result<Connection<'_>, Error> {
233        let data_source_name = SqlText::new(data_source_name);
234        let user = SqlText::new(user);
235        let pwd = SqlText::new(pwd);
236
237        let mut connection = self.allocate_connection()?;
238
239        options.apply(&connection)?;
240
241        connection
242            .connect(&data_source_name, &user, &pwd)
243            .into_result(&connection)?;
244        Ok(Connection::new(connection))
245    }
246
247    /// Allocates a connection handle and establishes connections to a driver and a data source.
248    ///
249    /// An alternative to `connect`. It supports data sources that require more connection
250    /// information than the three arguments in `connect` and data sources that are not defined in
251    /// the system information.
252    ///
253    /// To find out your connection string try: <https://www.connectionstrings.com/>
254    ///
255    /// # Example
256    ///
257    /// ```no_run
258    /// use odbc_api::{ConnectionOptions, Environment};
259    ///
260    /// let env = Environment::new()?;
261    ///
262    /// let connection_string = "
263    ///     Driver={ODBC Driver 18 for SQL Server};\
264    ///     Server=localhost;\
265    ///     UID=SA;\
266    ///     PWD=My@Test@Password1;\
267    /// ";
268    ///
269    /// let mut conn = env.connect_with_connection_string(
270    ///     connection_string,
271    ///     ConnectionOptions::default()
272    /// )?;
273    /// # Ok::<(), odbc_api::Error>(())
274    /// ```
275    pub fn connect_with_connection_string(
276        &self,
277        connection_string: &str,
278        options: ConnectionOptions,
279    ) -> Result<Connection<'_>, Error> {
280        let connection_string = SqlText::new(connection_string);
281        let mut connection = self.allocate_connection()?;
282
283        options.apply(&connection)?;
284
285        connection
286            .connect_with_connection_string(&connection_string)
287            .into_result(&connection)?;
288        Ok(Connection::new(connection))
289    }
290
291    /// Allocates a connection handle and establishes connections to a driver and a data source.
292    ///
293    /// An alternative to `connect` and `connect_with_connection_string`. This method can be
294    /// provided with an incomplete or even empty connection string. If any additional information
295    /// is required, the driver manager/driver will attempt to create a prompt to allow the user to
296    /// provide the additional information.
297    ///
298    /// If the connection is successful, the complete connection string (including any information
299    /// provided by the user through a prompt) is returned.
300    ///
301    /// # Parameters
302    ///
303    /// * `connection_string`: Connection string.
304    /// * `completed_connection_string`: Output buffer with the complete connection string. It is
305    ///   recommended to choose a buffer with at least `1024` bytes length. **Note**: Some driver
306    ///   implementation have poor error handling in case the provided buffer is too small. At the
307    ///   time of this writing:
308    ///   * Maria DB crashes with STATUS_TACK_BUFFER_OVERRUN
309    ///   * SQLite does not change the output buffer at all and does not indicate truncation.
310    /// * `driver_completion`: Specifies how and if the driver manager uses a prompt to complete
311    ///   the provided connection string. For arguments other than
312    ///   [`crate::DriverCompleteOption::NoPrompt`] this method is going to create a message only
313    ///   parent window for you on windows. On other platform this method is going to panic. In case
314    ///   you want to provide your own parent window please use [`Self::driver_connect_with_hwnd`].
315    ///
316    /// # Examples
317    ///
318    /// In the first example, we intentionally provide a blank connection string so the user will be
319    /// prompted to select a data source to use. Note that this functionality is only available on
320    /// windows.
321    ///
322    /// ```no_run
323    /// use odbc_api::{Environment, handles::OutputStringBuffer, DriverCompleteOption};
324    ///
325    /// let env = Environment::new()?;
326    ///
327    /// let mut output_buffer = OutputStringBuffer::with_buffer_size(1024);
328    /// let connection = env.driver_connect(
329    ///     "",
330    ///     &mut output_buffer,
331    ///     DriverCompleteOption::Prompt,
332    /// )?;
333    ///
334    /// // Check that the output buffer has been large enough to hold the entire connection string.
335    /// assert!(!output_buffer.is_truncated());
336    ///
337    /// // Now `connection_string` will contain the data source selected by the user.
338    /// let connection_string = output_buffer.to_utf8();
339    /// # Ok::<_,odbc_api::Error>(())
340    /// ```
341    ///
342    /// In the following examples we specify a DSN that requires login credentials, but the DSN does
343    /// not provide those credentials. Instead, the user will be prompted for a UID and PWD. The
344    /// returned `connection_string` will contain the `UID` and `PWD` provided by the user. Note
345    /// that this functionality is currently only available on windows targets.
346    ///
347    /// ```
348    /// # use odbc_api::DriverCompleteOption;
349    /// # #[cfg(target_os = "windows")]
350    /// # fn f(
351    /// #    mut output_buffer: odbc_api::handles::OutputStringBuffer,
352    /// #    env: odbc_api::Environment,
353    /// # ) -> Result<(), odbc_api::Error> {
354    /// let without_uid_or_pwd = "DSN=SomeSharedDatabase;";
355    /// let connection = env.driver_connect(
356    ///     &without_uid_or_pwd,
357    ///     &mut output_buffer,
358    ///     DriverCompleteOption::Complete,
359    /// )?;
360    /// let connection_string = output_buffer.to_utf8();
361    ///
362    /// // Now `connection_string` might be something like
363    /// // `DSN=SomeSharedDatabase;UID=SA;PWD=My@Test@Password1;`
364    /// # Ok(()) }
365    /// ```
366    ///
367    /// In this case, we use a DSN that is already sufficient and does not require a prompt. Because
368    /// a prompt is not needed, `window` is also not required. The returned `connection_string` will
369    /// be mostly the same as `already_sufficient` but the driver may append some extra attributes.
370    ///
371    /// ```
372    /// # use odbc_api::DriverCompleteOption;
373    /// # fn f(
374    /// #    mut output_buffer: odbc_api::handles::OutputStringBuffer,
375    /// #    env: odbc_api::Environment,
376    /// # ) -> Result<(), odbc_api::Error> {
377    /// let already_sufficient = "DSN=MicrosoftAccessFile;";
378    /// let connection = env.driver_connect(
379    ///    &already_sufficient,
380    ///    &mut output_buffer,
381    ///    DriverCompleteOption::NoPrompt,
382    /// )?;
383    /// let connection_string = output_buffer.to_utf8();
384    ///
385    /// // Now `connection_string` might be something like
386    /// // `DSN=MicrosoftAccessFile;DBQ=C:\Db\Example.accdb;DriverId=25;FIL=MS Access;MaxBufferSize=2048;`
387    /// # Ok(()) }
388    /// ```
389    pub fn driver_connect(
390        &self,
391        connection_string: &str,
392        completed_connection_string: &mut OutputStringBuffer,
393        driver_completion: DriverCompleteOption,
394    ) -> Result<Connection<'_>, Error> {
395        let mut driver_connect = |hwnd: HWnd| unsafe {
396            self.driver_connect_with_hwnd(
397                connection_string,
398                completed_connection_string,
399                driver_completion,
400                hwnd,
401            )
402        };
403
404        match driver_completion {
405            DriverCompleteOption::NoPrompt => (),
406            #[cfg(target_os = "windows")]
407            _ => {
408                // We need a parent window, let's provide a message only window.
409                let mut window_app = MessageOnlyWindowEventHandler {
410                    run_prompt_dialog: Some(driver_connect),
411                    result: None,
412                };
413                let mut event_loop = EventLoop::new().unwrap();
414                event_loop.run_app_on_demand(&mut window_app).unwrap();
415                return window_app.result.unwrap();
416            }
417            #[cfg(not(target_os = "windows"))]
418            _ => panic!("Prompt is not supported for non-windows systems."),
419        };
420        let hwnd = null_mut();
421        driver_connect(hwnd)
422    }
423
424    /// Allows to call driver connect with a user supplied HWnd. Same as [`Self::driver_connect`],
425    /// but with the possibility to provide your own parent window handle in case you want to show
426    /// a prompt to the user.
427    ///
428    /// # Safety
429    ///
430    /// `parent_window` must be a valid window handle, to a window type supported by the ODBC driver
431    /// manager. On windows this is a plain window handle, which is of course understood by the
432    /// windows built in ODBC driver manager. Other working combinations are unknown to the author.
433    pub unsafe fn driver_connect_with_hwnd(
434        &self,
435        connection_string: &str,
436        completed_connection_string: &mut OutputStringBuffer,
437        driver_completion: DriverCompleteOption,
438        parent_window: HWnd,
439    ) -> Result<Connection<'_>, Error> {
440        let mut connection = self.allocate_connection()?;
441        let connection_string = SqlText::new(connection_string);
442
443        let connection_string_is_complete = unsafe {
444            connection.driver_connect(
445                &connection_string,
446                parent_window,
447                completed_connection_string,
448                driver_completion.as_sys(),
449            )
450        }
451        .into_result_bool(&connection)?;
452        if !connection_string_is_complete {
453            return Err(Error::AbortedConnectionStringCompletion);
454        }
455        Ok(Connection::new(connection))
456    }
457
458    /// Get information about available drivers. Only 32 or 64 Bit drivers will be listed, depending
459    /// on whether you are building a 32 Bit or 64 Bit application.
460    ///
461    /// # Example
462    ///
463    /// ```no_run
464    /// use odbc_api::Environment;
465    ///
466    /// let env = Environment::new ()?;
467    /// for driver_info in env.drivers()? {
468    ///     println!("{:#?}", driver_info);
469    /// }
470    ///
471    /// # Ok::<_, odbc_api::Error>(())
472    /// ```
473    pub fn drivers(&self) -> Result<Vec<DriverInfo>, Error> {
474        let mut driver_info = Vec::new();
475
476        // Since we have exclusive ownership of the environment handle and we take the lock, we can
477        // guarantee that this method is currently the only one changing the state of the internal
478        // iterators of the environment.
479        let _lock = self.internal_state.lock().unwrap();
480        unsafe {
481            // Find required buffer size to avoid truncation.
482            let (mut desc_len, mut attr_len) = if let Some(res) = self
483                .environment
484                // Start with first so we are independent of state
485                .drivers_buffer_len(FetchOrientation::First)
486                .into_result_option(&self.environment)?
487            {
488                res
489            } else {
490                // No drivers present
491                return Ok(Vec::new());
492            };
493
494            // If there are, let's loop over the remaining drivers
495            while let Some((candidate_desc_len, candidate_attr_len)) = self
496                .environment
497                .drivers_buffer_len(FetchOrientation::Next)
498                .into_result_option(&self.environment)?
499            {
500                desc_len = max(candidate_desc_len, desc_len);
501                attr_len = max(candidate_attr_len, attr_len);
502            }
503
504            // Allocate +1 character extra for terminating zero
505            let mut desc_buf = SzBuffer::with_capacity(desc_len as usize);
506            // Do **not** use nul terminated buffer, as nul is used to delimit key value pairs of
507            // attributes.
508            let mut attr_buf: Vec<SqlChar> = vec![0; attr_len as usize];
509
510            while self
511                .environment
512                .drivers_buffer_fill(FetchOrientation::Next, desc_buf.mut_buf(), &mut attr_buf)
513                .into_result_bool(&self.environment)?
514            {
515                let description = desc_buf.to_utf8();
516                let attributes =
517                    slice_to_utf8(&attr_buf).expect("Attributes must be interpretable as UTF-8");
518
519                let attributes = attributes_iter(&attributes).collect();
520
521                driver_info.push(DriverInfo {
522                    description,
523                    attributes,
524                });
525            }
526        }
527
528        Ok(driver_info)
529    }
530
531    /// User and system data sources
532    ///
533    /// # Example
534    ///
535    /// ```no_run
536    /// use odbc_api::Environment;
537    ///
538    /// let env = Environment::new()?;
539    /// for data_source in env.data_sources()? {
540    ///     println!("{:#?}", data_source);
541    /// }
542    ///
543    /// # Ok::<_, odbc_api::Error>(())
544    /// ```
545    pub fn data_sources(&self) -> Result<Vec<DataSourceInfo>, Error> {
546        self.data_sources_impl(FetchOrientation::First)
547    }
548
549    /// Only system data sources
550    ///
551    /// # Example
552    ///
553    /// ```no_run
554    /// use odbc_api::Environment;
555    ///
556    /// let env = Environment::new ()?;
557    /// for data_source in env.system_data_sources()? {
558    ///     println!("{:#?}", data_source);
559    /// }
560    ///
561    /// # Ok::<_, odbc_api::Error>(())
562    /// ```
563    pub fn system_data_sources(&self) -> Result<Vec<DataSourceInfo>, Error> {
564        self.data_sources_impl(FetchOrientation::FirstSystem)
565    }
566
567    /// Only user data sources
568    ///
569    /// # Example
570    ///
571    /// ```no_run
572    /// use odbc_api::Environment;
573    ///
574    /// let mut env = unsafe { Environment::new () }?;
575    /// for data_source in env.user_data_sources()? {
576    ///     println!("{:#?}", data_source);
577    /// }
578    ///
579    /// # Ok::<_, odbc_api::Error>(())
580    /// ```
581    pub fn user_data_sources(&self) -> Result<Vec<DataSourceInfo>, Error> {
582        self.data_sources_impl(FetchOrientation::FirstUser)
583    }
584
585    fn data_sources_impl(&self, direction: FetchOrientation) -> Result<Vec<DataSourceInfo>, Error> {
586        let mut data_source_info = Vec::new();
587
588        // Since we have exclusive ownership of the environment handle and we take the lock, we can
589        // guarantee that this method is currently the only one changing the state of the internal
590        // iterators of the environment.
591        let _lock = self.internal_state.lock().unwrap();
592        unsafe {
593            // Find required buffer size to avoid truncation.
594            let (mut server_name_len, mut driver_len) = if let Some(res) = self
595                .environment
596                .data_source_buffer_len(direction)
597                .into_result_option(&self.environment)?
598            {
599                res
600            } else {
601                // No drivers present
602                return Ok(Vec::new());
603            };
604
605            // If there are let's loop over the rest
606            while let Some((candidate_name_len, candidate_decs_len)) = self
607                .environment
608                .drivers_buffer_len(FetchOrientation::Next)
609                .into_result_option(&self.environment)?
610            {
611                server_name_len = max(candidate_name_len, server_name_len);
612                driver_len = max(candidate_decs_len, driver_len);
613            }
614
615            let mut server_name_buf = SzBuffer::with_capacity(server_name_len as usize);
616            let mut driver_buf = SzBuffer::with_capacity(driver_len as usize);
617
618            let mut not_empty = self
619                .environment
620                .data_source_buffer_fill(direction, server_name_buf.mut_buf(), driver_buf.mut_buf())
621                .into_result_bool(&self.environment)?;
622
623            while not_empty {
624                let server_name = server_name_buf.to_utf8();
625                let driver = driver_buf.to_utf8();
626
627                data_source_info.push(DataSourceInfo {
628                    server_name,
629                    driver,
630                });
631                not_empty = self
632                    .environment
633                    .data_source_buffer_fill(
634                        FetchOrientation::Next,
635                        server_name_buf.mut_buf(),
636                        driver_buf.mut_buf(),
637                    )
638                    .into_result_bool(&self.environment)?;
639            }
640        }
641
642        Ok(data_source_info)
643    }
644
645    fn allocate_connection(&self) -> Result<handles::Connection, Error> {
646        // Hold lock diagnostics errors are consumed in this thread.
647        let _lock = self.internal_state.lock().unwrap();
648        self.environment
649            .allocate_connection()
650            .into_result(&self.environment)
651    }
652}
653
654/// An ODBC [`Environment`] with static lifetime. This function always returns a reference to the
655/// same instance. The environment is constructed then the function is called for the first time.
656/// Every time after the initial construction this function must succeed.
657///
658/// Useful if your application uses ODBC for the entirety of its lifetime, since using a static
659/// lifetime means there is one less lifetime you and the borrow checker need to worry about. If
660/// your application only wants to use odbc for part of its runtime, you may want to use
661/// [`Environment`] directly in order to explicitly free its associated resources earlier. No matter
662/// the application, it is recommended to only have one [`Environment`] per process.
663pub fn environment() -> Result<&'static Environment, Error> {
664    static ENV: OnceLock<Environment> = OnceLock::new();
665    if let Some(env) = ENV.get() {
666        // Environment already initialized, nothing to do, but to return it.
667        Ok(env)
668    } else {
669        // ODBC Environment not initialized yet. Let's do so and return it.
670        let env = Environment::new()?;
671        let env = ENV.get_or_init(|| env);
672        Ok(env)
673    }
674}
675
676/// Struct holding information available on a driver. Can be obtained via [`Environment::drivers`].
677#[derive(Clone, Debug, Eq, PartialEq)]
678pub struct DriverInfo {
679    /// Name of the ODBC driver
680    pub description: String,
681    /// Attributes values of the driver by key
682    pub attributes: HashMap<String, String>,
683}
684
685/// Holds name and description of a datasource
686///
687/// Can be obtained via [`Environment::data_sources`]
688#[derive(Clone, Debug, Eq, PartialEq)]
689pub struct DataSourceInfo {
690    /// Name of the data source
691    pub server_name: String,
692    /// Description of the data source
693    pub driver: String,
694}
695
696/// Message loop for prompt dialog. Used by [`Environment::driver_connect`].
697#[cfg(target_os = "windows")]
698struct MessageOnlyWindowEventHandler<'a, F> {
699    run_prompt_dialog: Option<F>,
700    result: Option<Result<Connection<'a>, Error>>,
701}
702
703#[cfg(target_os = "windows")]
704impl<'a, F> ApplicationHandler for MessageOnlyWindowEventHandler<'a, F>
705where
706    F: FnOnce(HWnd) -> Result<Connection<'a>, Error>,
707{
708    fn resumed(&mut self, event_loop: &ActiveEventLoop) {
709        let parent_window = event_loop
710            .create_window(Window::default_attributes().with_visible(false))
711            .unwrap();
712
713        use winit::raw_window_handle::{HasWindowHandle, RawWindowHandle, Win32WindowHandle};
714
715        let hwnd = match parent_window.window_handle().unwrap().as_raw() {
716            RawWindowHandle::Win32(Win32WindowHandle { hwnd, .. }) => hwnd.get() as HWnd,
717            _ => panic!("ODBC Prompt is only supported on window platforms"),
718        };
719
720        if let Some(run_dialog) = self.run_prompt_dialog.take() {
721            self.result = Some(run_dialog(hwnd))
722        }
723        event_loop.exit();
724    }
725
726    fn window_event(&mut self, _event_loop: &ActiveEventLoop, _id: WindowId, _event: WindowEvent) {}
727}
728
729/// Called by drivers to pares list of attributes
730///
731/// Key value pairs are separated by `\0`. Key and value are separated by `=`
732fn attributes_iter(attributes: &str) -> impl Iterator<Item = (String, String)> + '_ {
733    attributes
734        .split('\0')
735        .take_while(|kv_str| *kv_str != String::new())
736        .map(|kv_str| {
737            let mut iter = kv_str.split('=');
738            let key = iter.next().unwrap();
739            let value = iter.next().unwrap();
740            (key.to_string(), value.to_string())
741        })
742}
743
744#[cfg(test)]
745mod tests {
746
747    use super::*;
748
749    #[test]
750    fn parse_attributes() {
751        let buffer = "APILevel=2\0ConnectFunctions=YYY\0CPTimeout=60\0DriverODBCVer=03.\
752                      50\0FileUsage=0\0SQLLevel=1\0UsageCount=1\0\0";
753        let attributes: HashMap<_, _> = attributes_iter(buffer).collect();
754        assert_eq!(attributes["APILevel"], "2");
755        assert_eq!(attributes["ConnectFunctions"], "YYY");
756        assert_eq!(attributes["CPTimeout"], "60");
757        assert_eq!(attributes["DriverODBCVer"], "03.50");
758        assert_eq!(attributes["FileUsage"], "0");
759        assert_eq!(attributes["SQLLevel"], "1");
760        assert_eq!(attributes["UsageCount"], "1");
761    }
762
763    #[cfg(not(target_os = "windows"))]
764    #[test]
765    #[should_panic(expected = "Prompt is not supported for non-windows systems.")]
766    fn driver_connect_with_prompt_panics_under_linux() {
767        let env = Environment::new().unwrap();
768        let mut out = OutputStringBuffer::empty();
769        env.driver_connect("", &mut out, DriverCompleteOption::Prompt)
770            .unwrap();
771    }
772}