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
use itertools::Itertools;
use openvet_common::rust::CrateName;
use rusqlite::Connection;
use semver::Version;
use serde::{Deserialize, Serialize};
use std::marker::PhantomData;
#[cfg(test)]
use test_strategy::Arbitrary;
use thiserror::Error;

#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[serde(from = "i64")]
pub struct Reference<T> {
    value: i64,
    target: PhantomData<T>,
}

impl<T> Reference<T> {
    pub fn new(value: i64) -> Self {
        Self {
            value,
            target: PhantomData,
        }
    }
}

impl<T> From<i64> for Reference<T> {
    fn from(value: i64) -> Self {
        Self::new(value)
    }
}

#[derive(Error, Debug)]
pub enum InsertError {
    #[error(transparent)]
    Encoding(#[from] serde_rusqlite::Error),
    #[error(transparent)]
    Database(#[from] rusqlite::Error),
}

pub trait Insert: Serialize {
    fn table(&self) -> &str;

    fn insert_or_ignore(&self, connection: &Connection) -> Result<i64, InsertError> {
        let params = serde_rusqlite::to_params_named(self)?;
        let table = self.table();
        let columns = params
            .to_slice()
            .iter()
            .map(|(name, _)| &name[1..])
            .join(", ");
        let names = params
            .to_slice()
            .iter()
            .map(|(name, _)| self.column(name).unwrap_or(name))
            .join(", ");
        let query = format!("INSERT OR IGNORE INTO {table}({columns}) VALUES ({names})");
        connection.execute(&query, &*params.to_slice())?;
        Ok(0)
    }

    fn insert_or_update(&self, connection: &Connection) -> Result<i64, InsertError> {
        let params = serde_rusqlite::to_params_named(self)?;
        let table = self.table();
        let columns = params
            .to_slice()
            .iter()
            .map(|(name, _)| &name[1..])
            .join(", ");
        let names = params
            .to_slice()
            .iter()
            .map(|(name, _)| self.column(name).unwrap_or(name))
            .join(", ");
        let query = format!("INSERT OR UPDATE INTO {table}({columns}) VALUES ({names})");
        connection.execute(&query, &*params.to_slice())?;
        Ok(0)
    }

    fn insert(&self, connection: &Connection) -> Result<i64, InsertError> {
        let params = serde_rusqlite::to_params_named(self)?;
        let table = self.table();
        let columns = params
            .to_slice()
            .iter()
            .map(|(name, _)| &name[1..])
            .join(", ");
        let names = params
            .to_slice()
            .iter()
            .map(|(name, _)| self.column(name).unwrap_or(name))
            .join(", ");
        let query = format!("INSERT INTO {table}({columns}) VALUES ({names})");
        connection.execute(&query, &*params.to_slice())?;
        Ok(0)
    }

    fn column(&self, name: &str) -> Option<&str> {
        None
    }
}

#[derive(Serialize, Deserialize)]
pub struct RustCrateRow {
    id: Reference<Self>,
    #[serde(rename = "crate")]
    krate: CrateName,
}

#[derive(Serialize, Deserialize, Debug, PartialOrd, Ord, PartialEq, Eq)]
#[cfg_attr(test, derive(Arbitrary))]
pub struct InsertRustCrate {
    pub name: CrateName,
}

impl Insert for InsertRustCrate {
    fn table(&self) -> &str {
        "rust_crates"
    }
}

#[derive(Serialize, Deserialize)]
pub struct RustCrateVersionRow {
    pub id: Reference<Self>,
    #[serde(rename = "crate")]
    pub krate: CrateName,
    pub version: Version,
    pub files: Option<String>,
}

#[derive(Serialize, Deserialize, Debug)]
#[cfg_attr(test, derive(Arbitrary))]
pub struct InsertRustCrateVersion {
    #[serde(rename = "crate")]
    pub krate: CrateName,
    #[cfg_attr(test, strategy(openvet_common::proptest::version()))]
    pub version: Version,
}

impl Insert for InsertRustCrateVersion {
    fn table(&self) -> &str {
        "rust_crate_versions"
    }

    fn column(&self, name: &str) -> Option<&str> {
        match name {
            ":crate" => Some("(SELECT id FROM rust_crates WHERE name = :crate)"),
            _ => None,
        }
    }
}