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
use log::trace;
use mysql::Params;
use mysql::Params::Positional;
use mysql::Pool;
use smallvec::smallvec;

use crate::error::Error;
use crate::error::Result;
use crate::writer::Trade;
use crate::writer::Writer;

/// An constraint for MySQLWriter.
pub trait MySQLWriterElement {
    /// Converts a contents into MySQL params.
    fn to_params(&self) -> Params;
    /// Returns table definitions for MySQL.
    fn table_def() -> Vec<TableDef>;
    /// Optionally returns index definitions.
    fn index_names() -> Vec<String>;
    /// Returns a string to create a table.
    fn create_table_stmt(table_name: &str) -> String {
        // create column definition
        // e.g.
        //
        // ```
        // id BIGINT NOT NULL PRIMARY KEY,
        // traded_at TIMESTAMP(3) NOT NULL,
        // amount FLOAT NOT NULL,
        // price FLOAT NOT NULL
        // ```
        let columns = Self::table_def()
            .iter()
            .map(|TableDef(k, v)| format!("{} {}", k, v))
            .collect::<Vec<String>>();

        let index = Self::index_names()
            .iter()
            .map(|name| format!("KEY `ind_{s}` (`{s}`)", s = name))
            .collect::<Vec<String>>();

        let definition = [&columns[..], &index[..]].concat().join(", ");

        format!(
            r"CREATE TABLE IF NOT EXISTS {} ( {} );",
            table_name, definition
        )
    }
}

/// A definition for MySQL.
/// First value is a name of the column, and 2nd is a following definition in a `CREATE TABLE` statement.
///
/// # Example
///
/// ```
/// use pikmin::writer::db_mysql::TableDef;
/// fn table_def() -> Vec<TableDef> {
///     vec![
///         TableDef::new("id", "BIGINT NOT NULL PRIMARY KEY"),
///         TableDef::new("traded_at", "TIMESTAMP(3) NOT NULL"),
///         TableDef::new("amount", "FLOAT NOT NULL"),
///         TableDef::new("price", "FLOAT NOT NULL"),
///     ]
/// }
/// ```
#[derive(Debug)]
pub struct TableDef(String, String);

impl TableDef {
    /// Creates a column of a table definition.
    pub fn new(s1: &str, s2: &str) -> Self {
        TableDef(String::from(s1), String::from(s2))
    }
}

/// A writer implementation for MySQL.
#[derive(Debug)]
pub struct MySQLWriter<'a> {
    table_name: &'a str,
    connection: Pool,
}

impl<'a> MySQLWriter<'a> {
    /// Creates a writer for MySQL with a given URL and a table name.
    pub fn new(table_name: &'a str, database_url: &str) -> Self {
        trace!("connect to {}", database_url);
        let connection = Pool::new(database_url).expect("cannot connect to DB");

        MySQLWriter {
            table_name,
            connection,
        }
    }

    fn create_table<T: MySQLWriterElement>(&self) {
        let create_stmt = T::create_table_stmt(self.table_name);
        self.connection.prep_exec(create_stmt, ()).unwrap();
    }

    fn bulk_insert<T: MySQLWriterElement>(&self, v: &[T]) -> Result<u64> {
        // consider maximum number of params for MySQL
        const MAX_PARAM_NUM: usize = 10000;

        let col_names = T::table_def()
            .iter()
            .map(|TableDef(k, _)| k.clone())
            .collect::<Vec<String>>();

        v.chunks(MAX_PARAM_NUM)
            .map(|x| {
                let placeholder = format!(
                    "({})",
                    col_names
                        .iter()
                        .map(|_| "?")
                        .collect::<Vec<&str>>()
                        .join(",")
                );
                let stmt = format!(
                    r#"REPLACE INTO {} ({}) VALUES {} ;"#,
                    self.table_name,
                    col_names.join(","),
                    vec![placeholder; x.len()].join(",")
                );

                let params: Result<Params> = x
                    .iter()
                    .map(|e| e.to_params())
                    .map(|p: Params| {
                        p.into_positional(&col_names)
                            .map_err(|e| Error::MySqlMissingNamedParameter(Box::new(e)))
                    })
                    .collect::<Result<Vec<Params>>>()
                    .map(|vp| {
                        let u = vp
                            .into_iter()
                            .flat_map(|v| if let Positional(ps) = v { ps } else { smallvec![] })
                            .collect();
                        Positional(u)
                    });

                params.and_then(|p: Params| {
                    self.connection
                        .prep_exec(stmt, p)
                        .map(|result| result.affected_rows())
                        .map_err(Error::from)
                })
            })
            .collect::<Result<Vec<u64>>>()
            .and_then(|e| Ok(e.iter().sum()))
    }
}

impl<'a> Writer for MySQLWriter<'a> {
    fn write(&mut self, trades: &[Trade]) -> Result<u64> {
        self.create_table::<Trade>();
        self.bulk_insert(trades)
    }
}