#!/usr/bin/awk -f
#
# Convert NCBI createKeys.sql (sybase) to mysql.
#
{
    $0 = gensub("\\[dbo\\]\\.", "", "g", $0);
    $0 = gensub("\\[([^\\[]+)\\]", "\\1", "g", $0);
    $0 = gensub(" WITH NOCHECK", "", "g", $0);
}

# get keys from sql commands like
#  ALTER TABLE AccessionRejectionCriteria ADD 

($1=="ALTER") && ($2=="TABLE") && ($4=="ADD") {
    # beginning of new table
    table = $3;
    inAlter = 1;
}

inConstr && (/REFERENCES/ || /WITH/) {
    # end of constraints
    inConstr = 0;
}

($1=="GO") || ($1=="go") {
    # end of sql command
    inAlter = 0;
    inConstr = 0;
    if (startedAlter) {
        printf ";\n";
    }
    startedAlter = 0;
}

inConstr && /[a-zA-Z_]+/ {
    # found a key in constraints 
    field = gensub(",","","g",$1);
    if (!startedAlter) {
        printf "ALTER TABLE %s ADD INDEX (%s)", table, field;
        startedAlter = 1
    } else {
        printf ", ADD INDEX (%s)", field;
    }
}

inAlter && /CONSTRAINT/ {
    # beginning of constraints
    inConstr = 1;
}

