sqlitepipe 0.2.1

A simple tool for piping the output of a command into sqlite databases.
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
//! module for managing a transaction daemon

use log::debug;
use nanoserde::{DeBin, SerBin};
use rusqlite::{Connection, TEMP_DB, params_from_iter};
use snafu::{ResultExt, Snafu};

use crate::{
    StdinMode,
    column::Column,
    insert_row, prepare_db,
    sanitizing::SqlSanitize,
    stmt,
};

use std::{
    io::{BufRead, Read, Write},
    ops::Deref,
    os::unix::net::UnixListener,
    path::Path,
};

#[derive(Debug, Snafu)]
pub enum Error {
    /// A rusqlite error occurred within a specific context.
    #[snafu(display("Database error (context: {context}): {source}"))]
    DatabaseErrorContext {
        source: rusqlite::Error,
        context: &'static str,
    },

    /// Failed to write chunked data to a SQLite BLOB.
    #[snafu(display("Blob write error: {source}"))]
    BlobWriteError { source: std::io::Error },

    /// An error during an insert operation.
    #[snafu(display("Error during insert"))]
    InsertError { source: crate::Error },

    /// An error when receiving a packet.
    #[snafu(display("Error during receive"))]
    ReceiveMessageError { source: nanoserde::DeBinErr },

    /// Generic communication error.
    #[snafu(display("Communication error"))]
    CommunicationError { source: std::io::Error },

    /// Error while reading from a source stream.
    #[snafu(display("Source read error"))]
    SourceReadError { source: std::io::Error },

    /// Disk I/O error
    #[snafu(display("Disk io error"))]
    DiskIoError { source: std::io::Error },
}

/// Column data
#[derive(Debug, Clone, PartialEq, Eq, SerBin, DeBin)]
pub enum ColumnData {
    /// A raw key/value pair.
    Raw {
        key: String,
        value: String,
        json: bool,
    },
    /// A placeholder for blob data
    Blob {
        column: String,
        size: usize,
        json: bool,
    },
}

impl From<&ColumnData> for Column {
    fn from(value: &ColumnData) -> Self {
        match value {
            ColumnData::Raw { key, value, json } => Column::raw_column(key, value).set_json(*json),
            ColumnData::Blob {
                column,
                size: _,
                json,
            } => Column::blob_column(column).set_json(*json),
        }
    }
}

/// A helper enum for serializing/deserializing byte buffers that can be shared or owned
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ShareableBuffer<'a> {
    Owned(Vec<u8>),
    Shared(&'a [u8]),
}

impl<'a> Deref for ShareableBuffer<'a> {
    type Target = [u8];

    fn deref(&self) -> &Self::Target {
        match self {
            ShareableBuffer::Owned(items) => &items,
            ShareableBuffer::Shared(items) => items,
        }
    }
}

impl<'a> From<Vec<u8>> for ShareableBuffer<'a> {
    fn from(value: Vec<u8>) -> Self {
        Self::Owned(value)
    }
}

impl<'a> From<&'a [u8]> for ShareableBuffer<'a> {
    fn from(value: &'a [u8]) -> Self {
        Self::Shared(value)
    }
}

impl<'a> SerBin for ShareableBuffer<'a> {
    fn ser_bin(&self, output: &mut Vec<u8>) {
        let buf: &[u8] = self;
        let len = buf.len();
        len.ser_bin(output);
        buf.ser_bin(output);
    }
}

impl<'a> DeBin for ShareableBuffer<'a> {
    fn de_bin(offset: &mut usize, bytes: &[u8]) -> Result<Self, nanoserde::DeBinErr> {
        let buf = Vec::<u8>::de_bin(offset, bytes)?;
        Ok(ShareableBuffer::Owned(buf))
    }
}

/// A IPC message to communicate between daemon and client
#[derive(Debug, Clone, PartialEq, Eq, SerBin, DeBin)]
pub enum Message<'a> {
    /// Insert data into a table.
    Insert {
        table_name: String,
        data: Vec<ColumnData>,
    },
    /// Mark start of transferring a blob.
    BlobStart,
    /// Blob data.
    BlobData(ShareableBuffer<'a>),
    /// Client wants to disconnect.
    Disconnect,
    /// Commit transaction.
    Commit,
    /// Revert transaction.
    Revert,
}

/// Send a mesage into the given sink.
pub fn send_msg(message: &Message, buf: &mut impl Write) -> Result<(), Error> {
    let mut serialized_message = message.serialize_bin();
    let len = serialized_message.len() as u64;
    debug!("sending {message:?} len {len:?}");
    let mut ser_len = len.serialize_bin();
    buf.write_all(&mut ser_len).context(CommunicationSnafu)?;
    buf.write_all(&mut serialized_message)
        .context(CommunicationSnafu)?;
    Ok(())
}

/// Read a message from the given source.
pub fn receive_msg<'a>(read: &mut impl Read) -> Result<Message<'a>, Error> {
    let mut buf = [0; 8];
    read.read_exact(&mut buf).context(CommunicationSnafu)?;
    let msg_len = u64::deserialize_bin(&buf).context(ReceiveMessageSnafu)?;
    let mut buf = vec![0; msg_len as usize];
    read.read_exact(&mut buf).context(CommunicationSnafu)?;
    let msg = Message::deserialize_bin(&buf).context(ReceiveMessageSnafu)?;
    Ok(msg)
}

fn handle_msg_inner(conn: &Connection, message: &Message) -> Result<(), Error> {
    match message {
        Message::Insert { table_name, data } => {
            let mut total_size: Option<usize> = None;
            let columns: Vec<Column> = data
                .iter()
                .inspect(|v| {
                    if let ColumnData::Blob {
                        column: _,
                        size,
                        json: _,
                    } = v
                    {
                        total_size = Some(*size);
                    }
                })
                .map(|v| v.into())
                .collect();

            prepare_db(conn, table_name, false, &columns).context(InsertSnafu)?;

            if let Some(total_size) = total_size {
                let sanitized_table_name = table_name.to_sql_sanitized_string();

                let mut statement = conn
                    .prepare(&stmt::insert_blob(
                        &sanitized_table_name,
                        &columns,
                        total_size,
                    ))
                    .context(DatabaseErrorContextSnafu {
                        context: "insert blob",
                    })?;

                let values = columns.iter().filter_map(|n| n.value());

                debug!("executing {statement:?} with values {columns:?}");

                statement
                    .execute(params_from_iter(values))
                    .context(DatabaseErrorContextSnafu {
                        context: "insert blob",
                    })?;

                conn.execute(stmt::drop_temporary_blob_table(), ())
                    .context(DatabaseErrorContextSnafu {
                        context: "cleanup blob",
                    })?;
            } else {
                insert_row(conn, table_name, &columns).context(InsertSnafu)?;
            }
        }
        Message::BlobStart => {
            conn.execute(stmt::create_temporary_blob_table(), [])
                .context(DatabaseErrorContextSnafu {
                    context: "insert blob",
                })?;
        }
        Message::BlobData(data) => {
            conn.execute(&stmt::insert_zero_blob(data.len()), [])
                .context(DatabaseErrorContextSnafu {
                    context: "insert blob",
                })?;
            let rowid = conn.last_insert_rowid();
            let mut blob = conn
                .blob_open(TEMP_DB, "blob_insert", "data", rowid, false)
                .context(DatabaseErrorContextSnafu {
                    context: "open blob",
                })?;

            blob.write_all(&data).context(BlobWriteSnafu)?;
        }
        Message::Disconnect | Message::Commit | Message::Revert => {
            panic!("Commit/Abort must be handled outside")
        }
    };
    Ok(())
}

/// Main entry point for a daemon.
/// Opens the connection and connects to the socket.
pub fn tx_daemon_main(
    output_path: impl AsRef<Path>,
    tx_path: impl AsRef<Path>,
) -> Result<(), Error> {
    let tx_path = tx_path.as_ref();
    let conn = Connection::open(output_path).context(DatabaseErrorContextSnafu {
        context: "open connection",
    })?;

    let socket = UnixListener::bind(tx_path).context(CommunicationSnafu)?;

    tx_main(conn, socket)?;

    std::fs::remove_file(tx_path).context(DiskIoSnafu)?;
    Ok(())
}

/// Main entry point for tx management.
/// Expects the connection and socket to be already opened.
pub fn tx_main(mut conn: Connection, listener: UnixListener) -> Result<(), Error> {
    let tx = conn.transaction().context(DatabaseErrorContextSnafu {
        context: "create transaction",
    })?;

    'outer: loop {
        debug!("tx_main loop waiting for connection");
        let (mut stream, addr) = listener.accept().context(CommunicationSnafu)?;
        debug!("tx_main connected: {addr:?}");

        loop {
            debug!("tx_main loop waiting for message");
            let msg = receive_msg(&mut stream)?;
            debug!("tx_main received: {msg:?}");

            match msg {
                Message::Commit => {
                    tx.commit()
                        .context(DatabaseErrorContextSnafu { context: "commit" })?;
                    break 'outer;
                }
                Message::Revert => {
                    tx.rollback().context(DatabaseErrorContextSnafu {
                        context: "rollback",
                    })?;
                    break 'outer;
                }
                Message::Disconnect => {
                    break;
                }
                msg => handle_msg_inner(&tx, &msg)?,
            };
        }
    }

    Ok(())
}

/// Main entrypoint for clients sending data.
pub fn client_main(
    sink: &mut impl Write,
    table_name: &str,
    columns: &[Column],
    mode: StdinMode,
) -> Result<(), Error> {
    match mode {
        StdinMode::None => {
            let data = columns
                .iter()
                .map(|v| ColumnData::Raw {
                    key: v.name().to_string(),
                    value: v.raw_value().to_string(),
                    json: false,
                })
                .collect();
            let message = Message::Insert {
                table_name: table_name.to_string(),
                data,
            };
            send_msg(&message, sink)?;
        }
        StdinMode::Blob => {
            send_msg(&Message::BlobStart, sink)?;
            let mut total_size = 0usize;
            {
                let mut stdin = std::io::stdin().lock();
                let mut buf = vec![0; stmt::BLOB_BUF_SIZE];

                loop {
                    let count = stdin.read(&mut buf).context(SourceReadSnafu)?;
                    total_size += count;
                    debug!("read {count} to a total of {total_size}");
                    if count == 0 {
                        break;
                    }

                    send_msg(&Message::BlobData(ShareableBuffer::Shared(&buf)), sink)?;
                }
            }

            let data = columns
                .iter()
                .map(|col| match col.value() {
                    Some(v) => ColumnData::Raw {
                        key: col.name().to_owned(),
                        value: v.to_owned(),
                        json: false,
                    },
                    None => ColumnData::Blob {
                        column: col.name().to_owned(),
                        size: total_size,
                        json: col.is_json(),
                    },
                })
                .collect();

            send_msg(
                &Message::Insert {
                    table_name: table_name.to_owned(),
                    data,
                },
                sink,
            )?;
        }
        StdinMode::Lines => {
            let stdin = std::io::stdin().lock();
            for line in stdin.lines() {
                let line = line.context(SourceReadSnafu)?;
                let data = columns
                    .iter()
                    .map(|col| ColumnData::Raw {
                        key: col.name().to_owned(),
                        value: col.value_or_line(&line).to_owned(),
                        json: col.is_json(),
                    })
                    .collect();
                send_msg(
                    &Message::Insert {
                        table_name: table_name.to_owned(),
                        data,
                    },
                    sink,
                )?;
            }
        }
    }

    Ok(())
}

/// Entrypoint for committing transactions.
pub fn client_commit(sink: &mut impl Write) -> Result<(), Error> {
    send_msg(&Message::Commit, sink)?;
    Ok(())
}

/// Entrypoint for reverting transactions.
pub fn client_revert(sink: &mut impl Write) -> Result<(), Error> {
    send_msg(&Message::Revert, sink)?;
    Ok(())
}

/// Entrypoint for disconnecting.
pub fn client_disconnect(sink: &mut impl Write) -> Result<(), Error> {
    send_msg(&Message::Disconnect, sink)?;
    Ok(())
}