diesel 2.4.0

A safe, extensible ORM and Query Builder for PostgreSQL, SQLite, and MySQL
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
use diesel::prelude::*;
use diesel::sql_types::*;
use dotenvy::dotenv;

cfg_if::cfg_if! {
    if #[cfg(feature = "postgres")] {
        #[allow(dead_code)]
        type DB = diesel::pg::Pg;
        type DbConnection = PgConnection;

        fn database_url_for_env() -> String {
            database_url_from_env("PG_DATABASE_URL")
        }

        fn connection_no_transaction() -> PgConnection {
            let connection_url = database_url_for_env();
            PgConnection::establish(&connection_url).unwrap()
        }

        fn setup_database(connection: &mut PgConnection) {
            connection.begin_test_transaction().unwrap();
            clean_tables(connection);
            create_tables_with_data(connection);
        }

        fn clean_tables(connection: &mut PgConnection) {
            diesel::sql_query("DROP TABLE IF EXISTS users CASCADE").execute(connection).unwrap();
            diesel::sql_query("DROP TABLE IF EXISTS animals CASCADE").execute(connection).unwrap();
            diesel::sql_query("DROP TABLE IF EXISTS posts CASCADE").execute(connection).unwrap();
            diesel::sql_query("DROP TABLE IF EXISTS comments CASCADE").execute(connection).unwrap();
            diesel::sql_query("DROP TABLE IF EXISTS brands CASCADE").execute(connection).unwrap();
        }

        fn connection_no_data() -> PgConnection {
            let mut connection = connection_no_transaction();
            connection.begin_test_transaction().unwrap();
            clean_tables(&mut connection);
            connection
        }

        fn create_tables_with_data(connection: &mut PgConnection) {
            diesel::sql_query("CREATE TABLE users (
                id SERIAL PRIMARY KEY,
                name VARCHAR NOT NULL
            )")
                .execute(connection)
                .unwrap();
            diesel::sql_query("INSERT INTO users (name) VALUES ('Sean'), ('Tess')")
                .execute(connection)
                .unwrap();

            diesel::sql_query("CREATE TABLE animals (
                id SERIAL PRIMARY KEY,
                species VARCHAR NOT NULL,
                legs INTEGER NOT NULL,
                name VARCHAR
            )")
                .execute(connection)
                .unwrap();
            diesel::sql_query("INSERT INTO animals (species, legs, name) VALUES
                               ('dog', 4, 'Jack'),
                               ('spider', 8, null)"
            ).execute(connection).unwrap();

            diesel::sql_query("CREATE TABLE posts (
                id SERIAL PRIMARY KEY,
                user_id INTEGER NOT NULL,
                title VARCHAR NOT NULL
            )").execute(connection).unwrap();
            diesel::sql_query("INSERT INTO posts (user_id, title) VALUES
                (1, 'My first post'),
                (1, 'About Rust'),
                (2, 'My first post too')").execute(connection).unwrap();

            diesel::sql_query("CREATE TABLE comments (
                id SERIAL PRIMARY KEY,
                post_id INTEGER NOT NULL,
                body VARCHAR NOT NULL
            )").execute(connection).unwrap();
            diesel::sql_query("INSERT INTO comments (post_id, body) VALUES
                (1, 'Great post'),
                (2, 'Yay! I am learning Rust'),
                (3, 'I enjoyed your post')").execute(connection).unwrap();

            diesel::sql_query("CREATE TABLE brands (
                id SERIAL PRIMARY KEY,
                color VARCHAR NOT NULL DEFAULT 'Green',
                accent VARCHAR DEFAULT 'Blue'
            )").execute(connection).unwrap();
        }

        #[allow(dead_code)]
        fn establish_connection() -> PgConnection {
            let mut connection = connection_no_data();
            create_tables_with_data(&mut connection);
            connection
        }
    } else if #[cfg(feature = "sqlite")] {
        #[allow(dead_code)]
        type DB = diesel::sqlite::Sqlite;
        type DbConnection = SqliteConnection;

        fn database_url_for_env() -> String {
            String::from(":memory:")
        }

        fn connection_no_data() -> SqliteConnection {
            SqliteConnection::establish(":memory:").unwrap()
        }

        fn setup_database(connection: &mut SqliteConnection) {
            create_tables_with_data(connection);
        }

        fn create_tables_with_data(connection: &mut SqliteConnection) {
            diesel::sql_query("CREATE TABLE users (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                name VARCHAR NOT NULL
            )").execute(connection).unwrap();
            diesel::sql_query("INSERT INTO users (name) VALUES ('Sean'), ('Tess')")
                .execute(connection).unwrap();

            diesel::sql_query("CREATE TABLE animals (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                species VARCHAR NOT NULL,
                legs INTEGER NOT NULL,
                name VARCHAR
            )").execute(connection).unwrap();
            diesel::sql_query("INSERT INTO animals (species, legs, name) VALUES
                               ('dog', 4, 'Jack'),
                               ('spider', 8, null)"
            ).execute(connection).unwrap();

            diesel::sql_query("CREATE TABLE posts (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                user_id INTEGER NOT NULL,
                title VARCHAR NOT NULL
            )").execute(connection).unwrap();
            diesel::sql_query("INSERT INTO posts (user_id, title) VALUES
                (1, 'My first post'),
                (1, 'About Rust'),
                (2, 'My first post too')").execute(connection).unwrap();

            diesel::sql_query("CREATE TABLE comments (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                post_id INTEGER NOT NULL,
                body VARCHAR NOT NULL
            )").execute(connection).unwrap();
            diesel::sql_query("INSERT INTO comments (post_id, body) VALUES
                (1, 'Great post'),
                (2, 'Yay! I am learning Rust'),
                (3, 'I enjoyed your post')").execute(connection).unwrap();
        }

        #[allow(dead_code)]
        fn establish_connection() -> SqliteConnection {
            let mut connection = connection_no_data();
            create_tables_with_data(&mut connection);
            connection
        }

        macro_rules! assert_version {
            ($conn: ident, $major: literal, $minor: literal, $patch: literal) => {
                if $conn.version() < diesel::connection::DatabaseVersion::new($major, $minor, $patch) {
                    println!("SQLite version is too old, skipping the test.");
                    return Ok(());
                }
            }
        }

    } else if #[cfg(feature = "mariadb")] {
        #[allow(dead_code)]
        type DB = diesel::mariadb::Mariadb;
        type DbConnection = MariadbConnection;

        fn database_url_for_env() -> String {
            database_url_from_env("MARIADB_UNIT_TEST_DATABASE_URL")
        }

        fn setup_database(connection: &mut MariadbConnection) {
            clean_tables(connection);
            create_tables_with_data(connection);
        }

        fn clean_tables(_connection: &mut MariadbConnection) {}

        fn connection_no_data() -> MariadbConnection {
            let connection_url = database_url_for_env();
            let mut connection = MariadbConnection::establish(&connection_url).unwrap();
            clean_tables(&mut connection);
            connection
        }

        fn create_tables_with_data(connection: &mut MariadbConnection) {
            diesel::sql_query("CREATE TEMPORARY TABLE users (
                id INTEGER PRIMARY KEY AUTO_INCREMENT,
                name TEXT NOT NULL
            ) CHARACTER SET utf8mb4").execute(connection).unwrap();
            diesel::sql_query("INSERT INTO users (name) VALUES ('Sean'), ('Tess')")
                      .execute(connection).unwrap();

            diesel::sql_query("CREATE TEMPORARY TABLE animals (
                id INTEGER PRIMARY KEY AUTO_INCREMENT,
                species TEXT NOT NULL,
                legs INTEGER NOT NULL,
                name TEXT
            ) CHARACTER SET utf8mb4").execute(connection).unwrap();
            diesel::sql_query("INSERT INTO animals (species, legs, name) VALUES
                               ('dog', 4, 'Jack'),
                               ('spider', 8, null)").execute(connection).unwrap();

            diesel::sql_query("CREATE TEMPORARY TABLE posts (
                id INTEGER PRIMARY KEY AUTO_INCREMENT,
                user_id INTEGER NOT NULL,
                title TEXT NOT NULL
            ) CHARACTER SET utf8mb4").execute(connection).unwrap();
            diesel::sql_query("INSERT INTO posts (user_id, title) VALUES
                (1, 'My first post'),
                (1, 'About Rust'),
                (2, 'My first post too')").execute(connection).unwrap();

            diesel::sql_query("CREATE TEMPORARY TABLE comments (
                id INTEGER PRIMARY KEY AUTO_INCREMENT,
                post_id INTEGER NOT NULL,
                body TEXT NOT NULL
            ) CHARACTER SET utf8mb4").execute(connection).unwrap();
            diesel::sql_query("INSERT INTO comments (post_id, body) VALUES
                (1, 'Great post'),
                (2, 'Yay! I am learning Rust'),
                (3, 'I enjoyed your post')").execute(connection).unwrap();

            diesel::sql_query("CREATE TEMPORARY TABLE brands (
                id INTEGER PRIMARY KEY AUTO_INCREMENT,
                color VARCHAR(255) NOT NULL DEFAULT 'Green',
                accent VARCHAR(255) DEFAULT 'Blue'
            )").execute(connection).unwrap();
        }

        #[allow(dead_code)]
        fn establish_connection() -> MariadbConnection {
            let mut connection = connection_no_data();
            create_tables_with_data(&mut connection);
            connection.begin_test_transaction().unwrap();
            connection
        }

        #[allow(dead_code)]
        fn mariadb_server_supports_update_returning(connection: &mut MariadbConnection) -> bool {
            connection.version().expect("Failed to get Mariadb server version")
                >= diesel::connection::DatabaseVersion::new(13, 0, 0)
        }
    } else if #[cfg(feature = "mysql")] {
        #[allow(dead_code)]
        type DB = diesel::mysql::Mysql;
        type DbConnection = MysqlConnection;

        fn database_url_for_env() -> String {
            database_url_from_env("MYSQL_UNIT_TEST_DATABASE_URL")
        }

        fn setup_database(connection: &mut MysqlConnection) {
            clean_tables(connection);
            create_tables_with_data(connection);
        }

        fn clean_tables(_connection: &mut MysqlConnection) {}

        fn connection_no_data() -> MysqlConnection {
            let connection_url = database_url_for_env();
            let mut connection = MysqlConnection::establish(&connection_url).unwrap();
            clean_tables(&mut connection);
            connection
        }

        fn create_tables_with_data(connection: &mut MysqlConnection) {
            diesel::sql_query("CREATE TEMPORARY TABLE users (
                id INTEGER PRIMARY KEY AUTO_INCREMENT,
                name TEXT NOT NULL
            ) CHARACTER SET utf8mb4").execute(connection).unwrap();
            diesel::sql_query("INSERT INTO users (name) VALUES ('Sean'), ('Tess')")
                      .execute(connection).unwrap();

            diesel::sql_query("CREATE TEMPORARY TABLE animals (
                id INTEGER PRIMARY KEY AUTO_INCREMENT,
                species TEXT NOT NULL,
                legs INTEGER NOT NULL,
                name TEXT
            ) CHARACTER SET utf8mb4").execute(connection).unwrap();
            diesel::sql_query("INSERT INTO animals (species, legs, name) VALUES
                               ('dog', 4, 'Jack'),
                               ('spider', 8, null)").execute(connection).unwrap();

            diesel::sql_query("CREATE TEMPORARY TABLE posts (
                id INTEGER PRIMARY KEY AUTO_INCREMENT,
                user_id INTEGER NOT NULL,
                title TEXT NOT NULL
            ) CHARACTER SET utf8mb4").execute(connection).unwrap();
            diesel::sql_query("INSERT INTO posts (user_id, title) VALUES
                (1, 'My first post'),
                (1, 'About Rust'),
                (2, 'My first post too')").execute(connection).unwrap();

            diesel::sql_query("CREATE TEMPORARY TABLE comments (
                id INTEGER PRIMARY KEY AUTO_INCREMENT,
                post_id INTEGER NOT NULL,
                body TEXT NOT NULL
            ) CHARACTER SET utf8mb4").execute(connection).unwrap();
            diesel::sql_query("INSERT INTO comments (post_id, body) VALUES
                (1, 'Great post'),
                (2, 'Yay! I am learning Rust'),
                (3, 'I enjoyed your post')").execute(connection).unwrap();

            diesel::sql_query("CREATE TEMPORARY TABLE brands (
                id INTEGER PRIMARY KEY AUTO_INCREMENT,
                color VARCHAR(255) NOT NULL DEFAULT 'Green',
                accent VARCHAR(255) DEFAULT 'Blue'
            )").execute(connection).unwrap();
        }

        #[allow(dead_code)]
        fn establish_connection() -> MysqlConnection {
            let mut connection = connection_no_data();
            create_tables_with_data(&mut connection);
            connection.begin_test_transaction().unwrap();
            connection
        }
    } else {
        compile_error!(
            "At least one backend must be used to test this crate.\n \
            Pass argument `--features \"<backend>\"` with one or more of the following backends, \
            'mysql', 'mariadb', 'postgres', or 'sqlite'. \n\n \
            ex. cargo test --features \"mysql mariadb postgres sqlite\"\n"
        );
    }
}

fn database_url_from_env(backend_specific_env_var: &str) -> String {
    use std::env;

    dotenv().ok();

    env::var(backend_specific_env_var)
        .or_else(|_| env::var("DATABASE_URL"))
        .expect("DATABASE_URL must be set in order to run tests")
}

#[allow(unexpected_cfgs)]
mod schema {
    use diesel::prelude::*;

    pub mod sql_types {
        #[derive(diesel::query_builder::QueryId, Clone, diesel::sql_types::SqlType)]
        #[cfg_attr(feature = "postgres", diesel(postgres_type(name = "color")))]
        #[cfg_attr(feature = "mysql", diesel(mysql_type(name = "Enum")))]
        #[cfg_attr(feature = "mariadb", diesel(mariadb_type(name = "Enum")))]
        #[diesel(enum_type)]
        pub struct Color;
    }

    table! {
        animals {
            id -> Integer,
            species -> VarChar,
            legs -> Integer,
            name -> Nullable<VarChar>,
        }
    }

    table! {
        comments {
            id -> Integer,
            post_id -> Integer,
            body -> VarChar,
        }
    }

    table! {
        posts {
            id -> Integer,
            user_id -> Integer,
            title -> VarChar,
        }
    }

    table! {
        users {
            #[auto_increment]
            id -> Integer,
            name -> VarChar,
        }
    }

    #[cfg(not(any(feature = "__sqlite-shared", feature = "sqlite")))]
    table! {
        brands {
            id -> Integer,
            color -> VarChar,
            accent -> Nullable<VarChar>,
        }
    }

    joinable!(posts -> users (user_id));
    allow_tables_to_appear_in_same_query!(animals, comments, posts, users);
}