owoof 0.2.0

Uses SQLite to store data and a datalog-like format to query it.
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
//! import one csv into a sqlite database with owoof

use std::borrow::Cow;
use std::error::Error;
use std::iter;
use std::path::PathBuf;

use owoof::{AttributeRef, DontWoof, Optional};

use rusqlite::OpenFlags;

use anyhow::Context;

#[derive(Debug)]
struct Args<'a> {
    db: PathBuf,
    input: Option<PathBuf>,
    mappings: Vec<ToAttribute<'a>>,
    dry_run: bool,
    limit: usize,
    output: bool,
    csv_delimiter: u8,
}

#[derive(Debug)]
struct ToAttribute<'a> {
    column: Cow<'a, str>,
    attribute: &'a AttributeRef,
}

#[derive(Debug)]
struct ToPosition<'a> {
    attribute: &'a AttributeRef,
    position: usize,
}

fn do_import<'a>(args: Args<'a>) -> anyhow::Result<()> {
    let input = open_check_tty(args.input.as_ref())?;

    let mut reader = csv::ReaderBuilder::new()
        .flexible(true)
        .delimiter(args.csv_delimiter)
        .from_reader(input);
    let headers = reader.headers()?;
    let mut to_positions: Vec<ToPosition> =
        lookup_header_indices(headers, args.mappings.as_slice())?;

    if args.dry_run {
        eprintln!("the following mappings were planned");

        for mapping in args.mappings {
            eprintln!("{}\t{}", mapping.attribute, mapping.column);
        }

        eprintln!("but this is a dry run, nothing will be imported");
        return Ok(());
    }

    let id_mapping: Option<ToPosition> = to_positions
        .iter()
        .position(|m| m.attribute == AttributeRef::from_static(":db/id"))
        .map(|i| to_positions.remove(i));

    let mut db = rusqlite::Connection::open_with_flags(
        &args.db,
        OpenFlags::SQLITE_OPEN_READ_WRITE | OpenFlags::SQLITE_OPEN_NO_MUTEX,
    )?;
    let woof = DontWoof::new(&mut db)?;

    /* attribute identifiers -> attribute entities -- parallel sequence */
    let attributes: Vec<owoof::Encoded<owoof::Entity>> =
        find_or_assert_attributes(&woof, args.mappings.as_slice())?;

    let mut records_seen = 0usize;
    let mut limit = (0 != args.limit).then(|| args.limit);
    let mut output = if args.output {
        let mut w = csv::WriterBuilder::new()
            .delimiter(args.csv_delimiter)
            .from_writer(io::stdout());
        /* write headers */
        w.write_record(
            &iter::once(":db/id")
                .chain(headers.iter())
                .collect::<csv::StringRecord>(),
        )?;
        Some(w)
    } else {
        None
    };

    let mut record = csv::StringRecord::new();
    while Some(0) != limit && reader.read_record(&mut record)? {
        let e = if let Some(ToPosition { position, .. }) = id_mapping {
            let entity = record
                .get(position)
                .context("no value")?
                .parse::<owoof::Entity>()
                .context("parse entity")?;
            woof.encode(entity)?
        } else {
            woof.new_entity()?
        };

        /* This could have been written differently to use the Deserialize implementation on
         * owoof::Value if the csv crate API wasn't so awful.
         *
         * I can't ask it to deserialize a particular cell of a row -- like
         * `StringRecord::get_deserialize()` or something -- so we'd have to use
         * `StringRecord::deserialize` and deserialize the entire row.  But, since we only care
         * about some cells and not others, we'd want to use a `serde::de::DeserializeSeed` to skip
         * past the cells we don't care about.
         *
         * But, I don't think there's a way to use `DeserializeSeed` with the csv library because
         * it doesn't expose an actual deserializer...
         *
         * Instead, we just have `value_from_csv_text` which basically just does both the csv
         * library's deserializer.rs/infer_deserialize() and owoof::Value's Deserialize.  */
        to_positions
            .iter()
            .zip(attributes.iter().cloned())
            .map(|(to, a): (&ToPosition, _)| {
                let text = record.get(to.position).context("no value")?;
                let value: owoof::Value = value_from_csv_text(text);
                woof.encode(value)
                    .and_then(|v| woof.assert(e, a, v).map(drop))
                    .with_context(|| format!("failed to assert {:?}", text))
            })
            .zip(args.mappings.iter())
            .map(|(res, map)| res.with_context(|| format!("for column {:?}", map.column)))
            .collect::<anyhow::Result<()>>()
            .with_context(|| match record.position() {
                Some(p) => format!("on line {}", p.line()),
                None => format!("on line ???"),
            })?;

        records_seen += 1;

        limit.as_mut().map(|l| *l -= 1);

        if let Some(output) = output.as_mut() {
            output.write_record(
                &iter::once(woof.decode(e)?.to_string().as_str())
                    .chain(record.iter())
                    .collect::<csv::StringRecord>(),
            )?;
        }
    }

    woof.optimize()?;
    woof.into_tx().commit()?;

    eprintln!("imported {} rows/entities", records_seen);

    Ok(())
}

fn lookup_header_indices<'a>(
    headers: &csv::StringRecord,
    mappings: &[ToAttribute<'a>],
) -> anyhow::Result<Vec<ToPosition<'a>>> {
    mappings
        .iter()
        .map(|to| {
            let ToAttribute { attribute, column } = to;
            headers
                .iter()
                .position(|h| h == column)
                .map(|position| ToPosition { attribute, position })
                .ok_or(column)
        })
        .collect::<Result<Vec<ToPosition<'a>>, _>>()
        .map_err(|column| {
            let headers = headers
                .iter()
                .flat_map(|s| iter::once("\n» ").chain(iter::once(s)))
                .collect::<String>();
            anyhow::anyhow!("failed find column `{}` in headers:{}", column, headers)
        })
}

fn find_or_assert_attributes<'a>(
    woof: &DontWoof,
    mappings: &[ToAttribute<'a>],
) -> anyhow::Result<Vec<owoof::Encoded<owoof::Entity>>> {
    let db_attribute = woof.attribute(woof.encode(AttributeRef::from_static(":db/attribute"))?)?;

    mappings
        .iter()
        .map(|m| {
            let ident = woof.encode(m.attribute)?;
            match woof.attribute(ident).optional()? {
                Some(attribute) => Ok(attribute),
                None => woof
                    .fluent_entity()?
                    .assert(db_attribute, ident)
                    .map(owoof::Encoded::<owoof::Entity>::from),
            }
        })
        .collect::<Result<Vec<_>, _>>()
        .context("encode attribute")
}

/* Try parsing an #entity :attribute or a few other things and fall back to text otherwise. */
fn value_from_csv_text(s: &str) -> owoof::Value {
    use owoof::{Attribute, Entity, Value};
    Option::<Value>::None
        .or_else(|| s.parse::<Entity>().map(Value::from).ok())
        .or_else(|| s.parse::<Attribute>().map(Value::from).ok())
        .or_else(|| s.parse::<i64>().map(Value::from).ok())
        .or_else(|| s.parse::<f64>().map(Value::from).ok())
        .or_else(|| s.parse::<bool>().map(Value::from).ok())
        .or_else(|| s.parse::<uuid::Uuid>().map(Value::from).ok())
        .unwrap_or_else(|| Value::Text(s.to_owned()))
}

fn main() {
    let args_vec = std::env::args().collect::<Vec<String>>();
    let mut args = args_vec.iter().map(String::as_str);

    let exe = args
        .next()
        .map(|s| s.rsplit('/').next().unwrap_or(s))
        .unwrap_or("owoof-csv");

    match parse_args(args) {
        Err(ArgError::Usage) => usage_and_exit(exe),
        Err(err) => {
            eprintln!("oof! {}", err);
            print_traceback(&err);
            eprintln!("");
            usage_and_exit(exe)
        }
        Ok(args) => {
            if let Err(err) = do_import(args) {
                eprintln!("oof! {}", err);
                print_traceback(err.as_ref());
                std::process::exit(1);
            }
        }
    }
}

fn print_traceback(err: &dyn Error) {
    let mut source = err.source();
    while let Some(err) = source {
        eprintln!("   » {}", err);
        source = err.source();
    }
}

fn usage_and_exit(exe: &str) -> ! {
    eprintln!("usage: {} [options...] <mappings...>", exe);
    eprintln!("");
    eprintln!("[options...] is a sequence of any of the following.");
    eprintln!("\t-l, --limit N\timport only N rows, import everything if N is zero");
    eprintln!("\t-n, --dry-run\tcheck csv mappings but don't modify the database");
    eprintln!("\t-o, --output \twrites inserted :db/id to stdout (see below for more detail)");
    eprintln!(
        "\t--db         \t<{}> (defaults to OWOOF_DB environment variable)",
        default_db_path().display()
    );
    eprintln!("\t-i, --input <input.csv> (defaults to stdin)");
    eprintln!("");
    eprintln!("<mappings...> is a sequence that arguments that map csv headers to attributes.");
    eprintln!("\t':pet/name pet_name'\twill read values in the column pet_name and assert them with the :pet/name attribute");
    eprintln!("\t':pet/name'         \twill defaults the column name to `name`, the part after / with non-alphabet characters replaced with _");
    eprintln!("");
    eprintln!("Each row imported is an entity added to the database.  When --output is passed, a copy of the input csv is written to stdout along with a :db/id column that includes the entity id of each row.");
    eprintln!("");
    eprintln!("We try to convert values into an entity, attribute, number, or uuid before giving up and just inserting it as text.");
    std::process::exit(2);
}

fn parse_args<'a, I>(mut args: I) -> Result<Args<'a>, ArgError<'a>>
where
    I: Iterator<Item = &'a str>,
{
    let mut db = Option::<&str>::None;
    let mut input = Option::<&str>::None;
    let mut mappings = Vec::<&str>::default();
    let mut dry_run = false;
    let mut limit = 0usize;
    let mut output = false;
    let mut csv_delimiter = ",";

    while let Some(arg) = args.next() {
        match arg {
            "-h" | "--help" => return Err(ArgError::Usage),
            "-n" | "--dry-run" => dry_run = true,
            "-o" | "--output" => output = true,
            "-d" | "--delimiter" => {
                csv_delimiter = args.next().ok_or(ArgError::NeedsValue(arg))?
            }

            "-l" | "--limit" => {
                limit = args
                    .next()
                    .ok_or(ArgError::NeedsValue(arg))?
                    .parse()
                    .map_err(ArgError::invalid(arg))?
            }
            "--db" => {
                db.replace(args.next().ok_or(ArgError::NeedsValue(arg))?);
            }
            "-i" | "--input" => {
                input.replace(args.next().ok_or(ArgError::NeedsValue(arg))?);
            }
            "--" => {
                mappings.extend(args);
                break;
            }
            _ if arg.starts_with("-") => return Err(ArgError::Unknown(arg)),
            _ => mappings.push(arg),
        }
    }

    Ok(Args {
        output,
        dry_run,
        limit,
        db: db
            .map(|s| {
                s.parse()
                    .context("parse --db")
                    .map_err(ArgError::invalid("--db"))
            })
            .unwrap_or_else(|| Ok(default_db_path()))?,
        input: input
            .map(|s| {
                s.parse()
                    .context("parse input csv")
                    .map_err(ArgError::invalid("--csv"))
            })
            .transpose()?,
        mappings: mappings
            .into_iter()
            .map(|s| parse_mapping(s))
            .collect::<anyhow::Result<Vec<_>>>()
            .map_err(ArgError::invalid("<mappings...>"))?,
        csv_delimiter: {
            (csv_delimiter.len() == 1)
                .then(|| csv_delimiter.bytes().next().unwrap())
                .context("expected a single byte")
                .map_err(ArgError::invalid("--delimiter"))?
        },
    })
}

fn parse_mapping<'a>(s: &'a str) -> anyhow::Result<ToAttribute<'a>> {
    let attribute = s.split_whitespace().next().unwrap_or(s);
    let rest = s[attribute.len()..].trim();

    let attribute: &AttributeRef = attribute.try_into().context("parse attribute")?;

    let column = if rest.is_empty() {
        guess_csv_header_from_attribute(attribute).into()
    } else {
        rest.into()
    };

    Ok(ToAttribute { attribute, column })
}

fn guess_csv_header_from_attribute(attribute: &AttributeRef) -> String {
    let mut s = attribute
        .tail()
        .chars()
        .skip_while(|c| !c.is_alphabetic())
        .map(|c| if c.is_alphabetic() { c } else { '_' })
        .collect::<String>();
    if s.ends_with('_') {
        s = s.trim_end_matches('_').to_owned()
    }
    s
}

#[derive(Debug, thiserror::Error)]
enum ArgError<'a> {
    #[error("゚・✿ヾ╲(。◕‿◕。)╱✿・゚")]
    Usage,
    #[error("unknown argument {}", .0)]
    Unknown(&'a str),
    #[error("expected value for {}", .0)]
    NeedsValue(&'a str),
    #[error("invalid option for {}", .0)]
    Invalid(&'a str, #[source] anyhow::Error),
}

impl<'a> ArgError<'a> {
    fn invalid<I: Into<anyhow::Error>>(arg: &'a str) -> impl Fn(I) -> ArgError<'a> {
        move |e| ArgError::Invalid(arg, e.into())
    }
}

fn default_db_path() -> PathBuf {
    std::env::var_os("OWOOF_DB")
        .map(PathBuf::from)
        .unwrap_or("owoof.sqlite".into())
}

use std::{fs, io};

pub fn open_check_tty(input: Option<&PathBuf>) -> io::Result<Box<dyn io::Read>> {
    match input {
        Some(path) => {
            let file = fs::File::open(path)?;
            Ok(Box::new(io::BufReader::new(file)))
        }
        None => {
            if atty::is(atty::Stream::Stdin) {
                eprintln!("reading csv from stdin (and stdin looks like a tty) good luck!");
            }
            Ok(Box::new(io::stdin()))
        }
    }
}