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
//
// Copyright (C) 2018 Kubos Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License")
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

// Must be kept until diesel is updated:
//   https://github.com/diesel-rs/diesel/pull/1787
//   https://github.com/diesel-rs/diesel/issues/1785
#[macro_use]
extern crate diesel;

pub mod models;
pub use crate::models::*;

use diesel::dsl::sql;
use diesel::insert_into;
use diesel::prelude::*;
use diesel::sql_query;
use diesel::sql_types::Bool;
use diesel::sqlite::SqliteConnection;
use diesel::*;
use log::{error, info};

pub struct Database {
    pub connection: SqliteConnection,
}

impl Database {
    /// Construct new database structure and database file if needed
    ///
    /// # Arguments
    /// `path` - Path to database file
    ///
    /// # Panics
    ///
    /// Attempts to connect to sqlite database and will `panic!` if connection fails.
    pub fn new(path: &str) -> Self {
        if !::std::path::Path::new(path).exists() {
            info!("Creating database {}", path);
        }
        Database {
            connection: SqliteConnection::establish(&String::from(path)).unwrap_or_else(|_| {
                panic!("Could not create SQLite database connection to: {}", path)
            }),
        }
    }

    /// Check if database has correct table and creates table if needed
    ///
    /// # Panics
    ///
    /// Will `panic!` if fails to locate and/or create telemetry table
    pub fn setup(&self) {
        match select(sql::<Bool>(
            "EXISTS \
             (SELECT 1 \
             FROM sqlite_master \
             WHERE type = 'table' \
             AND name = 'telemetry')",
        ))
        .get_result::<bool>(&self.connection)
        {
            Err(err) => {
                error!("Error querying table: {:?}", err);
                panic!("Error querying table: {:?}", err)
            }
            Ok(true) => info!("Table exists"),
            Ok(false) => {
                info!("Telemetry table not found. Creating table.");
                match sql_query(
                    "CREATE TABLE telemetry (
                    timestamp DOUBLE NOT NULL,
                    subsystem VARCHAR(255) NOT NULL,
                    parameter VARCHAR(255) NOT NULL,
                    value VARCHAR(255) NOT NULL,
                    PRIMARY KEY (timestamp, subsystem, parameter))",
                )
                .execute(&self.connection)
                {
                    Ok(_) => info!("Telemetry table created"),
                    Err(err) => {
                        error!("Error creating table: {:?}", err);
                        panic!("Error creating table: {:?}", err)
                    }
                }
            }
        };
    }

    pub fn insert<'a>(
        &self,
        timestamp: f64,
        subsystem: &'a str,
        parameter: &'a str,
        value: &'a str,
    ) -> QueryResult<usize> {
        let new_entry = Entry {
            timestamp,
            subsystem: String::from(subsystem),
            parameter: String::from(parameter),
            value: String::from(value),
        };

        insert_into(telemetry::table)
            .values(&new_entry)
            .execute(&self.connection)
    }

    pub fn insert_systime<'a>(
        &self,
        subsystem: &'a str,
        parameter: &'a str,
        value: &'a str,
    ) -> QueryResult<usize> {
        let time = time::now_utc().to_timespec();
        let timestamp = time.sec as f64 + (f64::from(time.nsec) / 1_000_000_000.0);
        self.insert(timestamp, subsystem, parameter, value)
    }

    pub fn insert_bulk(&self, entries: Vec<Entry>) -> QueryResult<usize> {
        insert_into(telemetry::table)
            .values(&entries)
            .execute(&self.connection)
    }
}

table! {
    telemetry (timestamp) {
        timestamp -> Double,
        subsystem -> Text,
        parameter -> Text,
        value -> Text,
    }
}