|
| 1 | +# OpenSrv - MySQL |
| 2 | + |
| 3 | +Bindings for emulating a MySQL/MariaDB server. |
| 4 | + |
| 5 | +When developing new databases or caching layers, it can be immensely useful to test your system |
| 6 | +using existing applications. However, this often requires significant work modifying |
| 7 | +applications to use your database over the existing ones. This crate solves that problem by |
| 8 | +acting as a MySQL server, and delegating operations such as querying and query execution to |
| 9 | +user-defined logic. |
| 10 | + |
| 11 | +To start, implement `MysqlShim/AsyncMysqlShim` for your backend, and create a `MysqlIntermediary/AsyncMysqlIntermediary` over an |
| 12 | +instance of your backend and a connection stream. The appropriate methods will be called on |
| 13 | +your backend whenever a client issues a `QUERY`, `PREPARE`, or `EXECUTE` command, and you will |
| 14 | +have a chance to respond appropriately. For example, to write a shim that always responds to |
| 15 | +all commands with a "no results" reply: |
| 16 | + |
| 17 | +```rust |
| 18 | +use std::io; |
| 19 | +use std::net; |
| 20 | +use std::thread; |
| 21 | + |
| 22 | +use opensrv_mysql::*; |
| 23 | + |
| 24 | +struct Backend; |
| 25 | + |
| 26 | +impl<W: io::Write> MysqlShim<W> for Backend { |
| 27 | + type Error = io::Error; |
| 28 | + |
| 29 | + fn on_prepare(&mut self, _: &str, info: StatementMetaWriter<W>) -> io::Result<()> { |
| 30 | + info.reply(42, &[], &[]) |
| 31 | + } |
| 32 | + fn on_execute( |
| 33 | + &mut self, |
| 34 | + _: u32, |
| 35 | + _: opensrv_mysql::ParamParser, |
| 36 | + results: QueryResultWriter<W>, |
| 37 | + ) -> io::Result<()> { |
| 38 | + results.completed(OkResponse::default()) |
| 39 | + } |
| 40 | + fn on_close(&mut self, _: u32) {} |
| 41 | + |
| 42 | + fn on_query(&mut self, sql: &str, results: QueryResultWriter<W>) -> io::Result<()> { |
| 43 | + println!("execute sql {:?}", sql); |
| 44 | + results.start(&[])?.finish() |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +fn main() { |
| 49 | + let mut threads = Vec::new(); |
| 50 | + let listener = net::TcpListener::bind("127.0.0.1:3306").unwrap(); |
| 51 | + |
| 52 | + while let Ok((s, _)) = listener.accept() { |
| 53 | + threads.push(thread::spawn(move || { |
| 54 | + MysqlIntermediary::run_on_tcp(Backend, s).unwrap(); |
| 55 | + })); |
| 56 | + } |
| 57 | + |
| 58 | + for t in threads { |
| 59 | + t.join().unwrap(); |
| 60 | + } |
| 61 | +} |
| 62 | +``` |
0 commit comments