#!/bin/ash
#
# Selects rows from an rdbtable.
#
# Author: Carlo Strozzi <carlos@linux.it>

RCS_ID='$Id$'

my_name=$(basename $0)

while [ $# -ge 1 ] ; do
  case $1 in
    -h*) cat <<_EOH_

        NoSQL operator: ${my_name}

Usage:  ${my_name}  [options] [expression]

Options:
    -help   Print this help info.
    -n      Strip header from output.

Selects rows from the input rdbtable that satisfy an arbitrary AWK
expression using column names.  Chars that are special to the UNIX
shell must be quoted.

Column names in the AWK expression must be referred to with the construct
'\$P["column_name"]. For example, to select all rows that have the "NAME"
column equal to "Hobbs" the selection expression is:

                    '\$P["NAME"] == "Hobbs"' 

Likewise, more complex expressions can be used:

         '\$P["NAME"] == "Hobbs" && \$P["AGE"] ~ /^2[0-9]\$/'

Ordinary AWK field numbers may be used in expressions, i.e.:

           '\$(3) == "Hobbs" || \$(0) ~ /abcd/', and so on.

Any other valid AWK statement can be used, like 'NR == 5' , etc.

This operator reads an rdbtable via STDIN and writes an rdbtable
via STDOUT.  If no selection expression is provided, then no rows
are selected and only the table is header is written to STDOUT.


$RCS_ID

            ----------------------
NoSQL RDBMS, Copyright (C) 1998 Carlo Strozzi.
This program comes with ABSOLUTELY NO WARRANTY; for details
refer to the GNU General Public License.

You should have received a copy of the GNU General Public License
along with this program;  if not, write to the Free Software
Foundation, Inc., 59 Temple Place Suite 330, Boston, MA 02111-1307
USA.
            ----------------------

_EOH_
        exit 0
        ;;
    -n) shift; no_hdr=1 ;;
    *)  break ;;
  esac
done

awk 'BEGIN{ NULL=""; FS="\t" }
# Table comments.
r == 0 && $0 ~ /^ *#/ { if( "'${no_hdr}'" != 1 ) print; next }
# Column names and positions.
r == 0 {
  while( ++p <= NF ) {
    P[$p] = p
    N[p] = $p
  }
  r++
  if( "'${no_hdr}'" != 1 ) print
  next
}
# Column definitions.
r == 1 { if( "'${no_hdr}'" != 1 ) print; NR=0; r++; next }
'"$1"

exit 0
