#!/usr/bin/env perl

# usage docs at end of file

use strict;
use warnings;
use Data::Stag;

my %relation_type_h = ();
while (@ARGV && $ARGV[0] =~ /^(\-.+)/) {
    my $switch = shift @ARGV;
    if ($switch eq '-t' || $switch eq '--table') {
        while (@ARGV > 1 && $ARGV[0] !~ /^\-/) {
            $relation_type_h{shift @ARGV} = 'table';
        }
    }
    elsif ($switch eq '-v' || $switch eq '--view') {
        while (@ARGV > 1 && $ARGV[0] !~ /^\-/) {
            $relation_type_h{shift @ARGV} = 'view';
        }
    }
    elsif ($switch eq '-h' || $switch eq '--help') {
        print usage();
        exit 0;
    }
    else {
        die "unknown option: $switch";
    }
}
my $f = shift @ARGV;


my $bridge = Data::Stag->parse($f);
my $schema = $bridge->sget('@/schema');

print "CREATE SCHEMA $schema;\n\n";
foreach my $relation ($bridge->get_relation) {
    my $id = $relation->sget('@/id');
    my @indexes = $relation->get_index;
    my $relation_type = 'view';

    # anything with indexes is by default a table
    if (@indexes) {
        $relation_type = "table";
    }

    # command line override
    if ($relation_type_h{'ALL'}) {
        $relation_type = 
          $relation_type_h{'ALL'};
    }
    if ($relation_type_h{$id}) {
        $relation_type = 
          $relation_type_h{$id};
    }
    my $sql = $relation->sget_sql;
    $sql =~ s/^\s+//;
    $sql =~ s/\;\s*//;
    printf("CREATE %s %s.%s AS\n%s;\n",
           uc($relation_type), 
           $schema,
           $id,
           $sql);
    print "$_\n" foreach @indexes;
    print "\n\n";
}

exit 0;

# --

sub usage {
    return <<EOM
create-bridge-sql.pl [OPTIONS] bridge.sql.xml > bridge.sql      
Options:
  -t --table : list of relations to be materialized
  -v --view  : list of relations to be unmaterialized
ALL can be used to specify a default

Examples:
create-bridge-sql.pl -v term term2term godb-bridge.sql.xml > godb-bridge.sql
create-bridge-sql.pl -v ALL -t term godb-bridge.sql.xml > godb-bridge.sql      
create-bridge-sql.pl chado-bridge.sql.xml > chado-bridge.sql      

Description:

This script generates a 'bridge' layer over the main schema. This
allows chado to 'masquerade' as another database, allowing us to use
software written that database schema.

The bridge layer can be views or materialized views (tables), or a
mixture. If materialized views are created, the layer may need
recreated if the underlying data changes (the bridge may not implement
triggers to do this for you)

The bridge layer is created in a seperate schema - the user has
control over the search path; eg in postgresql:

  chado# SET SEARCH PATH TO godb,public;

Bridges typically live in chado/modules/*/bridges/*-bridge.sql.xml

TODO:
Currently the autogenerated bridge can only be applied once.
It would be nice (and easy) to have code to arbitrarily switch
between tables and views at any points in the database lifecycle

Also - finer grained control over indexes
EOM
      ;
}
