File: sqlite_formatter

package info (click to toggle)
cloc 2.06-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 8,064 kB
  • sloc: perl: 30,146; cpp: 1,219; python: 623; ansic: 334; asm: 267; makefile: 244; sh: 186; sql: 144; java: 136; ruby: 111; cs: 104; pascal: 52; lisp: 50; haskell: 35; f90: 35; cobol: 35; objc: 25; php: 22; javascript: 15; fortran: 9; ml: 8; xml: 7; tcl: 2
file content (62 lines) | stat: -rwxr-xr-x 1,814 bytes parent folder | download | duplicates (5)
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
#!/usr/bin/perl
use warnings;
use strict;
#
# Pretty printer for from sqlite3 output.
# Assumes column headers are enabled with
#   .header on
# in ~/.sqliterc
# al.danial@gmail.com  March 2010
#
# This program reads input from STDIN and writes to STDOUT.  A typical
# invocation looks like this:
#   sqlite3 code.db 'select project,file,nCode from t' | sqlite_formatter

my $sqlite_separator = '\|';

my @lines = ();

# ingest all lines
while (<>) {
    next if /^\s*$/;  # skip blank
    next if /^--\s+/; # skip comments
    chomp;
    push @lines, $_;
}

# split on |, the default sqlite3 output separator
my @column_width = ();
my $nCols        =  0;
my @data         = ();  # $data[$row][$column] = SQLite result
for (my $row = 0; $row < scalar @lines; $row++) {
    my @cols = split($sqlite_separator, $lines[$row]);
    $nCols =  scalar @cols;
    for (my $col = 0; $col < $nCols; $col++) {
        $data[$row][$col] = $cols[$col];
        $column_width[$col] = 0 unless defined $column_width[$col];
        $column_width[$col] = length($cols[$col]) if
            $column_width[$col] < length($cols[$col]);
    }
}

# write the results
my $format_str = "";
for (my $row = 0; $row < scalar @data; $row++) {
    # insert a separator row 
    if ($row == 1) {
        for (my $col = 0; $col < $nCols; $col++) {
            print '_' x $column_width[$col], " ";
        }
        print "\n";
    }
    for (my $col = 0; $col < $nCols; $col++) {
        if ($data[$row][$col] =~ /^[-]?\d+$/) {
            # an integer, align to right
            $format_str = "%" . $column_width[$col] . "d ";
        } else {
            $format_str = "%-" . $column_width[$col] . "s ";
        } # could use something for floating point numbers too...
        printf $format_str, $data[$row][$col];
    }
    print "\n";
}