Repository: blackbeam/rust-mysql-simple (language: rust)

Issue:
implement select_db()
The MySQL protocol defines COM_INIT_DB / 0x02 as "change the default schema of the connection" [1]. It is used by the MySQL CLI when doing a "USE db" statement and is implemented in the c client as:
 
    int mysql_select_db(MYSQL * mysql,
                         const char * db);

Would you consider accepting a pull request for this feature?

[1] https://dev.mysql.com/doc/internals/en/com-init-db.html


Discussion / hints:

Fix patch:
diff --git a/src/conn/mod.rs b/src/conn/mod.rs
index 5bf646cc..4eb2dfbc 100644
--- a/src/conn/mod.rs
+++ b/src/conn/mod.rs
@@ -1503,6 +1503,15 @@ impl Conn {
         }
     }
 
+    /// Executes [`COM_INIT_DB`](https://dev.mysql.com/doc/internals/en/com-init-db.html)
+    /// on `Conn`.
+    pub fn select_db(&mut self, schema: &str) -> bool {
+        match self.write_command_data(Command::COM_INIT_DB, schema.as_bytes()) {
+            Ok(_) => self.drop_packet().is_ok(),
+            _ => false,
+        }
+    }
+
     /// Starts new transaction with provided options.
     /// `readonly` is only available since MySQL 5.6.5.
     pub fn start_transaction<'a>(
@@ -2269,6 +2278,27 @@ mod test {
             );
         }
         #[test]
+        fn should_select_db() {
+            let mut opts = OptsBuilder::from_opts(get_opts());
+            opts.db_name(Some("mysql"));
+            opts.ip_or_hostname(Some("localhost"));
+            let mut conn = Conn::new(opts).unwrap();
+            assert!(conn
+                .query("CREATE DATABASE IF NOT EXISTS t_select_db")
+                .is_ok());
+            assert!(conn.select_db("t_select_db"));
+            assert_eq!(
+                conn.query("SELECT DATABASE()")
+                    .unwrap()
+                    .next()
+                    .unwrap()
+                    .unwrap()
+                    .unwrap(),
+                vec![Bytes(b"t_select_db".to_vec())]
+            );
+            assert!(conn.query("DROP DATABASE t_select_db").is_ok());
+        }
+        #[test]
         fn should_execute_queryes_and_parse_results() {
             let mut conn = Conn::new(get_opts()).unwrap();
             assert!(conn


Test patch: