Debian Codegraph @

src/doctest_setup.rs

raw
1 use diesel::prelude::*;
2 use dotenvy::dotenv;
3
4 cfg_if::cfg_if! {
5 if #[cfg(feature = "postgres")] {
6 #[allow(dead_code)]
7 type DB = diesel::pg::Pg;
8 type DbConnection = PgConnection;
9
10 fn database_url_for_env() -> String {
11 database_url_from_env("PG_DATABASE_URL")
12 }
13
14 fn connection_no_transaction() -> PgConnection {
15 let connection_url = database_url_for_env();
16 PgConnection::establish(&connection_url).unwrap()
17 }
18
19 fn setup_database(connection: &mut PgConnection) {
20 connection.begin_test_transaction().unwrap();
21 clean_tables(connection);
22 create_tables_with_data(connection);
23 }
24
25 fn clean_tables(connection: &mut PgConnection) {
26 diesel::sql_query("DROP TABLE IF EXISTS users CASCADE").execute(connection).unwrap();
27 diesel::sql_query("DROP TABLE IF EXISTS animals CASCADE").execute(connection).unwrap();
28 diesel::sql_query("DROP TABLE IF EXISTS posts CASCADE").execute(connection).unwrap();
29 diesel::sql_query("DROP TABLE IF EXISTS comments CASCADE").execute(connection).unwrap();
30 diesel::sql_query("DROP TABLE IF EXISTS brands CASCADE").execute(connection).unwrap();
31 }
32
33 fn connection_no_data() -> PgConnection {
34 let mut connection = connection_no_transaction();
35 connection.begin_test_transaction().unwrap();
36 clean_tables(&mut connection);
37 connection
38 }
39
40 fn create_tables_with_data(connection: &mut PgConnection) {
41 diesel::sql_query("CREATE TABLE users (
42 id SERIAL PRIMARY KEY,
43 name VARCHAR NOT NULL
44 )")
45 .execute(connection)
46 .unwrap();
47 diesel::sql_query("INSERT INTO users (name) VALUES ('Sean'), ('Tess')")
48 .execute(connection)
49 .unwrap();
50
51 diesel::sql_query("CREATE TABLE animals (
52 id SERIAL PRIMARY KEY,
53 species VARCHAR NOT NULL,
54 legs INTEGER NOT NULL,
55 name VARCHAR
56 )")
57 .execute(connection)
58 .unwrap();
59 diesel::sql_query("INSERT INTO animals (species, legs, name) VALUES
60 ('dog', 4, 'Jack'),
61 ('spider', 8, null)"
62 ).execute(connection).unwrap();
63
64 diesel::sql_query("CREATE TABLE posts (
65 id SERIAL PRIMARY KEY,
66 user_id INTEGER NOT NULL,
67 title VARCHAR NOT NULL
68 )").execute(connection).unwrap();
69 diesel::sql_query("INSERT INTO posts (user_id, title) VALUES
70 (1, 'My first post'),
71 (1, 'About Rust'),
72 (2, 'My first post too')").execute(connection).unwrap();
73
74 diesel::sql_query("CREATE TABLE comments (
75 id SERIAL PRIMARY KEY,
76 post_id INTEGER NOT NULL,
77 body VARCHAR NOT NULL
78 )").execute(connection).unwrap();
79 diesel::sql_query("INSERT INTO comments (post_id, body) VALUES
80 (1, 'Great post'),
81 (2, 'Yay! I am learning Rust'),
82 (3, 'I enjoyed your post')").execute(connection).unwrap();
83
84 diesel::sql_query("CREATE TABLE brands (
85 id SERIAL PRIMARY KEY,
86 color VARCHAR NOT NULL DEFAULT 'Green',
87 accent VARCHAR DEFAULT 'Blue'
88 )").execute(connection).unwrap();
89 }
90
91 #[allow(dead_code)]
92 fn establish_connection() -> PgConnection {
93 let mut connection = connection_no_data();
94 create_tables_with_data(&mut connection);
95 connection
96 }
97 } else if #[cfg(feature = "sqlite")] {
98 #[allow(dead_code)]
99 type DB = diesel::sqlite::Sqlite;
100 type DbConnection = SqliteConnection;
101
102 fn database_url_for_env() -> String {
103 String::from(":memory:")
104 }
105
106 fn connection_no_data() -> SqliteConnection {
107 SqliteConnection::establish(":memory:").unwrap()
108 }
109
110 fn setup_database(connection: &mut SqliteConnection) {
111 create_tables_with_data(connection);
112 }
113
114 fn create_tables_with_data(connection: &mut SqliteConnection) {
115 diesel::sql_query("CREATE TABLE users (
116 id INTEGER PRIMARY KEY AUTOINCREMENT,
117 name VARCHAR NOT NULL
118 )").execute(connection).unwrap();
119 diesel::sql_query("INSERT INTO users (name) VALUES ('Sean'), ('Tess')")
120 .execute(connection).unwrap();
121
122 diesel::sql_query("CREATE TABLE animals (
123 id INTEGER PRIMARY KEY AUTOINCREMENT,
124 species VARCHAR NOT NULL,
125 legs INTEGER NOT NULL,
126 name VARCHAR
127 )").execute(connection).unwrap();
128 diesel::sql_query("INSERT INTO animals (species, legs, name) VALUES
129 ('dog', 4, 'Jack'),
130 ('spider', 8, null)"
131 ).execute(connection).unwrap();
132
133 diesel::sql_query("CREATE TABLE posts (
134 id INTEGER PRIMARY KEY AUTOINCREMENT,
135 user_id INTEGER NOT NULL,
136 title VARCHAR NOT NULL
137 )").execute(connection).unwrap();
138 diesel::sql_query("INSERT INTO posts (user_id, title) VALUES
139 (1, 'My first post'),
140 (1, 'About Rust'),
141 (2, 'My first post too')").execute(connection).unwrap();
142
143 diesel::sql_query("CREATE TABLE comments (
144 id INTEGER PRIMARY KEY AUTOINCREMENT,
145 post_id INTEGER NOT NULL,
146 body VARCHAR NOT NULL
147 )").execute(connection).unwrap();
148 diesel::sql_query("INSERT INTO comments (post_id, body) VALUES
149 (1, 'Great post'),
150 (2, 'Yay! I am learning Rust'),
151 (3, 'I enjoyed your post')").execute(connection).unwrap();
152 }
153
154 #[allow(dead_code)]
155 fn establish_connection() -> SqliteConnection {
156 let mut connection = connection_no_data();
157 create_tables_with_data(&mut connection);
158 connection
159 }
160
161 #[allow(dead_code)]
162 fn sqlite_version(conn: &mut SqliteConnection) -> (u32, u32, u32) {
163 let version = diesel::select(diesel::dsl::sql::<diesel::sql_types::Text>("sqlite_version();"))
164 .get_result::<String>(conn)
165 .unwrap();
166
167 let mut version_components = version.split('.');
168 let major: u32 = version_components.next().unwrap().parse().unwrap();
169 let minor: u32 = version_components.next().unwrap().parse().unwrap();
170 let patch: u32 = version_components.next().unwrap().parse().unwrap();
171 (major, minor, patch)
172 }
173
174 macro_rules! assert_version {
175 ($conn: ident, $major: literal, $minor: literal, $patch: literal) => {
176 let version = sqlite_version($conn);
177 if version.0 < $major ||
178 (version.0 == $major && version.1 < $minor) ||
179 (version.0 == $major && version.1 == $minor && version.2 < $patch)
180 {
181 println!("SQLite version is too old, skipping the test.");
182 return Ok(());
183 }
184 }
185 }
186
187 } else if #[cfg(feature = "mysql")] {
188 #[allow(dead_code)]
189 type DB = diesel::mysql::Mysql;
190 type DbConnection = MysqlConnection;
191
192 fn database_url_for_env() -> String {
193 database_url_from_env("MYSQL_UNIT_TEST_DATABASE_URL")
194 }
195
196 fn setup_database(connection: &mut MysqlConnection) {
197 clean_tables(connection);
198 create_tables_with_data(connection);
199 }
200
201 fn clean_tables(_connection: &mut MysqlConnection) {}
202
203 fn connection_no_data() -> MysqlConnection {
204 let connection_url = database_url_for_env();
205 let mut connection = MysqlConnection::establish(&connection_url).unwrap();
206 clean_tables(&mut connection);
207 connection
208 }
209
210 fn create_tables_with_data(connection: &mut MysqlConnection) {
211 diesel::sql_query("CREATE TEMPORARY TABLE users (
212 id INTEGER PRIMARY KEY AUTO_INCREMENT,
213 name TEXT NOT NULL
214 ) CHARACTER SET utf8mb4").execute(connection).unwrap();
215 diesel::sql_query("INSERT INTO users (name) VALUES ('Sean'), ('Tess')")
216 .execute(connection).unwrap();
217
218 diesel::sql_query("CREATE TEMPORARY TABLE animals (
219 id INTEGER PRIMARY KEY AUTO_INCREMENT,
220 species TEXT NOT NULL,
221 legs INTEGER NOT NULL,
222 name TEXT
223 ) CHARACTER SET utf8mb4").execute(connection).unwrap();
224 diesel::sql_query("INSERT INTO animals (species, legs, name) VALUES
225 ('dog', 4, 'Jack'),
226 ('spider', 8, null)").execute(connection).unwrap();
227
228 diesel::sql_query("CREATE TEMPORARY TABLE posts (
229 id INTEGER PRIMARY KEY AUTO_INCREMENT,
230 user_id INTEGER NOT NULL,
231 title TEXT NOT NULL
232 ) CHARACTER SET utf8mb4").execute(connection).unwrap();
233 diesel::sql_query("INSERT INTO posts (user_id, title) VALUES
234 (1, 'My first post'),
235 (1, 'About Rust'),
236 (2, 'My first post too')").execute(connection).unwrap();
237
238 diesel::sql_query("CREATE TEMPORARY TABLE comments (
239 id INTEGER PRIMARY KEY AUTO_INCREMENT,
240 post_id INTEGER NOT NULL,
241 body TEXT NOT NULL
242 ) CHARACTER SET utf8mb4").execute(connection).unwrap();
243 diesel::sql_query("INSERT INTO comments (post_id, body) VALUES
244 (1, 'Great post'),
245 (2, 'Yay! I am learning Rust'),
246 (3, 'I enjoyed your post')").execute(connection).unwrap();
247
248 diesel::sql_query("CREATE TEMPORARY TABLE brands (
249 id INTEGER PRIMARY KEY AUTO_INCREMENT,
250 color VARCHAR(255) NOT NULL DEFAULT 'Green',
251 accent VARCHAR(255) DEFAULT 'Blue'
252 )").execute(connection).unwrap();
253 }
254
255 #[allow(dead_code)]
256 fn establish_connection() -> MysqlConnection {
257 let mut connection = connection_no_data();
258 create_tables_with_data(&mut connection);
259 connection.begin_test_transaction().unwrap();
260 connection
261 }
262 } else {
263 compile_error!(
264 "At least one backend must be used to test this crate.\n \
265 Pass argument `--features \"<backend>\"` with one or more of the following backends, \
266 'mysql', 'postgres', or 'sqlite'. \n\n \
267 ex. cargo test --features \"mysql postgres sqlite\"\n"
268 );
269 }
270 }
271
272 fn database_url_from_env(backend_specific_env_var: &str) -> String {
273 use std::env;
274
275 dotenv().ok();
276
277 env::var(backend_specific_env_var)
278 .or_else(|_| env::var("DATABASE_URL"))
279 .expect("DATABASE_URL must be set in order to run tests")
280 }
281
282 mod schema {
283 use diesel::prelude::*;
284
285 table! {
286 animals {
287 id -> Integer,
288 species -> VarChar,
289 legs -> Integer,
290 name -> Nullable<VarChar>,
291 }
292 }
293
294 table! {
295 comments {
296 id -> Integer,
297 post_id -> Integer,
298 body -> VarChar,
299 }
300 }
301
302 table! {
303 posts {
304 id -> Integer,
305 user_id -> Integer,
306 title -> VarChar,
307 }
308 }
309
310 table! {
311 users {
312 id -> Integer,
313 name -> VarChar,
314 }
315 }
316
317 #[cfg(not(feature = "sqlite"))]
318 table! {
319 brands {
320 id -> Integer,
321 color -> VarChar,
322 accent -> Nullable<VarChar>,
323 }
324 }
325
326 joinable!(posts -> users (user_id));
327 allow_tables_to_appear_in_same_query!(animals, comments, posts, users);
328 }