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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
#[macro_use]
extern crate diesel;
#[macro_use]
extern crate diesel_migrations;

#[macro_use]
extern crate prettytable;

pub mod config;
pub mod models;
pub mod prompt;
pub mod schema;
pub mod schematic;
pub mod tables;

use diesel::prelude::*;

use models::*;

use std::io::{StdinLock, Stdout};

pub struct Application<'a> {
    /// Config
    pub config: config::Config,

    /// Path to config
    pub config_path: std::path::PathBuf,

    /// Global prompt
    pub prompt: prompt::Prompt<StdinLock<'a>, Stdout>,

    /// Global conn
    pub conn: SqliteConnection,
}

// Migrate
embed_migrations!();

pub fn establish_connection(db_name: &str) -> SqliteConnection {
    // Get text version of configpath
    let mut database_url =
        config::get_default_config_path().unwrap_or_else(|_| panic!("Unable to get config path."));

    // Add database name
    database_url.push(db_name);

    // Establish the "connection" (We're using SQLite here so no connection excpet to the filesystem)
    let conn = SqliteConnection::establish(&database_url.to_string_lossy())
        .unwrap_or_else(|_| panic!("Error connecting to {}", &database_url.to_string_lossy()));

    // This will run migrations and also create a DB if it doesn't exist.
    embedded_migrations::run(&conn).expect("Unable to run migration.");

    conn
}

// Part related
pub fn create_part(
    conn: &SqliteConnection,
    part: &NewUpdatePart,
) -> std::result::Result<usize, diesel::result::Error> {
    use schema::parts;

    diesel::insert_into(parts::table).values(part).execute(conn)
}

pub fn update_part(
    conn: &SqliteConnection,
    id: &i32,
    part: &NewUpdatePart,
) -> std::result::Result<usize, diesel::result::Error> {
    use schema::parts;

    diesel::update(parts::dsl::parts.filter(parts::dsl::id.eq(id)))
        .set(part)
        .execute(conn)
}

pub fn rename_part(
    conn: &SqliteConnection,
    oldpn: &str,
    newpn: &str,
) -> std::result::Result<usize, diesel::result::Error> {
    use schema::parts::dsl::*;

    let part = find_part_by_pn(&conn, &oldpn).expect("Old part not found");

    diesel::update(parts.find(part.id))
        .set(pn.eq(newpn))
        .execute(conn)
}

pub fn delete_part(
    conn: &SqliteConnection,
    id: &i32,
) -> std::result::Result<usize, diesel::result::Error> {
    use schema::parts;

    diesel::delete(parts::dsl::parts.filter(parts::dsl::id.eq(id))).execute(conn)
}

pub fn find_part_by_pn(
    conn: &SqliteConnection,
    pn: &str,
) -> std::result::Result<Part, diesel::result::Error> {
    use schema::parts;

    parts::dsl::parts.filter(parts::dsl::pn.eq(pn)).first(conn)
}

pub fn find_part_by_mpn(
    conn: &SqliteConnection,
    mpn: &str,
) -> std::result::Result<Part, diesel::result::Error> {
    use schema::parts;

    println!("mpn: \"{}\"", mpn);

    parts::dsl::parts
        .filter(parts::dsl::mpn.eq(mpn))
        .first(conn)
}

pub fn find_part_by_pn_and_ver(
    conn: &SqliteConnection,
    pn: &str,
    ver: &i32,
) -> std::result::Result<Part, diesel::result::Error> {
    use schema::parts;

    parts::dsl::parts
        .filter(parts::dsl::pn.eq(pn))
        .filter(parts::dsl::ver.eq(ver))
        .first(conn)
}

pub fn find_part_by_id(
    conn: &SqliteConnection,
    id: &i32,
) -> std::result::Result<Part, diesel::result::Error> {
    use schema::parts;

    parts::dsl::parts.filter(parts::dsl::id.eq(id)).first(conn)
}

pub fn create_bom_line_item(
    conn: &SqliteConnection,
    part: &NewPartsParts,
) -> std::result::Result<usize, diesel::result::Error> {
    use schema::parts_parts;

    diesel::insert_into(parts_parts::table)
        .values(part)
        .execute(conn)
}

pub fn delete_bom_list_by_id_and_ver(
    conn: &SqliteConnection,
    bom_id: &i32,
    ver: &i32,
) -> std::result::Result<usize, diesel::result::Error> {
    use schema::parts_parts::dsl::*;

    // First get list of ids that match the bom_part_id
    let query = parts_parts
        .select(id)
        .filter(bom_part_id.eq(bom_id))
        .load::<i32>(conn)?;

    // Then make sure that the bom ver is equal. Match against the ids found in the first step
    let target = parts_parts.filter(bom_ver.eq(ver)).filter(id.eq_any(query));

    // Delete appropriately
    diesel::delete(target).execute(conn)
}

// Build related

pub fn create_build(
    conn: &SqliteConnection,
    build: &NewUpdateBuild,
) -> std::result::Result<usize, diesel::result::Error> {
    use schema::builds;

    diesel::insert_into(builds::table)
        .values(build)
        .execute(conn)
}

pub fn update_build_by_id(
    conn: &SqliteConnection,
    id: &i32,
    entry: &NewUpdateBuild,
) -> std::result::Result<usize, diesel::result::Error> {
    use schema::builds;

    diesel::update(builds::dsl::builds.filter(builds::dsl::id.eq(id)))
        .set(entry)
        .execute(conn)
}

pub fn find_builds_by_pn(
    conn: &SqliteConnection,
    pn: &str,
) -> std::result::Result<Vec<Build>, diesel::result::Error> {
    use schema::builds;

    let part = find_part_by_pn(&conn, &pn).expect("Unable to run parts query.");

    builds::dsl::builds
        .filter(builds::dsl::part_id.eq(part.id))
        .load::<Build>(conn)
}

pub fn find_build_by_id(
    conn: &SqliteConnection,
    id: &i32,
) -> std::result::Result<Build, diesel::result::Error> {
    use schema::builds;

    builds::dsl::builds
        .filter(builds::dsl::id.eq(id))
        .first(conn)
}

pub fn delete_build(
    conn: &SqliteConnection,
    id: &i32,
) -> std::result::Result<usize, diesel::result::Error> {
    use schema::builds;

    diesel::delete(builds::dsl::builds.filter(builds::dsl::id.eq(id))).execute(conn)
}

// Inventory related

pub fn create_inventory(
    conn: &SqliteConnection,
    entry: &NewUpdateInventoryEntry,
) -> std::result::Result<usize, diesel::result::Error> {
    use schema::inventories;

    diesel::insert_into(inventories::table)
        .values(entry)
        .execute(conn)
}

pub fn update_inventory_by_id(
    conn: &SqliteConnection,
    id: &i32,
    entry: &NewUpdateInventoryEntry,
) -> std::result::Result<usize, diesel::result::Error> {
    use schema::inventories;

    diesel::update(inventories::dsl::inventories.filter(inventories::dsl::id.eq(id)))
        .set(entry)
        .execute(conn)
}

pub fn find_inventories_by_part_id(
    conn: &SqliteConnection,
    id: &i32,
) -> std::result::Result<Vec<Inventory>, diesel::result::Error> {
    use schema::inventories;

    inventories::dsl::inventories
        .filter(inventories::dsl::part_id.eq(id))
        .load::<Inventory>(conn)
}

pub fn test_connection() -> SqliteConnection {
    // Start a connection from memory
    let conn = SqliteConnection::establish(":memory:").expect("Unable to establish db in memory!");

    // This will run the necessary migrations.
    embedded_migrations::run(&conn).expect("Unable to run test migration.");

    // Return the active connection
    conn
}

/* START: Part Related Tests */
mod part_tests {

    #[test]
    fn create_part_check_if_created() {
        use super::*;
        use models::Part;
        use schema::parts::dsl::*;

        let conn = test_connection();

        // Create NewUpdatePart instance
        let part = NewUpdatePart {
            pn: "CAP-0.1U-10V-0402",
            mpn: "ABCD",
            descr: "CAP 0.1U 10V 0402",
            ver: &1,
            mqty: &1,
        };

        // Create the part
        create_part(&conn, &part).expect("Error creating part!");

        // Serach for it and make sure that it matches
        let found: Part = parts.find(1).first(&conn).unwrap();

        // Make sure these guys are equal
        assert_eq!(part.pn, found.pn);
        assert_eq!(part.mpn, found.mpn);
        assert_eq!(part.descr, found.descr);
        assert_eq!(*part.ver, found.ver);
    }

    #[test]
    #[should_panic]
    // This is testing the schema more than anything
    // Only one part with the same PN!
    fn create_duplicate_pn_should_panic() {
        use super::*;
        let conn = test_connection();

        // Create NewUpdatePart instance
        let part = NewUpdatePart {
            pn: "CAP-0.1U-10V-0402",
            mpn: "ABCD",
            descr: "CAP 0.1U 10V 0402",
            ver: &1,
            mqty: &1,
        };

        // Create the part
        create_part(&conn, &part).expect("Error creating part!");

        // Create NewUpdatePart instance
        let part = NewUpdatePart {
            pn: "CAP-0.1U-10V-0402",
            mpn: "ABCD-ND",
            descr: "CAP 0.1U 10V 0402",
            ver: &1,
            mqty: &1,
        };

        // Do it again
        create_part(&conn, &part).expect("Error creating part!");
    }

    #[test]
    #[should_panic]
    // This is testing the schema more than anything
    // Only one part with the same MPN!
    fn create_duplicate_mpn_should_panic() {
        use super::*;
        let conn = test_connection();

        // Create NewUpdatePart instance
        let part = NewUpdatePart {
            pn: "CAP-0.1U-10V-0402",
            mpn: "ABCD",
            descr: "CAP 0.1U 10V 0402",
            ver: &1,
            mqty: &1,
        };

        // Create the part
        create_part(&conn, &part).expect("Error creating part!");

        // Create NewUpdatePart instance
        let part = NewUpdatePart {
            pn: "CAP-0.1U-10V-0402-01",
            mpn: "ABCD",
            descr: "CAP 0.1U 10V 0402",
            ver: &1,
            mqty: &1,
        };

        // Do it again
        create_part(&conn, &part).expect("Error creating part!");
    }

    #[test]
    fn create_and_update_part() {
        use super::*;
        use models::Part;
        use schema::parts::dsl::*;

        let conn = test_connection();

        // Create NewUpdatePart instance
        let part = NewUpdatePart {
            pn: "CAP-0.1U-10V-0402",
            mpn: "ABCD",
            descr: "CAP 0.1U 10V 0402",
            ver: &1,
            mqty: &1,
        };

        // Create the part
        create_part(&conn, &part).expect("Error creating part!");

        // Get part back
        let found = find_part_by_pn(&conn, &part.pn).expect("Error getting part back.");

        // Update the value
        let part = NewUpdatePart {
            pn: "CAP-0.1U-10V-0402",
            mpn: "ABCD",
            descr: "CAP 0.1 10V 0402 GOOD", // Only changing this guy
            ver: &1,
            mqty: &1,
        };

        // Update the part
        update_part(&conn, &found.id, &part).expect("Error creating part!");

        // Serach for it and make sure that it matches
        let found: Part = parts.find(1).first(&conn).unwrap();

        // Make sure these guys are equal
        assert_eq!(part.descr, found.descr);
    }
}

/* START: Inventory Related Tests */
mod inventory_tests {}

/* START: Build Related Tests */
mod build_tests {}