gqlitecli 0.14.0

Command Line Interface tool for GQLite
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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
use std::{
  fs,
  io::{self, BufRead},
};

fn print_help()
{
  println!(
    "List of commands:
.help             Show this message.
.once ?FILE?      Save result of next query in FILE.
.open ?FILE?      Close existing connection and reopen FILE.
.repair ?LEVEL?   Show, or set, what opening a database that needs a migration does with a value
                  that cannot be converted: lossless (refuse, the default) or besteffort (replace
                  the value by its original text and list it). The level is used by .open and .connect.
.connect ?URI?    Connect to the database given in uri.
.quit             Exit this program.
.read ?FILE?      Read input from the command line.

To execute a query, write the query and end it with a ';'"
  );
}

/// Longest original value shown in the report, the whole value is in the report of the API.
const REPORT_VALUE_WIDTH: usize = 100;

fn print_migration_report(connection: &gqlitedb::Connection)
{
  let report = connection.migration_report();
  if report.is_empty()
  {
    return;
  }
  println!(
    "The migration replaced {} value(s) that could not be converted by their original text:",
    report.replacements().len()
  );
  for r in report.replacements()
  {
    let original = if r.original.chars().count() > REPORT_VALUE_WIDTH
    {
      format!(
        "{}...",
        r.original
          .chars()
          .take(REPORT_VALUE_WIDTH)
          .collect::<String>()
      )
    }
    else
    {
      r.original.clone()
    };
    println!(
      "  {} in graph '{}', property '{}': {}",
      r.element, r.graph, r.property, original
    );
  }
}

fn print_results(arr: &gqlitedb::Table)
{
  let mut builder = tabled::builder::Builder::new();
  builder.push_record(arr.headers());
  for row in arr.row_iter()
  {
    builder.push_record(row.iter().map(|x| x.to_string()));
  }

  let table = builder
    .build()
    .with(tabled::settings::Style::ascii_rounded())
    .to_string();
  println!("{}", table);
}

fn print_query_result(qr: &gqlitedb::QueryResult)
{
  match qr
  {
    gqlitedb::QueryResult::Table(table) =>
    {
      print_results(table);
    }
    gqlitedb::QueryResult::Array(arr) =>
    {
      for a in arr
      {
        print_query_result(a);
      }
    }
    gqlitedb::QueryResult::Value(val) =>
    {
      println!("{:?}", val);
    }
    gqlitedb::QueryResult::Empty =>
    {
      println!("No results.");
    }
  }
}

//   ____ _ _ ___ _                 _
//  / ___| (_)_ _| |_ ___ _ __ __ _| |_ ___  _ __
// | |   | | || || __/ _ \ '__/ _` | __/ _ \| '__|
// | |___| | || || ||  __/ | | (_| | || (_) | |
//  \____|_|_|___|\__\___|_|  \__,_|\__\___/|_|

trait CliIterator<E>: Iterator<Item = Result<String, E>>
{
  fn add_history_entry(&mut self, _: &String) -> Result<(), E>
  {
    Ok(())
  }
}

impl CliIterator<std::io::Error> for io::Lines<io::BufReader<fs::File>> {}

struct ReadLineIterator<'de>
{
  rl: &'de mut rustyline::DefaultEditor,
  first: bool,
}

impl<'de> Iterator for ReadLineIterator<'de>
{
  type Item = rustyline::Result<String>;
  fn next(&mut self) -> Option<Self::Item>
  {
    let line = if self.first
    {
      self.first = false;
      self.rl.readline("gqlite> ")
    }
    else
    {
      self.rl.readline("   ...> ")
    };

    match line
    {
      Ok(line) => Some(Ok(line)),
      Err(rustyline::error::ReadlineError::Interrupted) => None,
      Err(other_error) => Some(Err(other_error)),
    }
  }
}

impl<'de> CliIterator<rustyline::error::ReadlineError> for ReadLineIterator<'de>
{
  fn add_history_entry(&mut self, h: &String) -> Result<(), rustyline::error::ReadlineError>
  {
    self.rl.add_history_entry(h).map(|_| ())
  }
}

//   ____ _ _
//  / ___| (_)
// | |   | | |
// | |___| | |
//  \____|_|_|

struct Cli
{
  connection: Option<gqlitedb::Connection>,
  repair: gqlitedb::Repair,
}

impl Cli
{
  /// Keep the connection that was opened, or tell why it was not.
  fn use_connection(&mut self, connection: gqlitedb::Result<gqlitedb::Connection>)
  {
    match connection
    {
      Ok(c) =>
      {
        print_migration_report(&c);
        self.connection = Some(c);
      }
      Err(msg) =>
      {
        println!("{:?}", msg);
      }
    }
  }

  fn process_lines<E>(
    &mut self,
    mut it: impl CliIterator<E>,
    exhaust_iterator: bool,
  ) -> Result<bool, E>
  {
    loop
    {
      let line = it.next().transpose()?;
      let line = match line
      {
        Some(line) => line,
        None => return Ok(false),
      };
      if !line.is_empty()
      {
        if line.starts_with(".")
        {
          it.add_history_entry(&line)?;
          let splited_line: Vec<_> = line.split(" ").collect();
          match splited_line[0]
          {
            ".help" =>
            {
              print_help();
            }
            ".open" =>
            {
              if splited_line.len() < 2
              {
                println!("Missing argument to .open");
              }
              else
              {
                let connection_res = gqlitedb::Connection::builder()
                  .path(splited_line[1])
                  .repair(self.repair)
                  .create();
                self.use_connection(connection_res);
              }
            }
            ".repair" =>
            {
              if splited_line.len() < 2
              {
                println!("Repair level: {}", self.repair);
              }
              else
              {
                match splited_line[1].parse()
                {
                  Ok(repair) =>
                  {
                    self.repair = repair;
                  }
                  Err(_) =>
                  {
                    println!(
                      "Unknown repair level '{}', use 'lossless' or 'besteffort'.",
                      splited_line[1]
                    );
                  }
                }
              }
            }
            ".connect" =>
            {
              if splited_line.len() < 2
              {
                println!("Missing argument to .open");
              }
              else
              {
                let connection_res = gqlitedb::Connection::builder()
                  .set_option("url", splited_line[1])
                  .backend(gqlitedb::Backend::Postgres)
                  .repair(self.repair)
                  .create();
                self.use_connection(connection_res);
              }
            }
            ".quit" =>
            {
              return Ok(true);
            }
            ".once" =>
            {
              println!("'.once' is not implemented yet.");
            }
            ".read" =>
            {
              if splited_line.len() < 2
              {
                println!("Missing argument to .read");
              }
              else
              {
                let file = fs::File::open(splited_line[1]);
                match file
                {
                  Ok(file) =>
                  {
                    let lines = io::BufReader::new(file).lines();
                    if let Err(e) = self.process_lines(lines, true)
                    {
                      println!(
                        "Error when processing file '{:?}': {:?}",
                        splited_line[1], e
                      );
                    }
                  }
                  Err(e) =>
                  {
                    println!(
                      "Read file '{:?}' failed with error '{:?}'.",
                      splited_line[1], e
                    );
                  }
                }
              }
            }
            unknown_command =>
            {
              println!(
                "Unknown command '{}', use '.help' to see the list of commands.",
                unknown_command
              );
            }
          }
        }
        else
        {
          let mut query = line;
          while !query.ends_with(";")
          {
            let line = it.next().transpose()?;
            match line
            {
              Some(line) =>
              {
                if line.is_empty()
                {
                  break;
                }
                else
                {
                  query += "\n";
                  query += &line;
                }
              }
              None => break,
            }
          }
          if !query.is_empty()
          {
            it.add_history_entry(&query)?;
            match self.connection
            {
              Some(ref c) =>
              {
                let qr = c.execute_oc_query(query, gqlitedb::ValueMap::new());
                match qr
                {
                  Ok(value) => print_query_result(&value),
                  Err(err) => match err.error()
                  {
                    gqlitedb::Error::CompileTime(ct) =>
                    {
                      println!("Compilation error:\n{}", ct);
                    }
                    _ =>
                    {
                      println!("Query execution failed: {:?}", err);
                    }
                  },
                }
              }
              None =>
              {
                println!("No database connection, use '.open' before executing a query.");
              }
            }
          }
        }
      }
      if !exhaust_iterator
      {
        return Ok(false);
      }
    }
  }
}

fn main_loop(rl: &mut rustyline::DefaultEditor) -> rustyline::Result<()>
{
  let mut cli = Cli {
    connection: None,
    repair: gqlitedb::Repair::default(),
  };

  let mut args = std::env::args();
  args.next(); // remove program name
  let mut filename = None;
  while let Some(arg) = args.next()
  {
    if arg == "--repair"
    {
      let level = args.next().unwrap_or_default();
      match level.parse()
      {
        Ok(repair) =>
        {
          cli.repair = repair;
        }
        Err(_) =>
        {
          println!(
            "Unknown repair level '{}', use 'lossless' or 'besteffort'.",
            level
          );
          return Ok(());
        }
      }
    }
    else
    {
      filename = Some(arg);
    }
  }
  if let Some(filename) = filename
  {
    let connection_res = gqlitedb::Connection::builder()
      .path(filename)
      .repair(cli.repair)
      .create();
    cli.use_connection(connection_res);
  }

  loop
  {
    if cli.process_lines(ReadLineIterator { rl, first: true }, false)?
    {
      return Ok(());
    }
  }
}

fn main() -> rustyline::Result<()>
{
  // `()` can be used when no completer is required
  let mut rl = rustyline::DefaultEditor::new()?;
  let gqlite_history = standard_paths::StandardPaths::new("gqlitecli", "gqlite.org")
    .writable_location(standard_paths::LocationType::ConfigLocation)?
    .join("gqlite_history");
  if let Err(e) = rl.load_history(&gqlite_history)
  {
    println!("Failed to read command line history: {:?}", e);
  }
  println!("Enter '.help' for usage hints.");
  match main_loop(&mut rl)
  {
    Ok(_) =>
    {}
    Err(rustyline::error::ReadlineError::Interrupted) =>
    {
      println!("CTRL-C");
    }
    Err(rustyline::error::ReadlineError::Eof) =>
    {
      println!("CTRL-D");
    }
    Err(err) =>
    {
      println!("Error: {:?}", err);
    }
  }
  rl.save_history(&gqlite_history)?;
  Ok(())
}