#****************************************************************************
#  ##   ##         #####   #####  ##     **       NoSQL RDBMS - fromRDB     *
#  ###  ##        ####### ####### ##     **        $Revision: 2.1 $			*
#  #### ##        ###     ##   ## ##     ************************************
#  #######  ####  #####   ##   ## ##     **      Carlo Strozzi (c) 1998     *
#  ####### ######   ##### ## # ## ##     ************************************
#  ## #### ##  ##     ### ##  ### ##     **           Written by            *
#  ##  ### ###### ####### ######  ###### **          Carlo Strozzi          *
#  ##   ##  ####   #####   #### # ###### **     e-mail: carlos@linux.it     *
#****************************************************************************
#   NoSQL RDBMS, Copyright (C) 1998 Carlo Strozzi.                          *
#   This program comes with ABSOLUTELY NO WARRANTY; for details             *
#   refer to the GNU General Public License.                                *
#****************************************************************************
#
# Converts an RDB table to NoSQL format. RDB header comments are
# NOT preserved during the conversion, as NoSQL tables do not
# support them. However, RDB table comments, column types
# and column documentation fields can optionally be saved in a
# separate file during the conversion process. The file format is
# compatible with NoSQL 'maketable' template files.
# 
# This operator reads an RDB table via STDIN and produces the NoSQL
# version of the same table on STDOUT.
#
########################################################################

BEGIN \
{
  NULL = ""; FS = OFS = "\t"

  # Get optional template file name.

  split( __nosql_args, args, " " )

  if ( args[1] == "-doc" \
	|| args[1] == "-o" || args[1] == "--output" ) tpl_file = args[2]
}

########################################################################
# Main loop
########################################################################

# Table comments.
r == 0 && $0 ~ /^ *#/ \
{
  if ( tpl_file != NULL ) print > tpl_file
  next
}

# Column names and positions.
r == 0 \
{
  print; num_cols = split( $0, c_names )

  # Compute max. column name width.

  for ( i in c_names )
  {
	new_width = length( c_names[i] )
	if ( new_width > max_name ) max_name = new_width
  }
  gsub( /[^\t]/, "-" ); print; r++; next
}

# Column types and documentation fields.
r == 1 { split( $0, c_defs ) ; r++; next }

{ print }

END \
{
  if ( tpl_file != NULL )
  {
	max_i = length( num_cols ) ; i = 0

	while ( c_names[++i] != NULL )
	{
	  j_mode = "%" max_i "s"
	  out_rec = sprintf( j_mode, i ) 
	  j_mode = "%" max_name+4 "s"
	  out_rec = out_rec sprintf( j_mode, c_names[i] ) "  " c_defs[i]
	  print out_rec > tpl_file
	}
  }
}

