#####################################################
# pgbashrc-7.3
#
# This file is copied to '/etc' directory.
# You may copy '/etc/pgbashrc' to '~/.pgbashrc', and
# you can modify your ~/.pgbashrc file. Pgbash tends
# to read ~/.pgbashrc first. If it does not exist, 
# Pgbash tents to read /etc/pgbashrc.
#
#
# Change Logs
# 2001.04.15: Update for PostrgeSQL 7.1
# 2001.06.11: Add OPTION_HEADERTR/HEADERTH/BODYTAG
# 2001.06.11: Add OPTION_INPUTTAG/OPTION_INPUTSIZE
# 2001.06.11: Allow to use ON/OFF as TRUE/FALSE.
# 2001.06.11: Add _lo_list
# 2001.11.25: pgbashrc-2.4 :
#             Update for PostrgeSQL-7.2
# 2002.01.28: Change the order of the help menu.
# 2002.07.17: pgbashrc-2.4a.2 :
#             Change \"...\" to "...".
# 2003.02.08: pgbashrc-7.3 : Update for PostgreSQL-7.3
#             Add 'schema', 'domain', etc.
#
#####################################################

#****************************************************
#	Path             
#****************************************************
#POSTGRES_HOME=/usr/local/pgsql
#export LD_LIBRARY_PATH=$POSTGRES_HOME/lib
#export PATH=$PATH:$POSTGRES_HOME/lib

#****************************************************
# Prompt           
# \u: login user name
# \w: current directory
# \h: host name
#****************************************************
#PS1="pgbash[\u@\h]\w> "
#PS1="[pgbash]\w> "
#PS1="pgbash[\u]\w> "
PS1="pgbash> "

#****************************************************
#	Help Menu
#****************************************************
function _help_menu {
	echo "  ?         : this help"
	echo "  ?u        : list database USERs"
	echo "  ?l        : list DATABASEs"
	echo "  ?d  [rel] : list RELATIONs for table/view/index/sequence"
	echo "  ?d{t|i|v} : list TABLEs/INDEXes/VIEWs"
	echo "  ?dp       : list PERMISSIONs"
	echo "  ?ds       : list SEQUENCEs"
	echo "  ?dA       : list AGGREGATEs"
	echo "  ?dD [obj] : list DESCRIPTIONs for table/type/function/operator"
	echo "  ?dF       : list FUNCTIONs"
	echo "  ?dO       : list OPERATORs"
	echo "  ?dS       : list SYSTEM_TABLEs"
	echo "  ?dT       : list data_TYPEs"
	echo "  ?dM       : list domains"
	echo "  ?m        : show CONNECTION NAMEs"
	echo "  ?o        : show current values of exec_sql_OPTIONs"
	echo "  ?s        : show STATUS after executing SQL"
	echo "  ?v        : show PostgreSQL and pgbash VERSION"
	echo "  E{+|-}    : turn on/off ECHO_QUERY sent to the backend"
	echo "  Q{+|-}    : turn on/off QUIET_MODE for system/sql error messages"
	echo "  L{+|-}    : turn on/off OUTER_FRAME_print"
	echo "  T{+|-}    : turn on/off TOP_header_print"
	echo "  B{+|-}    : turn on/off BOTTOM_count_print"
	echo "  A{+|-}    : turn on/off ALIGNMENT of plain text"
	echo "  X{+|-}    : turn on/off EXPANDED format"
	echo "  H{+|-}    : turn on/off HTML format"
	echo "  S+  [chr] : set SEPARATOR  (e.g. ','  ) or DEFAULT('|')"
	echo "  N+  [str] : set NULL_STRING(e.g. '*N*') or DEFAULT('')"
	echo "  Z+  [str] : set ZERO_STRING(e.g. '*0*') or DEFAULT('')"
	echo "  O+  [str] : set TABLE TAG  (e.g. 'cellpadding=4') or DEFAULT('')"
	echo " _lo_import : lo_import  <'COMMENT'>"
	echo " _lo_export : lo_export  "
	echo " _lo_unlink : lo_unlink  "
	echo " _lo_list   : list LARGE_OBJECTs (?dl)"
	echo "  ??        : help pgbash usage"
	echo "  ??h [SQL] : help SQL(or \"SQL\") syntax or all SQL reserved words"
	echo "  ??e       : help SQLCODE (sql ERROR code)"
	echo "  ??f       : help 'pgbashrc' FUNCTIONs for using a shell script"
	echo "  ??o       : help 'exec_sql' options"
}


#****************************************************
#	Help alias/function
#****************************************************
alias ?='_help_menu        | more'
alias ??='_help_usage      | more'
alias ??h='_help_sql'
alias ??f='_help_functions | more'
alias ??e='_help_sqlcode   | more'
alias ??o='help exec_sql   | more'

alias ?o='_show_exec_sql_option | more'
alias ?v=_show_version
alias ?s=_show_sqlcode
alias ?m=_show_connection

alias ?u='_list_users          | more'
alias ?du='_list_users         | more'
alias ?l='_list_databases      | more'
alias ?dt='_list_tables        | more'
alias ?di='_list_indexes       | more'
alias ?ds='_list_sequences     | more'
alias ?dv='_list_views         | more'
alias ?dp='_list_permissions   | more'
alias ?dl='_list_lobjects      | more'
alias ?dA='_list_aggregates    | more'
alias ?dF='_list_functions     | more'
alias ?dO='_list_operators     | more'
alias ?dS='_list_systables     | more'
alias ?dT='_list_types         | more'
alias ?dM='_list_domains       | more'

function ?d {
	case "$#" in
	0 ) _list_relations  | more   ;;
	* ) _list_relation   $1       ;;
	esac
}
function ?dD {
	case "$#" in
	0 ) _list_descriptions | more  ;;
	* ) _list_description  $1      ;;
	esac
}

alias E+='set OPTION_ECHO=TRUE;'
alias E-='set OPTION_ECHO=FALSE;'
alias Q+='set OPTION_QUIET=TRUE;'
alias Q-='set OPTION_QUIET=FALSE;'
alias L+='set OPTION_FRAME=TRUE;'
alias L-='set OPTION_FRAME=FALSE;'
alias X+='set OPTION_EXPANDED=TRUE;'
alias X-='set OPTION_EXPANDED=FALSE;'
alias H+='set OPTION_HTML=TRUE;'
alias H-='set OPTION_HTML=FALSE;'
alias A+='set OPTION_ALIGNMENT=TRUE;'
alias A-='set OPTION_ALIGNMENT=FALSE;'
alias T+='set OPTION_HEADER=TRUE;'
alias T-='set OPTION_HEADER=FALSE;'
alias B+='set OPTION_BOTTOM=TRUE;'
alias B-='set OPTION_BOTTOM=FALSE;'
function S+ {
	case "$#" in
 	0 ) exec_sql "set OPTION_SEPARATOR;"        ;;
	* ) exec_sql "set OPTION_SEPARATOR='$1';"   ;;
	esac
}
function N+ {
	case "$#" in
	0 ) exec_sql "set OPTION_NULLSTRING;"       ;;
	* ) exec_sql "set OPTION_NULLSTRING='$1';"  ;;
	esac
}
function Z+ {
	case "$#" in
	0 ) exec_sql "set OPTION_ZEROSTRING;"       ;;
	* ) exec_sql "set OPTION_ZEROSTRING='$1';"  ;;
	esac
}
function O+ {
	case "$#" in
	0 ) exec_sql "set OPTION_TABLETAG;"       ;;
	* ) exec_sql "set OPTION_TABLETAG='$1';"  ;;
	esac
}


#****************************************************
#	Help 
#****************************************************

#----- Usage --------------------------
function _help_usage {
	echo "# Usage:"
	echo "  1. Type 'connect to DB [as CONNECT_NAME] [user UID [PASSWD|NULL]];' , or"
	echo "          'connect to DEFAULT' is automatically issued before executing SQL."
	echo "     ex)"
	echo "     connect to testdb as db1 user admin xxxx;"
	echo "     connect to testdb as db2 user admin NULL; <-- password is unnecessary" 
	echo "     connect to testdb as db3 user admin; <-- password prompt is displayed"
	echo "     connect to testdb2;  <--- CONNECT_NAME becomes 'testdb'"
	echo "     connect to DEFAULT;  <--- DB/CONNECT_NAME/UID is login-userid"
	echo "     connect to db1@db.xxx.co.jp; <-- DB server name is 'db.xxx.co.jp'."
	echo " "
	echo "  2. Type 'set connection CONNECT_NAME;' to change the connection. , or"
	echo "          CURRENT connection is used."
	echo "     ex)"
	echo "     connect to db1 user admin xxxxx;"
	echo "     connect to db2;"
	echo "     set connection db1;"
	echo "     select * from test;"
	echo " "
	echo "  3. Type '[timespec] SQL; [pipeline][redirection][&]' to execute SQL."
	echo "     ex)"
	echo "     select * from test limit 300;"
	echo "     time select * from test; &> /tmp/test.dat"
	echo "     select * from test; | more"
	echo "     select * from test; &> /tmp/test.dat &"
	echo " "
	echo "  4. Type 'disconnect [CONNECT_NAME | ALL];'"
	echo "    (Connections are automatically closed when Pgbash is terminated.)"
	echo "     ex)"
	echo "     disconnect db1;"
	echo "     disconnect all;"
	echo " "
#	echo "# Usage of shell script"
#	echo " "
#	echo "  1. Shell script"
#	echo " "
#	echo "     #!/usr/local/bin/pgbash"
#	echo "     source ./pgbashrc"
#	echo "     #"
#	echo "     connect to testdb user admin NULL;"
#	echo "     _list_relation       <--- 'pgbashrc' is necessary"
#	echo "     select * from test;"
#	echo " "
#	echo "  2. CGI shell script"
#	echo "     #!/usr/local/bin/pgbash"
#	echo "     echo "Content-type: text/html" 
#	echo "     set EXEC_SQL_OPTION CGI; "
#	echo "     #"
#	echo "     connect to testdb user admin NULL;"
#	echo "     select * from test where aa=\"\$value\";"
#	echo " "

}

#----- Help sql commands -------------
function _help_sql {
	case "$#" in
	0 ) exec_sql -h help   ;;
	* ) exec_sql -h "$*"   ;;
	esac
}

#----- Help pgbash functions ---------
function _help_sqlcode {

	echo "# SQLCODE"
	echo "  ex)"
	echo "  begin;"
	echo "  declare cur cursor for select code,name from test order by code;"
	echo "  while (( SQLCODE == SQL_OK )); do"
	echo "     fetch in cur into :code, :name;"
	echo "     if (( SQLCODE < 0 || SQLCODE == SQL_NOT_FOUND)); then"
	echo "        break"
	echo "     else"
	echo "         echo \"code=\$code  name=\$name\"  "
	echo "     fi"
	echo "  done"
	echo "  end;"
	echo ""
	echo "+------------------------+-------------------------------------------+--------"
        echo "|      Value Name        |               Comment                     | Value"
	echo "+------------------------+-------------------------------------------+--------"
	echo "| SQL_OK                 | normal end.                               |$SQL_OK"
	echo "| SQL_NOT_FOUND          | EOF(End Of File).                         |$SQL_NOT_FOUND"
	echo "| SQL_SYSTEM_ERROR       | system error.                             |$SQL_SYSTEM_ERROR"
	echo "| SQL_TOO_MANY_ARGUMENTS | too many arguments in fetch_stmt.         |$SQL_TOO_MANY_ARGUMENTS"
	echo "| SQL_TOO_FEW_ARGUMENTS  | too few  arguments in fetch_stmt.         |$SQL_TOO_FEW_ARGUMENTS"
	echo "| SQL_CONNECT_ERROR      | database connection error.                |$SQL_CONNECT_ERROR"   
	echo "| SQL_INVALID_STMT       | invalid statements.                       |$SQL_INVALID_STMT"                
	echo "| SQL_READONLY_SHELLVAR  | can not set read-only shell variable.     |$SQL_READONLY_SHELLVAR"
	echo "| SQL_DB_NOT_OPEN        | database not open.                        |$SQL_DB_NOT_OPEN"
	echo "| SQL_CNAME_NOT_FOUND    | connect-name not found.                   |$SQL_CNAME_NOT_FOUND"
	echo "| SQL_CNAME_ALREADY_USE  | connect-name already exist.               |$SQL_CNAME_ALREADY_USE"
	echo "| SQL_INVALID_COMMAND    | invalid command.                          |$SQL_INVALID_COMMAND"
	echo "| SQL_INVALID_DATA       | invalid data.                             |$SQL_INVALID_DATA"
	echo "| SQL_BAD_RESPONSE       | bad response(backend maybe died).         |$SQL_BAD_RESPONSE"
	echo "| SQL_EMPTY_QUERY        | empty query (backend lost query).         |$SQL_EMPTY_QUERY"
	echo "| SQL_CONNECTION_BAD     | connection bad(disconnect backend)        |$SQL_FATAL_ERROR"
	echo "| SQL_FATAL_ERROR        | query fatal error   (SQL error on backend)|$SQL_FATAL_ERROR"
	echo "| SQL_NONFATAL_ERROR     | query nonfatal error(SQL error on backend)|$SQL_NONFATAL_ERROR"
	echo "| SQL_NULL               | indicator is NULL.                        |$SQL_NULL"
	echo "+------------------------+-------------------------------------------+--------"
}

#----- Help pgbash functions ---------
function _help_functions {

	echo "# 'pgbashrc' functions for using a shell script"
	echo "  ex)"
	echo "  #!/usr/local/bin/pgbash"
	echo "  source ~/.pgbashrc"
	echo "  _list_relations"
	echo "  _list_relation table_name"
        echo ""
	echo "+-------------------+-----------+---------------------------------------"
	echo "|  Function name    |Interactive|               Comment"
	echo "+-------------------+-----------+---------------------------------------"
	echo "| _list_users       | ?u        | list database USERs"
	echo "| _list_databases   | ?l        | list DATABASEs"
	echo "| _list_relations   | ?d        | list RELATIONs"
	echo "| _list_relation    | ?d  [rel] | list RELATION for tbl/view/idx/seq"
	echo "| _list_tables      | ?dt       | list TABLEs"
	echo "| _list_indexes     | ?di       | list INDEXes"
	echo "| _list_views       | ?dv       | list VIEWs"
	echo "| _list_sequences   | ?ds       | list SEQUENCEs"
	echo "| _list_permissions | ?dp       | list PERMISSIONs"
	echo "| _list_aggregates  | ?dA       | list AGGREGATEs"
	echo "| _list_descriptions| ?dD       | list DESCRIPTIONs"
	echo "| _list_description | ?dD [obj] | list DESCRIPTION for tbl/typ/func/ope"
	echo "| _list_functions   | ?dF       | list FUNCTIONs"
	echo "| _list_operators   | ?dO       | list OPERATORs"
	echo "| _list_systables   | ?dS       | list SYSTEM_TABLEs"
	echo "| _list_types       | ?dT       | list data_TYPEs"
	echo "| _list_domains     | ?dM       | list domains"
	echo "| _lo_import        |_lo_import | large_object_import"
	echo "| _lo_export        |_lo_export | large_object_export"
	echo "| _lo_unlink        |_lo_unlink | large_object_unlink"
	echo "| _lo_list          |_lo_list   | list large_objects"
	echo "+-------------------+-----------+---------------------------------------"
}

#****************************************************
#	Show status
#****************************************************

#----- Help exec_sql options ---------
function _show_exec_sql_option {

	echo "# EXEC_SQL_OPTION"
	echo "  Usage:"
	echo "  set EXEC_SQL_OPTION DEFAULT ;   --- reset DEFAULT"
	echo "  set EXEC_SQL_OPTION CGI ;       --- set CGI mode"
	echo "  set [=value] ;"
	echo " "
	echo "  ex)"
	echo "  SET OPTION_ECHO; or SET OPTION_ECHO=ON; or SET OPTION_ECHO=TRUE;"
	echo "  SET OPTION_BOTTOM=OFF; or SET OPTION_BOTTOM=FALSE;"
	echo "  set OPTION_SEPARATOR=',';"
	echo "  set OPTION_NULLSTRING=\"\\N\";"
	echo " "
	echo "+-------------------+-------------------------+-------+---------------"
	echo "|      |      Comment            |DEFAULT| Current Value "
	echo "+-------------------+-------------------------+-------+---------------"
	echo "| OPTION_ECHO       | turn on/off ECHO query  | OFF   | $OPTION_ECHO"
	echo "| OPTION_QUIET      | turn on/off QUIET mode  | OFF   | $OPTION_QUIET"
	echo "| OPTION_HEADER     | turn on/off TOP_header  | ON    | $OPTION_HEADER"
	echo "| OPTION_BOTTOM     | turn on/off BOTTOM_print| ON    | $OPTION_BOTTOM"
	echo "| OPTION_ALIGNMENT  | turn on/off ALIGNMENT   | ON    | $OPTION_ALIGNMENT"
	echo "| OPTION_FRAME      | turn on/off OUTER_FRAME | OFF   | $OPTION_FRAME"
	echo "| OPTION_EXPANDED   | turn on/off EXPANDED    | OFF   | $OPTION_EXPANDED"
	echo "| OPTION_SEPARATOR  | set SEPARATOR character | ''    | '$OPTION_SEPARATOR'"
	echo "| OPTION_NULLSTRING | set NULL string         | \"\"    | \"$OPTION_NULLSTRING\" "
	echo "| OPTION_ZEROSTRING | set ZERO string         | \"\"    | \"$OPTION_ZEROSTRING\" "
	echo "| OPTION_CAPTION    | set CAPTION             | \"\"    | \"$OPTION_CAPTION\" "
	echo "+-------------------+-------------------------+-------+---------------"
	echo ""
	echo "[ CGI_mode / HTML_output_mode ]"
	echo "+-------------------+-------------------------+-------+---------------"
	echo "|      |      Comment            |DEFAULT| Current Value "
	echo "+-------------------+-------------------------+-------+---------------"
	echo "| OPTION_HTML       | turn on/off HTML mode   | OFF   | $OPTION_HTML"
	echo "| OPTION_TABLETAG   | set HTML table tag      | \"\"    | \"$OPTION_TABLETAG\" "
	echo "| OPTION_HEADERTR   | set HTML header     | \"\"    | \"$OPTION_HEADERTR\" "
	echo "| OPTION_HEADERTH   | set HTML header     | \"\"    | \"$OPTION_HEADERTH\" "
	echo "| OPTION_BODYTAG    | set HTML body  tag  | \"\"    | \"$OPTION_BODYTAG\" "
	echo "| OPTION_INPUTTAG   | turn on/off INPUT tag   | OFF   | $OPTION_INPUTTAG"
	echo "| OPTION_INPUTSIZE  | set HTML input tag SIZE | \"\"    | \"$OPTION_INPUTSIZE\""
	echo "+-------------------+-------------------------+-------+---------------"
}

#------ show PostgreSQL and PGBASH VERSION ---------
function _show_version {		 

	OPTION_WORK=$OPTION_QUIET

	set OPTION_QUIET;
	begin; 
	declare cur cursor for select version();
	fetch in cur into :version;
	end;
	set OPTION_QUIET=$OPTION_WORK;

	echo "# $version"
	exec_sql -v
} 

#------ show SQL status -------------
function _show_sqlcode { # status after SQL execution
	exec_sql -s
}

#------ show all the CONNECTIONs ---------
function _show_connection { 
	exec_sql -Lm 
} 


#****************************************************
#	List Database Informations
#****************************************************

#------ list all the USERs ---------------
function _list_users { 		
	echo "[ List of user names ]"
	
        VER1=${POSTGRESQL_VERSION:0:1}
	VER2=${POSTGRESQL_VERSION:2:1}

    if (( VER1 >= 7 && VER2 >= 3 )); then

	#--- PostgreSQL-7.3 -------------#
	SELECT u.usename AS "User name", u.usesysid AS "User ID",
		CASE WHEN u.usesuper AND u.usecreatedb THEN 
			CAST('superuser, create database' AS pg_catalog.text)
			WHEN u.usesuper THEN CAST('superuser' AS pg_catalog.text)
			WHEN u.usecreatedb THEN CAST('create database' AS pg_catalog.text)
			ELSE CAST('' AS pg_catalog.text)
		END AS "Attributes"
	FROM pg_catalog.pg_user u
	ORDER BY 1;

    elif (( VER1 >= 7 && VER2 >= 0 )); then

	#--- PostgreSQL-7.2, 7.1, 7.0 ---#
	SELECT	usename AS "Username", 
		CASE	WHEN usesuper THEN CAST('yes' as text) 
			ELSE CAST('no' as text)
		END AS "SupperUser",
		CASE	WHEN usecreatedb THEN CAST('yes' as text) 
			ELSE CAST('no' as text)
		END AS "CreateDB"
	FROM pg_user;

    else
	#--- PostgreSQL-6.5 ---#
	SELECT usename AS "Username", usesuper AS "SupperUser",
		usecreatedb AS "CreateDB" 
	FROM pg_user;
    fi

    if (($SQLCODE == 0 && $SQLNTUPLE == 0)); then
	echo "# Did not find any user names."
    fi
} 

#----- List of all databases ---------
function _list_databases {
	echo "[ List of databases ]"

        VER1=${POSTGRESQL_VERSION:0:1}
	VER2=${POSTGRESQL_VERSION:2:1}

    if (( VER1 >= 7 && VER2 >= 1 )); then

	#--- PostgreSQL-7.2, 7.1 ---#
	SELECT d.datname as "Name", u.usename as "Owner",
		pg_encoding_to_char(d.encoding) as "Encoding"
	FROM pg_database d LEFT JOIN pg_user u ON d.datdba = u.usesysid
	ORDER BY 1;

    elif (( VER1 == 7 && VER2 == 0 )); then

	#--- PostgreSQL-7.0 ---#
	SELECT pg_database.datname as "Database", pg_user.usename as "Owner",
		pg_encoding_to_char(pg_database.encoding) as "Encoding"
	FROM pg_database, pg_user
	WHERE pg_database.datdba = pg_user.usesysid
	UNION
	SELECT pg_database.datname as "Database", NULL as "Owner",
		pg_encoding_to_char(pg_database.encoding) as "Encoding"
	FROM pg_database
	WHERE pg_database.datdba NOT IN (SELECT usesysid FROM pg_user)
	ORDER BY "Database";

    else

	#--- PostgreSQL-6.5 ---#
	SELECT pg_database.datname as "Database", pg_user.usename as "Owner",
		pg_database.encoding as "Encoding"
	FROM pg_database, pg_user
	WHERE pg_database.datdba = pg_user.usesysid
	UNION
	SELECT pg_database.datname as "Database", NULL as "Owner",
		pg_database.encoding as "Encoding"
	FROM pg_database
	WHERE pg_database.datdba NOT IN (SELECT usesysid FROM pg_user)
	ORDER BY "Database";

    fi

    if (($SQLCODE == 0 && $SQLNTUPLE == 0)); then
	echo "# Did not find any databases."
    fi
}
#----- List of relations ----------
function _list_relations { 
	echo "[ List of relations ]"

        VER1=${POSTGRESQL_VERSION:0:1}
	VER2=${POSTGRESQL_VERSION:2:1}

   if (( VER1 >= 7 && VER2 >= 3 )); then

	#--- PostgreSQL-7.3 --------#
	SELECT n.nspname as "Schema",
		c.relname as "Name",
		CASE c.relkind  WHEN 'r' THEN 'table' 
				WHEN 'v' THEN 'view' 
				WHEN 'i' THEN 'index' 
				WHEN 'S' THEN 'sequence' 
				WHEN 's' THEN 'special' 
		END as "Type",
		u.usename as "Owner"
	FROM pg_catalog.pg_class c 
	LEFT JOIN pg_catalog.pg_user u ON u.usesysid = c.relowner
	LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
	WHERE c.relkind IN ('r','v','S','') AND 
	n.nspname NOT IN ('pg_catalog', 'pg_toast') AND 
	pg_catalog.pg_table_is_visible(c.oid)
	ORDER BY 1,2;

   elif (( VER1 >= 7 && VER2 >= 1 )); then

	#--- PostgreSQL-7.2, 7.1 ---#
        SELECT	c.relname as "Name",
		CASE c.relkind	WHEN 'r' THEN 'table' 
	  			WHEN 'v' THEN 'view' 
				WHEN 'i' THEN 'index' 
				WHEN 'S' THEN 'sequence' 
				WHEN 's' THEN 'special' 
		END as "Type", 
		u.usename as "Owner"
	FROM pg_class c LEFT JOIN pg_user u ON c.relowner = u.usesysid
	WHERE c.relkind IN ('r','v','S','') AND c.relname !~ '^pg_'
	ORDER BY 1;

    else

	#--- PostgreSQL-7.0, 6.5 ---#
	SELECT c.relname as "Name", 'table'::text as "Type", u.usename as "Owner"
	FROM pg_class c, pg_user u
	WHERE c.relowner = u.usesysid AND c.relkind = 'r'
		AND not exists (select 1 from pg_views where viewname = c.relname)
		AND c.relname !~ '^pg_'
	UNION
	SELECT c.relname as "Name", 'table'::text as "Type", NULL as "Owner"
	FROM pg_class c
	WHERE c.relkind = 'r'
		AND not exists (select 1 from pg_views where viewname = c.relname)
		AND not exists (select 1 from pg_user where usesysid = c.relowner)
		AND c.relname !~ '^pg_' 
	UNION 
	SELECT c.relname as "Name", 'view'::text as "Type", u.usename as "Owner"
	FROM pg_class c, pg_user u
	WHERE c.relowner = u.usesysid AND c.relkind = 'r'
		AND exists (select 1 from pg_views where viewname = c.relname)
		AND c.relname !~ '^pg_'
	UNION
	SELECT c.relname as "Name", 'view'::text as "Type", NULL as "Owner"
	FROM pg_class c
	WHERE c.relkind = 'r'
		AND exists (select 1 from pg_views where viewname = c.relname)
		AND not exists (select 1 from pg_user where usesysid = c.relowner)
		AND c.relname !~ '^pg_' 
	UNION 
	SELECT c.relname as "Name",
		(CASE WHEN relkind = 'S' THEN 'sequence'::text ELSE 'index'::text END) as "Type",
		u.usename as "Owner"
	FROM pg_class c, pg_user u
	WHERE c.relowner = u.usesysid AND relkind in ('S') AND c.relname !~ '^pg_'
	UNION
	SELECT c.relname as "Name",
		(CASE WHEN relkind = 'S' THEN 'sequence'::text ELSE 'index'::text END) as "Type",
		NULL as "Owner"
	FROM pg_class c
	WHERE not exists (select 1 from pg_user where usesysid = c.relowner) AND relkind in ('S')
		AND c.relname !~ '^pg_' 
	ORDER BY "Name";

    fi

	if (($SQLCODE == 0 && $SQLNTUPLE == 0)); then
		echo "# Did not find any relations."
	fi
}
#----- List of Data Definision ----------
function _list_relation  {  # $1 : table/index/sequence name

	if (( $# == 0 )); then
		echo "# Relation name please!"
		return;
	fi

	echo "[ \"$1\" data definitions ]"

        VER1=${POSTGRESQL_VERSION:0:1}
	VER2=${POSTGRESQL_VERSION:2:1}

   if (( VER1 >= 7 && VER2 >= 1 )); then

	#--- PostgreSQL-7.2, 7.1 ---#
	SELECT	a.attname as "Attribute", 
		format_type(a.atttypid, a.atttypmod) as "Type", 
		CASE  	WHEN a.attnotnull='t' THEN 'not null' 
			ELSE NULL 
		END as "NotNull",
		CASE	WHEN a.atthasdef='t' THEN (
			SELECT substring(d.adsrc for 128) 
			FROM pg_attrdef d, pg_class c
			WHERE c.relname = '$1' AND c.oid = d.adrelid AND 
			d.adnum = a.attnum)
			ELSE NULL
		END as "Default"
	FROM pg_class c, pg_attribute a
	WHERE c.relname = '$1' AND a.attnum > 0 AND a.attrelid = c.oid
        ORDER BY a.attnum;

   else

	#--- PostgreSQL-7.0, 6.5 ---#
	SELECT  a.attname as "Attribute",
		t.typname as "Type",
		a.attnotnull as "NotNull"
	FROM pg_class c, pg_attribute a, pg_type t
	WHERE c.relname = '$1' AND a.attnum > 0 AND a.attrelid = c.oid AND 
		a.atttypid = t.oid
	ORDER BY a.attnum;
    fi

    if (( SQLCODE < 0 )); then
	return;
    fi
    if (($SQLCODE == 0 && $SQLNTUPLE == 0)); then
	echo "# Did not find the relation named \"$1\"."
	return;
    fi

 	exec_sql -qXTB -S ':' "
	SELECT c2.relname as \"PrimaryKey\"
	FROM pg_class c, pg_class c2, pg_index i
	WHERE c.relname = '$1' AND c.oid = i.indrelid AND i.indexrelid = c2.oid
		AND i.indisprimary AND i.indisunique ORDER BY c2.relname
	"
 	exec_sql -qXTB -S ':' "
	SELECT c2.relname as \"Unique Key\"
	FROM pg_class c, pg_class c2, pg_index i
	WHERE c.relname = '$1' AND c.oid = i.indrelid AND i.indexrelid = c2.oid
		AND NOT i.indisprimary AND i.indisunique ORDER BY c2.relname
	"
 	exec_sql -qXTB -S ':' "
	SELECT c2.relname as \"Index  Key\"
	FROM pg_class c, pg_class c2, pg_index i
	WHERE c.relname = '$1' AND c.oid = i.indrelid AND i.indexrelid = c2.oid
		AND NOT i.indisunique ORDER BY c2.relname;
	"
 	exec_sql -qXTB -S ':' "
	SELECT rcname as \"Attribute \", rcsrc as \"Constrain \"
	FROM pg_relcheck r, pg_class c
	WHERE c.relname='$1' AND c.oid = r.rcrelid
	"
 	exec_sql -qXTB -S ':' "
	SELECT r.rulename as \"Rule      \"
	FROM pg_rewrite r, pg_class c
	WHERE c.relname='$1' AND c.oid = r.ev_class
	"
 	exec_sql -qXTB -S ':' "
	SELECT t.tgname   as \"Trigger   \"
	FROM pg_trigger t, pg_class c
	WHERE c.relname='$1' AND c.oid = t.tgrelid
	"
#
}
#------ List of Tables -----
function _list_tables { 
	echo "[ List of tables ]"

        VER1=${POSTGRESQL_VERSION:0:1}
	VER2=${POSTGRESQL_VERSION:2:1}

   if (( VER1 >= 7 && VER2 >= 3 )); then

	#--- PostgreSQL-7.3 --------#
	SELECT n.nspname as "Schema",
		c.relname as "Name",
		CASE c.relkind  WHEN 'r' THEN 'table' 
				WHEN 'v' THEN 'view' 
				WHEN 'i' THEN 'index' 
				WHEN 'S' THEN 'sequence' 
				WHEN 's' THEN 'special' 
		END as "Type",
		u.usename as "Owner"
	FROM pg_catalog.pg_class c
	LEFT JOIN pg_catalog.pg_user u ON u.usesysid = c.relowner
	LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
	WHERE   c.relkind IN ('r','') AND 
		n.nspname NOT IN ('pg_catalog', 'pg_toast') AND 
		pg_catalog.pg_table_is_visible(c.oid)
	ORDER BY 1,2;

   elif (( VER1 >= 7 && VER2 >= 1 )); then

	#--- PostgreSQL-7.2, 7.1 ---#
	SELECT	c.relname as "Name", 
		CASE c.relkind	WHEN 'r' THEN 'table' 
				WHEN 'v' THEN 'view' 
				WHEN 'i' THEN 'index' 
				WHEN 'S' THEN 'sequence' 
				WHEN 's' THEN 'special' 
		END as "Type", 
		u.usename as "Owner"
	FROM pg_class c LEFT JOIN pg_user u ON c.relowner = u.usesysid
	WHERE c.relkind IN ('r','') AND c.relname !~ '^pg_'
	ORDER BY 1;

    else

	#--- PostgreSQL-7.0, 6.5 ---#
	SELECT c.relname as "Name", 'table'::text as "Type", u.usename as "Owner"
	FROM pg_class c, pg_user u
	WHERE c.relowner = u.usesysid AND c.relkind = 'r'
		AND not exists (select 1 from pg_views where viewname = c.relname)
		AND c.relname !~ '^pg_'
	UNION
	SELECT c.relname as "Name", 'table'::text as "Type", NULL as "Owner"
	FROM pg_class c
	WHERE c.relkind = 'r'
		AND not exists (select 1 from pg_views where viewname = c.relname)
		AND not exists (select 1 from pg_user where usesysid = c.relowner)
		AND c.relname !~ '^pg_' 
	ORDER BY "Name";

    fi

    if (($SQLCODE == 0 && $SQLNTUPLE == 0)); then
	echo "# Did not find any tables."
    fi
}  
#----- List of indexes ------
function _list_indexes { 
	echo "[ List of indexes ]"

        VER1=${POSTGRESQL_VERSION:0:1}
	VER2=${POSTGRESQL_VERSION:2:1}

   if (( VER1 >= 7 && VER2 >= 3 )); then

	#--- PostgreSQL-7.3 --------#
	SELECT n.nspname as "Schema", 
		c.relname as "Name",
		CASE c.relkind  WHEN 'r' THEN 'table' 
				WHEN 'v' THEN 'view' 
				WHEN 'i' THEN 'index' 
				WHEN 'S' THEN 'sequence' 
				WHEN 's' THEN 'special' 
		END as "Type",
		u.usename as "Owner", c2.relname as "Table"
	FROM pg_catalog.pg_class c
	JOIN pg_catalog.pg_index i ON i.indexrelid = c.oid
	JOIN pg_catalog.pg_class c2 ON i.indrelid = c2.oid
	LEFT JOIN pg_catalog.pg_user u ON u.usesysid = c.relowner
	LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
	WHERE c.relkind IN ('i','') AND 
		n.nspname NOT IN ('pg_catalog', 'pg_toast') AND 
		pg_catalog.pg_table_is_visible(c.oid)
	ORDER BY 1,2;

   elif (( VER1 >= 7 && VER2 >= 1 )); then

	#--- PostgreSQL-7.2, 7.1 ---#
	SELECT	c.relname as "Name",
		CASE c.relkind	WHEN 'r' THEN 'table' 
				WHEN 'v' THEN 'view' 
				WHEN 'i' THEN 'index' 
				WHEN 'S' THEN 'sequence' 
				WHEN 's' THEN 'special' 
		END as "Type", 
		u.usename as "Owner"
	FROM pg_class c LEFT JOIN pg_user u ON c.relowner = u.usesysid
	WHERE c.relkind IN ('i','') AND c.relname !~ '^pg_'
	ORDER BY 1;

   else

	#--- PostgreSQL-7.0, 6.5 ---#
	SELECT c.relname as "Name",
	(CASE WHEN relkind = 'S' THEN 'sequence'::text ELSE 'index'::text END) as "Type",
		u.usename as "Owner"
	FROM pg_class c, pg_user u
	WHERE c.relowner = u.usesysid AND relkind in ('i') AND c.relname !~ '^pg_'
	UNION
	SELECT c.relname as "Name",
	(CASE WHEN relkind = 'S' THEN 'sequence'::text ELSE 'index'::text END) as "Type",
		NULL as "Owner"
	FROM pg_class c
	WHERE not exists (select 1 from pg_user where usesysid = c.relowner) 
	       AND relkind in ('i') AND c.relname !~ '^pg_' 
	ORDER BY "Name";
    fi

    if (($SQLCODE == 0 && $SQLNTUPLE == 0)); then
	echo "# Did not find any indexes."
    fi
}  
#----- List of Seqences -----
function _list_sequences { 
	echo "[ List of sequences ]"

        VER1=${POSTGRESQL_VERSION:0:1}
	VER2=${POSTGRESQL_VERSION:2:1}

   if (( VER1 >= 7 && VER2 >= 3 )); then

	#--- PostgreSQL-7.3 --------\#
	SELECT n.nspname as "Schema",
		c.relname as "Name",
		CASE c.relkind  WHEN 'r' THEN 'table' 
				WHEN 'v' THEN 'view' 
				WHEN 'i' THEN 'index' 
				WHEN 'S' THEN 'sequence' 
				WHEN 's' THEN 'special' 
		END as "Type",
	      u.usename as "Owner"
	FROM pg_catalog.pg_class c
	LEFT JOIN pg_catalog.pg_user u ON u.usesysid = c.relowner
	LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
	WHERE c.relkind IN ('S','') AND 
		n.nspname NOT IN ('pg_catalog', 'pg_toast') AND 
		pg_catalog.pg_table_is_visible(c.oid)
	ORDER BY 1,2;

   elif (( VER1 >= 7 && VER2 >= 1 )); then

	#--- PostgreSQL-7.2, 7.1 ---\#
	SELECT	c.relname as "Name",
		CASE c.relkind	WHEN 'r' THEN 'table' 
				WHEN 'v' THEN 'view' 
				WHEN 'i' THEN 'index'
				WHEN 'S' THEN 'sequence' 
				WHEN 's' THEN 'special' 
		END as "Type", 
		u.usename as "Owner"
	FROM pg_class c LEFT JOIN pg_user u ON c.relowner = u.usesysid
	WHERE c.relkind IN ('S','') AND c.relname !~ '^pg_'
	ORDER BY 1;

    else

	#--- PostgreSQL-7.0, 6.5 ---#
	SELECT c.relname as "Name",
	(CASE WHEN relkind = 'S' THEN 'sequence'::text ELSE 'index'::text END) as "Type",
		u.usename as "Owner"
	FROM pg_class c, pg_user u
	WHERE c.relowner = u.usesysid AND relkind in ('S')
		AND c.relname !~ '^pg_'
	UNION
	SELECT c.relname as "Name",
	       (CASE WHEN relkind = 'S' THEN 'sequence'::text ELSE 'index'::text END) as "Type",
		NULL as "Owner"
	FROM pg_class c
	WHERE not exists (select 1 from pg_user where usesysid = c.relowner) 
 		AND relkind in ('S') AND c.relname !~ '^pg_' 
	ORDER BY "Name";
    fi	

    if (($SQLCODE == 0 && $SQLNTUPLE == 0)); then
	echo "# Did not find any sequences."
    fi
}  
#----- List of Views -----
function _list_views {
	echo "[ List of views ]"

        VER1=${POSTGRESQL_VERSION:0:1}
	VER2=${POSTGRESQL_VERSION:2:1}

   if (( VER1 >= 7 && VER2 >= 3 )); then

	#--- PostgreSQL-7.3 --------#
	SELECT n.nspname as "Schema", 
		c.relname as "Name",
		CASE c.relkind  WHEN 'r' THEN 'table' 
				WHEN 'v' THEN 'view' 
				WHEN 'i' THEN 'index' 
				WHEN 'S' THEN 'sequence' 
				WHEN 's' THEN 'special' 
		END as "Type",
		u.usename as "Owner"
	FROM pg_catalog.pg_class c
	LEFT JOIN pg_catalog.pg_user u ON u.usesysid = c.relowner
	LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
	WHERE c.relkind IN ('v','') AND 
		n.nspname NOT IN ('pg_catalog', 'pg_toast') AND 
		pg_catalog.pg_table_is_visible(c.oid)
	ORDER BY 1,2;

   elif (( VER1 >= 7 && VER2 >= 1 )); then

	#--- PostgreSQL-7.2, 7.1 ---#
	SELECT	c.relname as "Name",
		CASE c.relkind	WHEN 'r' THEN 'table' 
				WHEN 'v' THEN 'view' 
				WHEN 'i' THEN 'index' 
				WHEN 'S' THEN 'sequence' 
				WHEN 's' THEN 'special' 
		END as "Type", 
		u.usename as "Owner"
	FROM pg_class c LEFT JOIN pg_user u ON c.relowner = u.usesysid
	WHERE c.relkind IN ('v','') AND c.relname !~ '^pg_'
	ORDER BY 1;

    else

	#--- PostgreSQL-7.0, 6.5 ---#
	SELECT c.relname as "Name", 'view'::text as "Type", u.usename as "Owner"
	FROM pg_class c, pg_user u
	WHERE c.relowner = u.usesysid AND c.relkind = 'r'
		AND exists (select 1 from pg_views where viewname = c.relname)
		AND c.relname !~ '^pg_'
	UNION
	SELECT c.relname as "Name", 'view'::text as "Type", NULL as "Owner"
	FROM pg_class c
	WHERE c.relkind = 'r'
		AND exists (select 1 from pg_views where viewname = c.relname)
		AND not exists (select 1 from pg_user where usesysid = c.relowner)
		AND c.relname !~ '^pg_' 
	ORDER BY "Name";

    fi

    if (($SQLCODE == 0 && $SQLNTUPLE == 0)); then
	echo "# Did not find any views".
    fi
}
#----- List of Grant/Revoke permissions -----
function _list_permissions { 
	echo "[ List of access permissions ]"

        VER1=${POSTGRESQL_VERSION:0:1}
	VER2=${POSTGRESQL_VERSION:2:1}

    if (( VER1 >= 7 && VER2 >= 3 )); then

	#--- PostgreSQL-7.3 ---#
	SELECT n.nspname as "Schema", 
		c.relname as "Table", 
		c.relacl as "Access privileges"
	FROM pg_catalog.pg_class c
	LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
	WHERE c.relkind IN ('r', 'v', 'S') AND 
		pg_catalog.pg_table_is_visible(c.oid) AND n.nspname !~ '^pg_'
	ORDER BY 1, 2;

    elif (( VER1 >= 7 && VER2 >= 2 )); then

	#--- PostgreSQL-7.2 ---#
	SELECT relname as "Relation", relacl as "Access privileges"
	FROM   pg_class
	WHERE  relkind in ('r', 'v', 'S') AND relname NOT LIKE 'pg\$_%' ESCAPE '\$'
	ORDER BY 1;

    else

	#--- PostgreSQL-7.1, 7.0, 6.5 ---#
	SELECT relname as "Relation", relacl as "Access permissions"
	FROM   pg_class
	WHERE  relkind in ('r', 'v', 'S') AND relname !~ '^pg_'
	ORDER BY relname;
    fi

    if (($SQLCODE == 0 && $SQLNTUPLE == 0)); then
	echo "# Did not find any permissions."
    fi
}  
#----- List of large objects -----
function _list_lobjects {
	echo "[ List of large objects ]"

	SELECT objoid as "OID", description as "Description"
	FROM   pgbash_description
	ORDER BY "OID";

    if (($SQLCODE == 0 && $SQLNTUPLE == 0)); then
	echo "# Did not find any large objects."
    fi
}
#----- List of Aggregates --------------
function _list_aggregates { 
	echo "[ List of aggregates ]"

        VER1=${POSTGRESQL_VERSION:0:1}
	VER2=${POSTGRESQL_VERSION:2:1}

   if (( VER1 >= 7 && VER2 >= 3 )); then

	#--- PostgreSQL-7.3 ---#
	SELECT n.nspname as "Schema",
		p.proname AS "Name",
		CASE p.proargtypes[0] 
			WHEN 'pg_catalog."any"'::pg_catalog.regtype
			THEN CAST('(all types)' AS pg_catalog.text)
		        ELSE pg_catalog.format_type(p.proargtypes[0], NULL)
		END AS "Data type",
		pg_catalog.obj_description(p.oid, 'pg_proc') as "Description"
	FROM pg_catalog.pg_proc p
	LEFT JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace
	WHERE p.proisagg AND pg_catalog.pg_function_is_visible(p.oid)
	ORDER BY 1, 2, 3;

   elif (( VER1 >= 7 && VER2 >= 2 )); then

	#--- PostgreSQL-7.2 ---#
	SELECT	a.aggname AS "Name",
		CASE a.aggbasetype	WHEN 0 THEN CAST('(all types)' AS text)
					ELSE format_type(a.aggbasetype, NULL) 
		END AS "Data type",
		obj_description(a.oid, 'pg_aggregate') as "Description"
	FROM pg_aggregate a
	ORDER BY 1, 2;

   elif (( VER1 == 7 && VER2 == 1 )); then

	#--- PostgreSQL-7.1 ---#
	SELECT	a.aggname AS "Name", 
		format_type(a.aggbasetype, NULL) AS "Type",
		obj_description(a.oid) as "Description"
	FROM pg_aggregate a WHERE a.aggbasetype <> 0
	UNION
	SELECT a.aggname AS "Name", '(all types)' as "Type", 
		obj_description(a.oid) as "Description"
	FROM pg_aggregate a WHERE a.aggbasetype = 0
	ORDER BY "Name", "Type";

    else

	#--- PostgreSQL-7.0, 6.5 ---#
	SELECT	a.aggname AS "Name",
		t.typname AS "Type",
		obj_description(a.oid) as "Description"
	FROM pg_aggregate a, pg_type t
	WHERE a.aggbasetype = t.oid
	UNION
	SELECT	a.aggname AS "Name", 
		'(all types)' as "Type",
		obj_description(a.oid) as "Description"
	FROM pg_aggregate a
	WHERE a.aggbasetype = 0
	ORDER BY "Name", "Type";

    fi

    if (($SQLCODE == 0 && $SQLNTUPLE == 0)); then
	echo "# Did not find any aggregates."
    fi
}
#----- List of Functions --------------
function _list_functions { 
	echo "[ List of functions ]"

        VER1=${POSTGRESQL_VERSION:0:1}
	VER2=${POSTGRESQL_VERSION:2:1}

   if (( VER1 >= 7 && VER2 >= 3 )); then

	#--- PostgreSQL-7.3 --------#
	SELECT 
		CASE WHEN p.proretset THEN 'setof ' ELSE '' END ||
			pg_catalog.format_type(p.prorettype, NULL) as "Result data type",
		n.nspname as "Schema", p.proname as "Name",
		pg_catalog.oidvectortypes(p.proargtypes) as "Argument data types"
	FROM pg_catalog.pg_proc p
	LEFT JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace 
	WHERE p.prorettype <> 'pg_catalog.cstring'::pg_catalog.regtype AND 
		p.proargtypes[0] <> 'pg_catalog.cstring'::pg_catalog.regtype 
		AND NOT p.proisagg AND pg_catalog.pg_function_is_visible(p.oid)
	ORDER BY 2, 3, 1, 4;

   elif (( VER1 >= 7 && VER2 >= 1 )); then

	#--- PostgreSQL-7.2, 7.1 ---#
	SELECT	format_type(p.prorettype, NULL) as "Result", 
		p.proname as "Function",
		oidvectortypes(p.proargtypes) as "Arguments"
	FROM pg_proc p
	WHERE p.prorettype <> 0 AND (pronargs = 0 OR oidvectortypes(p.proargtypes) <> '')
	ORDER BY 2, 1, 3;

    elif (( VER1 == 7 && VER2 == 0 )); then

	#--- PostgreSQL-7.0 ---#
	SELECT	t.typname as "Result", 
		p.proname as "Function",
		oidvectortypes(p.proargtypes) as "Arguments"
	FROM pg_proc p, pg_type t
	WHERE p.prorettype = t.oid and (pronargs = 0 or oidvectortypes(p.proargtypes) != '')
	ORDER BY "Function", "Result", "Arguments";

    else

	#--- PostgreSQL 6.5 ---#
	SELECT	t.typname AS "Result", 
		p.proname AS "Function", 
		oid8types(p.proargtypes) AS "Arguments",
		obj_description(p.oid) AS "Description"
	FROM pg_proc p, pg_type t 
	WHERE p.prorettype = t.oid AND 
     		(pronargs = 0 or oid8types(p.proargtypes) != '') AND 
      		p.proname ~ '^df' 
	ORDER BY "Result", "Function", "Arguments";

    fi

	if (($SQLCODE == 0 && $SQLNTUPLE == 0)); then
		echo "# Did not find any functions."
	fi
}  
#----- List of Operations
function _list_operators { 
	echo "[ List of operators ]"

        VER1=${POSTGRESQL_VERSION:0:1}
	VER2=${POSTGRESQL_VERSION:2:1}

   if (( VER1 >= 7 && VER2 >= 3 )); then
   
	#--- PostgreSQL-7.3 ---#
	SELECT n.nspname as "Schema", 
		o.oprname AS "Name",
		CASE WHEN o.oprkind='l' THEN 
			NULL ELSE pg_catalog.format_type(o.oprleft, NULL) 
		END AS "Left arg type",
		CASE WHEN o.oprkind='r' THEN 
			NULL ELSE pg_catalog.format_type(o.oprright, NULL) 
		END AS "Right argtype",
		pg_catalog.format_type(o.oprresult, NULL) AS "Result type",
		coalesce(pg_catalog.obj_description(o.oid, 'pg_operator'),
		pg_catalog.obj_description(o.oprcode, 'pg_proc')) AS "Description"
	FROM pg_catalog.pg_operator o
	LEFT JOIN pg_catalog.pg_namespace n ON n.oid = o.oprnamespace
	WHERE pg_catalog.pg_operator_is_visible(o.oid)
	ORDER BY 1, 2, 3, 4;

   elif (( VER1 >= 7 && VER2 >= 2 )); then
   
	#--- PostgreSQL-7.2 ---#
	SELECT	o.oprname AS "Name", 
		CASE	WHEN o.oprkind='l' THEN NULL 
			ELSE format_type(o.oprleft, NULL) 
		END AS "Left arg type", 
		CASE 	WHEN o.oprkind='r' THEN NULL 
			ELSE format_type(o.oprright, NULL) 
		END AS "Right arg type", 
		format_type(p.prorettype, NULL) AS "Result type", 
		obj_description(p.oid, 'pg_proc') as "Description"
	FROM pg_proc p, pg_operator o
	WHERE RegprocToOid(o.oprcode) = p.oid
	ORDER BY 1, 2, 3, 4;

   elif (( VER1 == 7 && VER2 == 1 )); then

	#--- PostgreSQL-7.1 ---#
	SELECT o.oprname AS "Op",
		format_type(o.oprleft, NULL) AS "Left arg",
		format_type(o.oprright, NULL) AS "Righr arg",
		format_type(p.prorettype, NULL) AS "Result",
		obj_description(p.oid) as "Description"
	FROM   pg_proc p, pg_operator o
	WHERE  RegprocToOid(o.oprcode) = p.oid AND p.pronargs = 2 
	UNION 
	SELECT o.oprname as "Op", ''::name AS "Left arg",
		format_type(o.oprright, NULL) AS "Righr arg",
		format_type(o.oprresult, NULL) AS "Result",
		obj_description(p.oid) as "Description"
	FROM   pg_operator o, pg_proc p
	WHERE  RegprocToOid(o.oprcode) = p.oid AND o.oprkind = 'l' 
	UNION 
	SELECT o.oprname  as "Op", format_type(o.oprleft, NULL) AS "Left arg",
		''::name AS "Righr arg", format_type(o.oprresult, NULL) AS "Result",
		obj_description(p.oid) as "Description"
	FROM   pg_operator o, pg_proc p
	WHERE  RegprocToOid(o.oprcode) = p.oid AND o.oprkind = 'r' 
	ORDER BY "Op", "Left arg", "Righr arg", "Result";

    else

	#--- PostgreSQL-7.0, 6.5 ---#
	SELECT o.oprname AS "Op", t1.typname AS "Left arg", t2.typname AS "Right arg",
		t0.typname AS "Result", obj_description(p.oid) as "Description"
	FROM   pg_proc p, pg_type t0, pg_type t1, pg_type t2, pg_operator o
	WHERE  p.prorettype = t0.oid AND RegprocToOid(o.oprcode) = p.oid AND
		p.pronargs = 2 AND o.oprleft = t1.oid AND o.oprright = t2.oid 
	UNION 
	SELECT o.oprname as "Op", ''::name AS "Left arg", t1.typname AS "Right arg",
		t0.typname AS "Result", obj_description(p.oid) as "Description"
	FROM   pg_operator o, pg_proc p, pg_type t0, pg_type t1
	WHERE  RegprocToOid(o.oprcode) = p.oid AND o.oprresult = t0.oid AND
		o.oprkind = 'l' AND o.oprright = t1.oid 
	UNION 
	SELECT o.oprname  as "Op", t1.typname AS "Left arg", ''::name AS "Right arg",
		t0.typname AS "Result", obj_description(p.oid) as "Description"
	FROM   pg_operator o, pg_proc p, pg_type t0, pg_type t1
	WHERE  RegprocToOid(o.oprcode) = p.oid AND o.oprresult = t0.oid AND
		o.oprkind = 'r' AND o.oprleft = t1.oid 
	ORDER BY "Op", "Left arg", "Right arg", "Result";

    fi

    if (($SQLCODE == 0 && $SQLNTUPLE == 0)); then
	echo "# Did not find any operations."
    fi
}  
#----- List of System tables -----
function _list_systables { 
	echo "[ List of system tables ]"

        VER1=${POSTGRESQL_VERSION:0:1}
	VER2=${POSTGRESQL_VERSION:2:1}

   if (( VER1 >= 7 && VER2 >= 1 )); then

	#--- PostgreSQL-7.2, 7.1 ---#
	SELECT	c.relname as "Name",
		CASE c.relkind	WHEN 'r' THEN 'table' 
				WHEN 'v' THEN 'view' 
				WHEN 'i' THEN 'index' 
				WHEN 'S' THEN 'sequence' 
				WHEN 's' THEN 'special' 
		END as "Type", 
		u.usename as "Owner"
	FROM pg_class c LEFT JOIN pg_user u ON c.relowner = u.usesysid
	WHERE c.relkind IN ('r','v','S','s','') AND c.relname ~ '^pg_'
	ORDER BY 1;

    else

	#--- PostgreQSL-7.0, 6.5 ---#
	SELECT c.relname as "Name", 'table'::text as "Type", u.usename as "Owner"
	FROM pg_class c, pg_user u
	WHERE c.relowner = u.usesysid AND c.relkind = 'r'
		AND not exists (select 1 from pg_views where viewname = c.relname)
		AND c.relname ~ '^pg_'
	UNION
	SELECT c.relname as "Name", 'table'::text as "Type", NULL as "Owner"
	FROM pg_class c
	WHERE c.relkind = 'r'
		AND not exists (select 1 from pg_views where viewname = c.relname)
		AND not exists (select 1 from pg_user where usesysid = c.relowner)
		AND c.relname ~ '^pg_' 
	UNION 
	SELECT c.relname as "Name", 'view'::text as "Type", u.usename as "Owner"
	FROM pg_class c, pg_user u
	WHERE c.relowner = u.usesysid AND c.relkind = 'r'
		AND exists (select 1 from pg_views where viewname = c.relname)
		AND c.relname ~ '^pg_'
	UNION
	SELECT c.relname as "Name", 'view'::text as "Type", NULL as "Owner"
	FROM pg_class c
	WHERE c.relkind = 'r'
		AND exists (select 1 from pg_views where viewname = c.relname)
		AND not exists (select 1 from pg_user where usesysid = c.relowner)
		AND c.relname ~ '^pg_'
	UNION 
	SELECT c.relname as "Name",
		(CASE WHEN relkind = 'S' THEN 'sequence'::text ELSE 'index'::text END) as "Type",
		u.usename as "Owner"
	FROM pg_class c, pg_user u
	WHERE c.relowner = u.usesysid AND relkind in ('S')
	AND c.relname ~ '^pg_'
	UNION
	SELECT c.relname as "Name",
		(CASE WHEN relkind = 'S' THEN 'sequence'::text ELSE 'index'::text END) as "Type",
		NULL as "Owner"
		FROM pg_class c
	WHERE not exists (select 1 from pg_user where usesysid = c.relowner) AND relkind in ('S')
		AND c.relname ~ '^pg_' 
	UNION 
	SELECT c.relname as "Name", 'special'::text as "Type", u.usename as "Owner"
	FROM pg_class c, pg_user u
	WHERE c.relowner = u.usesysid AND c.relkind = 's'
	UNION
	SELECT c.relname as "Name", 'special'::text as "Type", NULL as "Owner"
	FROM pg_class c
	WHERE c.relkind = 's'
		AND not exists (select 1 from pg_user where usesysid = c.relowner)
	ORDER BY "Name";

    fi

	if (($SQLCODE == 0 && $SQLNTUPLE == 0)); then
		echo "# Did not find any system tables."
	fi
}  
#----- List of TYPEs
function _list_types { 
	echo "[ List of data types ]"

        VER1=${POSTGRESQL_VERSION:0:1}
	VER2=${POSTGRESQL_VERSION:2:1}

   if (( VER1 >= 7 && VER2 >= 3 )); then

	#--- PostgreSQL-7.3 ---#
	SELECT n.nspname as "Schema",
		pg_catalog.format_type(t.oid, NULL) AS "Name",
		pg_catalog.obj_description(t.oid, 'pg_type') as "Description"
	FROM pg_catalog.pg_type t
	LEFT JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace
	WHERE (t.typrelid = 0 OR 
		(SELECT c.relkind = 'c' 
		 FROM pg_catalog.pg_class c 
		 WHERE c.oid = t.typrelid)
		 ) 
		 AND t.typname !~ '^_' AND pg_catalog.pg_type_is_visible(t.oid)
	 ORDER BY 1, 2;

   elif (( VER1 >= 7 && VER2 >= 2 )); then

	#--- PostgreSQL-7.2 ---#
	SELECT	format_type(t.oid, NULL) AS "Name",
		obj_description(t.oid, 'pg_type') as "Description"
	FROM pg_type t
	WHERE t.typrelid = 0 AND t.typname !~ '^_.*'
	ORDER BY 1;

   elif (( VER1 >= 7 && VER2 == 1 )); then

	#--- PostgreSQL-7.1 ---#
	SELECT	format_type(t.oid, NULL) AS "Type",
		obj_description(t.oid) as "Description"
	FROM pg_type t
	WHERE t.typrelid = 0 AND t.typname !~ '^_.*'
	ORDER BY "Type";

    else

	#--- PostrgeSQL-7.0, 6.5 ---#
	SELECT	t.typname AS "Type", 
		obj_description(t.oid) as "Description"
	FROM pg_type t
	WHERE t.typrelid = 0 AND t.typname !~ '^_.*'
	ORDER BY t.typname;

   fi

   if (($SQLCODE == 0 && $SQLNTUPLE == 0)); then
	echo "# Did not find any data types."
   fi
}  
#----- List of Descriptions ------
function _list_descriptions { 
	echo "[ List of descriptions ]"

        VER1=${POSTGRESQL_VERSION:0:1}
	VER2=${POSTGRESQL_VERSION:2:1}

    if (( VER1 == 7 && VER2 >= 3 )); then

	#--- PostgreSQL-7.3 ---#
	SELECT DISTINCT tt.nspname AS "Schema", 
			tt.name AS "Name", 
			tt.object AS "Object", d.description AS "Description"
	FROM (  SELECT p.oid as oid, p.tableoid as tableoid, n.nspname as nspname,
		CAST(p.proname AS pg_catalog.text) as name,  
		CAST('aggregate' AS pg_catalog.text) as object
		FROM pg_catalog.pg_proc p
		LEFT JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace
		WHERE p.proisagg AND pg_catalog.pg_function_is_visible(p.oid)
		UNION ALL
		SELECT p.oid as oid, p.tableoid as tableoid, n.nspname as nspname,
		CAST(p.proname AS pg_catalog.text) as name,  
		CAST('function' AS pg_catalog.text) as object
		FROM pg_catalog.pg_proc p
		LEFT JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace
		WHERE p.prorettype <> 'pg_catalog.cstring'::pg_catalog.regtype AND 
			p.proargtypes[0] <> 'pg_catalog.cstring'::pg_catalog.regtype 
			AND NOT p.proisagg AND pg_catalog.pg_function_is_visible(p.oid)
		UNION ALL
		SELECT o.oid as oid, o.tableoid as tableoid, n.nspname as nspname,
		CAST(o.oprname AS pg_catalog.text) as name,  
		CAST('operator' AS pg_catalog.text) as object
		FROM pg_catalog.pg_operator o
		LEFT JOIN pg_catalog.pg_namespace n ON n.oid = o.oprnamespace
		WHERE pg_catalog.pg_operator_is_visible(o.oid)
		UNION ALL
		SELECT t.oid as oid, t.tableoid as tableoid, n.nspname as nspname, 
			pg_catalog.format_type(t.oid, NULL) as name,  
		CAST('data type' AS pg_catalog.text) as object
		FROM pg_catalog.pg_type t
		LEFT JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace
		WHERE pg_catalog.pg_type_is_visible(t.oid)
		UNION ALL
		SELECT c.oid as oid, c.tableoid as tableoid, n.nspname as nspname,
		CAST(c.relname AS pg_catalog.text) as name,
		CAST( CASE c.relkind    WHEN 'r' THEN 'table' 
					WHEN 'v' THEN 'view' 
					WHEN 'i' THEN 'index' 
					WHEN 'S' THEN 'sequence' 
			END  AS pg_catalog.text) as object
		FROM pg_catalog.pg_class c
		LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
		WHERE c.relkind IN ('r', 'v', 'i', 'S') AND 
			pg_catalog.pg_table_is_visible(c.oid)
		UNION ALL
		SELECT r.oid as oid, r.tableoid as tableoid, n.nspname as nspname, 
		CAST(r.rulename AS pg_catalog.text) as name,  
		CAST('rule' AS pg_catalog.text) as object
		FROM pg_catalog.pg_rewrite r 
		JOIN pg_catalog.pg_class c ON c.oid = r.ev_class
		LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
		WHERE r.rulename != '_RETURN' AND pg_catalog.pg_table_is_visible(c.oid)
		UNION ALL
		SELECT t.oid as oid, t.tableoid as tableoid, n.nspname as nspname,
		CAST(t.tgname AS pg_catalog.text) as name, 
		CAST('trigger' AS pg_catalog.text) as object
		FROM pg_catalog.pg_trigger t
		JOIN pg_catalog.pg_class c ON c.oid = t.tgrelid
		LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
		WHERE pg_catalog.pg_table_is_visible(c.oid)
	) AS tt
	JOIN pg_catalog.pg_description d 
	ON (tt.oid = d.objoid and tt.tableoid = d.classoid and d.objsubid = 0)
	ORDER BY 1, 2, 3;

    elif (( VER1 == 7 && VER2 >= 2 )); then

	#--- PostgreSQL-7.2 ---#
	SELECT DISTINCT tt.name AS "Name", tt.object AS "Object", d.description AS "Description"
	FROM ( SELECT a.oid as oid, a.tableoid as tableoid,
		CAST(a.aggname AS text) as name, 
		CAST('aggregate' AS text) as object
		FROM pg_aggregate a
		UNION ALL
		SELECT p.oid as oid, p.tableoid as tableoid,
			CAST(p.proname AS text) as name, 
			CAST('function' AS text) as object
		FROM pg_proc p
		WHERE p.pronargs = 0 or oidvectortypes(p.proargtypes) <> ''
		UNION ALL
        	SELECT RegprocToOid(o.oprcode) as oid,
	  		(SELECT oid FROM pg_class WHERE relname = 'pg_proc') as tableoid,
	    		CAST(o.oprname AS text) as name, 
			CAST('operator' AS text) as object
		FROM pg_operator o
		UNION ALL
		SELECT t.oid as oid, t.tableoid as tableoid,
			format_type(t.oid, NULL) as name,
			CAST('data type' AS text) as object
		FROM pg_type t
		UNION ALL
		SELECT c.oid as oid, c.tableoid as tableoid,
			CAST(c.relname AS text) as name,
			CAST( CASE c.relkind	WHEN 'r' THEN 'table' 
						WHEN 'v' THEN 'view' 
						WHEN 'i' THEN 'index' 
						WHEN 'S' THEN 'sequence' 
			END  AS text) as object
		FROM pg_class c
		UNION ALL
		SELECT r.oid as oid, r.tableoid as tableoid,
			CAST(r.rulename AS text) as name,
			CAST('rule' AS text) as object
		FROM pg_rewrite r
		WHERE r.rulename !~ '^_RET'
		UNION ALL
		SELECT t.oid as oid, t.tableoid as tableoid,
			CAST(t.tgname AS text) as name, 
			CAST('trigger' AS text) as object
		FROM pg_trigger t
		) AS tt, pg_description d
	WHERE tt.oid = d.objoid and tt.tableoid = d.classoid and d.objsubid = 0
	ORDER BY 1;

    elif (( VER1 == 7 && VER2 == 1 )); then

	#--- PostgreSQL-7.1 ---#
	SELECT DISTINCT a.aggname::text as "Name", 'aggregate'::text as "Object", 
			d.description as "Description" 
	FROM pg_aggregate a, pg_description d
	WHERE a.oid = d.objoid 
	UNION ALL 
	SELECT DISTINCT p.proname::text as "Name", 'function'::text as "Object", 
			d.description as "Description"
	FROM pg_proc p, pg_description d
	WHERE p.oid = d.objoid AND (p.pronargs = 0 or oidvectortypes(p.proargtypes) != '') 
	UNION ALL 
	SELECT DISTINCT o.oprname::text as "Name", 'operator'::text as "Object", 
			d.description as "Description"
	FROM pg_operator o, pg_description d
	WHERE RegprocToOid(o.oprcode) = d.objoid 
	UNION ALL 
	SELECT DISTINCT format_type(t.oid, NULL) as "Name", 'type'::text as "Object",
			d.description as "Description"
	FROM pg_type t, pg_description d
	WHERE t.oid = d.objoid 
	UNION ALL 
	SELECT DISTINCT c.relname::text as "Name", 'relation'::text||'('||c.relkind||')' 
			as "Object", d.description as "Description"
	FROM pg_class c, pg_description d
	WHERE c.oid = d.objoid 
	UNION ALL 
	SELECT DISTINCT r.rulename::text as "Name", 'rule'::text as "Object", 
			d.description as "Description"
	FROM pg_rewrite r, pg_description d
	WHERE r.oid = d.objoid AND r.rulename !~ '^_RET' 
	UNION ALL 
	SELECT DISTINCT t.tgname::text as "Name", 'trigger'::text as "Object", 
			d.description as "Description"
	FROM pg_trigger t, pg_description d
	WHERE t.oid = d.objoid 
	ORDER BY "Name";

    elif (( VER1 == 7 && VER2 == 0 )); then

	#--- PostgreSQL-7.0 ---#
	SELECT DISTINCT a.aggname as "Name", 'aggregate'::text as "Object", d.description as "Description"
	FROM pg_aggregate a, pg_description d
	WHERE a.oid = d.objoid 
	UNION ALL 
	SELECT DISTINCT p.proname as "Name", 'function'::text as "Object", d.description as "Description"
	FROM pg_proc p, pg_description d
	WHERE p.oid = d.objoid AND (p.pronargs = 0 or oidvectortypes(p.proargtypes) != '') 
	UNION ALL
	SELECT DISTINCT o.oprname as "Name", 'operator'::text as "Object", d.description as "Description"
	FROM pg_operator o, pg_description d
	WHERE RegprocToOid(o.oprcode) = d.objoid 
	UNION ALL 
	SELECT DISTINCT t.typname as "Name", 'type'::text as "Object", d.description as "Description"
	FROM pg_type t, pg_description d
	WHERE t.oid = d.objoid 
	UNION ALL 
	SELECT DISTINCT c.relname as "Name", 'relation'::text||'('||c.relkind||')' as "Object", d.description as "Description"
	FROM pg_class c, pg_description d
	WHERE c.oid = d.objoid 
	UNION ALL 
	SELECT DISTINCT r.rulename as "Name", 'rule'::text as "Object", d.description as "Description"
	FROM pg_rewrite r, pg_description d
	WHERE r.oid = d.objoid AND r.rulename !~ '^_RET' 
	UNION ALL 
	SELECT DISTINCT t.tgname as "Name", 'trigger'::text as "Object", d.description as "Description"
	FROM pg_trigger t, pg_description d
	WHERE t.oid = d.objoid 
	ORDER BY "Name";

    else

	#--- PostgreSQL-6.5 ---#
	SELECT DISTINCT description 
	FROM pg_class, pg_description 
	WHERE pg_class.relname ~ '^' and pg_class.oid = pg_description.objoid
	UNION ALL
	SELECT DISTINCT description 
	FROM pg_type, pg_description 
	WHERE pg_type.typname ~ '^' and  pg_type.oid = pg_description.objoid;

    fi

    if (($SQLCODE == 0 && $SQLNTUPLE == 0)); then
	echo "# Did not find any descriptions."
    fi
}
#----- List of Descriptions -----
function _list_description { # $1: table/type/function/operator name

	if (( $# == 0 )); then
		echo "# Object name please!"
		return;
	fi

	echo "[ Object \"$1\" descriptions ]"

        VER1=${POSTGRESQL_VERSION:0:1}
	VER2=${POSTGRESQL_VERSION:2:1}

   if (( VER1 == 7 && VER2 >= 2 )); then

	#--- PostgreSQL-7.2 ---#
	SELECT DISTINCT tt.name AS "Name", tt.object AS "Object", d.description AS "Description"
	FROM ( SELECT a.oid as oid, a.tableoid as tableoid, 
			CAST(a.aggname AS text) as name, 
			CAST('aggregate' AS text) as object
		FROM pg_aggregate a
		UNION ALL
		SELECT p.oid as oid, p.tableoid as tableoid,
			CAST(p.proname AS text) as name, 
			CAST('function' AS text) as object
		FROM pg_proc p
		WHERE p.pronargs = 0 or oidvectortypes(p.proargtypes) <> ''
		UNION ALL
		SELECT RegprocToOid(o.oprcode) as oid,
			(SELECT oid FROM pg_class WHERE relname = 'pg_proc') as tableoid,
			CAST(o.oprname AS text) as name, 
			CAST('operator' AS text) as object
		FROM pg_operator o
		UNION ALL
		SELECT t.oid as oid, t.tableoid as tableoid,
			format_type(t.oid, NULL) as name, 
			CAST('data type' AS text) as object
		FROM pg_type t
		UNION ALL
		SELECT c.oid as oid, c.tableoid as tableoid,
			CAST(c.relname AS text) as name,
			CAST( CASE c.relkind	WHEN 'r' THEN 'table' 
						WHEN 'v' THEN 'view'
						WHEN 'i' THEN 'index' 
						WHEN 'S' THEN 'sequence' 
			END  AS text) as object
		FROM pg_class c
		UNION ALL
		SELECT r.oid as oid, r.tableoid as tableoid,
			CAST(r.rulename AS text) as name, 
			CAST('rule' AS text) as object
		FROM pg_rewrite r
		WHERE r.rulename !~ '^_RET'
		UNION ALL
		SELECT t.oid as oid, t.tableoid as tableoid,
			CAST(t.tgname AS text) as name, 
			CAST('trigger' AS text) as object
		FROM pg_trigger t
		) AS tt, pg_description d
	WHERE tt.oid = d.objoid and tt.tableoid = d.classoid and d.objsubid = 0
		AND tt.name ~ '^$1'
	ORDER BY 1;

   elif (( VER1 == 7 && VER2 == 1 )); then

	#--- PostgreSQL-7.1 ---#
	SELECT DISTINCT a.aggname::text as "Name", 'aggregate'::text as "Object", 
			d.description as "Description" 
	FROM pg_aggregate a, pg_description d
	WHERE a.oid = d.objoid AND a.aggname ~ '^$1' 
	UNION ALL 
	SELECT DISTINCT p.proname::text as "Name", 'function'::text as "Object", 
			d.description as "Description"
	FROM pg_proc p, pg_description d
	WHERE p.oid = d.objoid AND (p.pronargs = 0 or oidvectortypes(p.proargtypes) != '')
		AND p.proname ~ '^$1' 
	UNION ALL 
	SELECT DISTINCT o.oprname::text as "Name", 'operator'::text as "Object", 
			d.description as "Description"
	FROM pg_operator o, pg_description d
	WHERE RegprocToOid(o.oprcode) = d.objoid AND o.oprname = '$1' 
	UNION ALL 
	SELECT DISTINCT format_type(t.oid, NULL) as "Name", 'type'::text as "Object",
			d.description as "Description"
	FROM pg_type t, pg_description d
	WHERE t.oid = d.objoid AND t.typname ~ '^$1' 
	UNION ALL 
	SELECT DISTINCT c.relname::text as "Name", 'relation'::text||'('||c.relkind||')' 
			as "Object", d.description as "Description"
	FROM pg_class c, pg_description d
	WHERE c.oid = d.objoid AND c.relname ~ '^$1' 
	UNION ALL 
	SELECT DISTINCT r.rulename::text as "Name", 'rule'::text as "Object", 
			d.description as "Description"
	FROM pg_rewrite r, pg_description d
	WHERE r.oid = d.objoid AND r.rulename !~ '^_RET' AND r.rulename ~ '^$1' 
	UNION ALL 
	SELECT DISTINCT t.tgname::text as "Name", 'trigger'::text as "Object", d.description as "Description"
	FROM pg_trigger t, pg_description d
	WHERE t.oid = d.objoid AND t.tgname ~ '^$1' 
	ORDER BY "Name";

   elif (( VER1 == 7 && VER2 == 0 )); then

	#--- PostgreSQL-7.0 ---#
	SELECT DISTINCT a.aggname as "Name", 'aggregate'::text as "Object", d.description as "Description"
	FROM pg_aggregate a, pg_description d
	WHERE a.oid = d.objoid AND a.aggname ~ '^$1' 
	UNION ALL 
	SELECT DISTINCT p.proname as "Name", 'function'::text as "Object", d.description as "Description"
	FROM pg_proc p, pg_description d
	WHERE p.oid = d.objoid AND (p.pronargs = 0 or oidvectortypes(p.proargtypes) != '')
		AND p.proname ~ '^$1' 
	UNION ALL 
	SELECT DISTINCT o.oprname as "Name", 'operator'::text as "Object", d.description as "Description"
	FROM pg_operator o, pg_description d
	WHERE RegprocToOid(o.oprcode) = d.objoid AND o.oprname = '$1' 
	UNION ALL 
	SELECT DISTINCT t.typname as "Name", 'type'::text as "Object", d.description as "Description"
	FROM pg_type t, pg_description d
	WHERE t.oid = d.objoid AND t.typname ~ '^$1' 
	UNION ALL 
	SELECT DISTINCT c.relname as "Name", 'relation'::text||'('||c.relkind||')' as "Object", d.description as "Description"
	FROM pg_class c, pg_description d
	WHERE c.oid = d.objoid AND c.relname ~ '^$1' 
	UNION ALL 
	SELECT DISTINCT r.rulename as "Name", 'rule'::text as "Object", d.description as "Description"
	FROM pg_rewrite r, pg_description d
	WHERE r.oid = d.objoid AND r.rulename !~ '^_RET' AND r.rulename ~ '^$1' 
	UNION ALL 
	SELECT DISTINCT t.tgname as "Name", 'trigger'::text as "Object", d.description as "Description"
	FROM pg_trigger t, pg_description d
	WHERE t.oid = d.objoid AND t.tgname ~ '^$1' 
	ORDER BY "Name";

    else

	#--- PostgreSQL-6.5 ---#
	SELECT DISTINCT description
	FROM pg_class, pg_description
	WHERE pg_class.relname ~ '^$1' and pg_class.oid = pg_description.objoid
	UNION ALL
	SELECT DISTINCT description
	FROM pg_type, pg_description
	WHERE pg_type.typname ~ '^$1' and  pg_type.oid = pg_description.objoid;

    fi

    if (($SQLCODE == 0 && $SQLNTUPLE == 0)); then
	echo "# Did not find the description named \"$1\"."
    fi
}

#----- List of domains
function _list_domains { 
	echo "[ List of domains ]"

        VER1=${POSTGRESQL_VERSION:0:1}
	VER2=${POSTGRESQL_VERSION:2:1}

   if (( VER1 >= 7 && VER2 >= 3 )); then

	#--- PostgreSQL-7.3 ---#
	SELECT n.nspname as "Schema", t.typname as "Name",
		pg_catalog.format_type(t.typbasetype, t.typtypmod) as "Type",
		CASE WHEN t.typnotnull AND t.typdefault IS NOT NULL 
			THEN 'not null default '||t.typdefault
	  	     WHEN t.typnotnull AND t.typdefault IS NULL THEN 'not null'
		     WHEN NOT t.typnotnull AND t.typdefault IS NOT NULL 
		     	THEN 'default '||t.typdefault
			ELSE ''
		END as "Modifier"
	FROM pg_catalog.pg_type t
	LEFT JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace
	WHERE t.typtype = 'd' AND pg_catalog.pg_type_is_visible(t.oid)
	ORDER BY 1, 2;

    fi

    if (($SQLCODE == 0 && $SQLNTUPLE == 0)); then
	echo "# Did not find any domains."
    fi
}


#****************************************************
#       Execute Program 
#****************************************************
function _lo_export { 
	case "$#" in
	0 ) echo "_lo_export  " ;;
	* ) exec_sql -x lo_export "$1,'$2'"     ;;
	esac
}
function _lo_import { 
	case "$#" in
	0 ) echo "_lo_import  <'COMMENT'>" ;;
	* ) exec_sql -x lo_import "'$1','$2'"         ;;
	esac
}
function _lo_unlink { 
	case "$#" in
	0 ) echo "_lo_unlink "   ;;
	* ) exec_sql -x lo_unlink "$1" ;;
	esac
}
function _lo_list {
	_list_lobjects
}


#****************************************************
#	Useful Tools 
#****************************************************
#
#----- select * from tbname [limit xx]
#function sel {
#	exec_sql "select * from $*" 
#}
#----- declare cursor
#function dec {
#	exec_sql "declare dec_cur cursor for select * from $*"
#}
#----- fetch xx in cur
#function fet {
#	case "$#" in
#	0 ) exec_sql "fetch in dec_cur" ;;
#	* ) exec_sql "fetch $* in dec_cur" ;;
#	esac
#}
#----- insert into tbname values(xx)
#function ins {
#	if(( $# >= 1 )); then
#		echo "Enter data separated with a [Tab] followed by a newline"
#		echo "End with a '\\.'"
#	fi
#
#	case "$#" in
#	1 ) copy $1()   from STDIN ;;
#	2 ) copy $1($2) from STDIN" ;;
#	* ) echo "pgbash: parameter error" ;;
#	esac
#}