toado 0.12.5

A simple interactive task and project manager for the command line
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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
//! Database query utilites

use std::fmt::{self};

pub use projects::*;
pub use tasks::*;

use crate::Tables;

mod projects;
mod tasks;

//
// Query Structs
//

/// Base database query trait
trait Query: fmt::Display {
    fn query_table(&self) -> crate::Tables;
}

/// Database addition query supertrait
trait AddQuery: Query + fmt::Display {
    /// Vector of key value pairs for query (ie. ("name", "lorem ipsum"))
    fn key_value_pairs(&self) -> KeyValuePairs;

    /// Returns keys and values as seperate list strings
    fn get_key_value_strings(&self) -> (String, String) {
        let (keys, values): (Vec<&str>, Vec<String>) = self.key_value_pairs().0.into_iter().unzip();
        let values: Vec<String> = values.into_iter().map(|v| quote_string(&v)).collect(); // Add quotes to
                                                                                          // values
        (keys.join(", "), values.join(", "))
    }

    /// Creates a query string from struct data
    fn build_query_string(&self) -> String {
        let (keys, values) = self.get_key_value_strings();
        format!(
            "INSERT INTO {}({keys}) VALUES({values});",
            self.query_table()
        )
    }
}

/// Database update query trait
trait UpdateQuery: Query + fmt::Display {
    type Action: fmt::Display;

    fn condition(&self) -> Option<&str>;
    fn update_cols(&self) -> UpdateCols<Self::Action>;

    fn build_query_string(&self) -> String {
        let mut query_string = format!("UPDATE {} SET {}", self.query_table(), self.update_cols());

        if let Some(condition) = self.condition() {
            query_string.push_str(&format!(" WHERE {condition};"));
        } else {
            query_string.push(';')
        }

        query_string
    }
}

/// Database delete query trait
trait DeleteQuery: Query + fmt::Display {
    /// Get the condition for selecting which row(s) to delete. If None, deletes all rows in table
    fn condition(&self) -> &Option<String>;

    /// Creates a query string from struct data
    fn build_query_string(&self) -> String {
        let mut query_string = format!("DELETE FROM {}", self.query_table());

        if let Some(condition) = self.condition() {
            query_string.push_str(&format!(" WHERE {condition};"))
        } else {
            query_string.push(';');
        }

        query_string
    }
}

/// Select query filters tuple type
type SelectFilters<'a> = (
    &'a Option<String>,   // Condition
    &'a Option<OrderBy>,  // Order by col
    &'a OrderBy,          // Default order by col
    &'a Option<OrderDir>, // Order direction
    &'a Option<RowLimit>, // Row limit
    &'a Option<usize>,    // Row offset
);

/// Database select query trait
trait SelectQuery<'a>: Query + fmt::Display {
    /// Get query filter values
    fn query_filters(&self) -> SelectFilters;

    fn select_cols(&self) -> &QueryCols<'a>;

    /// Appends selection filters to a query string
    fn append_filters(&self, mut query_string: String) -> String {
        let (condition, order_by, order_by_default, order_dir, limit, offset) =
            self.query_filters();

        //
        // Query Conditions
        //
        if let Some(condition) = condition {
            // If select condtions provided, add to query string
            query_string.push_str(&format!(" WHERE {}", condition));
        }

        //
        // Query Order
        //

        // Default order by priority
        let order_by = order_by.unwrap_or(*order_by_default);

        query_string.push_str(&format!(
            " ORDER BY {} {}",
            order_by,
            match order_dir {
                // Set order direction if provided, else use defaults
                Some(dir) => dir,
                None => match order_by {
                    OrderBy::Priority => &OrderDir::Desc,
                    _ => &OrderDir::Asc,
                },
            }
        ));

        //
        // Query Limit
        //
        match limit {
            Some(RowLimit::Limit(limit)) => query_string.push_str(&format!(" LIMIT {limit}")),
            Some(RowLimit::All) => {}
            None => query_string.push_str(" LIMIT 10"),
        }

        //
        // Query Offset
        //
        if limit.is_none()
            || limit
                .as_ref()
                .is_some_and(|limit| !matches!(limit, RowLimit::All))
        {
            if let Some(offset) = offset {
                query_string.push_str(&format!(" OFFSET {offset}"))
            }
        }

        query_string.push(';');
        query_string
    }

    /// Creates a query string from struct data
    fn build_query_string(&self) -> String {
        let query_string = format!("SELECT {} FROM {}", self.select_cols(), self.query_table());
        self.append_filters(query_string)
    }
}

//
// Assign Query
//

/// Database query for assigning a task to a project
pub struct AssignTaskQuery {
    task_id: i64,
    project_id: i64,
}

impl AssignTaskQuery {
    pub fn new(task_id: i64, project_id: i64) -> Self {
        Self {
            task_id,
            project_id,
        }
    }
}

impl Query for AssignTaskQuery {
    fn query_table(&self) -> crate::Tables {
        Tables::TaskAssignments
    }
}

impl AddQuery for AssignTaskQuery {
    fn key_value_pairs(&self) -> KeyValuePairs {
        KeyValuePairs(vec![
            ("task_id", self.task_id.to_string()),
            ("project_id", self.project_id.to_string()),
        ])
    }
}

impl fmt::Display for AssignTaskQuery {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.build_query_string())
    }
}

//
// Unassign Query
//

pub struct UnassignTaskQuery {
    condition: Option<String>,
}

impl UnassignTaskQuery {
    pub fn new(task_id: i64, project_id: i64) -> Self {
        let condition = Some(format!(
            "{} and {}",
            QueryConditions::Equal {
                col: "task_id",
                value: &task_id
            },
            QueryConditions::Equal {
                col: "project_id",
                value: &project_id
            }
        ));

        Self { condition }
    }
}

impl Query for UnassignTaskQuery {
    fn query_table(&self) -> crate::Tables {
        Tables::TaskAssignments
    }
}

impl DeleteQuery for UnassignTaskQuery {
    fn condition(&self) -> &Option<String> {
        &self.condition
    }
}

impl fmt::Display for UnassignTaskQuery {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.build_query_string())
    }
}

//
// Utils
//

/// Columns to use in query
pub enum QueryCols<'a> {
    /// All columns
    All,
    /// Subset of row columns by name
    Some(Vec<&'a str>),
}

// Implements String conversion for QueryCols
impl fmt::Display for QueryCols<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{}",
            match self {
                Self::All => "*".to_string(),
                Self::Some(cols) => cols.join(", "),
            }
        )
    }
}

/// Update action for a database column
#[derive(Clone, Copy)]
pub enum UpdateAction<T>
where
    T: fmt::Display,
{
    /// Update column with a value
    Some(T),
    /// Set column to null
    Null,
    /// Don't update column
    None,
}

impl<T> UpdateAction<T>
where
    T: fmt::Display,
{
    /// Maps inner value T to U using mapping function F
    fn map<U, F>(self, f: F) -> UpdateAction<U>
    where
        U: fmt::Display,
        F: FnOnce(T) -> U,
    {
        match self {
            Self::Some(value) => UpdateAction::Some(f(value)),
            Self::Null => UpdateAction::Null,
            Self::None => UpdateAction::None,
        }
    }

    fn map_from<U, F>(from: &UpdateAction<T>, f: F) -> UpdateAction<U>
    where
        U: fmt::Display,
        F: FnOnce(&T) -> U,
    {
        match from {
            Self::Some(x) => UpdateAction::Some(f(x)),
            Self::None => UpdateAction::None,
            Self::Null => UpdateAction::Null,
        }
    }

    /// Returns true if the UpdateAction value None
    fn is_none(&self) -> bool {
        matches!(&self, Self::None)
    }
    /// Create the sql update statment string for a given column.
    /// Avoid using this when the UpdateAction value is None
    fn to_statment(&self, col: &str) -> String {
        match &self {
            Self::Some(value) => format!("{col} = '{value}'"),
            Self::Null => format!("{col} = NULL"),
            Self::None => "".to_string(),
        }
    }
}

impl<T> From<Option<T>> for UpdateAction<T>
where
    T: fmt::Display,
{
    fn from(value: Option<T>) -> Self {
        match value {
            Some(value) => Self::Some(value),
            None => Self::None,
        }
    }
}

impl From<String> for UpdateAction<String> {
    fn from(value: String) -> Self {
        if value.is_empty() {
            UpdateAction::Null
        } else {
            UpdateAction::Some(value)
        }
    }
}

/// Columns to update in an update query
struct UpdateCols<'a, T>(Vec<(&'a str, UpdateAction<T>)>)
where
    T: fmt::Display;

impl<T> fmt::Display for UpdateCols<'_, T>
where
    T: fmt::Display,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let actions: Vec<String> = self
            .0
            .iter()
            .filter(|col| !col.1.is_none())
            .map(|col| col.1.to_statment(col.0))
            .collect();

        write!(f, "{}", actions.join(", "))
    }
}

/// Table column to order selection by
#[derive(Clone, Copy, clap::ValueEnum)]
pub enum OrderBy {
    Id,
    Name,
    Priority,
    // TODO: These options cause an sql error
    // StartDate,
    // EndDate,
}

impl fmt::Display for OrderBy {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{}",
            match self {
                Self::Id => "id",
                Self::Name => "name",
                Self::Priority => "priority",
                // Self::StartDate => "start_date",
                // Self::EndDate => "end_date",
            }
        )
    }
}

/// Direction of selection order.
/// Asc: smallest value to largest
/// Desc: Largest value to smallest
#[derive(Clone, Copy, clap::ValueEnum)]
pub enum OrderDir {
    Asc,
    Desc,
}

impl fmt::Display for OrderDir {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{}",
            match self {
                Self::Asc => "ASC",
                Self::Desc => "DESC",
            }
        )
    }
}

/// Defines the total number of rows to limit a query to
pub enum RowLimit {
    /// A set number of rows
    Limit(usize),
    /// No limit of rows
    All,
}

pub struct KeyValuePairs<'a>(Vec<(&'a str, String)>);

impl<'a> KeyValuePairs<'a> {
    /// Push a key value pair to a vector of pairs if value is Some
    fn push_pairs_if_some(&mut self, key: &'a str, value: Option<String>) {
        if let Some(value) = value {
            self.0.push((key, value))
        }
    }
}

/// Database statment conditions
pub enum QueryConditions<'a, T>
where
    T: fmt::Display,
{
    Equal { col: &'a str, value: T },
    NotEqual { col: &'a str, value: T },
    GreaterThan { col: &'a str, value: T },
    LessThan { col: &'a str, value: T },
    GreaterThanOrEqual { col: &'a str, value: T },
    LessThanOrEqual { col: &'a str, value: T },
    Between { col: &'a str, values: (T, T) },
    Like { col: &'a str, value: T },
    In { col: &'a str, values: Vec<T> },
}

// Implements String conversion for QueryConditions
impl<'a, T> fmt::Display for QueryConditions<'a, T>
where
    T: fmt::Display,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{}",
            match self {
                QueryConditions::Equal { col, value } => format!("{col} = {value}"),
                QueryConditions::NotEqual { col, value } => format!("{col} != {value}"),
                QueryConditions::GreaterThan { col, value } => format!("{col} > {value}"),
                QueryConditions::LessThan { col, value } => format!("{col} < {value}"),
                QueryConditions::GreaterThanOrEqual { col, value } => format!("{col} >= {value}"),
                QueryConditions::LessThanOrEqual { col, value } => format!("{col} <= {value}"),
                QueryConditions::Between { col, values } => {
                    format!("{col} BETWEEN {} AND {}", values.0, values.1)
                }
                QueryConditions::Like { col, value } => format!("{col} LIKE {value}"),
                QueryConditions::In { col, values } => format!(
                    "{col} IN ({})",
                    values
                        .iter()
                        .map(|item| item.to_string())
                        .collect::<Vec<String>>()
                        .join(", ") // Convert vector of values into string of format "a, b, c"
                ),
            }
        )
    }
}

/// Surronds input str with single quote
fn quote_string(str: &str) -> String {
    format!("'{str}'")
}