#!/usr/bin/perl

use constant 'OUTDIR' => '/var/app/orchard/database/art_relations/build/changelog/dml';

use strict;
use warnings;
use open ':std', ':encoding(UTF-8)';

use Git;
use JSON::XS;
use FileHandle;
use Text::CSV::Easy(qw/csv_build csv_parse/);
use Getopt::Long::Descriptive(qw/describe_options/);

use lib '/var/app/orchard/collab/jgetter/perllib';
use Orchard::DB::Connect;

my $cnt = (qq{ SELECT table_rows FROM information_schema.tables WHERE table_schema=? AND table_name=? });
my $dbh = Orchard::DB::Connect->connect('orchrpt');
my $sth = $dbh->prepare(
    qq{
SELECT
	c.table_schema,
	c.table_name,
	c.column_name,
	c.column_type,
	c.data_type
FROM
	information_schema.columns c
WHERE 1
	AND lower(c.table_name) NOT LIKE '%rollback%'
	AND c.column_name LIKE '%period%'
	AND c.column_type LIKE '%tinyint%'
ORDER BY 
	c.table_schema
}
);
$sth->execute();
while ( my $row = $sth->fetchrow_hashref() ) {
    my $schema = $row->{'table_schema'};
    my $table  = $row->{'table_name'};
    my $column = $row->{'column_name'};
    print STDERR "Counting rows from $schema.$table ... \n";
    my $count = ( $dbh->selectcol_arrayref( $cnt, undef, ( $schema, $table ) ) )->[0];
    my $line  = csv_build( ( $schema, $table, $column, $count ) );
    print "$line\n";
}
