diesel/mariadb/connection.rs
1use crate::mariadb::Mariadb;
2
3/// A connection to a Mariadb database. Connection URLs should be in the form
4/// `mariadb://[user[:password]@]host/database_name[?unix_socket=socket-path]`
5///
6///* `host` can be an IP address or a hostname. If it is set to `localhost`, a connection
7/// will be attempted through the socket at `/tmp/mysql.sock`. If you want to connect to
8/// a local server via TCP (e.g. docker containers), use `0.0.0.0` or `127.0.0.1` instead.
9/// * `unix_socket` expects the path to the unix socket
10///
11/// Errors carry the SQLSTATE the server or client library reports in
12/// [`DatabaseErrorInformation::sqlstate`](crate::result::DatabaseErrorInformation::sqlstate),
13/// including custom codes raised with
14/// [`SIGNAL`](https://mariadb.com/docs/server/reference/sql-statements/programmatic-compound-statements/signal).
15/// The server reports `HY000` for errors without a specific SQLSTATE, as
16/// described at <https://mariadb.com/docs/server/reference/sql-statements/programmatic-compound-statements/programmatic-compound-statements-diagnostics/sqlstate>.
17/// [`sql_state`](crate::mysql_like::sql_state) names the codes.
18///
19/// Errors also carry the error number in
20/// [`DatabaseErrorInformation::native_code`](crate::result::DatabaseErrorInformation::native_code),
21/// listed at <https://mariadb.com/docs/server/reference/error-codes>.
22///
23/// # Supported loading model implementations
24///
25/// * [`DefaultLoadingMode`](crate::connection::DefaultLoadingMode)
26///
27/// As `MariadbConnection` only supports a single loading mode implementation
28/// it is **not required** to explicitly specify a loading mode
29/// when calling [`RunQueryDsl::load_iter()`](crate::query_dsl::RunQueryDsl::load_iter)
30/// or [`LoadConnection::load`](crate::connection::LoadConnection::load)
31///
32/// ## DefaultLoadingMode
33///
34/// `MariadbConnection` only supports a single loading mode, which loads
35/// values row by row from the result set.
36///
37/// ```rust,dejadoc
38/// # include!("../doctest_setup.rs");
39/// #
40/// # fn main() {
41/// # run_test().unwrap();
42/// # }
43/// #
44/// # fn run_test() -> QueryResult<()> {
45/// # use schema::users;
46/// # let connection = &mut establish_connection();
47/// use diesel::connection::DefaultLoadingMode;
48/// { // scope to restrict the lifetime of the iterator
49/// let iter1 = users::table.load_iter::<(i32, String), DefaultLoadingMode>(connection)?;
50///
51/// for r in iter1 {
52/// let (id, name) = r?;
53/// println!("Id: {} Name: {}", id, name);
54/// }
55/// }
56///
57/// // works without specifying the loading mode
58/// let iter2 = users::table.load_iter::<(i32, String), _>(connection)?;
59///
60/// for r in iter2 {
61/// let (id, name) = r?;
62/// println!("Id: {} Name: {}", id, name);
63/// }
64/// # Ok(())
65/// # }
66/// ```
67///
68/// This mode does **not support** creating
69/// multiple iterators using the same connection.
70///
71/// ```compile_fail,dejadoc
72/// # include!("../../doctest_setup.rs");
73/// #
74/// # fn main() {
75/// # run_test().unwrap();
76/// # }
77/// #
78/// # fn run_test() -> QueryResult<()> {
79/// # use schema::users;
80/// # let connection = &mut establish_connection();
81/// use diesel::connection::DefaultLoadingMode;
82///
83/// let iter1 = users::table.load_iter::<(i32, String), DefaultLoadingMode>(connection)?;
84/// let iter2 = users::table.load_iter::<(i32, String), DefaultLoadingMode>(connection)?;
85///
86/// for r in iter1 {
87/// let (id, name) = r?;
88/// println!("Id: {} Name: {}", id, name);
89/// }
90///
91/// for r in iter2 {
92/// let (id, name) = r?;
93/// println!("Id: {} Name: {}", id, name);
94/// }
95/// # Ok(())
96/// # }
97/// ```
98pub type MariadbConnection = crate::mysql_like::MysqlLikeConnection<Mariadb>;
99
100#[cfg(test)]
101mod tests {
102 extern crate dotenvy;
103
104 use super::*;
105 use std::env;
106
107 use crate::connection::Connection;
108 use crate::connection::SimpleConnection;
109 use crate::query_dsl::RunQueryDsl;
110
111 fn connection() -> MariadbConnection {
112 dotenvy::dotenv().ok();
113 let database_url = env::var("MARIADB_UNIT_TEST_DATABASE_URL")
114 .or_else(|_| env::var("MARIADB_DATABASE_URL"))
115 .or_else(|_| env::var("DATABASE_URL"))
116 .expect("DATABASE_URL must be set in order to run unit tests");
117 MariadbConnection::establish(&database_url).unwrap()
118 }
119
120 #[diesel_test_helper::test]
121 fn batch_execute_handles_single_queries_with_results() {
122 let connection = &mut connection();
123 assert!(connection.batch_execute("SELECT 1").is_ok());
124 assert!(connection.batch_execute("SELECT 1").is_ok());
125 }
126
127 #[diesel_test_helper::test]
128 fn batch_execute_handles_multi_queries_with_results() {
129 let connection = &mut connection();
130 let query = "SELECT 1; SELECT 2; SELECT 3;";
131 assert!(connection.batch_execute(query).is_ok());
132 assert!(connection.batch_execute(query).is_ok());
133 }
134
135 #[diesel_test_helper::test]
136 fn execute_handles_queries_which_return_results() {
137 let connection = &mut connection();
138 assert!(crate::sql_query("SELECT 1").execute(connection).is_ok());
139 assert!(crate::sql_query("SELECT 1").execute(connection).is_ok());
140 }
141
142 #[diesel_test_helper::test]
143 fn check_client_found_rows_flag() {
144 let conn = &mut crate::test_helpers::connection();
145 crate::sql_query("DROP TABLE IF EXISTS update_test CASCADE")
146 .execute(conn)
147 .unwrap();
148
149 crate::sql_query("CREATE TABLE update_test(id INTEGER PRIMARY KEY, num INTEGER NOT NULL)")
150 .execute(conn)
151 .unwrap();
152
153 crate::sql_query("INSERT INTO update_test(id, num) VALUES (1, 5)")
154 .execute(conn)
155 .unwrap();
156
157 let output = crate::sql_query("UPDATE update_test SET num = 5 WHERE id = 1")
158 .execute(conn)
159 .unwrap();
160
161 assert_eq!(output, 1);
162 }
163
164 #[crate::declare_sql_function]
165 extern "SQL" {
166 fn version() -> crate::sql_types::Text;
167 }
168
169 #[diesel_test_helper::test]
170 fn version_matches_the_server_reported_version() {
171 let connection = &mut connection();
172 let expected = connection.version().unwrap().to_string();
173 let reported = crate::select(version())
174 .get_result::<String>(connection)
175 .unwrap();
176 assert!(
177 reported.starts_with(&format!("{expected}-")),
178 "`{reported}` does not start with `{expected}-`"
179 );
180 }
181}