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
use std::{collections::HashSet, error::Error, path::PathBuf, process::ExitCode, str::FromStr};

use clap::{self, Parser};
use log::{debug, error};
use rusqlite::Connection;
use snafu::{ResultExt, Snafu, Whatever, ensure_whatever, whatever};
#[cfg(feature = "tx")]
use sqlitepipe::txmgmt::client_revert;
use sqlitepipe::{StdinMode, column::Column, insert_blob, insert_lines, insert_row, prepare_db};

#[cfg(feature = "tx")]
use {
    snafu::OptionExt,
    sqlitepipe::txmgmt::{client_commit, client_disconnect, client_main, tx_daemon_main},
    std::os::unix::net::UnixStream,
};

type Result<T> = std::result::Result<T, Whatever>;

mod defaults {
    pub const BLOB_COLUMN: &'static str = "blob";
    pub const LINE_COLUMN: &'static str = "line";
    pub const TABLE_NAME: &'static str = "data";
    pub const DATABASE_PATH: &'static str = "stdin.data.sqlite3";
    #[cfg(feature = "tx")]
    pub const TX_PATH: &'static str = "sqlitepipe_tx.socket";
}

#[derive(Debug, Snafu)]
#[snafu(display("{message}"))]
struct KeyValueParseError {
    message: String,
}

#[derive(Debug, Clone)]
struct KeyValueArg {
    pub key: String,
    pub value: String,
}

impl From<(&str, &str)> for KeyValueArg {
    fn from(value: (&str, &str)) -> Self {
        KeyValueArg {
            key: value.0.to_string(),
            value: value.1.to_string(),
        }
    }
}

impl FromStr for KeyValueArg {
    type Err = KeyValueParseError;

    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        let Some(kv) = s.split_once('=') else {
            return Err(KeyValueParseError {
                message: "invalid key value pair; missing '='".to_string(),
            });
        };
        Ok(kv.into())
    }
}

#[derive(Debug, Default, clap::Args)]
#[group(multiple = false)]
struct StdinArgs {
    /// Don't ingest stdin. [cannot be used in combination with --stdin-blob or --stdin-line]
    #[arg(short = 'n', long)]
    stdin_none: bool,

    /// Ingest stdin as a single blob and store in a single row. [cannot be used in combination with --stdin-none or --stdin-line] [default: blob]
    #[arg(
        short = 'b',
        long,
        default_missing_value = defaults::BLOB_COLUMN,
        require_equals = true,
        num_args = 0..=1,
    )]
    stdin_blob: Option<String>,

    /// Ingest stdin as a document with lines. Store each line in a separate column. [cannot be used in combination with --stdin-none or --stdin-blob] [default: line]
    #[arg(
        short = 'l',
        long,
        default_missing_value = defaults::LINE_COLUMN,
        require_equals = true,
        num_args = 0..=1,
    )]
    stdin_lines: Option<String>,
}

impl StdinArgs {
    fn mode(&self) -> StdinMode {
        if self.stdin_blob.is_some() {
            StdinMode::Blob
        } else if self.stdin_lines.is_some() {
            StdinMode::Lines
        } else {
            StdinMode::None
        }
    }
}

#[cfg(feature = "tx")]
#[derive(Debug, clap::Args)]
#[group(multiple = false)]
struct TransactionArgs {
    /// start a transaction at the given path. [default: sqlitepipe_tx.socket]
    #[arg(
        long,
        default_missing_value = defaults::TX_PATH,
        require_equals = true,
        num_args = 0..=1,
    )]
    start_transaction: Option<PathBuf>,
    /// commit a transaction at the given path. [default: sqlitepipe_tx.socket]
    #[arg(
        long,
        default_missing_value = defaults::TX_PATH,
        require_equals = true,
        num_args = 0..=1,
    )]
    commit_transaction: Option<PathBuf>,
    /// revert a transaction at the given path. [default: sqlitepipe_tx.socket]
    #[arg(
        long,
        default_missing_value = defaults::TX_PATH,
        require_equals = true,
        num_args = 0..=1,
    )]
    revert_transaction: Option<PathBuf>,
    /// add data to a transaction at the given path. [default: sqlitepipe_tx.socket]
    #[arg(
        long,
        default_missing_value = defaults::TX_PATH,
        require_equals = true,
        num_args = 0..=1,
    )]
    transaction: Option<PathBuf>,
}

/// Ingest stdin and write to a database.
#[derive(Debug, clap::Parser)]
struct Args {
    /// Path to the database. [default: stdin.data.sqlite3]
    #[arg(short, long)]
    output_db: Option<PathBuf>,

    /// Name of table where to put the data. [default: data]
    #[arg(short, long)]
    table_name: Option<String>,

    /// If set, delete existing data from the given table. Note: Other tables are left unaffected.
    #[arg(short, long)]
    reset: bool,

    /// Raw values to insert, given as a `<column_name>=<value>` tuple`. Can be given multiple times.
    /// Any column that doesn't exist yet will be added automatically.
    #[arg(short, long)]
    value: Vec<KeyValueArg>,

    /// Treat stdin as json input.
    /// If stdin is read as blob, the blob is converted to JSONB before inserting it.
    /// If stdin is read as lines, each line is converted to JSONB before inserting it.
    #[arg(short, long)]
    json_input: bool,

    #[clap(flatten)]
    stdin_args: StdinArgs,

    #[cfg(feature = "tx")]
    #[clap(flatten)]
    tx_args: TransactionArgs,
}

fn get_all_columns(
    columns: &Vec<KeyValueArg>,
    stdin_args: &StdinArgs,
    stdin_is_json: bool,
) -> Result<Vec<Column>> {
    let mut result: Vec<_> = columns
        .iter()
        .map(|v| Column::raw_column(&v.key, &v.value))
        .collect();
    let unique_names: HashSet<_> = result.iter().map(|v| v.name()).collect();

    let mut new_col = None;

    if let Some(stdin_blob_column) = &stdin_args.stdin_blob {
        if unique_names.contains(&stdin_blob_column.as_str()) {
            whatever!("name clash with column name and blob column: {stdin_blob_column}");
        }

        ensure_whatever!(
            new_col.is_none(),
            "more than one special column not allowed"
        );
        let col = Column::blob_column(stdin_blob_column).set_json(stdin_is_json);
        new_col = Some(col);
    }
    if let Some(stdin_lines_column) = &stdin_args.stdin_lines {
        if unique_names.contains(&stdin_lines_column.as_str()) {
            whatever!("name clash with column name and line column: {stdin_lines_column}");
        }

        ensure_whatever!(
            new_col.is_none(),
            "more than one special column not allowed"
        );

        let col = Column::line_column(stdin_lines_column).set_json(stdin_is_json);
        new_col = Some(col);
    }

    if let Some(col) = new_col {
        result.push(col);
    }

    Ok(result)
}

fn get_args() -> Args {
    let mut args = Args::parse();
    if !args.stdin_args.stdin_none
        && args.stdin_args.stdin_blob.is_none()
        && args.stdin_args.stdin_lines.is_none()
    {
        args.stdin_args = StdinArgs {
            stdin_blob: Some(defaults::BLOB_COLUMN.to_string()),
            ..Default::default()
        };
    }
    args
}

fn normal_main(args: Args) -> Result<()> {
    let raw_table_name = args
        .table_name
        .as_ref()
        .map(|v| v.as_str())
        .unwrap_or_else(|| defaults::TABLE_NAME);

    let output_path = args
        .output_db
        .as_ref()
        .map(|v| v.to_owned())
        .unwrap_or_else(|| defaults::DATABASE_PATH.into());

    let columns = get_all_columns(&args.value, &args.stdin_args, args.json_input)?;

    if columns.is_empty() {
        whatever!("No data to insert.");
    }

    let mut conn = Connection::open(output_path).whatever_context("sqlite")?;

    let tx = conn.transaction().whatever_context("sqlite")?;

    prepare_db(&tx, &raw_table_name, args.reset, &columns).whatever_context("prepare_db")?;

    match args.stdin_args.mode() {
        StdinMode::None => {
            insert_row(&tx, &raw_table_name, &columns).whatever_context("insert_row")?;
        }
        StdinMode::Blob => {
            let mut stdin = std::io::stdin().lock();
            insert_blob(&tx, &raw_table_name, &columns, &mut stdin)
                .whatever_context("insert_blob")?;
        }
        StdinMode::Lines => {
            let stdin = std::io::stdin().lock();
            insert_lines(&tx, &raw_table_name, &columns, stdin).whatever_context("insert_lines")?;
        }
    }

    tx.commit().whatever_context("sqlite")?;

    Ok(())
}

#[cfg(feature = "tx")]
fn start_transaction(args: Args) -> Result<()> {
    use fork::Fork;

    let output_path = args
        .output_db
        .as_ref()
        .map(|v| v.to_owned())
        .unwrap_or_else(|| defaults::DATABASE_PATH.into());

    let tx_path = args
        .tx_args
        .start_transaction
        .whatever_context("need tx path")?;

    let child = fork::daemon(true, false).whatever_context("fork")?;

    if let Fork::Child = child {
        if let Err(_e) = tx_daemon_main(output_path, tx_path) {
            // TODO error handling of fork
        }
    }

    Ok(())
}

#[cfg(feature = "tx")]
fn commit_transaction(args: Args) -> Result<()> {
    let tx_path = args
        .tx_args
        .commit_transaction
        .whatever_context("need tx path")?;

    let mut socket = UnixStream::connect(tx_path).whatever_context("connect socket")?;

    client_commit(&mut socket).whatever_context("client commit")?;

    Ok(())
}

#[cfg(feature = "tx")]
fn revert_transaction(args: Args) -> Result<()> {
    let tx_path = args
        .tx_args
        .revert_transaction
        .whatever_context("need tx path")?;

    let mut socket = UnixStream::connect(tx_path).whatever_context("connect socket")?;

    client_revert(&mut socket).whatever_context("client revert")?;

    Ok(())
}

#[cfg(feature = "tx")]
fn transfer_transaction(args: Args) -> Result<()> {
    let tx_path = args.tx_args.transaction.whatever_context("need tx path")?;

    let mut socket = UnixStream::connect(tx_path).whatever_context("connect socket")?;

    let raw_table_name = args
        .table_name
        .as_ref()
        .map(|v| v.as_str())
        .unwrap_or_else(|| defaults::TABLE_NAME);

    let columns = get_all_columns(&args.value, &args.stdin_args, args.json_input)?;

    if columns.is_empty() {
        whatever!("No data to insert.");
    }

    client_main(
        &mut socket,
        raw_table_name,
        &columns,
        args.stdin_args.mode(),
    )
    .whatever_context("client main")?;

    client_disconnect(&mut socket).whatever_context("disconnect")?;

    Ok(())
}

#[cfg(feature = "tx")]
fn main_with_error(args: Args) -> Result<()> {
    debug!("Args: {args:?}");

    if args.tx_args.start_transaction.is_some() {
        start_transaction(args)?;
    } else if args.tx_args.commit_transaction.is_some() {
        commit_transaction(args)?;
    } else if args.tx_args.revert_transaction.is_some() {
        revert_transaction(args)?;
    } else if args.tx_args.transaction.is_some() {
        transfer_transaction(args)?;
    } else {
        normal_main(args)?;
    }

    Ok(())
}

#[cfg(not(feature = "tx"))]
fn main_with_error(args: Args) -> Result<()> {
    debug!("Args: {args:?}");

    normal_main(args)?;

    Ok(())
}

fn main() -> ExitCode {
    env_logger::init();

    let args = get_args();

    if let Err(e) = main_with_error(args) {
        if let Some(source) = e.source() {
            error!("{source}");
        } else {
            error!("Error: {e}");
        }
        debug!("Detailed error: {e:?}");
        ExitCode::FAILURE
    } else {
        ExitCode::SUCCESS
    }
}