├── .github └── workflows │ └── rust.yml ├── .gitignore ├── CONTRIBUTING.md ├── Cargo.toml ├── LICENSE ├── README.md ├── docker-compose.yaml ├── rdbc-cli ├── .gitignore ├── Cargo.toml ├── README.md └── src │ └── main.rs ├── rdbc-mysql ├── Cargo.toml └── src │ └── lib.rs ├── rdbc-odbc ├── Cargo.toml ├── README.md └── src │ └── lib.rs ├── rdbc-postgres ├── Cargo.toml └── src │ └── lib.rs ├── rdbc-sqlite ├── Cargo.toml └── src │ └── lib.rs ├── rdbc ├── Cargo.toml └── src │ └── lib.rs └── rust-toolchain /.github/workflows/rust.yml: -------------------------------------------------------------------------------- 1 | name: Rust 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | build: 7 | 8 | runs-on: ubuntu-latest 9 | 10 | steps: 11 | - uses: actions/checkout@v1 12 | - name: Start database servers 13 | run: docker-compose up -d 14 | - name: Check formatting 15 | run: cargo fmt --all -- --check 16 | - name: Build 17 | run: cargo build 18 | - name: Run tests 19 | run: cargo test 20 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | /target/ 4 | 5 | # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries 6 | # More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html 7 | Cargo.lock 8 | 9 | # These are backup files generated by rustfmt 10 | **/*.rs.bk 11 | 12 | .idea 13 | 14 | postgres-data 15 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to RDBC 2 | 3 | RDBC is licensed under [Apache Licence, Version 2.0](/LICENSE). 4 | 5 | Unless you explicitly state otherwise, any contribution you intentionally submit for inclusion in the work, as defined in the Apache-2.0 license, shall be licensed under Apache-2.0, without any additional terms or conditions. 6 | 7 | # Building 8 | 9 | Use `docker-compose up -d` to start up Postgres and MySQL containers to test against. 10 | 11 | Use `cargo test` to run the unit tests. 12 | 13 | # Formatting 14 | 15 | Run the following command to format code before creating a pull request. 16 | 17 | ```bash 18 | cargo fmt --all 19 | ``` 20 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [workspace] 2 | 3 | members = [ 4 | "rdbc", 5 | "rdbc-mysql", 6 | "rdbc-postgres", 7 | "rdbc-sqlite", 8 | # "rdbc-odbc", 9 | "rdbc-cli", 10 | ] 11 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | # Rust DataBase Connectivity (RDBC) 3 | 4 | [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) 5 | [![Docs](https://docs.rs/rdbc/badge.svg)](https://docs.rs/rdbc) 6 | [![Version](https://img.shields.io/crates/v/rdbc.svg)](https://crates.io/crates/rdbc) 7 | 8 | Love them or hate them, the [ODBC](https://en.wikipedia.org/wiki/Open_Database_Connectivity) and [JDBC](https://en.wikipedia.org/wiki/Java_Database_Connectivity) standards have made it easy to use a wide range of desktop and server products with many different databases thanks to the availability of database drivers implementing these standards. 9 | 10 | This project provides a Rust equivalent API as well as reference implementations (drivers) for Postgres, MySQL, and SQLite. There is also an RDBC-ODBC driver being developed, that will allow ODBC drivers to be called via the RDBC API, so that it is also possible to connect to databases that do not yet have Rust drivers available. 11 | 12 | Note that the provided RDBC drivers are just wrappers around existing database driver crates and this project is not attempting to build new drivers from scratch but rather make it possible to leverage existing drivers through a common API. 13 | 14 | # Why do we need this when we have Diesel? 15 | 16 | This is filling a different need. I love the [Diesel](https://diesel.rs/) approach for building applications but if you are building a generic SQL tool, a business intelligence tool, or a distributed query engine, there is a need to connect to different databases and execute arbitrary SQL. This is where we need a standard API and available drivers. 17 | 18 | # RDBC API PoC 19 | 20 | Note that the design of the RDBC API is intentionally modeled directly after ODBC and JDBC (except that indices are 0-based rather than 1-based) and that is likely to change to make this more idiomatic for Rust. 21 | 22 | There is currently no `async` support and that will be addressed soon. 23 | 24 | There are also design flaws with the current design, such as the limitation of only being able to create one prepared statement per connection. 25 | 26 | Work is in progress of the next iteration of this project and there will definitely be breaking changes. 27 | 28 | 29 | ```rust 30 | /// Represents database driver that can be shared between threads, and can therefore implement 31 | /// a connection pool 32 | pub trait Driver: Sync + Send { 33 | /// Create a connection to the database. Note that connections are intended to be used 34 | /// in a single thread since most database connections are not thread-safe 35 | fn connect(&self, url: &str) -> Result>; 36 | } 37 | 38 | /// Represents a connection to a database 39 | pub trait Connection { 40 | /// Create a statement for execution 41 | fn create(&mut self, sql: &str) -> Result>; 42 | 43 | /// Create a prepared statement for execution 44 | fn prepare(&mut self, sql: &str) -> Result>; 45 | } 46 | 47 | /// Represents an executable statement 48 | pub trait Statement { 49 | /// Execute a query that is expected to return a result set, such as a `SELECT` statement 50 | fn execute_query(&mut self, params: &[Value]) -> Result>; 51 | 52 | /// Execute a query that is expected to update some rows. 53 | fn execute_update(&mut self, params: &[Value]) -> Result; 54 | } 55 | 56 | /// Result set from executing a query against a statement 57 | pub trait ResultSet { 58 | /// get meta data about this result set 59 | fn meta_data(&self) -> Result>; 60 | 61 | /// Move the cursor to the next available row if one exists and return true if it does 62 | fn next(&mut self) -> bool; 63 | 64 | fn get_i8(&self, i: u64) -> Result>; 65 | fn get_i16(&self, i: u64) -> Result>; 66 | fn get_i32(&self, i: u64) -> Result>; 67 | fn get_i64(&self, i: u64) -> Result>; 68 | fn get_f32(&self, i: u64) -> Result>; 69 | fn get_f64(&self, i: u64) -> Result>; 70 | fn get_string(&self, i: u64) -> Result>; 71 | fn get_bytes(&self, i: u64) -> Result>>; 72 | 73 | // NOTE that only a subset of data types are supported so far in this PoC 74 | // and accessors need to be added for other types such as date and time 75 | } 76 | 77 | /// Meta data for result set 78 | pub trait ResultSetMetaData { 79 | fn num_columns(&self) -> u64; 80 | fn column_name(&self, i: usize) -> String; 81 | fn column_type(&self, i: usize) -> DataType; 82 | } 83 | ``` 84 | 85 | # Examples 86 | 87 | ## Execute a Query 88 | 89 | ```rust 90 | let driver: Arc = Arc::new(PostgresDriver::new()); 91 | let mut conn = driver.connect("postgres://user:password@127.0.0.1:5433")?; 92 | let mut stmt = conn.prepare("SELECT a FROM test")?; 93 | let mut rs = stmt.execute_query(&vec![])?; 94 | while rs.next() { 95 | println!("{:?}", rs.get_string(1)?); 96 | } 97 | ``` 98 | 99 | # Current Status 100 | 101 | This is just an experimental PoC and is not currently suitable for anything. However, I do intend to make it useful pretty quickly and I am tracking issues [here](https://github.com/andygrove/rdbc/issues). 102 | 103 | The immediate priorities though are: 104 | 105 | - [x] Announce project and get initial feedback 106 | - [x] Support parameterized queries 107 | - [x] Support prepared statements 108 | - [x] Implement simple SQL console CLI 109 | - [ ] Design for async 110 | - [ ] Support connection pooling 111 | - [ ] Implement comprehensive unit and integration tests 112 | - [ ] Add support for more data types 113 | - [ ] Implement RDBC-ODBC bridge 114 | - [ ] Implement dynamic loading of drivers at runtime 115 | 116 | # License 117 | 118 | RDBC is licensed under [Apache Licence, Version 2.0](/LICENSE). 119 | 120 | # Contributing 121 | 122 | Please refer to the [contributors guide](CONTRIBUTING.md) before contributing to this project and for information on building and testing locally. -------------------------------------------------------------------------------- /docker-compose.yaml: -------------------------------------------------------------------------------- 1 | version: "3.3" 2 | services: 3 | mysql: 4 | image: "mysql:5.7" 5 | command: --default-authentication-plugin=mysql_native_password 6 | restart: always 7 | environment: 8 | - MYSQL_ROOT_PASSWORD=secret 9 | ports: 10 | - 3307:3306 11 | postgres: 12 | image: "postgres" 13 | # Setup the username, password, and database name. You can changes these values. 14 | environment: 15 | - POSTGRES_USER=rdbc 16 | - POSTGRES_PASSWORD=secret 17 | ports: 18 | - "5433:5432" 19 | # Set a volume so that database is not lost after shutting down the container. 20 | # I used the name postgres-data but you can changed it to something else. 21 | volumes: 22 | - ./postgres-data:/var/lib/postgresql/data -------------------------------------------------------------------------------- /rdbc-cli/.gitignore: -------------------------------------------------------------------------------- 1 | .history -------------------------------------------------------------------------------- /rdbc-cli/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "rdbc-cli" 3 | description = "Command line tool for querying RDBC data sources" 4 | version = "0.1.6" 5 | authors = ["Andy Grove "] 6 | license = "Apache-2.0" 7 | edition = "2018" 8 | 9 | [dependencies] 10 | rdbc = { path = "../rdbc", version = "0.1.6" } 11 | rdbc-mysql = { path = "../rdbc-mysql", version = "0.1.6" } 12 | rdbc-postgres = { path = "../rdbc-postgres", version = "0.1.6" } 13 | rdbc-sqlite = { path = "../rdbc-sqlite", version = "0.1.6" } 14 | 15 | clap = "2.33.0" 16 | rustyline = "4.1.0" -------------------------------------------------------------------------------- /rdbc-cli/README.md: -------------------------------------------------------------------------------- 1 | # RDBC CLI 2 | 3 | ```bash 4 | cargo run -- -d postgres -c postgres://rdbc:secret@127.0.0.1:5433 5 | ``` 6 | 7 | ```bash 8 | cargo run -- -d mysql -c mysql://root:secret@127.0.0.1:3307 9 | ``` 10 | 11 | -------------------------------------------------------------------------------- /rdbc-cli/src/main.rs: -------------------------------------------------------------------------------- 1 | use clap::{crate_version, App, Arg}; 2 | use rustyline::Editor; 3 | 4 | use rdbc::{Connection, DataType, Result}; 5 | use rdbc_mysql::MySQLDriver; 6 | use rdbc_postgres::PostgresDriver; 7 | use rdbc_sqlite::SqliteDriver; 8 | 9 | fn main() -> Result<()> { 10 | let matches = App::new("rdbc-cli") 11 | .version(crate_version!()) 12 | .about("Rust DataBase Connectivity CLI") 13 | .arg( 14 | Arg::with_name("driver") 15 | .help("RDBC driver name") 16 | .short("d") 17 | .long("driver") 18 | .takes_value(true), 19 | ) 20 | .arg( 21 | Arg::with_name("connection-url") 22 | .help("The database connection URL") 23 | .short("c") 24 | .long("connection-url") 25 | .takes_value(true), 26 | ) 27 | .get_matches(); 28 | 29 | let driver = matches.value_of("driver").unwrap(); 30 | let url = matches.value_of("connection-url").unwrap(); 31 | println!("Connecting to {} driver with url: {}", driver, url); 32 | 33 | let driver: Box = match driver { 34 | "mysql" => Box::new(MySQLDriver::new()), 35 | "postgres" => Box::new(PostgresDriver::new()), 36 | "sqlite" => Box::new(SqliteDriver::new()), 37 | _ => panic!("Invalid driver"), 38 | }; 39 | 40 | let mut conn = driver.connect(url).unwrap(); 41 | 42 | let mut rl = Editor::<()>::new(); 43 | rl.load_history(".history").ok(); 44 | 45 | let mut query = "".to_owned(); 46 | loop { 47 | let readline = rl.readline("> "); 48 | match readline { 49 | Ok(ref line) if line.trim_end().ends_with(';') => { 50 | query.push_str(line.trim_end()); 51 | rl.add_history_entry(query.clone()); 52 | 53 | match execute(&mut *conn, &query) { 54 | Ok(_) => {} 55 | Err(e) => println!("Error: {:?}", e), 56 | } 57 | 58 | query = "".to_owned(); 59 | } 60 | Ok(ref line) => { 61 | query.push_str(line); 62 | query.push_str(" "); 63 | } 64 | Err(_) => { 65 | break; 66 | } 67 | } 68 | } 69 | 70 | rl.save_history(".history").ok(); 71 | 72 | Ok(()) 73 | } 74 | 75 | fn execute(conn: &mut dyn Connection, sql: &str) -> Result<()> { 76 | println!("Executing {}", sql); 77 | let mut stmt = conn.create(sql)?; 78 | let mut rs = stmt.execute_query(&vec![])?; 79 | let meta = rs.meta_data()?; 80 | 81 | for i in 0..meta.num_columns() { 82 | if i > 0 { 83 | print!("\t"); 84 | } 85 | print!("{}", meta.column_name(i)); 86 | } 87 | println!(); 88 | 89 | while rs.next() { 90 | for i in 0..meta.num_columns() { 91 | if i > 0 { 92 | print!("\t"); 93 | } 94 | match meta.column_type(i) { 95 | DataType::Utf8 => print!("{:?}", rs.get_string(i)), 96 | DataType::Integer => print!("{:?}", rs.get_i32(i)), 97 | // TODO other types 98 | _ => print!("{:?}", rs.get_string(i)), 99 | } 100 | } 101 | println!(); 102 | } 103 | 104 | Ok(()) 105 | } 106 | -------------------------------------------------------------------------------- /rdbc-mysql/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "rdbc-mysql" 3 | description = " MySQL RDBC Driver" 4 | version = "0.1.6" 5 | authors = ["Andy Grove "] 6 | license = "Apache-2.0" 7 | 8 | edition = "2018" 9 | 10 | [dependencies] 11 | rdbc = { path = "../rdbc", version = "0.1.6" } 12 | 13 | mysql = "17.0.0" 14 | mysql_common = "0.19.2" 15 | twox-hash = "1.5.0" 16 | sqlparser = "0.5.0" -------------------------------------------------------------------------------- /rdbc-mysql/src/lib.rs: -------------------------------------------------------------------------------- 1 | //! MySQL RDBC Driver 2 | //! 3 | //! This crate implements an RDBC Driver for the `mysql` crate. 4 | //! 5 | //! The RDBC (Rust DataBase Connectivity) API is loosely based on the ODBC and JDBC standards. 6 | //! 7 | //! ```rust,no_run 8 | //! use rdbc::*; 9 | //! use rdbc_mysql::MySQLDriver; 10 | //! 11 | //! let driver = MySQLDriver::new(); 12 | //! let mut conn = driver.connect("mysql://root:password@localhost:3307/mysql").unwrap(); 13 | //! let mut stmt = conn.prepare("SELECT a FROM b WHERE c = ?").unwrap(); 14 | //! let mut rs = stmt.execute_query(&[Value::Int32(123)]).unwrap(); 15 | //! while rs.next() { 16 | //! println!("{:?}", rs.get_string(1)); 17 | //! } 18 | //! ``` 19 | 20 | use mysql as my; 21 | use mysql_common::constants::ColumnType; 22 | 23 | use sqlparser::dialect::MySqlDialect; 24 | use sqlparser::tokenizer::{Token, Tokenizer, Word}; 25 | 26 | /// Convert a MySQL error into an RDBC error 27 | fn to_rdbc_err(e: my::error::Error) -> rdbc::Error { 28 | rdbc::Error::General(e.to_string()) 29 | } 30 | 31 | fn value_to_rdbc_err(e: my::FromValueError) -> rdbc::Error { 32 | rdbc::Error::General(e.to_string()) 33 | } 34 | 35 | pub struct MySQLDriver {} 36 | 37 | impl MySQLDriver { 38 | pub fn new() -> Self { 39 | MySQLDriver {} 40 | } 41 | } 42 | 43 | impl rdbc::Driver for MySQLDriver { 44 | fn connect(&self, url: &str) -> rdbc::Result> { 45 | let opts = my::Opts::from_url(&url).expect("DATABASE_URL invalid"); 46 | let conn = my::Conn::new(opts).map_err(to_rdbc_err)?; 47 | Ok(Box::new(MySQLConnection { conn })) 48 | } 49 | } 50 | 51 | struct MySQLConnection { 52 | conn: my::Conn, 53 | } 54 | 55 | impl rdbc::Connection for MySQLConnection { 56 | fn create(&mut self, sql: &str) -> rdbc::Result> { 57 | Ok(Box::new(MySQLStatement { 58 | conn: &mut self.conn, 59 | sql: sql.to_owned(), 60 | })) 61 | } 62 | 63 | fn prepare<'a>(&'a mut self, sql: &str) -> rdbc::Result> { 64 | let stmt = self.conn.prepare(&sql).map_err(to_rdbc_err)?; 65 | Ok(Box::new(MySQLPreparedStatement { stmt })) 66 | } 67 | } 68 | 69 | struct MySQLStatement<'a> { 70 | conn: &'a mut my::Conn, 71 | sql: String, 72 | } 73 | 74 | impl<'a> rdbc::Statement for MySQLStatement<'a> { 75 | fn execute_query( 76 | &mut self, 77 | params: &[rdbc::Value], 78 | ) -> rdbc::Result> { 79 | let sql = rewrite(&self.sql, params)?; 80 | let result = self.conn.query(&sql).map_err(to_rdbc_err)?; 81 | Ok(Box::new(MySQLResultSet { result, row: None })) 82 | } 83 | 84 | fn execute_update(&mut self, params: &[rdbc::Value]) -> rdbc::Result { 85 | let sql = rewrite(&self.sql, params)?; 86 | self.conn 87 | .query(&sql) 88 | .map_err(to_rdbc_err) 89 | .map(|result| result.affected_rows()) 90 | } 91 | } 92 | 93 | struct MySQLPreparedStatement<'a> { 94 | stmt: my::Stmt<'a>, 95 | } 96 | 97 | impl<'a> rdbc::Statement for MySQLPreparedStatement<'a> { 98 | fn execute_query( 99 | &mut self, 100 | params: &[rdbc::Value], 101 | ) -> rdbc::Result> { 102 | let result = self 103 | .stmt 104 | .execute(to_my_params(params)) 105 | .map_err(to_rdbc_err)?; 106 | 107 | Ok(Box::new(MySQLResultSet { result, row: None })) 108 | } 109 | 110 | fn execute_update(&mut self, params: &[rdbc::Value]) -> rdbc::Result { 111 | self.stmt 112 | .execute(to_my_params(params)) 113 | .map_err(to_rdbc_err) 114 | .map(|result| result.affected_rows()) 115 | } 116 | } 117 | 118 | pub struct MySQLResultSet<'a> { 119 | result: my::QueryResult<'a>, 120 | row: Option>, 121 | } 122 | 123 | macro_rules! impl_resultset_fns { 124 | ($($fn: ident -> $ty: ty),*) => { 125 | $( 126 | fn $fn(&self, i: u64) -> rdbc::Result> { 127 | match &self.row { 128 | Some(Ok(row)) => row 129 | .get_opt(i as usize) 130 | .expect("we will never `take` the value so the outer `Option` is always `Some`") 131 | .map(|v| Some(v)) 132 | .map_err(value_to_rdbc_err), 133 | _ => Ok(None), 134 | } 135 | } 136 | )* 137 | } 138 | } 139 | 140 | impl<'a> rdbc::ResultSet for MySQLResultSet<'a> { 141 | fn meta_data(&self) -> rdbc::Result> { 142 | let meta: Vec = self 143 | .result 144 | .columns_ref() 145 | .iter() 146 | .map(|c| rdbc::Column::new(&c.name_str(), to_rdbc_type(&c.column_type()))) 147 | .collect(); 148 | Ok(Box::new(meta)) 149 | } 150 | 151 | fn next(&mut self) -> bool { 152 | self.row = self.result.next(); 153 | self.row.is_some() 154 | } 155 | 156 | impl_resultset_fns! { 157 | get_i8 -> i8, 158 | get_i16 -> i16, 159 | get_i32 -> i32, 160 | get_i64 -> i64, 161 | get_f32 -> f32, 162 | get_f64 -> f64, 163 | get_string -> String, 164 | get_bytes -> Vec 165 | } 166 | } 167 | 168 | fn to_rdbc_type(t: &ColumnType) -> rdbc::DataType { 169 | match t { 170 | ColumnType::MYSQL_TYPE_FLOAT => rdbc::DataType::Float, 171 | ColumnType::MYSQL_TYPE_DOUBLE => rdbc::DataType::Double, 172 | ColumnType::MYSQL_TYPE_TINY => rdbc::DataType::Byte, 173 | ColumnType::MYSQL_TYPE_SHORT => rdbc::DataType::Short, 174 | ColumnType::MYSQL_TYPE_LONG => rdbc::DataType::Integer, 175 | ColumnType::MYSQL_TYPE_LONGLONG => rdbc::DataType::Integer, // TODO: 64-bit integer type? 176 | ColumnType::MYSQL_TYPE_DECIMAL => rdbc::DataType::Decimal, 177 | ColumnType::MYSQL_TYPE_NEWDECIMAL => rdbc::DataType::Decimal, 178 | ColumnType::MYSQL_TYPE_STRING => rdbc::DataType::Utf8, 179 | ColumnType::MYSQL_TYPE_VAR_STRING => rdbc::DataType::Utf8, 180 | ColumnType::MYSQL_TYPE_VARCHAR => rdbc::DataType::Utf8, 181 | ColumnType::MYSQL_TYPE_TINY_BLOB => rdbc::DataType::Binary, 182 | ColumnType::MYSQL_TYPE_MEDIUM_BLOB => rdbc::DataType::Binary, 183 | ColumnType::MYSQL_TYPE_LONG_BLOB => rdbc::DataType::Binary, 184 | ColumnType::MYSQL_TYPE_BLOB => rdbc::DataType::Binary, 185 | ColumnType::MYSQL_TYPE_BIT => rdbc::DataType::Bool, 186 | ColumnType::MYSQL_TYPE_DATE => rdbc::DataType::Date, 187 | ColumnType::MYSQL_TYPE_TIME => rdbc::DataType::Time, 188 | ColumnType::MYSQL_TYPE_TIMESTAMP => rdbc::DataType::Datetime, // TODO: Data type for timestamps in UTC? 189 | ColumnType::MYSQL_TYPE_DATETIME => rdbc::DataType::Datetime, 190 | mysql_datatype => todo!("Datatype not currently supported: {:?}", mysql_datatype), 191 | } 192 | } 193 | 194 | fn to_my_value(v: &rdbc::Value) -> my::Value { 195 | match v { 196 | rdbc::Value::Int32(n) => my::Value::Int(*n as i64), 197 | rdbc::Value::UInt32(n) => my::Value::Int(*n as i64), 198 | rdbc::Value::String(s) => my::Value::from(s), 199 | //TODO all types 200 | } 201 | } 202 | 203 | /// Convert RDBC parameters to MySQL parameters 204 | fn to_my_params(params: &[rdbc::Value]) -> my::Params { 205 | my::Params::Positional(params.iter().map(|v| to_my_value(v)).collect()) 206 | } 207 | 208 | fn rewrite(sql: &str, params: &[rdbc::Value]) -> rdbc::Result { 209 | let dialect = MySqlDialect {}; 210 | let mut tokenizer = Tokenizer::new(&dialect, sql); 211 | tokenizer 212 | .tokenize() 213 | .and_then(|tokens| { 214 | let mut i = 0; 215 | 216 | let tokens: Vec = tokens 217 | .iter() 218 | .map(|t| match t { 219 | Token::Char(c) if *c == '?' => { 220 | let param = ¶ms[i]; 221 | i += 1; 222 | Token::Word(Word { 223 | value: param.to_string(), 224 | quote_style: None, 225 | keyword: "".to_owned(), 226 | }) 227 | } 228 | _ => t.clone(), 229 | }) 230 | .collect(); 231 | 232 | let sql = tokens 233 | .iter() 234 | .map(|t| format!("{}", t)) 235 | .collect::>() 236 | .join(""); 237 | 238 | Ok(sql) 239 | }) 240 | .map_err(|e| rdbc::Error::General(format!("{:?}", e))) 241 | } 242 | 243 | #[cfg(test)] 244 | mod tests { 245 | 246 | use super::*; 247 | use std::sync::Arc; 248 | 249 | #[test] 250 | fn execute_query() -> rdbc::Result<()> { 251 | execute("DROP TABLE IF EXISTS test", &vec![])?; 252 | execute("CREATE TABLE test (a INT NOT NULL)", &vec![])?; 253 | execute( 254 | "INSERT INTO test (a) VALUES (?)", 255 | &vec![rdbc::Value::Int32(123)], 256 | )?; 257 | 258 | let driver: Arc = Arc::new(MySQLDriver::new()); 259 | let mut conn = driver.connect("mysql://root:secret@127.0.0.1:3307/mysql")?; 260 | let mut stmt = conn.prepare("SELECT a FROM test")?; 261 | let mut rs = stmt.execute_query(&vec![])?; 262 | assert!(rs.next()); 263 | assert_eq!(Some(123), rs.get_i32(0)?); 264 | assert!(!rs.next()); 265 | 266 | Ok(()) 267 | } 268 | 269 | fn execute(sql: &str, values: &Vec) -> rdbc::Result { 270 | println!("Executing '{}' with {} params", sql, values.len()); 271 | let driver: Arc = Arc::new(MySQLDriver::new()); 272 | let mut conn = driver.connect("mysql://root:secret@127.0.0.1:3307/mysql")?; 273 | let mut stmt = conn.create(sql)?; 274 | stmt.execute_update(values) 275 | } 276 | } 277 | -------------------------------------------------------------------------------- /rdbc-odbc/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "rdbc-odbc" 3 | description = "RDBC-ODBC Bridge" 4 | authors = ["Andy Grove "] 5 | license = "Apache-2.0" 6 | version = "0.1.6" 7 | edition = "2018" 8 | 9 | [dependencies] 10 | rdbc = { path = "../rdbc", version = "0.1.6" } 11 | 12 | odbc = "0.16.1" 13 | -------------------------------------------------------------------------------- /rdbc-odbc/README.md: -------------------------------------------------------------------------------- 1 | # rdbc-odbc 2 | 3 | RDBC Driver that delegates to ODBC. 4 | 5 | # Pre-requisites (Linux) 6 | 7 | Install [unixODBC](http://www.unixodbc.org/) 8 | 9 | -------------------------------------------------------------------------------- /rdbc-odbc/src/lib.rs: -------------------------------------------------------------------------------- 1 | use std::cell::RefCell; 2 | use std::rc::Rc; 3 | 4 | use odbc; 5 | use odbc::odbc_safe::{AutocommitMode, Version, Odbc3}; 6 | use odbc::{Environment, HasResult, Allocated, NoResult, Prepared}; 7 | 8 | use rdbc; 9 | use rdbc::{Error, ResultSet, Statement, Value, ResultSetMetaData}; 10 | use odbc::ResultSetState::{NoData, Data}; 11 | 12 | struct OdbcDriver { 13 | env: Environment 14 | } 15 | 16 | impl OdbcDriver { 17 | 18 | pub fn new() -> Self { 19 | 20 | let env = odbc::create_environment_v3() 21 | .map_err(|e| e.unwrap()) 22 | .unwrap(); 23 | 24 | OdbcDriver { env } 25 | } 26 | 27 | pub fn connect(&self, connect_string: &str) -> Rc> { 28 | let conn = self.env.connect_with_connection_string(connect_string).unwrap(); 29 | Rc::new(RefCell::new(OdbcConnection { conn })) 30 | } 31 | } 32 | 33 | struct OdbcConnection<'a, V> where V: AutocommitMode { 34 | conn: odbc::Connection<'a, V> 35 | } 36 | 37 | impl<'a, V> rdbc::Connection for OdbcConnection<'a, V> where V: AutocommitMode { 38 | 39 | fn create(&mut self, sql: &str) -> rdbc::Result>> { 40 | self.prepare(sql) 41 | } 42 | 43 | fn prepare(&mut self, sql: &str) -> rdbc::Result>> { 44 | let stmt = odbc::Statement::with_parent(&self.conn).unwrap(); 45 | let stmt = stmt.prepare(&sql).unwrap(); 46 | Ok(Rc::new(RefCell::new(OdbcStatement { stmt })) as Rc>) 47 | } 48 | } 49 | 50 | struct OdbcStatement<'con, 'b, AC> where AC: AutocommitMode { 51 | stmt: odbc::Statement<'con, 'b, Prepared, NoResult, AC>, 52 | } 53 | 54 | impl<'con, 'b, AC> rdbc::Statement for OdbcStatement<'con, 'b, AC> where AC: AutocommitMode { 55 | 56 | fn execute_query( 57 | &mut self, 58 | params: &[Value], 59 | ) -> rdbc::Result>> { 60 | 61 | //TODO bind params 62 | //self.stmt.bind_parameter(0, "foo"); 63 | 64 | // match self.stmt.execute().unwrap() { 65 | // Data(mut stmt) => { 66 | // //Ok(Rc::new(RefCell::new(OdbcStatement { stmt, sql: sql.to_owned() })) as Rc>) 67 | // unimplemented!() 68 | // }, 69 | // NoData(_) => unimplemented!() 70 | // } 71 | 72 | unimplemented!() 73 | } 74 | 75 | fn execute_update(&mut self, params: &[Value]) -> rdbc::Result { 76 | unimplemented!() 77 | } 78 | } 79 | 80 | struct OdbcResultSet {} 81 | 82 | impl rdbc::ResultSet for OdbcResultSet { 83 | 84 | fn meta_data(&self) -> Result, Error> { 85 | unimplemented!() 86 | } 87 | 88 | fn next(&mut self) -> bool { 89 | unimplemented!() 90 | } 91 | 92 | fn get_i32(&self, i: u64) -> Option { 93 | unimplemented!() 94 | } 95 | 96 | fn get_string(&self, i: u64) -> Option { 97 | unimplemented!() 98 | } 99 | } 100 | 101 | //fn execute_statement<'env>(conn: &Connection<'env>) -> Result<()> { 102 | // let stmt = Statement::with_parent(conn)?; 103 | // 104 | // match stmt.exec_direct(&sql_text)? { 105 | // Data(mut stmt) => { 106 | // let cols = stmt.num_result_cols()?; 107 | // while let Some(mut cursor) = stmt.fetch()? { 108 | // for i in 1..(cols + 1) { 109 | // match cursor.get_data::<&str>(i as u16)? { 110 | // Some(val) => print!(" {}", val), 111 | // None => print!(" NULL"), 112 | // } 113 | // } 114 | // println!(""); 115 | // } 116 | // } 117 | // NoData(_) => println!("Query executed, no data returned"), 118 | // } 119 | // 120 | // Ok(()) 121 | //} 122 | -------------------------------------------------------------------------------- /rdbc-postgres/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "rdbc-postgres" 3 | description = " Postgres RDBC Driver" 4 | version = "0.1.6" 5 | authors = ["Andy Grove "] 6 | license = "Apache-2.0" 7 | 8 | edition = "2018" 9 | 10 | [dependencies] 11 | rdbc = { path = "../rdbc", version = "0.1.6" } 12 | 13 | postgres = "0.15.2" 14 | sqlparser = "0.5.0" -------------------------------------------------------------------------------- /rdbc-postgres/src/lib.rs: -------------------------------------------------------------------------------- 1 | //! Postgres RDBC Driver 2 | //! 3 | //! This crate implements an RDBC Driver for the `postgres` crate. 4 | //! 5 | //! The RDBC (Rust DataBase Connectivity) API is loosely based on the ODBC and JDBC standards. 6 | //! 7 | //! ```rust,no_run 8 | //! use rdbc::*; 9 | //! use rdbc_postgres::PostgresDriver; 10 | //! 11 | //! let driver = PostgresDriver::new(); 12 | //! let mut conn = driver.connect("postgres://postgres:password@localhost:5433").unwrap(); 13 | //! let mut stmt = conn.prepare("SELECT a FROM b WHERE c = ?").unwrap(); 14 | //! let mut rs = stmt.execute_query(&[Value::Int32(123)]).unwrap(); 15 | //! while rs.next() { 16 | //! println!("{:?}", rs.get_string(1)); 17 | //! } 18 | //! ``` 19 | 20 | use postgres::rows::Rows; 21 | use postgres::{Connection, TlsMode}; 22 | 23 | use sqlparser::dialect::PostgreSqlDialect; 24 | use sqlparser::tokenizer::{Token, Tokenizer, Word}; 25 | 26 | use postgres::types::Type; 27 | use rdbc::Column; 28 | 29 | pub struct PostgresDriver {} 30 | 31 | impl PostgresDriver { 32 | pub fn new() -> Self { 33 | PostgresDriver {} 34 | } 35 | } 36 | 37 | impl rdbc::Driver for PostgresDriver { 38 | fn connect(&self, url: &str) -> rdbc::Result> { 39 | let c = postgres::Connection::connect(url, TlsMode::None).map_err(to_rdbc_err)?; 40 | Ok(Box::new(PConnection::new(c))) 41 | } 42 | } 43 | 44 | struct PConnection { 45 | conn: Connection, 46 | } 47 | 48 | impl PConnection { 49 | pub fn new(conn: Connection) -> Self { 50 | Self { conn } 51 | } 52 | } 53 | 54 | impl rdbc::Connection for PConnection { 55 | fn create(&mut self, sql: &str) -> rdbc::Result> { 56 | self.prepare(sql) 57 | } 58 | 59 | fn prepare(&mut self, sql: &str) -> rdbc::Result> { 60 | // translate SQL, mapping ? into $1 style bound param placeholder 61 | let dialect = PostgreSqlDialect {}; 62 | let mut tokenizer = Tokenizer::new(&dialect, sql); 63 | let tokens = tokenizer.tokenize().unwrap(); 64 | let mut i = 0; 65 | let tokens: Vec = tokens 66 | .iter() 67 | .map(|t| match t { 68 | Token::Char(c) if *c == '?' => { 69 | i += 1; 70 | Token::Word(Word { 71 | value: format!("${}", i), 72 | quote_style: None, 73 | keyword: "".to_owned(), 74 | }) 75 | } 76 | _ => t.clone(), 77 | }) 78 | .collect(); 79 | let sql = tokens 80 | .iter() 81 | .map(|t| format!("{}", t)) 82 | .collect::>() 83 | .join(""); 84 | 85 | Ok(Box::new(PStatement { 86 | conn: &self.conn, 87 | sql, 88 | })) 89 | } 90 | } 91 | 92 | struct PStatement<'a> { 93 | conn: &'a Connection, 94 | sql: String, 95 | } 96 | 97 | impl<'a> rdbc::Statement for PStatement<'a> { 98 | fn execute_query( 99 | &mut self, 100 | params: &[rdbc::Value], 101 | ) -> rdbc::Result> { 102 | let params = to_postgres_value(params); 103 | let params: Vec<&dyn postgres::types::ToSql> = params.iter().map(|v| v.as_ref()).collect(); 104 | let rows = self 105 | .conn 106 | .query(&self.sql, params.as_slice()) 107 | .map_err(to_rdbc_err)?; 108 | let meta = rows 109 | .columns() 110 | .iter() 111 | .map(|c| rdbc::Column::new(c.name(), to_rdbc_type(c.type_()))) 112 | .collect(); 113 | 114 | Ok(Box::new(PResultSet { meta, i: 0, rows })) 115 | } 116 | 117 | fn execute_update(&mut self, params: &[rdbc::Value]) -> rdbc::Result { 118 | let params = to_postgres_value(params); 119 | let params: Vec<&dyn postgres::types::ToSql> = params.iter().map(|v| v.as_ref()).collect(); 120 | self.conn 121 | .execute(&self.sql, params.as_slice()) 122 | .map_err(to_rdbc_err) 123 | } 124 | } 125 | 126 | struct PResultSet { 127 | meta: Vec, 128 | i: usize, 129 | rows: Rows, 130 | } 131 | 132 | macro_rules! impl_resultset_fns { 133 | ($($fn: ident -> $ty: ty),*) => { 134 | $( 135 | fn $fn(&self, i: u64) -> rdbc::Result> { 136 | Ok(self.rows.get(self.i - 1).get(i as usize)) 137 | } 138 | )* 139 | } 140 | } 141 | 142 | impl rdbc::ResultSet for PResultSet { 143 | fn meta_data(&self) -> rdbc::Result> { 144 | Ok(Box::new(self.meta.clone())) 145 | } 146 | 147 | fn next(&mut self) -> bool { 148 | if self.i < self.rows.len() { 149 | self.i = self.i + 1; 150 | true 151 | } else { 152 | false 153 | } 154 | } 155 | 156 | impl_resultset_fns! { 157 | get_i8 -> i8, 158 | get_i16 -> i16, 159 | get_i32 -> i32, 160 | get_i64 -> i64, 161 | get_f32 -> f32, 162 | get_f64 -> f64, 163 | get_string -> String, 164 | get_bytes -> Vec 165 | } 166 | } 167 | 168 | /// Convert a Postgres error into an RDBC error 169 | fn to_rdbc_err(e: postgres::error::Error) -> rdbc::Error { 170 | rdbc::Error::General(format!("{:?}", e)) 171 | } 172 | 173 | fn to_rdbc_type(ty: &Type) -> rdbc::DataType { 174 | match ty.name() { 175 | "" => rdbc::DataType::Bool, 176 | //TODO all types 177 | _ => rdbc::DataType::Utf8, 178 | } 179 | } 180 | 181 | fn to_postgres_value(values: &[rdbc::Value]) -> Vec> { 182 | values 183 | .iter() 184 | .map(|v| match v { 185 | rdbc::Value::String(s) => Box::new(s.clone()) as Box, 186 | rdbc::Value::Int32(n) => Box::new(*n) as Box, 187 | rdbc::Value::UInt32(n) => Box::new(*n) as Box, 188 | //TODO all types 189 | }) 190 | .collect() 191 | } 192 | 193 | #[cfg(test)] 194 | mod tests { 195 | 196 | use super::*; 197 | use std::sync::Arc; 198 | 199 | #[test] 200 | fn execute_query() -> rdbc::Result<()> { 201 | execute("DROP TABLE IF EXISTS test", &vec![])?; 202 | execute("CREATE TABLE test (a INT NOT NULL)", &vec![])?; 203 | execute( 204 | "INSERT INTO test (a) VALUES (?)", 205 | &vec![rdbc::Value::Int32(123)], 206 | )?; 207 | 208 | let driver: Arc = Arc::new(PostgresDriver::new()); 209 | let mut conn = driver.connect("postgres://rdbc:secret@127.0.0.1:5433")?; 210 | let mut stmt = conn.prepare("SELECT a FROM test")?; 211 | let mut rs = stmt.execute_query(&vec![])?; 212 | 213 | assert!(rs.next()); 214 | assert_eq!(Some(123), rs.get_i32(0)?); 215 | assert!(!rs.next()); 216 | 217 | Ok(()) 218 | } 219 | 220 | fn execute(sql: &str, values: &Vec) -> rdbc::Result { 221 | println!("Executing '{}' with {} params", sql, values.len()); 222 | let driver: Arc = Arc::new(PostgresDriver::new()); 223 | let mut conn = driver.connect("postgres://rdbc:secret@127.0.0.1:5433")?; 224 | let mut stmt = conn.prepare(sql)?; 225 | stmt.execute_update(values) 226 | } 227 | } 228 | -------------------------------------------------------------------------------- /rdbc-sqlite/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "rdbc-sqlite" 3 | description = "SQLite RDBC Driver" 4 | version = "0.1.6" 5 | authors = ["Andy Grove ", "Manuel Woelker "] 6 | license = "Apache-2.0" 7 | 8 | edition = "2018" 9 | 10 | [dependencies] 11 | rdbc = { path = "../rdbc", version = "0.1.6" } 12 | 13 | rusqlite = { version = "0.21.0", features = ["bundled"]} 14 | fallible-streaming-iterator = "0.1" -------------------------------------------------------------------------------- /rdbc-sqlite/src/lib.rs: -------------------------------------------------------------------------------- 1 | //! SQLite RDBC Driver 2 | //! 3 | //! This crate implements an RDBC Driver for the `rusqlite` crate. 4 | //! 5 | //! The RDBC (Rust DataBase Connectivity) API is loosely based on the ODBC and JDBC standards. 6 | //! 7 | //! ```rust 8 | //! use std::sync::Arc; 9 | //! use rdbc::{self, Value}; 10 | //! use rdbc_sqlite::SqliteDriver; 11 | //! let driver: Arc = Arc::new(SqliteDriver::new()); 12 | //! let mut conn = driver.connect("").unwrap(); 13 | //! let stmt = conn.prepare("CREATE TABLE test (a INT NOT NULL)").unwrap().execute_update(&[]).unwrap(); 14 | //! let stmt = conn.prepare("INSERT INTO test (a) VALUES (?)").unwrap().execute_update(&[rdbc::Value::Int32(123)]).unwrap(); 15 | //! let mut stmt = conn.prepare("SELECT a FROM test").unwrap(); 16 | //! let mut rs = stmt.execute_query(&[]).unwrap(); 17 | //! assert!(rs.next()); 18 | //! assert_eq!(Some(123), rs.get_i32(0).unwrap()); 19 | //! ``` 20 | 21 | use fallible_streaming_iterator::FallibleStreamingIterator; 22 | use rusqlite::Rows; 23 | 24 | /// Convert a Sqlite error into an RDBC error 25 | fn to_rdbc_err(e: rusqlite::Error) -> rdbc::Error { 26 | rdbc::Error::General(format!("{:?}", e)) 27 | } 28 | 29 | pub struct SqliteDriver {} 30 | 31 | impl SqliteDriver { 32 | pub fn new() -> Self { 33 | SqliteDriver {} 34 | } 35 | } 36 | 37 | impl rdbc::Driver for SqliteDriver { 38 | fn connect(&self, _url: &str) -> rdbc::Result> { 39 | let c = rusqlite::Connection::open_in_memory().map_err(to_rdbc_err)?; 40 | Ok(Box::new(SConnection::new(c))) 41 | } 42 | } 43 | 44 | struct SConnection { 45 | conn: rusqlite::Connection, 46 | } 47 | 48 | impl SConnection { 49 | pub fn new(conn: rusqlite::Connection) -> Self { 50 | Self { conn } 51 | } 52 | } 53 | 54 | impl rdbc::Connection for SConnection { 55 | fn create(&mut self, sql: &str) -> rdbc::Result> { 56 | self.prepare(sql) 57 | } 58 | 59 | fn prepare(&mut self, sql: &str) -> rdbc::Result> { 60 | let stmt = self.conn.prepare(sql).map_err(to_rdbc_err)?; 61 | Ok(Box::new(SStatement { stmt })) 62 | } 63 | } 64 | 65 | struct SStatement<'a> { 66 | stmt: rusqlite::Statement<'a>, 67 | } 68 | 69 | impl<'a> rdbc::Statement for SStatement<'a> { 70 | fn execute_query( 71 | &mut self, 72 | params: &[rdbc::Value], 73 | ) -> rdbc::Result> { 74 | let params = Values(params); 75 | let rows = self.stmt.query(¶ms).map_err(to_rdbc_err)?; 76 | Ok(Box::new(SResultSet { rows })) 77 | } 78 | 79 | fn execute_update(&mut self, params: &[rdbc::Value]) -> rdbc::Result { 80 | let params = Values(params); 81 | return self 82 | .stmt 83 | .execute(¶ms) 84 | .map_err(to_rdbc_err) 85 | .map(|n| n as u64); 86 | } 87 | } 88 | 89 | macro_rules! impl_resultset_fns { 90 | ($($fn: ident -> $ty: ty),*) => { 91 | $( 92 | fn $fn(&self, i: u64) -> rdbc::Result> { 93 | self.rows 94 | .get() 95 | .unwrap() 96 | .get(i as usize) 97 | .map_err(to_rdbc_err) 98 | } 99 | )* 100 | } 101 | } 102 | 103 | struct SResultSet<'stmt> { 104 | rows: Rows<'stmt>, 105 | } 106 | 107 | impl<'stmt> rdbc::ResultSet for SResultSet<'stmt> { 108 | fn meta_data(&self) -> rdbc::Result> { 109 | let meta: Vec = self 110 | .rows 111 | .columns() 112 | .unwrap() 113 | .iter() 114 | .map(|c| rdbc::Column::new(c.name(), to_rdbc_type(c.decl_type()))) 115 | .collect(); 116 | Ok(Box::new(meta)) 117 | } 118 | 119 | fn next(&mut self) -> bool { 120 | self.rows.next().unwrap().is_some() 121 | } 122 | 123 | fn get_f32(&self, _i: u64) -> rdbc::Result> { 124 | Err(rdbc::Error::General("f32 not supported".to_owned())) 125 | } 126 | 127 | impl_resultset_fns! { 128 | get_i8 -> i8, 129 | get_i16 -> i16, 130 | get_i32 -> i32, 131 | get_i64 -> i64, 132 | get_f64 -> f64, 133 | get_string -> String, 134 | get_bytes -> Vec 135 | } 136 | } 137 | 138 | fn to_rdbc_type(t: Option<&str>) -> rdbc::DataType { 139 | //TODO implement for real 140 | match t { 141 | Some("INT") => rdbc::DataType::Integer, 142 | _ => rdbc::DataType::Utf8, 143 | } 144 | } 145 | 146 | struct Values<'a>(&'a [rdbc::Value]); 147 | struct ValuesIter<'a>(std::slice::Iter<'a, rdbc::Value>); 148 | 149 | impl<'a> IntoIterator for &'a Values<'a> { 150 | type IntoIter = ValuesIter<'a>; 151 | type Item = &'a dyn rusqlite::types::ToSql; 152 | 153 | fn into_iter(self) -> ValuesIter<'a> { 154 | ValuesIter(self.0.iter()) 155 | } 156 | } 157 | impl<'a> Iterator for ValuesIter<'a> { 158 | type Item = &'a dyn rusqlite::types::ToSql; 159 | 160 | fn next(&mut self) -> Option<&'a dyn rusqlite::types::ToSql> { 161 | self.0.next().map(|v| match v { 162 | rdbc::Value::String(ref s) => s as &dyn rusqlite::types::ToSql, 163 | rdbc::Value::Int32(ref n) => n as &dyn rusqlite::types::ToSql, 164 | rdbc::Value::UInt32(ref n) => n as &dyn rusqlite::types::ToSql, 165 | }) 166 | } 167 | } 168 | 169 | #[cfg(test)] 170 | mod tests { 171 | use super::*; 172 | use rdbc::{Connection, DataType}; 173 | use std::sync::Arc; 174 | 175 | #[test] 176 | fn execute_query() -> rdbc::Result<()> { 177 | let driver: Arc = Arc::new(SqliteDriver::new()); 178 | let url = ""; 179 | let mut conn = driver.connect(url)?; 180 | execute(&mut *conn, "DROP TABLE IF EXISTS test", &vec![])?; 181 | execute(&mut *conn, "CREATE TABLE test (a INT NOT NULL)", &vec![])?; 182 | execute( 183 | &mut *conn, 184 | "INSERT INTO test (a) VALUES (?)", 185 | &vec![rdbc::Value::Int32(123)], 186 | )?; 187 | 188 | let mut stmt = conn.prepare("SELECT a FROM test")?; 189 | let mut rs = stmt.execute_query(&vec![])?; 190 | 191 | let meta = rs.meta_data()?; 192 | assert_eq!(1, meta.num_columns()); 193 | assert_eq!("a".to_owned(), meta.column_name(0)); 194 | assert_eq!(DataType::Integer, meta.column_type(0)); 195 | 196 | assert!(rs.next()); 197 | assert_eq!(Some(123), rs.get_i32(0)?); 198 | assert!(!rs.next()); 199 | 200 | Ok(()) 201 | } 202 | 203 | fn execute( 204 | conn: &mut dyn Connection, 205 | sql: &str, 206 | values: &Vec, 207 | ) -> rdbc::Result { 208 | println!("Executing '{}' with {} params", sql, values.len()); 209 | let mut stmt = conn.prepare(sql)?; 210 | stmt.execute_update(values) 211 | } 212 | } 213 | -------------------------------------------------------------------------------- /rdbc/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "rdbc" 3 | description = "Rust DataBase Connectivity (RDBC) API" 4 | version = "0.1.6" 5 | authors = ["Andy Grove "] 6 | license = "Apache-2.0" 7 | edition = "2018" 8 | 9 | [dependencies] 10 | -------------------------------------------------------------------------------- /rdbc/src/lib.rs: -------------------------------------------------------------------------------- 1 | //! The RDBC (Rust DataBase Connectivity) API is loosely based on the ODBC and JDBC standards 2 | //! and provides a database agnostic programming interface for executing queries and fetching 3 | //! results. 4 | //! 5 | //! Reference implementation RDBC Drivers exist for Postgres, MySQL and SQLite. 6 | //! 7 | //! The following example demonstrates how RDBC can be used to run a trivial query against Postgres. 8 | //! 9 | //! ```rust,ignore 10 | //! use rdbc::*; 11 | //! use rdbc_postgres::PostgresDriver; 12 | //! 13 | //! let driver = PostgresDriver::new(); 14 | //! let mut conn = driver.connect("postgres://postgres:password@localhost:5433").unwrap(); 15 | //! let mut stmt = conn.prepare("SELECT a FROM b WHERE c = ?").unwrap(); 16 | //! let mut rs = stmt.execute_query(&[Value::Int32(123)]).unwrap(); 17 | //! while rs.next() { 18 | //! println!("{:?}", rs.get_string(1)); 19 | //! } 20 | //! ``` 21 | 22 | /// RDBC Error 23 | #[derive(Debug)] 24 | pub enum Error { 25 | General(String), 26 | } 27 | 28 | #[derive(Debug, Clone)] 29 | pub enum Value { 30 | Int32(i32), 31 | UInt32(u32), 32 | String(String), 33 | //TODO add other types 34 | } 35 | 36 | impl ToString for Value { 37 | fn to_string(&self) -> String { 38 | match self { 39 | Value::Int32(n) => format!("{}", n), 40 | Value::UInt32(n) => format!("{}", n), 41 | Value::String(s) => format!("'{}'", s), 42 | } 43 | } 44 | } 45 | 46 | /// RDBC Result type 47 | pub type Result = std::result::Result; 48 | 49 | /// Represents database driver that can be shared between threads, and can therefore implement 50 | /// a connection pool 51 | pub trait Driver: Sync + Send { 52 | /// Create a connection to the database. Note that connections are intended to be used 53 | /// in a single thread since most database connections are not thread-safe 54 | fn connect(&self, url: &str) -> Result>; 55 | } 56 | 57 | /// Represents a connection to a database 58 | pub trait Connection { 59 | /// Create a statement for execution 60 | fn create(&mut self, sql: &str) -> Result>; 61 | 62 | /// Create a prepared statement for execution 63 | fn prepare(&mut self, sql: &str) -> Result>; 64 | } 65 | 66 | /// Represents an executable statement 67 | pub trait Statement { 68 | /// Execute a query that is expected to return a result set, such as a `SELECT` statement 69 | fn execute_query(&mut self, params: &[Value]) -> Result>; 70 | 71 | /// Execute a query that is expected to update some rows. 72 | fn execute_update(&mut self, params: &[Value]) -> Result; 73 | } 74 | 75 | /// Result set from executing a query against a statement 76 | pub trait ResultSet { 77 | /// get meta data about this result set 78 | fn meta_data(&self) -> Result>; 79 | 80 | /// Move the cursor to the next available row if one exists and return true if it does 81 | fn next(&mut self) -> bool; 82 | 83 | fn get_i8(&self, i: u64) -> Result>; 84 | fn get_i16(&self, i: u64) -> Result>; 85 | fn get_i32(&self, i: u64) -> Result>; 86 | fn get_i64(&self, i: u64) -> Result>; 87 | fn get_f32(&self, i: u64) -> Result>; 88 | fn get_f64(&self, i: u64) -> Result>; 89 | fn get_string(&self, i: u64) -> Result>; 90 | fn get_bytes(&self, i: u64) -> Result>>; 91 | } 92 | 93 | /// Meta data for result set 94 | pub trait ResultSetMetaData { 95 | fn num_columns(&self) -> u64; 96 | fn column_name(&self, i: u64) -> String; 97 | fn column_type(&self, i: u64) -> DataType; 98 | } 99 | 100 | /// RDBC Data Types 101 | #[derive(Debug, Copy, Clone, PartialEq, Eq)] 102 | pub enum DataType { 103 | Bool, 104 | Byte, 105 | Char, 106 | Short, 107 | Integer, 108 | Float, 109 | Double, 110 | Decimal, 111 | Date, 112 | Time, 113 | Datetime, 114 | Utf8, 115 | Binary, 116 | } 117 | 118 | #[derive(Debug, Clone)] 119 | pub struct Column { 120 | name: String, 121 | data_type: DataType, 122 | } 123 | 124 | impl Column { 125 | pub fn new(name: &str, data_type: DataType) -> Self { 126 | Column { 127 | name: name.to_owned(), 128 | data_type, 129 | } 130 | } 131 | } 132 | 133 | impl ResultSetMetaData for Vec { 134 | fn num_columns(&self) -> u64 { 135 | self.len() as u64 136 | } 137 | 138 | fn column_name(&self, i: u64) -> String { 139 | self[i as usize].name.clone() 140 | } 141 | 142 | fn column_type(&self, i: u64) -> DataType { 143 | self[i as usize].data_type 144 | } 145 | } 146 | -------------------------------------------------------------------------------- /rust-toolchain: -------------------------------------------------------------------------------- 1 | 1.40.0 --------------------------------------------------------------------------------