#!/bin/ash
# *********************************************************************
# psqltotable: take PostgreSQL statements and format the corresponding
#	       query output into a NoSQL table.
# Copyright (c) 2004,2006 Carlo Strozzi
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 dated June, 1991.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# 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., 675 Mass Ave, Cambridge, MA 02139, USA.
#
# *********************************************************************
# $Id: psqltotable,v 1.2 2006/03/10 11:26:13 carlo Exp $

# Get local settings and apply defaults.
: ${NOSQL_INSTALL:=/usr/local/nosql}

tab="	"			# Warning: this must be a physical TAB!

while [ $# -gt 0 ]
do
   case $1 in
	-i|--input)	shift;	args="$args -f $1" ;;
	-p|--port)	shift;	args="$args -p $1" ;;
	-H|--host)	shift;	args="$args -h $1" ;;
	-U|--user)	shift;	args="$args -U $1" ;;
	-h|--help)
		grep -v '^#' $NOSQL_INSTALL/help/psqltotable.txt
		exit 0
	;;
	--show-copying)
	     cat $NOSQL_INSTALL/doc/COPYING
	     exit 1
	;;
	--show-warranty)
	     cat $NOSQL_INSTALL/doc/WARRANTY
	     exit 1
	;;
	-*) ;;				# Skip unknown options.
	*) args="$args $1" ;;		# Database name.
   esac
   shift
done

psql -F "$tab" -q -P footer --no-align $args |
  mawk -F '\t' 'NR==1{
	gsub(/[^a-zA-Z0-9_\t]/,"_")
	sub(/^/,"\001");gsub(/\t/,"\t\001")
	print
  }
  NR > 1 {
	for (i=1;i<=NF;i++) {
	    sub(/^ +/,"",$i); sub(/ +$/,"",$i)
	    if (i>1) printf("\t")
	    printf("%s",$i)
	}
	print ""
  }'

# EOF
