proposal - psql: possibility to specify sort for describe commands, when size is printed

Started by Pavel Stehulealmost 9 years ago50 messages
#1Pavel Stehule
pavel.stehule@gmail.com

Hi

Currently is not possible to control sort columns for \d* commands. Usually
schema and table name is used. Really often task is collect the most big
objects in database. "\dt+, \di+" shows necessary information, but not in
practical order.

Instead introduction some additional flags to backslash commands, I propose
a special psql variable that can be used for specification of order used
when some plus command is used.

some like

set EXTENDED_DESCRIBE_SORT size_desc
\dt+
\l+
\di+

Possible variants: schema_table, table_schema, size_desc, size_asc

Comments, notes?

Regards

Pavel

#2Pavel Stehule
pavel.stehule@gmail.com
In reply to: Pavel Stehule (#1)
1 attachment(s)
Re: proposal - psql: possibility to specify sort for describe commands, when size is printed

Hi

2017-02-23 12:17 GMT+01:00 Pavel Stehule <pavel.stehule@gmail.com>:

Hi

Currently is not possible to control sort columns for \d* commands.
Usually schema and table name is used. Really often task is collect the
most big objects in database. "\dt+, \di+" shows necessary information, but
not in practical order.

Instead introduction some additional flags to backslash commands, I
propose a special psql variable that can be used for specification of order
used when some plus command is used.

some like

set EXTENDED_DESCRIBE_SORT size_desc
\dt+
\l+
\di+

Possible variants: schema_table, table_schema, size_desc, size_asc

Comments, notes?

here is a patch

Regards

Pavel

Show quoted text

Regards

Pavel

Attachments:

psql-extended-describe-order.patchtext/x-patch; charset=US-ASCII; name=psql-extended-describe-order.patchDownload
diff --git a/doc/src/sgml/ref/psql-ref.sgml b/doc/src/sgml/ref/psql-ref.sgml
index ae58708aae..b4dfd1f71c 100644
--- a/doc/src/sgml/ref/psql-ref.sgml
+++ b/doc/src/sgml/ref/psql-ref.sgml
@@ -3495,6 +3495,18 @@ bar
       </varlistentry>
 
       <varlistentry>
+        <term><varname>VERBOSE_SORT</varname></term>
+        <listitem>
+        <para>
+        This variable can be set to the values <literal>schema_name</>,
+        <literal>name_schema</>, <literal>size_asc</literal>, or
+        <literal>size_desc</> to control the order of content of 
+        decrible command.
+        </para>
+        </listitem>
+      </varlistentry>
+
+      <varlistentry>
         <term><varname>VERBOSITY</varname></term>
         <listitem>
         <para>
diff --git a/src/bin/psql/describe.c b/src/bin/psql/describe.c
index e2e4cbcc08..7ae5992b90 100644
--- a/src/bin/psql/describe.c
+++ b/src/bin/psql/describe.c
@@ -263,7 +263,18 @@ describeTablespaces(const char *pattern, bool verbose)
 						  NULL, "spcname", NULL,
 						  NULL);
 
-	appendPQExpBufferStr(&buf, "ORDER BY 1;");
+
+	if (verbose && pset.sversion >= 90200)
+	{
+		if (pset.verbose_sort == PSQL_SORT_SIZE_ASC)
+			appendPQExpBufferStr(&buf, "ORDER BY pg_catalog.pg_tablespace_size(oid), 1;");
+		else if (pset.verbose_sort == PSQL_SORT_SIZE_DESC)
+			appendPQExpBufferStr(&buf, "ORDER BY pg_catalog.pg_tablespace_size(oid) DESC, 1;");
+		else
+			appendPQExpBufferStr(&buf, "ORDER BY 1;");
+	}
+	else
+		appendPQExpBufferStr(&buf, "ORDER BY 1;");
 
 	res = PSQLexec(buf.data);
 	termPQExpBuffer(&buf);
@@ -822,7 +833,21 @@ listAllDbs(const char *pattern, bool verbose)
 		processSQLNamePattern(pset.db, &buf, pattern, false, false,
 							  NULL, "d.datname", NULL, NULL);
 
-	appendPQExpBufferStr(&buf, "ORDER BY 1;");
+	if (verbose && pset.sversion >= 80200)
+	{
+		if (pset.verbose_sort == PSQL_SORT_SIZE_ASC)
+			appendPQExpBuffer(&buf,
+						  "ORDER BY CASE WHEN pg_catalog.has_database_privilege(d.datname, 'CONNECT')\n"
+						  "              THEN pg_catalog.pg_database_size(d.datname) END ASC, 1;\n");
+		else if (pset.verbose_sort == PSQL_SORT_SIZE_DESC)
+			appendPQExpBuffer(&buf,
+						  "ORDER BY CASE WHEN pg_catalog.has_database_privilege(d.datname, 'CONNECT')\n"
+						  "              THEN pg_catalog.pg_database_size(d.datname) END DESC, 1;\n");
+		else
+			appendPQExpBufferStr(&buf, "ORDER BY 1;");
+	}
+	else
+		appendPQExpBufferStr(&buf, "ORDER BY 1;");
 	res = PSQLexec(buf.data);
 	termPQExpBuffer(&buf);
 	if (!res)
@@ -3258,7 +3283,29 @@ listTables(const char *tabtypes, const char *pattern, bool verbose, bool showSys
 						  "n.nspname", "c.relname", NULL,
 						  "pg_catalog.pg_table_is_visible(c.oid)");
 
-	appendPQExpBufferStr(&buf, "ORDER BY 1,2;");
+	if (verbose && pset.sversion >= 80100)
+	{
+		if (pset.verbose_sort == PSQL_SORT_SCHEMA_NAME)
+			appendPQExpBufferStr(&buf, "ORDER BY 1,2;");
+		else if (pset.verbose_sort == PSQL_SORT_NAME_SCHEMA)
+			appendPQExpBufferStr(&buf, "ORDER BY 2,1;");
+		else
+		{
+			if (pset.sversion >= 90000)
+				appendPQExpBufferStr(&buf,
+					"ORDER BY pg_catalog.pg_table_size(c.oid) ");
+			else
+				appendPQExpBufferStr(&buf,
+					"ORDER BY pg_catalog.pg_relation_size(c.oid) ");
+
+			if (pset.verbose_sort == PSQL_SORT_SIZE_DESC)
+				appendPQExpBufferStr(&buf, "DESC, 1,2;");
+			else
+				appendPQExpBufferStr(&buf, "ASC, 1,2;");
+		}
+	}
+	else
+		appendPQExpBufferStr(&buf, "ORDER BY 1,2;");
 
 	res = PSQLexec(buf.data);
 	termPQExpBuffer(&buf);
diff --git a/src/bin/psql/help.c b/src/bin/psql/help.c
index 3e3cab4941..09c1a49413 100644
--- a/src/bin/psql/help.c
+++ b/src/bin/psql/help.c
@@ -327,7 +327,7 @@ helpVariables(unsigned short int pager)
 	 * Windows builds currently print one more line than non-Windows builds.
 	 * Using the larger number is fine.
 	 */
-	output = PageOutput(88, pager ? &(pset.popt.topt) : NULL);
+	output = PageOutput(90, pager ? &(pset.popt.topt) : NULL);
 
 	fprintf(output, _("List of specially treated variables\n\n"));
 
@@ -364,6 +364,8 @@ helpVariables(unsigned short int pager)
 	fprintf(output, _("  SINGLESTEP         single-step mode (same as -s option)\n"));
 	fprintf(output, _("  USER               the currently connected database user\n"));
 	fprintf(output, _("  VERBOSITY          controls verbosity of error reports [default, verbose, terse]\n"));
+	fprintf(output, _("  VERBOSE_SORT       controls sort of result in verbose mode\n"
+	"                     [schema_name, name_schema, size_desc, size_asc]\n"));
 
 	fprintf(output, _("\nDisplay settings:\n"));
 	fprintf(output, _("Usage:\n"));
diff --git a/src/bin/psql/settings.h b/src/bin/psql/settings.h
index 195f5a1184..eb89741526 100644
--- a/src/bin/psql/settings.h
+++ b/src/bin/psql/settings.h
@@ -77,6 +77,14 @@ enum trivalue
 	TRI_YES
 };
 
+typedef enum
+{
+	PSQL_SORT_SCHEMA_NAME,
+	PSQL_SORT_NAME_SCHEMA,
+	PSQL_SORT_SIZE_ASC,
+	PSQL_SORT_SIZE_DESC
+} PSQL_SORT;
+
 typedef struct _psqlSettings
 {
 	PGconn	   *db;				/* connection to backend */
@@ -137,6 +145,7 @@ typedef struct _psqlSettings
 	const char *prompt3;
 	PGVerbosity verbosity;		/* current error verbosity level */
 	PGContextVisibility show_context;	/* current context display level */
+	PSQL_SORT	verbose_sort;	/* kind of sort when describe verbose is used */
 } PsqlSettings;
 
 extern PsqlSettings pset;
diff --git a/src/bin/psql/startup.c b/src/bin/psql/startup.c
index 88d686a5b7..8971e927d5 100644
--- a/src/bin/psql/startup.c
+++ b/src/bin/psql/startup.c
@@ -172,6 +172,8 @@ main(int argc, char *argv[])
 	SetVariable(pset.vars, "PROMPT2", DEFAULT_PROMPT2);
 	SetVariable(pset.vars, "PROMPT3", DEFAULT_PROMPT3);
 
+	SetVariable(pset.vars, "VERBOSE_SORT", "schema_name");
+
 	parse_psql_options(argc, argv, &options);
 
 	/*
@@ -1072,6 +1074,36 @@ verbosity_hook(const char *newval)
 }
 
 static char *
+verbose_sort_substitute_hook(char *newval)
+{
+	if (newval == NULL)
+		newval = pg_strdup("schema_name");
+	return newval;
+}
+
+static bool
+verbose_sort_hook(const char *newval)
+{
+	Assert(newval != NULL);		/* else substitute hook messed up */
+	if (pg_strcasecmp(newval, "schema_name") == 0)
+		pset.verbose_sort = PSQL_SORT_SCHEMA_NAME;
+	else if (pg_strcasecmp(newval, "name_schema") == 0)
+		pset.verbose_sort = PSQL_SORT_NAME_SCHEMA;
+	else if (pg_strcasecmp(newval, "size_desc") == 0)
+		pset.verbose_sort = PSQL_SORT_SIZE_DESC;
+	else if (pg_strcasecmp(newval, "size_asc") == 0)
+		pset.verbose_sort = PSQL_SORT_SIZE_ASC;
+	else
+	{
+		PsqlVarEnumError("VERBOSE_SORT", newval, "schema_name, name_schema, size_desc, size_asc");
+		return false;
+	}
+
+	return true;
+}
+
+
+static char *
 show_context_substitute_hook(char *newval)
 {
 	if (newval == NULL)
@@ -1160,6 +1192,9 @@ EstablishVariableSpace(void)
 	SetVariableHooks(pset.vars, "VERBOSITY",
 					 verbosity_substitute_hook,
 					 verbosity_hook);
+	SetVariableHooks(pset.vars, "VERBOSE_SORT",
+					 verbose_sort_substitute_hook,
+					 verbose_sort_hook);
 	SetVariableHooks(pset.vars, "SHOW_CONTEXT",
 					 show_context_substitute_hook,
 					 show_context_hook);
diff --git a/src/bin/psql/tab-complete.c b/src/bin/psql/tab-complete.c
index 94814c20d0..2bc8af5ae4 100644
--- a/src/bin/psql/tab-complete.c
+++ b/src/bin/psql/tab-complete.c
@@ -3320,6 +3320,9 @@ psql_completion(const char *text, int start, int end)
 			COMPLETE_WITH_LIST_CS3("never", "errors", "always");
 		else if (TailMatchesCS1("VERBOSITY"))
 			COMPLETE_WITH_LIST_CS3("default", "verbose", "terse");
+		else if (TailMatchesCS1("VERBOSE_SORT"))
+			COMPLETE_WITH_LIST_CS4("schema_name", "name_schema",
+								   "size_desc", "size_asc");
 	}
 	else if (TailMatchesCS1("\\sf*"))
 		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_functions, NULL);
#3Peter Eisentraut
peter.eisentraut@2ndquadrant.com
In reply to: Pavel Stehule (#2)
Re: Re: proposal - psql: possibility to specify sort for describe commands, when size is printed

On 2/24/17 16:32, Pavel Stehule wrote:

set EXTENDED_DESCRIBE_SORT size_desc
\dt+
\l+
\di+

Possible variants: schema_table, table_schema, size_desc, size_asc

I can see this being useful, but I think it needs to be organized a
little better.

Sort key and sort direction should be separate settings.

I'm not sure why we need to have separate settings to sort by schema
name and table name. But if we do, then we should support that for all
object types. I think maybe that's something we shouldn't get into
right now.

So I would have one setting for sort key = {name|size} and on for sort
direction = {asc|desc}.

--
Peter Eisentraut http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

#4Stephen Frost
sfrost@snowman.net
In reply to: Peter Eisentraut (#3)
Re: Re: proposal - psql: possibility to specify sort for describe commands, when size is printed

* Peter Eisentraut (peter.eisentraut@2ndquadrant.com) wrote:

On 2/24/17 16:32, Pavel Stehule wrote:

set EXTENDED_DESCRIBE_SORT size_desc
\dt+
\l+
\di+

Possible variants: schema_table, table_schema, size_desc, size_asc

I can see this being useful, but I think it needs to be organized a
little better.

Sort key and sort direction should be separate settings.

I'm not sure why we need to have separate settings to sort by schema
name and table name. But if we do, then we should support that for all
object types. I think maybe that's something we shouldn't get into
right now.

So I would have one setting for sort key = {name|size} and on for sort
direction = {asc|desc}.

Perhaps I'm trying to be overly cute here, but why not let the user
simply provide a bit of SQL to be put at the end of the query?

That is, something like:

\pset EXTENDED_DESCRIBE_ORDER_LIMIT 'ORDER BY 5 DESC LIMIT 10'

Thanks!

Stephen

#5Alexander Korotkov
a.korotkov@postgrespro.ru
In reply to: Peter Eisentraut (#3)
Re: Re: proposal - psql: possibility to specify sort for describe commands, when size is printed

On Fri, Mar 10, 2017 at 5:10 PM, Peter Eisentraut <
peter.eisentraut@2ndquadrant.com> wrote:

On 2/24/17 16:32, Pavel Stehule wrote:

set EXTENDED_DESCRIBE_SORT size_desc
\dt+
\l+
\di+

Possible variants: schema_table, table_schema, size_desc, size_asc

I can see this being useful, but I think it needs to be organized a
little better.

Sort key and sort direction should be separate settings.

I agree.

I'm not sure why we need to have separate settings to sort by schema

name and table name.

I think sorting by schema name, object name makes sense for people, who
have objects of same name in different schemas.

------
Alexander Korotkov
Postgres Professional: http://www.postgrespro.com
The Russian Postgres Company

#6Pavel Stehule
pavel.stehule@gmail.com
In reply to: Peter Eisentraut (#3)
Re: Re: proposal - psql: possibility to specify sort for describe commands, when size is printed

2017-03-10 15:10 GMT+01:00 Peter Eisentraut <
peter.eisentraut@2ndquadrant.com>:

On 2/24/17 16:32, Pavel Stehule wrote:

set EXTENDED_DESCRIBE_SORT size_desc
\dt+
\l+
\di+

Possible variants: schema_table, table_schema, size_desc, size_asc

I can see this being useful, but I think it needs to be organized a
little better.

Sort key and sort direction should be separate settings.

ok

maybe

PREFERRED_SORT_COLUMNS
and PREFERRED_SORT_DIRECTION ?

I'm not sure why we need to have separate settings to sort by schema
name and table name. But if we do, then we should support that for all
object types. I think maybe that's something we shouldn't get into
right now.

It can be useful, when you repeat one table name in more schema - usually,
where schema is related per one customer, project, ...

Regards

Pavel

Show quoted text

So I would have one setting for sort key = {name|size} and on for sort
direction = {asc|desc}.

--
Peter Eisentraut http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services

#7Alexander Korotkov
a.korotkov@postgrespro.ru
In reply to: Stephen Frost (#4)
Re: Re: proposal - psql: possibility to specify sort for describe commands, when size is printed

On Fri, Mar 10, 2017 at 5:16 PM, Stephen Frost <sfrost@snowman.net> wrote:

* Peter Eisentraut (peter.eisentraut@2ndquadrant.com) wrote:

On 2/24/17 16:32, Pavel Stehule wrote:

set EXTENDED_DESCRIBE_SORT size_desc
\dt+
\l+
\di+

Possible variants: schema_table, table_schema, size_desc, size_asc

I can see this being useful, but I think it needs to be organized a
little better.

Sort key and sort direction should be separate settings.

I'm not sure why we need to have separate settings to sort by schema
name and table name. But if we do, then we should support that for all
object types. I think maybe that's something we shouldn't get into
right now.

So I would have one setting for sort key = {name|size} and on for sort
direction = {asc|desc}.

Perhaps I'm trying to be overly cute here, but why not let the user
simply provide a bit of SQL to be put at the end of the query?

That is, something like:

\pset EXTENDED_DESCRIBE_ORDER_LIMIT 'ORDER BY 5 DESC LIMIT 10'

I think that's the question of usability. After all, one can manually type
corresponding SQL instead of \d* commands. However, it's quite cumbersome
to do this every time.
I found quite useful to being able to switch between different sortings
quickly. For instance, after seeing tables sorted by name, user can
require them sorted by size descending, then sorted by size ascending,
etc...
Therefore, I find user-defined SQL clause to be cumbersome. Even psql
variable itself seems to be cumbersome for me.
I would propose to add sorting as second optional argument to \d*
commands. Any thoughts?

------
Alexander Korotkov
Postgres Professional: http://www.postgrespro.com
The Russian Postgres Company

#8Pavel Stehule
pavel.stehule@gmail.com
In reply to: Stephen Frost (#4)
Re: Re: proposal - psql: possibility to specify sort for describe commands, when size is printed

2017-03-10 15:16 GMT+01:00 Stephen Frost <sfrost@snowman.net>:

* Peter Eisentraut (peter.eisentraut@2ndquadrant.com) wrote:

On 2/24/17 16:32, Pavel Stehule wrote:

set EXTENDED_DESCRIBE_SORT size_desc
\dt+
\l+
\di+

Possible variants: schema_table, table_schema, size_desc, size_asc

I can see this being useful, but I think it needs to be organized a
little better.

Sort key and sort direction should be separate settings.

I'm not sure why we need to have separate settings to sort by schema
name and table name. But if we do, then we should support that for all
object types. I think maybe that's something we shouldn't get into
right now.

So I would have one setting for sort key = {name|size} and on for sort
direction = {asc|desc}.

Perhaps I'm trying to be overly cute here, but why not let the user
simply provide a bit of SQL to be put at the end of the query?

That is, something like:

\pset EXTENDED_DESCRIBE_ORDER_LIMIT 'ORDER BY 5 DESC LIMIT 10'

For example - the size is displayed in pretty form - raw form is not
displayed - so simple ORDER BY clause is not possible.

But setting LIMIT is not bad idea - although it is probably much more
complex for implementation.

\pset DESCRIBE_LIMIT 100
\pset EXTENDED_DESCRIBE_LIMIT 100

can be implemented as next step

Regards

Pavel

Show quoted text

Thanks!

Stephen

#9Peter Eisentraut
peter.eisentraut@2ndquadrant.com
In reply to: Pavel Stehule (#6)
Re: Re: proposal - psql: possibility to specify sort for describe commands, when size is printed

On 3/10/17 09:57, Pavel Stehule wrote:

PREFERRED_SORT_COLUMNS
and PREFERRED_SORT_DIRECTION ?

I think the name "preferred" implies that it will be ignored if it's not
found or something like that, but I don't think that's what you are
implementing.

--
Peter Eisentraut http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

#10Pavel Stehule
pavel.stehule@gmail.com
In reply to: Alexander Korotkov (#7)
Re: Re: proposal - psql: possibility to specify sort for describe commands, when size is printed

2017-03-10 16:00 GMT+01:00 Alexander Korotkov <a.korotkov@postgrespro.ru>:

On Fri, Mar 10, 2017 at 5:16 PM, Stephen Frost <sfrost@snowman.net> wrote:

* Peter Eisentraut (peter.eisentraut@2ndquadrant.com) wrote:

On 2/24/17 16:32, Pavel Stehule wrote:

set EXTENDED_DESCRIBE_SORT size_desc
\dt+
\l+
\di+

Possible variants: schema_table, table_schema, size_desc, size_asc

I can see this being useful, but I think it needs to be organized a
little better.

Sort key and sort direction should be separate settings.

I'm not sure why we need to have separate settings to sort by schema
name and table name. But if we do, then we should support that for all
object types. I think maybe that's something we shouldn't get into
right now.

So I would have one setting for sort key = {name|size} and on for sort
direction = {asc|desc}.

Perhaps I'm trying to be overly cute here, but why not let the user
simply provide a bit of SQL to be put at the end of the query?

That is, something like:

\pset EXTENDED_DESCRIBE_ORDER_LIMIT 'ORDER BY 5 DESC LIMIT 10'

I think that's the question of usability. After all, one can manually
type corresponding SQL instead of \d* commands. However, it's quite
cumbersome to do this every time.
I found quite useful to being able to switch between different sortings
quickly. For instance, after seeing tables sorted by name, user can
require them sorted by size descending, then sorted by size ascending,
etc...
Therefore, I find user-defined SQL clause to be cumbersome. Even psql
variable itself seems to be cumbersome for me.
I would propose to add sorting as second optional argument to \d*
commands. Any thoughts?

This proposal was here already - maybe two years ago. The psql command
parser doesn't allow any complex syntax - more - the more parameters in one
psql commands is hard to remember, hard to read.

With my proposal, and patch I would to cover following use case. It is real
case. Anytime when we used \dt+ in psql we needed sort by size desc. When
we should to see a size, then the top is interesting. This case is not
absolute, but very often, so I would to create some simple way, how to do
some parametrization (really simple).

Pavel

Show quoted text

------
Alexander Korotkov
Postgres Professional: http://www.postgrespro.com
The Russian Postgres Company

#11Pavel Stehule
pavel.stehule@gmail.com
In reply to: Peter Eisentraut (#9)
Re: Re: proposal - psql: possibility to specify sort for describe commands, when size is printed

2017-03-10 16:05 GMT+01:00 Peter Eisentraut <
peter.eisentraut@2ndquadrant.com>:

On 3/10/17 09:57, Pavel Stehule wrote:

PREFERRED_SORT_COLUMNS
and PREFERRED_SORT_DIRECTION ?

I think the name "preferred" implies that it will be ignored if it's not
found or something like that, but I don't think that's what you are
implementing.

ok if it will be used only for verbose describe commands , then the name
EXTENDED_DESCRIBE_SORT_COLUMNS, and EXTENDED_DESCRIBE_SORT_DIRECTION.

Pavel

Show quoted text

--
Peter Eisentraut http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services

#12Pavel Stehule
pavel.stehule@gmail.com
In reply to: Alexander Korotkov (#5)
1 attachment(s)
Re: Re: proposal - psql: possibility to specify sort for describe commands, when size is printed

2017-03-10 15:45 GMT+01:00 Alexander Korotkov <a.korotkov@postgrespro.ru>:

On Fri, Mar 10, 2017 at 5:10 PM, Peter Eisentraut <
peter.eisentraut@2ndquadrant.com> wrote:

On 2/24/17 16:32, Pavel Stehule wrote:

set EXTENDED_DESCRIBE_SORT size_desc
\dt+
\l+
\di+

Possible variants: schema_table, table_schema, size_desc, size_asc

I can see this being useful, but I think it needs to be organized a
little better.

Sort key and sort direction should be separate settings.

I agree.

I'm not sure why we need to have separate settings to sort by schema

name and table name.

I think sorting by schema name, object name makes sense for people, who
have objects of same name in different schemas.

I am sending a updated version with separated sort direction in special
variable

There is a question. Has desc direction sense for columns like schema or
table name?

Using desc, asc for size is natural. But for tablename?

Regards

Pavel

Show quoted text

------
Alexander Korotkov
Postgres Professional: http://www.postgrespro.com
The Russian Postgres Company

Attachments:

psql-extended-describe-sort.patchtext/x-patch; charset=US-ASCII; name=psql-extended-describe-sort.patchDownload
diff --git a/doc/src/sgml/ref/psql-ref.sgml b/doc/src/sgml/ref/psql-ref.sgml
index 2a9c412020..747db58dd8 100644
--- a/doc/src/sgml/ref/psql-ref.sgml
+++ b/doc/src/sgml/ref/psql-ref.sgml
@@ -3507,6 +3507,27 @@ bar
       </varlistentry>
 
       <varlistentry>
+        <term><varname>VERBOSE_SORT_COLUMNS</varname></term>
+        <listitem>
+        <para>
+        This variable can be set to the values <literal>schema_name</>,
+        <literal>name_schema</> or <literal>size</> to control the 
+        order of content of decrible command.
+        </para>
+        </listitem>
+      </varlistentry>
+
+      <varlistentry>
+        <term><varname>VERBOSE_SORT_DIRECTION</varname></term>
+        <listitem>
+        <para>
+        This variable can be set to the values <literal>asc</>,
+        or <literal>desc</> to control the order of content of decrible command.
+        </para>
+        </listitem>
+      </varlistentry>
+
+      <varlistentry>
         <term><varname>VERBOSITY</varname></term>
         <listitem>
         <para>
diff --git a/src/bin/psql/describe.c b/src/bin/psql/describe.c
index 61a3e2a848..7ba24ea883 100644
--- a/src/bin/psql/describe.c
+++ b/src/bin/psql/describe.c
@@ -197,6 +197,9 @@ describeAccessMethods(const char *pattern, bool verbose)
 	return true;
 }
 
+#define SORT_DIRECTION_STR(v)		((v) == PSQL_SORT_ASC ? "ASC" : "DESC")
+
+
 /* \db
  * Takes an optional regexp to select particular tablespaces
  */
@@ -264,7 +267,18 @@ describeTablespaces(const char *pattern, bool verbose)
 						  NULL, "spcname", NULL,
 						  NULL);
 
-	appendPQExpBufferStr(&buf, "ORDER BY 1;");
+
+	if (verbose && pset.sversion >= 90200)
+	{
+		if (pset.verbose_sort_columns == PSQL_SORT_SIZE)
+			appendPQExpBuffer(&buf,
+							  "ORDER BY pg_catalog.pg_tablespace_size(oid) %s, 1;",
+							  SORT_DIRECTION_STR(pset.verbose_sort_direction));
+		else
+			appendPQExpBufferStr(&buf, "ORDER BY 1;");
+	}
+	else
+		appendPQExpBufferStr(&buf, "ORDER BY 1;");
 
 	res = PSQLexec(buf.data);
 	termPQExpBuffer(&buf);
@@ -824,7 +838,19 @@ listAllDbs(const char *pattern, bool verbose)
 		processSQLNamePattern(pset.db, &buf, pattern, false, false,
 							  NULL, "d.datname", NULL, NULL);
 
-	appendPQExpBufferStr(&buf, "ORDER BY 1;");
+	if (verbose && pset.sversion >= 80200)
+	{
+		if (pset.verbose_sort_columns == PSQL_SORT_SIZE)
+			appendPQExpBuffer(&buf,
+						  "ORDER BY CASE WHEN pg_catalog.has_database_privilege(d.datname, 'CONNECT')\n"
+						  "              THEN pg_catalog.pg_database_size(d.datname) END %s, 1;\n",
+						  SORT_DIRECTION_STR(pset.verbose_sort_direction));
+		else
+			appendPQExpBufferStr(&buf, "ORDER BY 1");
+	}
+	else
+		appendPQExpBufferStr(&buf, "ORDER BY 1");
+
 	res = PSQLexec(buf.data);
 	termPQExpBuffer(&buf);
 	if (!res)
@@ -3295,7 +3321,26 @@ listTables(const char *tabtypes, const char *pattern, bool verbose, bool showSys
 						  "n.nspname", "c.relname", NULL,
 						  "pg_catalog.pg_table_is_visible(c.oid)");
 
-	appendPQExpBufferStr(&buf, "ORDER BY 1,2;");
+	if (verbose && pset.sversion >= 80100)
+	{
+		if (pset.verbose_sort_columns == PSQL_SORT_SCHEMA_NAME)
+			appendPQExpBufferStr(&buf, "ORDER BY 1,2;");
+		else if (pset.verbose_sort_columns == PSQL_SORT_NAME_SCHEMA)
+			appendPQExpBufferStr(&buf, "ORDER BY 2,1;");
+		else
+		{
+			if (pset.sversion >= 90000)
+				appendPQExpBuffer(&buf,
+					"ORDER BY pg_catalog.pg_table_size(c.oid) %s, 1,2",
+					SORT_DIRECTION_STR(pset.verbose_sort_direction));
+			else
+				appendPQExpBuffer(&buf,
+					"ORDER BY pg_catalog.pg_relation_size(c.oid) %s, 1,2",
+					SORT_DIRECTION_STR(pset.verbose_sort_direction));
+		}
+	}
+	else
+		appendPQExpBufferStr(&buf, "ORDER BY 1,2;");
 
 	res = PSQLexec(buf.data);
 	termPQExpBuffer(&buf);
diff --git a/src/bin/psql/help.c b/src/bin/psql/help.c
index ba14df0344..1ebe397a85 100644
--- a/src/bin/psql/help.c
+++ b/src/bin/psql/help.c
@@ -327,7 +327,7 @@ helpVariables(unsigned short int pager)
 	 * Windows builds currently print one more line than non-Windows builds.
 	 * Using the larger number is fine.
 	 */
-	output = PageOutput(88, pager ? &(pset.popt.topt) : NULL);
+	output = PageOutput(92, pager ? &(pset.popt.topt) : NULL);
 
 	fprintf(output, _("List of specially treated variables\n\n"));
 
@@ -364,6 +364,10 @@ helpVariables(unsigned short int pager)
 	fprintf(output, _("  SINGLESTEP         single-step mode (same as -s option)\n"));
 	fprintf(output, _("  USER               the currently connected database user\n"));
 	fprintf(output, _("  VERBOSITY          controls verbosity of error reports [default, verbose, terse]\n"));
+	fprintf(output, _("  VERBOSE_SORT_COLUMNS\n"
+					  "                     sort columns for verbose mode [schema_name, name_schema, size]\n"));
+	fprintf(output, _("  VERBOSE_SORT_DIRECTION\n"
+					  "                     direction of sort of verbose mode [asc, desc]\n"));
 
 	fprintf(output, _("\nDisplay settings:\n"));
 	fprintf(output, _("Usage:\n"));
diff --git a/src/bin/psql/settings.h b/src/bin/psql/settings.h
index 70ff1812c8..0f2af11d89 100644
--- a/src/bin/psql/settings.h
+++ b/src/bin/psql/settings.h
@@ -77,6 +77,19 @@ enum trivalue
 	TRI_YES
 };
 
+typedef enum
+{
+	PSQL_SORT_SCHEMA_NAME,
+	PSQL_SORT_NAME_SCHEMA,
+	PSQL_SORT_SIZE,
+} PSQL_SORT_COLUMNS;
+
+typedef enum
+{
+	PSQL_SORT_ASC,
+	PSQL_SORT_DESC
+} PSQL_SORT_DIRECTION;
+
 typedef struct _psqlSettings
 {
 	PGconn	   *db;				/* connection to backend */
@@ -138,6 +151,8 @@ typedef struct _psqlSettings
 	const char *prompt3;
 	PGVerbosity verbosity;		/* current error verbosity level */
 	PGContextVisibility show_context;	/* current context display level */
+	PSQL_SORT_COLUMNS	verbose_sort_columns;	/* sort columns for describe verbose command */
+	PSQL_SORT_DIRECTION verbose_sort_direction;	/* sort direction for describe verbose command */
 } PsqlSettings;
 
 extern PsqlSettings pset;
diff --git a/src/bin/psql/startup.c b/src/bin/psql/startup.c
index 694f0ef257..c25140e33d 100644
--- a/src/bin/psql/startup.c
+++ b/src/bin/psql/startup.c
@@ -168,6 +168,9 @@ main(int argc, char *argv[])
 	SetVariable(pset.vars, "PROMPT2", DEFAULT_PROMPT2);
 	SetVariable(pset.vars, "PROMPT3", DEFAULT_PROMPT3);
 
+	SetVariable(pset.vars, "VERBOSE_SORT_COLUMNS", "schema_name");
+	SetVariable(pset.vars, "VERBOSE_SORT_DIRECTION", "asc");
+
 	parse_psql_options(argc, argv, &options);
 
 	/*
@@ -1068,6 +1071,60 @@ verbosity_hook(const char *newval)
 }
 
 static char *
+verbose_sort_columns_substitute_hook(char *newval)
+{
+	if (newval == NULL)
+		newval = pg_strdup("schema_name");
+	return newval;
+}
+
+static bool
+verbose_sort_columns_hook(const char *newval)
+{
+	Assert(newval != NULL);		/* else substitute hook messed up */
+	if (pg_strcasecmp(newval, "schema_name") == 0)
+		pset.verbose_sort_columns = PSQL_SORT_SCHEMA_NAME;
+	else if (pg_strcasecmp(newval, "name_schema") == 0)
+		pset.verbose_sort_columns = PSQL_SORT_NAME_SCHEMA;
+	else if (pg_strcasecmp(newval, "size") == 0)
+		pset.verbose_sort_columns = PSQL_SORT_SIZE;
+	else
+	{
+		PsqlVarEnumError("VERBOSE_SORT_COLUMNS", newval,
+						 "schema_name, name_schema, size");
+		return false;
+	}
+
+	return true;
+}
+
+static char *
+verbose_sort_direction_substitute_hook(char *newval)
+{
+	if (newval == NULL)
+		newval = pg_strdup("asc");
+	return newval;
+}
+
+static bool
+verbose_sort_direction_hook(const char *newval)
+{
+	Assert(newval != NULL);		/* else substitute hook messed up */
+	if (pg_strcasecmp(newval, "asc") == 0)
+		pset.verbose_sort_direction = PSQL_SORT_ASC;
+	else if (pg_strcasecmp(newval, "desc") == 0)
+		pset.verbose_sort_direction = PSQL_SORT_DESC;
+	else
+	{
+		PsqlVarEnumError("VERBOSE_SORT_DIRECTION", newval, "asc, desc");
+		return false;
+	}
+
+	return true;
+}
+
+
+static char *
 show_context_substitute_hook(char *newval)
 {
 	if (newval == NULL)
@@ -1156,6 +1213,12 @@ EstablishVariableSpace(void)
 	SetVariableHooks(pset.vars, "VERBOSITY",
 					 verbosity_substitute_hook,
 					 verbosity_hook);
+	SetVariableHooks(pset.vars, "VERBOSE_SORT_COLUMNS",
+					 verbose_sort_columns_substitute_hook,
+					 verbose_sort_columns_hook);
+	SetVariableHooks(pset.vars, "VERBOSE_SORT_DIRECTION",
+					 verbose_sort_direction_substitute_hook,
+					 verbose_sort_direction_hook);
 	SetVariableHooks(pset.vars, "SHOW_CONTEXT",
 					 show_context_substitute_hook,
 					 show_context_hook);
diff --git a/src/bin/psql/tab-complete.c b/src/bin/psql/tab-complete.c
index e8458e939e..a252c5fa33 100644
--- a/src/bin/psql/tab-complete.c
+++ b/src/bin/psql/tab-complete.c
@@ -3416,6 +3416,10 @@ psql_completion(const char *text, int start, int end)
 			COMPLETE_WITH_LIST_CS3("never", "errors", "always");
 		else if (TailMatchesCS1("VERBOSITY"))
 			COMPLETE_WITH_LIST_CS3("default", "verbose", "terse");
+		else if (TailMatchesCS1("VERBOSE_SORT_COLUMNS"))
+			COMPLETE_WITH_LIST_CS3("schema_name", "name_schema","size");
+		else if (TailMatchesCS1("VERBOSE_SORT_DIRECTION"))
+			COMPLETE_WITH_LIST_CS2("asc", "desc");
 	}
 	else if (TailMatchesCS1("\\sf*"))
 		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_functions, NULL);
#13David Steele
david@pgmasters.net
In reply to: Pavel Stehule (#12)
Re: proposal - psql: possibility to specify sort for describe commands, when size is printed

Hi Alexander,

On 3/11/17 7:06 AM, Pavel Stehule wrote:

I am sending a updated version with separated sort direction in special
variable

There is a question. Has desc direction sense for columns like schema or
table name?

Using desc, asc for size is natural. But for tablename?

Do you know when you'll have a chance to review the updated patch?

Thanks,
--
-David
david@pgmasters.net

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

#14Alexander Korotkov
a.korotkov@postgrespro.ru
In reply to: Pavel Stehule (#10)
Re: Re: proposal - psql: possibility to specify sort for describe commands, when size is printed

On Fri, Mar 10, 2017 at 6:06 PM, Pavel Stehule <pavel.stehule@gmail.com>
wrote:

2017-03-10 16:00 GMT+01:00 Alexander Korotkov <a.korotkov@postgrespro.ru>:

On Fri, Mar 10, 2017 at 5:16 PM, Stephen Frost <sfrost@snowman.net>
wrote:

* Peter Eisentraut (peter.eisentraut@2ndquadrant.com) wrote:

On 2/24/17 16:32, Pavel Stehule wrote:

set EXTENDED_DESCRIBE_SORT size_desc
\dt+
\l+
\di+

Possible variants: schema_table, table_schema, size_desc,

size_asc

I can see this being useful, but I think it needs to be organized a
little better.

Sort key and sort direction should be separate settings.

I'm not sure why we need to have separate settings to sort by schema
name and table name. But if we do, then we should support that for all
object types. I think maybe that's something we shouldn't get into
right now.

So I would have one setting for sort key = {name|size} and on for sort
direction = {asc|desc}.

Perhaps I'm trying to be overly cute here, but why not let the user
simply provide a bit of SQL to be put at the end of the query?

That is, something like:

\pset EXTENDED_DESCRIBE_ORDER_LIMIT 'ORDER BY 5 DESC LIMIT 10'

I think that's the question of usability. After all, one can manually
type corresponding SQL instead of \d* commands. However, it's quite
cumbersome to do this every time.
I found quite useful to being able to switch between different sortings
quickly. For instance, after seeing tables sorted by name, user can
require them sorted by size descending, then sorted by size ascending,
etc...
Therefore, I find user-defined SQL clause to be cumbersome. Even psql
variable itself seems to be cumbersome for me.
I would propose to add sorting as second optional argument to \d*
commands. Any thoughts?

This proposal was here already - maybe two years ago. The psql command
parser doesn't allow any complex syntax - more - the more parameters in one
psql commands is hard to remember, hard to read.

Could you please provide a link to this discussion. Probably working with
multiple parameters in psql commands require some rework, but that's
definitely doable.

With my proposal, and patch I would to cover following use case. It is
real case. Anytime when we used \dt+ in psql we needed sort by size desc.
When we should to see a size, then the top is interesting. This case is not
absolute, but very often, so I would to create some simple way, how to do
some parametrization (really simple).

We could combine both approaches: add parameters to psql commands and add
psql DEFAULT_(SORT_COLUMNS|DIRECTION|LIMIT) parameters.

------
Alexander Korotkov
Postgres Professional: http://www.postgrespro.com
The Russian Postgres Company

#15Pavel Stehule
pavel.stehule@gmail.com
In reply to: Alexander Korotkov (#14)
Re: Re: proposal - psql: possibility to specify sort for describe commands, when size is printed

2017-03-27 13:59 GMT+02:00 Alexander Korotkov <a.korotkov@postgrespro.ru>:

On Fri, Mar 10, 2017 at 6:06 PM, Pavel Stehule <pavel.stehule@gmail.com>
wrote:

2017-03-10 16:00 GMT+01:00 Alexander Korotkov <a.korotkov@postgrespro.ru>
:

On Fri, Mar 10, 2017 at 5:16 PM, Stephen Frost <sfrost@snowman.net>
wrote:

* Peter Eisentraut (peter.eisentraut@2ndquadrant.com) wrote:

On 2/24/17 16:32, Pavel Stehule wrote:

set EXTENDED_DESCRIBE_SORT size_desc
\dt+
\l+
\di+

Possible variants: schema_table, table_schema, size_desc,

size_asc

I can see this being useful, but I think it needs to be organized a
little better.

Sort key and sort direction should be separate settings.

I'm not sure why we need to have separate settings to sort by schema
name and table name. But if we do, then we should support that for

all

object types. I think maybe that's something we shouldn't get into
right now.

So I would have one setting for sort key = {name|size} and on for sort
direction = {asc|desc}.

Perhaps I'm trying to be overly cute here, but why not let the user
simply provide a bit of SQL to be put at the end of the query?

That is, something like:

\pset EXTENDED_DESCRIBE_ORDER_LIMIT 'ORDER BY 5 DESC LIMIT 10'

I think that's the question of usability. After all, one can manually
type corresponding SQL instead of \d* commands. However, it's quite
cumbersome to do this every time.
I found quite useful to being able to switch between different sortings
quickly. For instance, after seeing tables sorted by name, user can
require them sorted by size descending, then sorted by size ascending,
etc...
Therefore, I find user-defined SQL clause to be cumbersome. Even psql
variable itself seems to be cumbersome for me.
I would propose to add sorting as second optional argument to \d*
commands. Any thoughts?

This proposal was here already - maybe two years ago. The psql command
parser doesn't allow any complex syntax - more - the more parameters in one
psql commands is hard to remember, hard to read.

Could you please provide a link to this discussion. Probably working with
multiple parameters in psql commands require some rework, but that's
definitely doable.

http://grokbase.com/t/postgresql/pgsql-hackers/137nt5p6s0/proposal-psql-show-longest-tables/oldest
/messages/by-id/AANLkTikyaeJ0XdKDzxSvqPE8kaRRTiUQJQHwNJ8ecN2W@mail.gmail.com

With my proposal, and patch I would to cover following use case. It is
real case. Anytime when we used \dt+ in psql we needed sort by size desc.
When we should to see a size, then the top is interesting. This case is not
absolute, but very often, so I would to create some simple way, how to do
some parametrization (really simple).

We could combine both approaches: add parameters to psql commands and add
psql DEFAULT_(SORT_COLUMNS|DIRECTION|LIMIT) parameters.

It is possible - This moment is my interest concentrated to psql settings -
the unpractical order in \dt+ irritate me :). I understand so it depends on
use-case. I worked in OLAP and still I have lot of customers with
performance incidents - the first task - show most big tables, most big
indexes.

Regards

Pavel

Show quoted text

------
Alexander Korotkov
Postgres Professional: http://www.postgrespro.com
The Russian Postgres Company

#16Alexander Korotkov
a.korotkov@postgrespro.ru
In reply to: Pavel Stehule (#15)
Re: Re: proposal - psql: possibility to specify sort for describe commands, when size is printed

On Tue, Mar 28, 2017 at 10:12 AM, Pavel Stehule <pavel.stehule@gmail.com>
wrote:

2017-03-27 13:59 GMT+02:00 Alexander Korotkov <a.korotkov@postgrespro.ru>:

On Fri, Mar 10, 2017 at 6:06 PM, Pavel Stehule <pavel.stehule@gmail.com>
wrote:

2017-03-10 16:00 GMT+01:00 Alexander Korotkov <a.korotkov@postgrespro.ru

:

On Fri, Mar 10, 2017 at 5:16 PM, Stephen Frost <sfrost@snowman.net>
wrote:

* Peter Eisentraut (peter.eisentraut@2ndquadrant.com) wrote:

On 2/24/17 16:32, Pavel Stehule wrote:

set EXTENDED_DESCRIBE_SORT size_desc
\dt+
\l+
\di+

Possible variants: schema_table, table_schema, size_desc,

size_asc

I can see this being useful, but I think it needs to be organized a
little better.

Sort key and sort direction should be separate settings.

I'm not sure why we need to have separate settings to sort by schema
name and table name. But if we do, then we should support that for

all

object types. I think maybe that's something we shouldn't get into
right now.

So I would have one setting for sort key = {name|size} and on for

sort

direction = {asc|desc}.

Perhaps I'm trying to be overly cute here, but why not let the user
simply provide a bit of SQL to be put at the end of the query?

That is, something like:

\pset EXTENDED_DESCRIBE_ORDER_LIMIT 'ORDER BY 5 DESC LIMIT 10'

I think that's the question of usability. After all, one can manually
type corresponding SQL instead of \d* commands. However, it's quite
cumbersome to do this every time.
I found quite useful to being able to switch between different sortings
quickly. For instance, after seeing tables sorted by name, user can
require them sorted by size descending, then sorted by size ascending,
etc...
Therefore, I find user-defined SQL clause to be cumbersome. Even psql
variable itself seems to be cumbersome for me.
I would propose to add sorting as second optional argument to \d*
commands. Any thoughts?

This proposal was here already - maybe two years ago. The psql command
parser doesn't allow any complex syntax - more - the more parameters in one
psql commands is hard to remember, hard to read.

Could you please provide a link to this discussion. Probably working
with multiple parameters in psql commands require some rework, but that's
definitely doable.

http://grokbase.com/t/postgresql/pgsql-hackers/
137nt5p6s0/proposal-psql-show-longest-tables/oldest
/messages/by-id/AANLkTikyaeJ0XdKDzxSvqPE8kaRRT
iUQJQHwNJ8ecN2W@mail.gmail.com

I took a look to these threads, but I didn't find place where difficulties
of adding extra arguments to psql commands are pointed.
Could you, please, point particular messages about it?

------
Alexander Korotkov
Postgres Professional: http://www.postgrespro.com
The Russian Postgres Company

#17Pavel Stehule
pavel.stehule@gmail.com
In reply to: Alexander Korotkov (#16)
Re: Re: proposal - psql: possibility to specify sort for describe commands, when size is printed

This proposal was here already - maybe two years ago. The psql command
parser doesn't allow any complex syntax - more - the more parameters in one
psql commands is hard to remember, hard to read.

Could you please provide a link to this discussion. Probably working
with multiple parameters in psql commands require some rework, but that's
definitely doable.

http://grokbase.com/t/postgresql/pgsql-hackers/137nt5p6s0/
proposal-psql-show-longest-tables/oldest
/messages/by-id/AANLkTikyaeJ0XdKDzxSvq
PE8kaRRTiUQJQHwNJ8ecN2W@mail.gmail.com

I took a look to these threads, but I didn't find place where difficulties
of adding extra arguments to psql commands are pointed.
Could you, please, point particular messages about it?

I am sorry - maybe my memory doesn't serve well

Pavel

Show quoted text

------
Alexander Korotkov
Postgres Professional: http://www.postgrespro.com
The Russian Postgres Company

#18Andres Freund
andres@anarazel.de
In reply to: Pavel Stehule (#12)
Re: Re: proposal - psql: possibility to specify sort for describe commands, when size is printed

Hi,

On 2017-03-11 13:06:13 +0100, Pavel Stehule wrote:

2017-03-10 15:45 GMT+01:00 Alexander Korotkov <a.korotkov@postgrespro.ru>:

On Fri, Mar 10, 2017 at 5:10 PM, Peter Eisentraut <
peter.eisentraut@2ndquadrant.com> wrote:

On 2/24/17 16:32, Pavel Stehule wrote:

set EXTENDED_DESCRIBE_SORT size_desc
\dt+
\l+
\di+

Possible variants: schema_table, table_schema, size_desc, size_asc

I can see this being useful, but I think it needs to be organized a
little better.

Sort key and sort direction should be separate settings.

I agree.

I'm not sure why we need to have separate settings to sort by schema

name and table name.

I think sorting by schema name, object name makes sense for people, who
have objects of same name in different schemas.

I am sending a updated version with separated sort direction in special
variable

There is a question. Has desc direction sense for columns like schema or
table name?

Using desc, asc for size is natural. But for tablename?

I think it's pretty clear that we don't have sufficient agreement on the
design, not to speak of an implementation for an agreed upon design, to
get this into v10. The patch also has been submitted late in the v10
cycle, and has received attention. I'm therefore moving it to the next
commitfest.

Regards,

Andres

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

#19Peter Eisentraut
peter.eisentraut@2ndquadrant.com
In reply to: Pavel Stehule (#12)
Re: Re: proposal - psql: possibility to specify sort for describe commands, when size is printed

On 3/11/17 07:06, Pavel Stehule wrote:

I am sending a updated version with separated sort direction in special
variable

This patch also needs a rebase.

--
Peter Eisentraut http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

#20Pavel Stehule
pavel.stehule@gmail.com
In reply to: Peter Eisentraut (#19)
1 attachment(s)
Re: Re: proposal - psql: possibility to specify sort for describe commands, when size is printed

Hi

2017-08-15 4:37 GMT+02:00 Peter Eisentraut <peter.eisentraut@2ndquadrant.com

:

On 3/11/17 07:06, Pavel Stehule wrote:

I am sending a updated version with separated sort direction in special
variable

This patch also needs a rebase.

I am sending rebased patch

Regards

Pavel

Show quoted text

--
Peter Eisentraut http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services

Attachments:

psql-extended-describe-sort-2.patchtext/x-patch; charset=US-ASCII; name=psql-extended-describe-sort-2.patchDownload
diff --git a/doc/src/sgml/ref/psql-ref.sgml b/doc/src/sgml/ref/psql-ref.sgml
index c592edac60..9bc391cb39 100644
--- a/doc/src/sgml/ref/psql-ref.sgml
+++ b/doc/src/sgml/ref/psql-ref.sgml
@@ -3719,6 +3719,27 @@ bar
       </varlistentry>
 
       <varlistentry>
+        <term><varname>VERBOSE_SORT_COLUMNS</varname></term>
+        <listitem>
+        <para>
+        This variable can be set to the values <literal>schema_name</>,
+        <literal>name_schema</> or <literal>size</> to control the 
+        order of content of decrible command.
+        </para>
+        </listitem>
+      </varlistentry>
+
+      <varlistentry>
+        <term><varname>VERBOSE_SORT_DIRECTION</varname></term>
+        <listitem>
+        <para>
+        This variable can be set to the values <literal>asc</>,
+        or <literal>desc</> to control the order of content of decrible command.
+        </para>
+        </listitem>
+      </varlistentry>
+
+      <varlistentry>
         <term><varname>VERBOSITY</varname></term>
         <listitem>
         <para>
diff --git a/src/bin/psql/describe.c b/src/bin/psql/describe.c
index f6049cc9e5..1b2346d38b 100644
--- a/src/bin/psql/describe.c
+++ b/src/bin/psql/describe.c
@@ -200,6 +200,8 @@ describeAccessMethods(const char *pattern, bool verbose)
 	return true;
 }
 
+#define SORT_DIRECTION_STR(v)		((v) == PSQL_SORT_ASC ? "ASC" : "DESC")
+
 /*
  * \db
  * Takes an optional regexp to select particular tablespaces
@@ -268,7 +270,18 @@ describeTablespaces(const char *pattern, bool verbose)
 						  NULL, "spcname", NULL,
 						  NULL);
 
-	appendPQExpBufferStr(&buf, "ORDER BY 1;");
+
+	if (verbose && pset.sversion >= 90200)
+	{
+		if (pset.verbose_sort_columns == PSQL_SORT_SIZE)
+			appendPQExpBuffer(&buf,
+							  "ORDER BY pg_catalog.pg_tablespace_size(oid) %s, 1;",
+							  SORT_DIRECTION_STR(pset.verbose_sort_direction));
+		else
+			appendPQExpBufferStr(&buf, "ORDER BY 1;");
+	}
+	else
+		appendPQExpBufferStr(&buf, "ORDER BY 1;");
 
 	res = PSQLexec(buf.data);
 	termPQExpBuffer(&buf);
@@ -830,7 +843,19 @@ listAllDbs(const char *pattern, bool verbose)
 		processSQLNamePattern(pset.db, &buf, pattern, false, false,
 							  NULL, "d.datname", NULL, NULL);
 
-	appendPQExpBufferStr(&buf, "ORDER BY 1;");
+	if (verbose && pset.sversion >= 80200)
+	{
+		if (pset.verbose_sort_columns == PSQL_SORT_SIZE)
+			appendPQExpBuffer(&buf,
+						  "ORDER BY CASE WHEN pg_catalog.has_database_privilege(d.datname, 'CONNECT')\n"
+						  "              THEN pg_catalog.pg_database_size(d.datname) END %s, 1;\n",
+						  SORT_DIRECTION_STR(pset.verbose_sort_direction));
+		else
+			appendPQExpBufferStr(&buf, "ORDER BY 1");
+	}
+	else
+		appendPQExpBufferStr(&buf, "ORDER BY 1");
+
 	res = PSQLexec(buf.data);
 	termPQExpBuffer(&buf);
 	if (!res)
@@ -3422,7 +3447,26 @@ listTables(const char *tabtypes, const char *pattern, bool verbose, bool showSys
 						  "n.nspname", "c.relname", NULL,
 						  "pg_catalog.pg_table_is_visible(c.oid)");
 
-	appendPQExpBufferStr(&buf, "ORDER BY 1,2;");
+	if (verbose && pset.sversion >= 80100)
+	{
+		if (pset.verbose_sort_columns == PSQL_SORT_SCHEMA_NAME)
+			appendPQExpBufferStr(&buf, "ORDER BY 1,2;");
+		else if (pset.verbose_sort_columns == PSQL_SORT_NAME_SCHEMA)
+			appendPQExpBufferStr(&buf, "ORDER BY 2,1;");
+		else
+		{
+			if (pset.sversion >= 90000)
+				appendPQExpBuffer(&buf,
+					"ORDER BY pg_catalog.pg_table_size(c.oid) %s, 1,2",
+					SORT_DIRECTION_STR(pset.verbose_sort_direction));
+			else
+				appendPQExpBuffer(&buf,
+					"ORDER BY pg_catalog.pg_relation_size(c.oid) %s, 1,2",
+					SORT_DIRECTION_STR(pset.verbose_sort_direction));
+		}
+	}
+	else
+		appendPQExpBufferStr(&buf, "ORDER BY 1,2;");
 
 	res = PSQLexec(buf.data);
 	termPQExpBuffer(&buf);
diff --git a/src/bin/psql/help.c b/src/bin/psql/help.c
index b3dbb5946e..abdc6555b6 100644
--- a/src/bin/psql/help.c
+++ b/src/bin/psql/help.c
@@ -336,7 +336,7 @@ helpVariables(unsigned short int pager)
 	 * Windows builds currently print one more line than non-Windows builds.
 	 * Using the larger number is fine.
 	 */
-	output = PageOutput(88, pager ? &(pset.popt.topt) : NULL);
+	output = PageOutput(92, pager ? &(pset.popt.topt) : NULL);
 
 	fprintf(output, _("List of specially treated variables\n\n"));
 
@@ -373,6 +373,10 @@ helpVariables(unsigned short int pager)
 	fprintf(output, _("  SINGLESTEP         single-step mode (same as -s option)\n"));
 	fprintf(output, _("  USER               the currently connected database user\n"));
 	fprintf(output, _("  VERBOSITY          controls verbosity of error reports [default, verbose, terse]\n"));
+	fprintf(output, _("  VERBOSE_SORT_COLUMNS\n"
+					  "                     sort columns for verbose mode [schema_name, name_schema, size]\n"));
+	fprintf(output, _("  VERBOSE_SORT_DIRECTION\n"
+					  "                     direction of sort of verbose mode [asc, desc]\n"));
 
 	fprintf(output, _("\nDisplay settings:\n"));
 	fprintf(output, _("Usage:\n"));
diff --git a/src/bin/psql/settings.h b/src/bin/psql/settings.h
index b78f151acd..32249df15c 100644
--- a/src/bin/psql/settings.h
+++ b/src/bin/psql/settings.h
@@ -77,6 +77,19 @@ enum trivalue
 	TRI_YES
 };
 
+typedef enum
+{
+	PSQL_SORT_SCHEMA_NAME,
+	PSQL_SORT_NAME_SCHEMA,
+	PSQL_SORT_SIZE,
+} PSQL_SORT_COLUMNS;
+
+typedef enum
+{
+	PSQL_SORT_ASC,
+	PSQL_SORT_DESC
+} PSQL_SORT_DIRECTION;
+
 typedef struct _psqlSettings
 {
 	PGconn	   *db;				/* connection to backend */
@@ -138,6 +151,8 @@ typedef struct _psqlSettings
 	const char *prompt3;
 	PGVerbosity verbosity;		/* current error verbosity level */
 	PGContextVisibility show_context;	/* current context display level */
+	PSQL_SORT_COLUMNS	verbose_sort_columns;	/* sort columns for describe verbose command */
+	PSQL_SORT_DIRECTION verbose_sort_direction;	/* sort direction for describe verbose command */
 } PsqlSettings;
 
 extern PsqlSettings pset;
diff --git a/src/bin/psql/startup.c b/src/bin/psql/startup.c
index 7f767976a5..8e3fb1bd78 100644
--- a/src/bin/psql/startup.c
+++ b/src/bin/psql/startup.c
@@ -168,6 +168,9 @@ main(int argc, char *argv[])
 	SetVariable(pset.vars, "PROMPT2", DEFAULT_PROMPT2);
 	SetVariable(pset.vars, "PROMPT3", DEFAULT_PROMPT3);
 
+	SetVariable(pset.vars, "VERBOSE_SORT_COLUMNS", "schema_name");
+	SetVariable(pset.vars, "VERBOSE_SORT_DIRECTION", "asc");
+
 	parse_psql_options(argc, argv, &options);
 
 	/*
@@ -1075,6 +1078,60 @@ verbosity_hook(const char *newval)
 }
 
 static char *
+verbose_sort_columns_substitute_hook(char *newval)
+{
+	if (newval == NULL)
+		newval = pg_strdup("schema_name");
+	return newval;
+}
+
+static bool
+verbose_sort_columns_hook(const char *newval)
+{
+	Assert(newval != NULL);		/* else substitute hook messed up */
+	if (pg_strcasecmp(newval, "schema_name") == 0)
+		pset.verbose_sort_columns = PSQL_SORT_SCHEMA_NAME;
+	else if (pg_strcasecmp(newval, "name_schema") == 0)
+		pset.verbose_sort_columns = PSQL_SORT_NAME_SCHEMA;
+	else if (pg_strcasecmp(newval, "size") == 0)
+		pset.verbose_sort_columns = PSQL_SORT_SIZE;
+	else
+	{
+		PsqlVarEnumError("VERBOSE_SORT_COLUMNS", newval,
+						 "schema_name, name_schema, size");
+		return false;
+	}
+
+	return true;
+}
+
+static char *
+verbose_sort_direction_substitute_hook(char *newval)
+{
+	if (newval == NULL)
+		newval = pg_strdup("asc");
+	return newval;
+}
+
+static bool
+verbose_sort_direction_hook(const char *newval)
+{
+	Assert(newval != NULL);		/* else substitute hook messed up */
+	if (pg_strcasecmp(newval, "asc") == 0)
+		pset.verbose_sort_direction = PSQL_SORT_ASC;
+	else if (pg_strcasecmp(newval, "desc") == 0)
+		pset.verbose_sort_direction = PSQL_SORT_DESC;
+	else
+	{
+		PsqlVarEnumError("VERBOSE_SORT_DIRECTION", newval, "asc, desc");
+		return false;
+	}
+
+	return true;
+}
+
+
+static char *
 show_context_substitute_hook(char *newval)
 {
 	if (newval == NULL)
@@ -1163,6 +1220,12 @@ EstablishVariableSpace(void)
 	SetVariableHooks(pset.vars, "VERBOSITY",
 					 verbosity_substitute_hook,
 					 verbosity_hook);
+	SetVariableHooks(pset.vars, "VERBOSE_SORT_COLUMNS",
+					 verbose_sort_columns_substitute_hook,
+					 verbose_sort_columns_hook);
+	SetVariableHooks(pset.vars, "VERBOSE_SORT_DIRECTION",
+					 verbose_sort_direction_substitute_hook,
+					 verbose_sort_direction_hook);
 	SetVariableHooks(pset.vars, "SHOW_CONTEXT",
 					 show_context_substitute_hook,
 					 show_context_hook);
diff --git a/src/bin/psql/tab-complete.c b/src/bin/psql/tab-complete.c
index 1583cfa998..963f537a24 100644
--- a/src/bin/psql/tab-complete.c
+++ b/src/bin/psql/tab-complete.c
@@ -3564,6 +3564,10 @@ psql_completion(const char *text, int start, int end)
 			COMPLETE_WITH_LIST_CS3("never", "errors", "always");
 		else if (TailMatchesCS1("VERBOSITY"))
 			COMPLETE_WITH_LIST_CS3("default", "verbose", "terse");
+		else if (TailMatchesCS1("VERBOSE_SORT_COLUMNS"))
+			COMPLETE_WITH_LIST_CS3("schema_name", "name_schema","size");
+		else if (TailMatchesCS1("VERBOSE_SORT_DIRECTION"))
+			COMPLETE_WITH_LIST_CS2("asc", "desc");
 	}
 	else if (TailMatchesCS1("\\sf*"))
 		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_functions, NULL);
#21Pavel Stehule
pavel.stehule@gmail.com
In reply to: Pavel Stehule (#20)
1 attachment(s)
Re: Re: proposal - psql: possibility to specify sort for describe commands, when size is printed

2017-08-16 14:06 GMT+02:00 Pavel Stehule <pavel.stehule@gmail.com>:

Hi

2017-08-15 4:37 GMT+02:00 Peter Eisentraut <peter.eisentraut@2ndquadrant.
com>:

On 3/11/17 07:06, Pavel Stehule wrote:

I am sending a updated version with separated sort direction in special
variable

This patch also needs a rebase.

I am sending rebased patch

rebased again + fix obsolete help

Regards

Pavel

Show quoted text

Regards

Pavel

--
Peter Eisentraut http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services

Attachments:

psql-extended-describe-sort-3.patchtext/x-patch; charset=US-ASCII; name=psql-extended-describe-sort-3.patchDownload
diff --git a/doc/src/sgml/ref/psql-ref.sgml b/doc/src/sgml/ref/psql-ref.sgml
index 79468a5663..d51c4bf900 100644
--- a/doc/src/sgml/ref/psql-ref.sgml
+++ b/doc/src/sgml/ref/psql-ref.sgml
@@ -3796,6 +3796,27 @@ bar
       </varlistentry>
 
       <varlistentry>
+        <term><varname>VERBOSE_SORT_COLUMNS</varname></term>
+        <listitem>
+        <para>
+        This variable can be set to the values <literal>schema_name</>,
+        <literal>name_schema</> or <literal>size</> to control the 
+        order of content of decrible command.
+        </para>
+        </listitem>
+      </varlistentry>
+
+      <varlistentry>
+        <term><varname>VERBOSE_SORT_DIRECTION</varname></term>
+        <listitem>
+        <para>
+        This variable can be set to the values <literal>asc</>,
+        or <literal>desc</> to control the order of content of decrible command.
+        </para>
+        </listitem>
+      </varlistentry>
+
+      <varlistentry>
         <term><varname>VERBOSITY</varname></term>
         <listitem>
         <para>
diff --git a/src/bin/psql/describe.c b/src/bin/psql/describe.c
index 6fb9bdd063..3ead55856d 100644
--- a/src/bin/psql/describe.c
+++ b/src/bin/psql/describe.c
@@ -200,6 +200,8 @@ describeAccessMethods(const char *pattern, bool verbose)
 	return true;
 }
 
+#define SORT_DIRECTION_STR(v)		((v) == PSQL_SORT_ASC ? "ASC" : "DESC")
+
 /*
  * \db
  * Takes an optional regexp to select particular tablespaces
@@ -268,7 +270,18 @@ describeTablespaces(const char *pattern, bool verbose)
 						  NULL, "spcname", NULL,
 						  NULL);
 
-	appendPQExpBufferStr(&buf, "ORDER BY 1;");
+
+	if (verbose && pset.sversion >= 90200)
+	{
+		if (pset.verbose_sort_columns == PSQL_SORT_SIZE)
+			appendPQExpBuffer(&buf,
+							  "ORDER BY pg_catalog.pg_tablespace_size(oid) %s, 1;",
+							  SORT_DIRECTION_STR(pset.verbose_sort_direction));
+		else
+			appendPQExpBufferStr(&buf, "ORDER BY 1;");
+	}
+	else
+		appendPQExpBufferStr(&buf, "ORDER BY 1;");
 
 	res = PSQLexec(buf.data);
 	termPQExpBuffer(&buf);
@@ -830,7 +843,19 @@ listAllDbs(const char *pattern, bool verbose)
 		processSQLNamePattern(pset.db, &buf, pattern, false, false,
 							  NULL, "d.datname", NULL, NULL);
 
-	appendPQExpBufferStr(&buf, "ORDER BY 1;");
+	if (verbose && pset.sversion >= 80200)
+	{
+		if (pset.verbose_sort_columns == PSQL_SORT_SIZE)
+			appendPQExpBuffer(&buf,
+						  "ORDER BY CASE WHEN pg_catalog.has_database_privilege(d.datname, 'CONNECT')\n"
+						  "              THEN pg_catalog.pg_database_size(d.datname) END %s, 1;\n",
+						  SORT_DIRECTION_STR(pset.verbose_sort_direction));
+		else
+			appendPQExpBufferStr(&buf, "ORDER BY 1");
+	}
+	else
+		appendPQExpBufferStr(&buf, "ORDER BY 1");
+
 	res = PSQLexec(buf.data);
 	termPQExpBuffer(&buf);
 	if (!res)
@@ -3424,7 +3449,26 @@ listTables(const char *tabtypes, const char *pattern, bool verbose, bool showSys
 						  "n.nspname", "c.relname", NULL,
 						  "pg_catalog.pg_table_is_visible(c.oid)");
 
-	appendPQExpBufferStr(&buf, "ORDER BY 1,2;");
+	if (verbose && pset.sversion >= 80100)
+	{
+		if (pset.verbose_sort_columns == PSQL_SORT_SCHEMA_NAME)
+			appendPQExpBufferStr(&buf, "ORDER BY 1,2;");
+		else if (pset.verbose_sort_columns == PSQL_SORT_NAME_SCHEMA)
+			appendPQExpBufferStr(&buf, "ORDER BY 2,1;");
+		else
+		{
+			if (pset.sversion >= 90000)
+				appendPQExpBuffer(&buf,
+					"ORDER BY pg_catalog.pg_table_size(c.oid) %s, 1,2",
+					SORT_DIRECTION_STR(pset.verbose_sort_direction));
+			else
+				appendPQExpBuffer(&buf,
+					"ORDER BY pg_catalog.pg_relation_size(c.oid) %s, 1,2",
+					SORT_DIRECTION_STR(pset.verbose_sort_direction));
+		}
+	}
+	else
+		appendPQExpBufferStr(&buf, "ORDER BY 1,2;");
 
 	res = PSQLexec(buf.data);
 	termPQExpBuffer(&buf);
diff --git a/src/bin/psql/help.c b/src/bin/psql/help.c
index 4d1c0ec3c6..a28fe07aa2 100644
--- a/src/bin/psql/help.c
+++ b/src/bin/psql/help.c
@@ -337,7 +337,7 @@ helpVariables(unsigned short int pager)
 	 * Windows builds currently print one more line than non-Windows builds.
 	 * Using the larger number is fine.
 	 */
-	output = PageOutput(147, pager ? &(pset.popt.topt) : NULL);
+	output = PageOutput(151, pager ? &(pset.popt.topt) : NULL);
 
 	fprintf(output, _("List of specially treated variables\n\n"));
 
@@ -401,6 +401,10 @@ helpVariables(unsigned short int pager)
 					  "    the currently connected database user\n"));
 	fprintf(output, _("  VERBOSITY\n"
 					  "    controls verbosity of error reports [default, verbose, terse]\n"));
+	fprintf(output, _("  VERBOSE_SORT_COLUMNS\n"
+					  "    controls sort of result in verbose mode [schema_name, name_schema, size]\n"));
+	fprintf(output, _("  VERBOSE_SORT_DIRECTION\n"
+					  "    controls direction of order of result in verbose mode [asc, desc]\n"));
 	fprintf(output, _("  VERSION\n"
 					  "  VERSION_NAME\n"
 					  "  VERSION_NUM\n"
diff --git a/src/bin/psql/settings.h b/src/bin/psql/settings.h
index 96338c3197..5a5fa0adac 100644
--- a/src/bin/psql/settings.h
+++ b/src/bin/psql/settings.h
@@ -77,6 +77,19 @@ enum trivalue
 	TRI_YES
 };
 
+typedef enum
+{
+	PSQL_SORT_SCHEMA_NAME,
+	PSQL_SORT_NAME_SCHEMA,
+	PSQL_SORT_SIZE,
+} PSQL_SORT_COLUMNS;
+
+typedef enum
+{
+	PSQL_SORT_ASC,
+	PSQL_SORT_DESC
+} PSQL_SORT_DIRECTION;
+
 typedef struct _psqlSettings
 {
 	PGconn	   *db;				/* connection to backend */
@@ -139,6 +152,8 @@ typedef struct _psqlSettings
 	const char *prompt3;
 	PGVerbosity verbosity;		/* current error verbosity level */
 	PGContextVisibility show_context;	/* current context display level */
+	PSQL_SORT_COLUMNS	verbose_sort_columns;	/* sort columns for describe verbose command */
+	PSQL_SORT_DIRECTION verbose_sort_direction;	/* sort direction for describe verbose command */
 } PsqlSettings;
 
 extern PsqlSettings pset;
diff --git a/src/bin/psql/startup.c b/src/bin/psql/startup.c
index 1e48f4ad5a..f03dcc62cd 100644
--- a/src/bin/psql/startup.c
+++ b/src/bin/psql/startup.c
@@ -171,6 +171,9 @@ main(int argc, char *argv[])
 	SetVariable(pset.vars, "PROMPT2", DEFAULT_PROMPT2);
 	SetVariable(pset.vars, "PROMPT3", DEFAULT_PROMPT3);
 
+	SetVariable(pset.vars, "VERBOSE_SORT_COLUMNS", "schema_name");
+	SetVariable(pset.vars, "VERBOSE_SORT_DIRECTION", "asc");
+
 	parse_psql_options(argc, argv, &options);
 
 	/*
@@ -1078,6 +1081,60 @@ verbosity_hook(const char *newval)
 }
 
 static char *
+verbose_sort_columns_substitute_hook(char *newval)
+{
+	if (newval == NULL)
+		newval = pg_strdup("schema_name");
+	return newval;
+}
+
+static bool
+verbose_sort_columns_hook(const char *newval)
+{
+	Assert(newval != NULL);		/* else substitute hook messed up */
+	if (pg_strcasecmp(newval, "schema_name") == 0)
+		pset.verbose_sort_columns = PSQL_SORT_SCHEMA_NAME;
+	else if (pg_strcasecmp(newval, "name_schema") == 0)
+		pset.verbose_sort_columns = PSQL_SORT_NAME_SCHEMA;
+	else if (pg_strcasecmp(newval, "size") == 0)
+		pset.verbose_sort_columns = PSQL_SORT_SIZE;
+	else
+	{
+		PsqlVarEnumError("VERBOSE_SORT_COLUMNS", newval,
+						 "schema_name, name_schema, size");
+		return false;
+	}
+
+	return true;
+}
+
+static char *
+verbose_sort_direction_substitute_hook(char *newval)
+{
+	if (newval == NULL)
+		newval = pg_strdup("asc");
+	return newval;
+}
+
+static bool
+verbose_sort_direction_hook(const char *newval)
+{
+	Assert(newval != NULL);		/* else substitute hook messed up */
+	if (pg_strcasecmp(newval, "asc") == 0)
+		pset.verbose_sort_direction = PSQL_SORT_ASC;
+	else if (pg_strcasecmp(newval, "desc") == 0)
+		pset.verbose_sort_direction = PSQL_SORT_DESC;
+	else
+	{
+		PsqlVarEnumError("VERBOSE_SORT_DIRECTION", newval, "asc, desc");
+		return false;
+	}
+
+	return true;
+}
+
+
+static char *
 show_context_substitute_hook(char *newval)
 {
 	if (newval == NULL)
@@ -1166,6 +1223,12 @@ EstablishVariableSpace(void)
 	SetVariableHooks(pset.vars, "VERBOSITY",
 					 verbosity_substitute_hook,
 					 verbosity_hook);
+	SetVariableHooks(pset.vars, "VERBOSE_SORT_COLUMNS",
+					 verbose_sort_columns_substitute_hook,
+					 verbose_sort_columns_hook);
+	SetVariableHooks(pset.vars, "VERBOSE_SORT_DIRECTION",
+					 verbose_sort_direction_substitute_hook,
+					 verbose_sort_direction_hook);
 	SetVariableHooks(pset.vars, "SHOW_CONTEXT",
 					 show_context_substitute_hook,
 					 show_context_hook);
diff --git a/src/bin/psql/tab-complete.c b/src/bin/psql/tab-complete.c
index 2ab8809fa5..4c0dab5ec8 100644
--- a/src/bin/psql/tab-complete.c
+++ b/src/bin/psql/tab-complete.c
@@ -3567,6 +3567,10 @@ psql_completion(const char *text, int start, int end)
 			COMPLETE_WITH_LIST_CS3("never", "errors", "always");
 		else if (TailMatchesCS1("VERBOSITY"))
 			COMPLETE_WITH_LIST_CS3("default", "verbose", "terse");
+		else if (TailMatchesCS1("VERBOSE_SORT_COLUMNS"))
+			COMPLETE_WITH_LIST_CS3("schema_name", "name_schema","size");
+		else if (TailMatchesCS1("VERBOSE_SORT_DIRECTION"))
+			COMPLETE_WITH_LIST_CS2("asc", "desc");
 	}
 	else if (TailMatchesCS1("\\sf*"))
 		COMPLETE_WITH_SCHEMA_QUERY(Query_for_list_of_functions, NULL);
#22Alexander Korotkov
a.korotkov@postgrespro.ru
In reply to: Pavel Stehule (#21)
Re: Re: proposal - psql: possibility to specify sort for describe commands, when size is printed

On Fri, Sep 8, 2017 at 7:13 AM, Pavel Stehule <pavel.stehule@gmail.com>
wrote:

2017-08-16 14:06 GMT+02:00 Pavel Stehule <pavel.stehule@gmail.com>:

Hi

2017-08-15 4:37 GMT+02:00 Peter Eisentraut <peter.eisentraut@2ndquadrant.
com>:

On 3/11/17 07:06, Pavel Stehule wrote:

I am sending a updated version with separated sort direction in special
variable

This patch also needs a rebase.

I am sending rebased patch

rebased again + fix obsolete help

For me, patch applies cleanly, builds and passed regression tests.
However, patch misses regression tests covering added functionality.
Patch is definitely harmless, i.e. it doesn't affect anybody who doesn't
use new functionality.
But I still would prefer ordering to be options of \d* commands while psql
variables be defaults for those options...

------
Alexander Korotkov
Postgres Professional: http://www.postgrespro.com
The Russian Postgres Company

#23Pavel Stehule
pavel.stehule@gmail.com
In reply to: Alexander Korotkov (#22)
Re: Re: proposal - psql: possibility to specify sort for describe commands, when size is printed

Hi

2017-09-19 16:14 GMT+02:00 Alexander Korotkov <a.korotkov@postgrespro.ru>:

On Fri, Sep 8, 2017 at 7:13 AM, Pavel Stehule <pavel.stehule@gmail.com>
wrote:

2017-08-16 14:06 GMT+02:00 Pavel Stehule <pavel.stehule@gmail.com>:

Hi

2017-08-15 4:37 GMT+02:00 Peter Eisentraut <
peter.eisentraut@2ndquadrant.com>:

On 3/11/17 07:06, Pavel Stehule wrote:

I am sending a updated version with separated sort direction in

special

variable

This patch also needs a rebase.

I am sending rebased patch

rebased again + fix obsolete help

For me, patch applies cleanly, builds and passed regression tests.
However, patch misses regression tests covering added functionality.

I am not sure if there are any tests related to output of \dt+ commands -
there result is platform depend.

Patch is definitely harmless, i.e. it doesn't affect anybody who doesn't
use new functionality.
But I still would prefer ordering to be options of \d* commands while psql
variables be defaults for those options...

I understand

a) I don't think so commands like \dt++ (or similar) is good idea - these
commands should be simple how it is possible

b) this patch doesn't block any other design - more it opens the door
because the executive part will be implemented and users can have a
experience with with different output sorts - so if people will need more
quick change of result sort, then the work in this area will continue.

Regards

Pavel

Show quoted text

------
Alexander Korotkov
Postgres Professional: http://www.postgrespro.com
The Russian Postgres Company

#24Alexander Korotkov
a.korotkov@postgrespro.ru
In reply to: Pavel Stehule (#23)
Re: Re: proposal - psql: possibility to specify sort for describe commands, when size is printed

On Tue, Sep 19, 2017 at 7:54 PM, Pavel Stehule <pavel.stehule@gmail.com>
wrote:

2017-09-19 16:14 GMT+02:00 Alexander Korotkov <a.korotkov@postgrespro.ru>:

On Fri, Sep 8, 2017 at 7:13 AM, Pavel Stehule <pavel.stehule@gmail.com>
wrote:

2017-08-16 14:06 GMT+02:00 Pavel Stehule <pavel.stehule@gmail.com>:

Hi

2017-08-15 4:37 GMT+02:00 Peter Eisentraut <
peter.eisentraut@2ndquadrant.com>:

On 3/11/17 07:06, Pavel Stehule wrote:

I am sending a updated version with separated sort direction in

special

variable

This patch also needs a rebase.

I am sending rebased patch

rebased again + fix obsolete help

For me, patch applies cleanly, builds and passed regression tests.
However, patch misses regression tests covering added functionality.

I am not sure if there are any tests related to output of \dt+ commands -
there result is platform depend.

BTW, why isn't order by name_schema available for \dt? If it's available
we could at least cover this case by plain regression tests.
\dt+ could be covered by TAP tests, but it isn't yet. I think one day we
should add them. However, I don't think we should force you to write them
in order to push this simple patch.

Patch is definitely harmless, i.e. it doesn't affect anybody who doesn't

use new functionality.
But I still would prefer ordering to be options of \d* commands while
psql variables be defaults for those options...

I understand

a) I don't think so commands like \dt++ (or similar) is good idea - these
commands should be simple how it is possible

I don't particularly like \dt++, but second argument is probably an option.

b) this patch doesn't block any other design - more it opens the door
because the executive part will be implemented and users can have a
experience with with different output sorts - so if people will need more
quick change of result sort, then the work in this area will continue.

OK. As reviewer, I'm not going to block this patch if you see its
functionality limited by just psql variables.
I think you should add support of name_schema \dt and some regression tests
for this case, before I can mark this as "ready for committer".

------
Alexander Korotkov
Postgres Professional: http://www.postgrespro.com
The Russian Postgres Company

#25Peter Eisentraut
peter.eisentraut@2ndquadrant.com
In reply to: Pavel Stehule (#23)
Re: Re: proposal - psql: possibility to specify sort for describe commands, when size is printed

On 9/19/17 12:54, Pavel Stehule wrote:

However, patch misses regression tests covering added functionality.

I am not sure if there are any tests related to output of \dt+ commands
- there result is platform depend.

How so?

--
Peter Eisentraut http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

#26Peter Eisentraut
peter.eisentraut@2ndquadrant.com
In reply to: Pavel Stehule (#21)
Re: Re: proposal - psql: possibility to specify sort for describe commands, when size is printed

On 9/8/17 00:13, Pavel Stehule wrote:

I am sending rebased patch

rebased again + fix obsolete help

Why are the variables called VERBOSE_SORT_* ? What is verbose about them?

--
Peter Eisentraut http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

#27Alexander Korotkov
a.korotkov@postgrespro.ru
In reply to: Peter Eisentraut (#25)
Re: Re: proposal - psql: possibility to specify sort for describe commands, when size is printed

On Thu, Sep 21, 2017 at 1:52 AM, Peter Eisentraut <
peter.eisentraut@2ndquadrant.com> wrote:

On 9/19/17 12:54, Pavel Stehule wrote:

However, patch misses regression tests covering added functionality.

I am not sure if there are any tests related to output of \dt+ commands
- there result is platform depend.

How so?

\dt+ reports relation sizes whose are platform depended.

------
Alexander Korotkov
Postgres Professional: http://www.postgrespro.com
The Russian Postgres Company

#28Alexander Korotkov
a.korotkov@postgrespro.ru
In reply to: Peter Eisentraut (#26)
Re: Re: proposal - psql: possibility to specify sort for describe commands, when size is printed

On Thu, Sep 21, 2017 at 1:53 AM, Peter Eisentraut <
peter.eisentraut@2ndquadrant.com> wrote:

On 9/8/17 00:13, Pavel Stehule wrote:

I am sending rebased patch

rebased again + fix obsolete help

Why are the variables called VERBOSE_SORT_* ? What is verbose about them?

I assume Pavel called them so, because they are working only for "verbose"
mode of command. I.e. they are working for \dt+ not \dt.
However, in \dt 2 of 3 sorting modes might work: schema_name and
name_schema. Thus, I think it worths enabling these variables for "non
verbose" mode of commands too.

------
Alexander Korotkov
Postgres Professional: http://www.postgrespro.com
The Russian Postgres Company

#29Pavel Stehule
pavel.stehule@gmail.com
In reply to: Alexander Korotkov (#28)
Re: Re: proposal - psql: possibility to specify sort for describe commands, when size is printed

2017-09-21 10:19 GMT+02:00 Alexander Korotkov <a.korotkov@postgrespro.ru>:

On Thu, Sep 21, 2017 at 1:53 AM, Peter Eisentraut <
peter.eisentraut@2ndquadrant.com> wrote:

On 9/8/17 00:13, Pavel Stehule wrote:

I am sending rebased patch

rebased again + fix obsolete help

Why are the variables called VERBOSE_SORT_* ? What is verbose about them?

I assume Pavel called them so, because they are working only for "verbose"
mode of command. I.e. they are working for \dt+ not \dt.
However, in \dt 2 of 3 sorting modes might work: schema_name and
name_schema. Thus, I think it worths enabling these variables for "non
verbose" mode of commands too.

yes. It was designed for + commands only. Can be enhanced to all commands -
then VERBOSE prefix should be removed - not sure if it is necessary. For me
interesting different order than default is only in verbose mode.

Show quoted text

------
Alexander Korotkov
Postgres Professional: http://www.postgrespro.com
The Russian Postgres Company

#30Peter Eisentraut
peter.eisentraut@2ndquadrant.com
In reply to: Pavel Stehule (#29)
Re: Re: proposal - psql: possibility to specify sort for describe commands, when size is printed

On 9/21/17 04:27, Pavel Stehule wrote:

yes. It was designed for + commands only. Can be enhanced to all
commands - then VERBOSE prefix should be removed - not sure if it is
necessary. For me interesting different order than default is only in
verbose mode.

I see where you are coming from, but there is no association in the
existing UI that equates "+" to the word "verbose". I think just
removing the verbose prefix and applying the sorting behavior in all
cases should be easier to explain and implement.

--
Peter Eisentraut http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

#31Pavel Stehule
pavel.stehule@gmail.com
In reply to: Peter Eisentraut (#30)
Re: Re: proposal - psql: possibility to specify sort for describe commands, when size is printed

2017-09-21 15:30 GMT+02:00 Peter Eisentraut <
peter.eisentraut@2ndquadrant.com>:

On 9/21/17 04:27, Pavel Stehule wrote:

yes. It was designed for + commands only. Can be enhanced to all
commands - then VERBOSE prefix should be removed - not sure if it is
necessary. For me interesting different order than default is only in
verbose mode.

I see where you are coming from, but there is no association in the
existing UI that equates "+" to the word "verbose". I think just
removing the verbose prefix and applying the sorting behavior in all
cases should be easier to explain and implement.

I though about it - but I am not sure if one kind of these variables is
practical.

if I don't need a size, then sort by schema, name is ok (I didn't need any
else ever). With only one kind of these variables, this setting is common -
what is not practical.

I need sort by size in verbose mode (where size is visible) in 100% - so it
will be saved to psqlrc. And when size will be invisible, then sort by size
is not practical, and can be messy (because size is not visible).

So I don't think so removing VERBOSE prefix is a good idea - or we should
to do different design (have not a idea how)

Regards

Pavel

Show quoted text

--
Peter Eisentraut http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services

#32Peter Eisentraut
peter.eisentraut@2ndquadrant.com
In reply to: Pavel Stehule (#31)
Re: Re: proposal - psql: possibility to specify sort for describe commands, when size is printed

On 9/21/17 13:54, Pavel Stehule wrote:

I see where you are coming from, but there is no association in the
existing UI that equates "+" to the word "verbose".  I think just
removing the verbose prefix and applying the sorting behavior in all
cases should be easier to explain and implement.

I though about it - but I am not sure if one kind of these variables is
practical.

if I don't need a size, then sort by schema, name is ok (I didn't need
any else ever). With only one kind of these variables, this setting is
common - what is not practical.

But you are proposing also to add a variable configuring the sort
direction. It would be weird that \dX+ observed the sort direction but
\dX did not.

--
Peter Eisentraut http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

#33Pavel Stehule
pavel.stehule@gmail.com
In reply to: Peter Eisentraut (#32)
Re: Re: proposal - psql: possibility to specify sort for describe commands, when size is printed

2017-09-21 20:20 GMT+02:00 Peter Eisentraut <
peter.eisentraut@2ndquadrant.com>:

On 9/21/17 13:54, Pavel Stehule wrote:

I see where you are coming from, but there is no association in the
existing UI that equates "+" to the word "verbose". I think just
removing the verbose prefix and applying the sorting behavior in all
cases should be easier to explain and implement.

I though about it - but I am not sure if one kind of these variables is
practical.

if I don't need a size, then sort by schema, name is ok (I didn't need
any else ever). With only one kind of these variables, this setting is
common - what is not practical.

But you are proposing also to add a variable configuring the sort
direction. It would be weird that \dX+ observed the sort direction but
\dX did not.

yes and no.

schema_name, name_schema or SORT_DIRECTION has sense for both type of
commands.

size sort has sense only for \dX+ command.

I am thinking about solution and the most clean I see two distinct
variables:

SORT_COLUMNS and VERBOSE_SORT_COLUMNS

when VERBOSE_SORT_COLUMNS will be undefined, then SORT_COLUMNS is used for
\dX+ command too.

Is it acceptable?

Show quoted text

--
Peter Eisentraut http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services

#34Pavel Stehule
pavel.stehule@gmail.com
In reply to: Pavel Stehule (#33)
Re: Re: proposal - psql: possibility to specify sort for describe commands, when size is printed

2017-09-21 20:30 GMT+02:00 Pavel Stehule <pavel.stehule@gmail.com>:

2017-09-21 20:20 GMT+02:00 Peter Eisentraut <peter.eisentraut@2ndquadrant.
com>:

On 9/21/17 13:54, Pavel Stehule wrote:

I see where you are coming from, but there is no association in the
existing UI that equates "+" to the word "verbose". I think just
removing the verbose prefix and applying the sorting behavior in all
cases should be easier to explain and implement.

I though about it - but I am not sure if one kind of these variables is
practical.

if I don't need a size, then sort by schema, name is ok (I didn't need
any else ever). With only one kind of these variables, this setting is
common - what is not practical.

But you are proposing also to add a variable configuring the sort
direction. It would be weird that \dX+ observed the sort direction but
\dX did not.

yes and no.

schema_name, name_schema or SORT_DIRECTION has sense for both type of
commands.

size sort has sense only for \dX+ command.

I am thinking about solution and the most clean I see two distinct
variables:

SORT_COLUMNS and VERBOSE_SORT_COLUMNS

when VERBOSE_SORT_COLUMNS will be undefined, then SORT_COLUMNS is used for
\dX+ command too.

Is it acceptable?

I though more about it, and I am thinking so this direction is not good.

Example: somebody set SORT_COLUMNS to schema_name value. This is nonsense
for \l command

Now, I am thinking so more correct and practical design is based on special
mode, activated by variable

PREFER_SIZE_SORT .. (off, asc, desc)

This has sense for wide group of commands that can show size. And when size
is not visible, then this option is not active.

What do you think about this proposal?

Regards

Pavel

Show quoted text

--
Peter Eisentraut http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services

#35Peter Eisentraut
peter.eisentraut@2ndquadrant.com
In reply to: Pavel Stehule (#34)
Re: Re: proposal - psql: possibility to specify sort for describe commands, when size is printed

On 9/22/17 09:16, Pavel Stehule wrote:

Example: somebody set SORT_COLUMNS to schema_name value. This is
nonsense for \l command

Now, I am thinking so more correct and practical design is based on
special mode, activated by variable

PREFER_SIZE_SORT .. (off, asc, desc)

This has sense for wide group of commands that can show size. And when
size is not visible, then this option is not active.

Maybe this shouldn't be a variable at all. It's not like you'll set
this as a global preference. You probably want it for one command only.
So a per-command option might make more sense.

--
Peter Eisentraut http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

#36Pavel Stehule
pavel.stehule@gmail.com
In reply to: Peter Eisentraut (#35)
Re: Re: proposal - psql: possibility to specify sort for describe commands, when size is printed

2017-09-22 21:12 GMT+02:00 Peter Eisentraut <
peter.eisentraut@2ndquadrant.com>:

On 9/22/17 09:16, Pavel Stehule wrote:

Example: somebody set SORT_COLUMNS to schema_name value. This is
nonsense for \l command

Now, I am thinking so more correct and practical design is based on
special mode, activated by variable

PREFER_SIZE_SORT .. (off, asc, desc)

This has sense for wide group of commands that can show size. And when
size is not visible, then this option is not active.

Maybe this shouldn't be a variable at all. It's not like you'll set
this as a global preference. You probably want it for one command only.
So a per-command option might make more sense.

Sure, I cannot to know, what users will do. But, when I need to see a size
of objects, then I prefer the sort by size desc every time. If I need to
find some object, then I can to use a searching in pager. So in my case,
this settings will be in psqlrc. In GoodData we used years own
customization - the order by size was hardcoded and nobody reported me any
issue.

Alexander proposed some per command option, but current syntax of psql
commands don't allows some simple parametrization. If it can be user
friendly, then it should be short. From implementation perspective, it
should be simply parsed. It should be intuitive too - too much symbols
together is not good idea.

Maybe some prefix design - but it is not design for common people (although
these people don't use psql usually)

'\sort size \dt ?

\dt:sort_by_size
\dt+:sort_by_size ?

I don't see any good design in this direction

Regards

Pavel

Show quoted text

--
Peter Eisentraut http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services

#37Pavel Stehule
pavel.stehule@gmail.com
In reply to: Pavel Stehule (#36)
1 attachment(s)
Re: Re: proposal - psql: possibility to specify sort for describe commands, when size is printed

Hi

2017-09-22 21:31 GMT+02:00 Pavel Stehule <pavel.stehule@gmail.com>:

2017-09-22 21:12 GMT+02:00 Peter Eisentraut <peter.eisentraut@2ndquadrant.
com>:

On 9/22/17 09:16, Pavel Stehule wrote:

Example: somebody set SORT_COLUMNS to schema_name value. This is
nonsense for \l command

Now, I am thinking so more correct and practical design is based on
special mode, activated by variable

PREFER_SIZE_SORT .. (off, asc, desc)

This has sense for wide group of commands that can show size. And when
size is not visible, then this option is not active.

Maybe this shouldn't be a variable at all. It's not like you'll set
this as a global preference. You probably want it for one command only.
So a per-command option might make more sense.

Sure, I cannot to know, what users will do. But, when I need to see a size
of objects, then I prefer the sort by size desc every time. If I need to
find some object, then I can to use a searching in pager. So in my case,
this settings will be in psqlrc. In GoodData we used years own
customization - the order by size was hardcoded and nobody reported me any
issue.

Alexander proposed some per command option, but current syntax of psql
commands don't allows some simple parametrization. If it can be user
friendly, then it should be short. From implementation perspective, it
should be simply parsed. It should be intuitive too - too much symbols
together is not good idea.

Maybe some prefix design - but it is not design for common people
(although these people don't use psql usually)

'\sort size \dt ?

\dt:sort_by_size
\dt+:sort_by_size ?

I don't see any good design in this direction

I though about Alexander proposal, and I am thinking so it can be probably
best if we respect psql design. I implemented two command suffixes
(supported only when it has sense) "s" sorted by size and "d" as descent

so list of tables can be sorted with commands:

\dt+sd (in this case, the order is not strict), so command
\dtsd+ is working too (same \disd+ or \di+sd)

These two chars are acceptable. Same principle is used for \l command

\lsd+ or \l+sd

What do you think about it?

Regards

Pavel

Show quoted text

Regards

Pavel

--
Peter Eisentraut http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services

Attachments:

psql-sortdesc-suffix.patchtext/x-patch; charset=US-ASCII; name=psql-sortdesc-suffix.patchDownload
diff --git a/src/bin/psql/command.c b/src/bin/psql/command.c
index 041b5e0c87..548b0d8d41 100644
--- a/src/bin/psql/command.c
+++ b/src/bin/psql/command.c
@@ -349,8 +349,9 @@ exec_command(const char *cmd,
 		status = exec_command_include(scan_state, active_branch, cmd);
 	else if (strcmp(cmd, "if") == 0)
 		status = exec_command_if(scan_state, cstack, query_buf);
-	else if (strcmp(cmd, "l") == 0 || strcmp(cmd, "list") == 0 ||
-			 strcmp(cmd, "l+") == 0 || strcmp(cmd, "list+") == 0)
+	else if (strcmp(cmd, "list") == 0 || strcmp(cmd, "list+") == 0 ||
+			 strcmp(cmd, "l") == 0 || strncmp(cmd, "l+", 2) == 0 ||
+			 strncmp(cmd, "ls", 2) == 0)
 		status = exec_command_list(scan_state, active_branch, cmd);
 	else if (strncmp(cmd, "lo_", 3) == 0)
 		status = exec_command_lo(scan_state, active_branch, cmd);
@@ -702,7 +703,9 @@ exec_command_d(PsqlScanState scan_state, bool active_branch, const char *cmd)
 	{
 		char	   *pattern;
 		bool		show_verbose,
-					show_system;
+					show_system,
+					sort_size,
+					sort_desc;
 
 		/* We don't do SQLID reduction on the pattern yet */
 		pattern = psql_scan_slash_option(scan_state,
@@ -711,6 +714,9 @@ exec_command_d(PsqlScanState scan_state, bool active_branch, const char *cmd)
 		show_verbose = strchr(cmd, '+') ? true : false;
 		show_system = strchr(cmd, 'S') ? true : false;
 
+		sort_size = false;
+		sort_desc = false;
+
 		switch (cmd[1])
 		{
 			case '\0':
@@ -720,7 +726,8 @@ exec_command_d(PsqlScanState scan_state, bool active_branch, const char *cmd)
 					success = describeTableDetails(pattern, show_verbose, show_system);
 				else
 					/* standard listing of interesting things */
-					success = listTables("tvmsE", NULL, show_verbose, show_system);
+					success = listTables("tvmsE", NULL, show_verbose, show_system,
+										 false, false);
 				break;
 			case 'A':
 				success = describeAccessMethods(pattern, show_verbose);
@@ -789,12 +796,19 @@ exec_command_d(PsqlScanState scan_state, bool active_branch, const char *cmd)
 				success = describeTypes(pattern, show_verbose, show_system);
 				break;
 			case 't':
-			case 'v':
 			case 'm':
 			case 'i':
+				if (strlen(cmd) >= 2)
+				{
+					sort_size = strchr(&cmd[2], 's') ? true : false;
+					sort_desc = strchr(&cmd[2], 'd') ? true : false;
+				}
+
+			case 'v':
 			case 's':
 			case 'E':
-				success = listTables(&cmd[1], pattern, show_verbose, show_system);
+				success = listTables(&cmd[1], pattern, show_verbose, show_system,
+									 sort_size, sort_desc);
 				break;
 			case 'r':
 				if (cmd[2] == 'd' && cmd[3] == 's')
@@ -1655,13 +1669,17 @@ exec_command_list(PsqlScanState scan_state, bool active_branch, const char *cmd)
 	{
 		char	   *pattern;
 		bool		show_verbose;
+		bool		sort_size;
+		bool		sort_desc;
 
 		pattern = psql_scan_slash_option(scan_state,
 										 OT_NORMAL, NULL, true);
 
 		show_verbose = strchr(cmd, '+') ? true : false;
+		sort_size = strchr(cmd, 's') ? true : false;
+		sort_desc = strchr(cmd, 'd') ? true : false;
 
-		success = listAllDbs(pattern, show_verbose);
+		success = listAllDbs(pattern, show_verbose, sort_size, sort_desc);
 
 		if (pattern)
 			free(pattern);
diff --git a/src/bin/psql/describe.c b/src/bin/psql/describe.c
index 638275ca2f..e0acb95166 100644
--- a/src/bin/psql/describe.c
+++ b/src/bin/psql/describe.c
@@ -782,7 +782,7 @@ describeOperators(const char *pattern, bool verbose, bool showSystem)
  * for \l, \list, and -l switch
  */
 bool
-listAllDbs(const char *pattern, bool verbose)
+listAllDbs(const char *pattern, bool verbose, bool sort_size, bool sort_desc)
 {
 	PGresult   *res;
 	PQExpBufferData buf;
@@ -830,7 +830,27 @@ listAllDbs(const char *pattern, bool verbose)
 		processSQLNamePattern(pset.db, &buf, pattern, false, false,
 							  NULL, "d.datname", NULL, NULL);
 
-	appendPQExpBufferStr(&buf, "ORDER BY 1;");
+	if (sort_size)
+	{
+		if (pset.sversion < 80200)
+		{
+			char		sverbuf[32];
+
+			psql_error("The server (version %s) does not support database size function.\n",
+					   formatPGVersionNumber(pset.sversion, false,
+											 sverbuf, sizeof(sverbuf)));
+			return true;
+		}
+
+		appendPQExpBufferStr(&buf, "ORDER BY pg_catalog.pg_database_size(d.datname)");
+
+		if (sort_desc)
+				appendPQExpBuffer(&buf, " DESC");
+
+		appendPQExpBuffer(&buf, ", 1;");
+	}
+	else
+		appendPQExpBufferStr(&buf, "ORDER BY 1;");
 	res = PSQLexec(buf.data);
 	termPQExpBuffer(&buf);
 	if (!res)
@@ -3336,7 +3356,8 @@ listDbRoleSettings(const char *pattern, const char *pattern2)
  * (any order of the above is fine)
  */
 bool
-listTables(const char *tabtypes, const char *pattern, bool verbose, bool showSystem)
+listTables(const char *tabtypes, const char *pattern, bool verbose, bool showSystem,
+		   bool sort_size, bool sort_desc)
 {
 	bool		showTables = strchr(tabtypes, 't') != NULL;
 	bool		showIndexes = strchr(tabtypes, 'i') != NULL;
@@ -3457,7 +3478,34 @@ listTables(const char *tabtypes, const char *pattern, bool verbose, bool showSys
 						  "n.nspname", "c.relname", NULL,
 						  "pg_catalog.pg_table_is_visible(c.oid)");
 
-	appendPQExpBufferStr(&buf, "ORDER BY 1,2;");
+	if (sort_size)
+	{
+		appendPQExpBufferStr(&buf, "ORDER BY ");
+
+		/*
+		 * As of PostgreSQL 9.0, use pg_table_size() to show a more accurate
+		 * size of a table, including FSM, VM and TOAST tables.
+		 */
+		if (pset.sversion >= 90000)
+			appendPQExpBuffer(&buf, "pg_catalog.pg_table_size(c.oid)");
+		else if (pset.sversion >= 80100)
+			appendPQExpBuffer(&buf, "pg_catalog.pg_relation_size(c.oid)");
+		else
+		{
+			char		sverbuf[32];
+
+			psql_error("The server (version %s) does not support table size function.\n",
+					   formatPGVersionNumber(pset.sversion, false,
+											 sverbuf, sizeof(sverbuf)));
+			return true;
+		}
+
+		if (sort_desc)
+			appendPQExpBufferStr(&buf, "DESC");
+		appendPQExpBufferStr(&buf, " , 1,2;");
+	}
+	else
+		appendPQExpBufferStr(&buf, "ORDER BY 1,2;");
 
 	res = PSQLexec(buf.data);
 	termPQExpBuffer(&buf);
diff --git a/src/bin/psql/describe.h b/src/bin/psql/describe.h
index 14a5667f3e..1941aab181 100644
--- a/src/bin/psql/describe.h
+++ b/src/bin/psql/describe.h
@@ -58,10 +58,11 @@ extern bool listTSDictionaries(const char *pattern, bool verbose);
 extern bool listTSTemplates(const char *pattern, bool verbose);
 
 /* \l */
-extern bool listAllDbs(const char *pattern, bool verbose);
+extern bool listAllDbs(const char *pattern, bool verbose, bool sort_size, bool sort_desc);
 
 /* \dt, \di, \ds, \dS, etc. */
-extern bool listTables(const char *tabtypes, const char *pattern, bool verbose, bool showSystem);
+extern bool listTables(const char *tabtypes, const char *pattern, bool verbose, bool showSystem,
+					   bool sort_size, bool sort_desc);
 
 /* \dD */
 extern bool listDomains(const char *pattern, bool verbose, bool showSystem);
diff --git a/src/bin/psql/help.c b/src/bin/psql/help.c
index a926c40b9b..620b8930a5 100644
--- a/src/bin/psql/help.c
+++ b/src/bin/psql/help.c
@@ -241,10 +241,10 @@ slashUsage(unsigned short int pager)
 	fprintf(output, _("  \\dFp[+] [PATTERN]      list text search parsers\n"));
 	fprintf(output, _("  \\dFt[+] [PATTERN]      list text search templates\n"));
 	fprintf(output, _("  \\dg[S+] [PATTERN]      list roles\n"));
-	fprintf(output, _("  \\di[S+] [PATTERN]      list indexes\n"));
+	fprintf(output, _("  \\di[Ssd+] [PATTERN]    list indexes\n"));
 	fprintf(output, _("  \\dl                    list large objects, same as \\lo_list\n"));
 	fprintf(output, _("  \\dL[S+] [PATTERN]      list procedural languages\n"));
-	fprintf(output, _("  \\dm[S+] [PATTERN]      list materialized views\n"));
+	fprintf(output, _("  \\dm[Ssd+] [PATTERN]    list materialized views\n"));
 	fprintf(output, _("  \\dn[S+] [PATTERN]      list schemas\n"));
 	fprintf(output, _("  \\do[S]  [PATTERN]      list operators\n"));
 	fprintf(output, _("  \\dO[S+] [PATTERN]      list collations\n"));
@@ -253,13 +253,13 @@ slashUsage(unsigned short int pager)
 	fprintf(output, _("  \\dRp[+] [PATTERN]      list replication publications\n"));
 	fprintf(output, _("  \\dRs[+] [PATTERN]      list replication subscriptions\n"));
 	fprintf(output, _("  \\ds[S+] [PATTERN]      list sequences\n"));
-	fprintf(output, _("  \\dt[S+] [PATTERN]      list tables\n"));
+	fprintf(output, _("  \\dt[Ssd+] [PATTERN]    list tables\n"));
 	fprintf(output, _("  \\dT[S+] [PATTERN]      list data types\n"));
 	fprintf(output, _("  \\du[S+] [PATTERN]      list roles\n"));
 	fprintf(output, _("  \\dv[S+] [PATTERN]      list views\n"));
 	fprintf(output, _("  \\dx[+]  [PATTERN]      list extensions\n"));
 	fprintf(output, _("  \\dy     [PATTERN]      list event triggers\n"));
-	fprintf(output, _("  \\l[+]   [PATTERN]      list databases\n"));
+	fprintf(output, _("  \\l[sd+] [PATTERN]      list databases\n"));
 	fprintf(output, _("  \\sf[+]  FUNCNAME       show a function's definition\n"));
 	fprintf(output, _("  \\sv[+]  VIEWNAME       show a view's definition\n"));
 	fprintf(output, _("  \\z      [PATTERN]      same as \\dp\n"));
#38Alexander Korotkov
a.korotkov@postgrespro.ru
In reply to: Pavel Stehule (#37)
Re: Re: proposal - psql: possibility to specify sort for describe commands, when size is printed

On Sat, Oct 28, 2017 at 3:46 PM, Pavel Stehule <pavel.stehule@gmail.com>
wrote:

2017-09-22 21:31 GMT+02:00 Pavel Stehule <pavel.stehule@gmail.com>:

2017-09-22 21:12 GMT+02:00 Peter Eisentraut <
peter.eisentraut@2ndquadrant.com>:

On 9/22/17 09:16, Pavel Stehule wrote:

Example: somebody set SORT_COLUMNS to schema_name value. This is
nonsense for \l command

Now, I am thinking so more correct and practical design is based on
special mode, activated by variable

PREFER_SIZE_SORT .. (off, asc, desc)

This has sense for wide group of commands that can show size. And when
size is not visible, then this option is not active.

Maybe this shouldn't be a variable at all. It's not like you'll set
this as a global preference. You probably want it for one command only.
So a per-command option might make more sense.

Sure, I cannot to know, what users will do. But, when I need to see a
size of objects, then I prefer the sort by size desc every time. If I need
to find some object, then I can to use a searching in pager. So in my case,
this settings will be in psqlrc. In GoodData we used years own
customization - the order by size was hardcoded and nobody reported me any
issue.

Alexander proposed some per command option, but current syntax of psql
commands don't allows some simple parametrization. If it can be user
friendly, then it should be short. From implementation perspective, it
should be simply parsed. It should be intuitive too - too much symbols
together is not good idea.

Maybe some prefix design - but it is not design for common people
(although these people don't use psql usually)

'\sort size \dt ?

\dt:sort_by_size
\dt+:sort_by_size ?

I don't see any good design in this direction

I though about Alexander proposal, and I am thinking so it can be probably
best if we respect psql design. I implemented two command suffixes
(supported only when it has sense) "s" sorted by size and "d" as descent

so list of tables can be sorted with commands:

\dt+sd (in this case, the order is not strict), so command
\dtsd+ is working too (same \disd+ or \di+sd)

These two chars are acceptable. Same principle is used for \l command

\lsd+ or \l+sd

What do you think about it?

I think \lsd+ command would be another postgres meme :)
BTW, are you going to provide an ability to sort by name, schema?

------
Alexander Korotkov
Postgres Professional: http://www.postgrespro.com
The Russian Postgres Company

#39Pavel Stehule
pavel.stehule@gmail.com
In reply to: Alexander Korotkov (#38)
Re: Re: proposal - psql: possibility to specify sort for describe commands, when size is printed

2017-10-28 23:35 GMT+02:00 Alexander Korotkov <a.korotkov@postgrespro.ru>:

On Sat, Oct 28, 2017 at 3:46 PM, Pavel Stehule <pavel.stehule@gmail.com>
wrote:

2017-09-22 21:31 GMT+02:00 Pavel Stehule <pavel.stehule@gmail.com>:

2017-09-22 21:12 GMT+02:00 Peter Eisentraut <
peter.eisentraut@2ndquadrant.com>:

On 9/22/17 09:16, Pavel Stehule wrote:

Example: somebody set SORT_COLUMNS to schema_name value. This is
nonsense for \l command

Now, I am thinking so more correct and practical design is based on
special mode, activated by variable

PREFER_SIZE_SORT .. (off, asc, desc)

This has sense for wide group of commands that can show size. And when
size is not visible, then this option is not active.

Maybe this shouldn't be a variable at all. It's not like you'll set
this as a global preference. You probably want it for one command only.
So a per-command option might make more sense.

Sure, I cannot to know, what users will do. But, when I need to see a
size of objects, then I prefer the sort by size desc every time. If I need
to find some object, then I can to use a searching in pager. So in my case,
this settings will be in psqlrc. In GoodData we used years own
customization - the order by size was hardcoded and nobody reported me any
issue.

Alexander proposed some per command option, but current syntax of psql
commands don't allows some simple parametrization. If it can be user
friendly, then it should be short. From implementation perspective, it
should be simply parsed. It should be intuitive too - too much symbols
together is not good idea.

Maybe some prefix design - but it is not design for common people
(although these people don't use psql usually)

'\sort size \dt ?

\dt:sort_by_size
\dt+:sort_by_size ?

I don't see any good design in this direction

I though about Alexander proposal, and I am thinking so it can be
probably best if we respect psql design. I implemented two command suffixes
(supported only when it has sense) "s" sorted by size and "d" as descent

so list of tables can be sorted with commands:

\dt+sd (in this case, the order is not strict), so command
\dtsd+ is working too (same \disd+ or \di+sd)

These two chars are acceptable. Same principle is used for \l command

\lsd+ or \l+sd

What do you think about it?

I think \lsd+ command would be another postgres meme :)
BTW, are you going to provide an ability to sort by name, schema?

It has sense only for tables - probably only \dtn "n" like name

Show quoted text

------
Alexander Korotkov
Postgres Professional: http://www.postgrespro.com
The Russian Postgres Company

#40Alexander Korotkov
a.korotkov@postgrespro.ru
In reply to: Pavel Stehule (#39)
Re: Re: proposal - psql: possibility to specify sort for describe commands, when size is printed

On Sun, Oct 29, 2017 at 12:47 AM, Pavel Stehule <pavel.stehule@gmail.com>
wrote:

2017-10-28 23:35 GMT+02:00 Alexander Korotkov <a.korotkov@postgrespro.ru>:

On Sat, Oct 28, 2017 at 3:46 PM, Pavel Stehule <pavel.stehule@gmail.com>
wrote:

2017-09-22 21:31 GMT+02:00 Pavel Stehule <pavel.stehule@gmail.com>:

2017-09-22 21:12 GMT+02:00 Peter Eisentraut <
peter.eisentraut@2ndquadrant.com>:

On 9/22/17 09:16, Pavel Stehule wrote:

Example: somebody set SORT_COLUMNS to schema_name value. This is
nonsense for \l command

Now, I am thinking so more correct and practical design is based on
special mode, activated by variable

PREFER_SIZE_SORT .. (off, asc, desc)

This has sense for wide group of commands that can show size. And

when

size is not visible, then this option is not active.

Maybe this shouldn't be a variable at all. It's not like you'll set
this as a global preference. You probably want it for one command
only.
So a per-command option might make more sense.

Sure, I cannot to know, what users will do. But, when I need to see a
size of objects, then I prefer the sort by size desc every time. If I need
to find some object, then I can to use a searching in pager. So in my case,
this settings will be in psqlrc. In GoodData we used years own
customization - the order by size was hardcoded and nobody reported me any
issue.

Alexander proposed some per command option, but current syntax of psql
commands don't allows some simple parametrization. If it can be user
friendly, then it should be short. From implementation perspective, it
should be simply parsed. It should be intuitive too - too much symbols
together is not good idea.

Maybe some prefix design - but it is not design for common people
(although these people don't use psql usually)

'\sort size \dt ?

\dt:sort_by_size
\dt+:sort_by_size ?

I don't see any good design in this direction

I though about Alexander proposal, and I am thinking so it can be
probably best if we respect psql design. I implemented two command suffixes
(supported only when it has sense) "s" sorted by size and "d" as descent

so list of tables can be sorted with commands:

\dt+sd (in this case, the order is not strict), so command
\dtsd+ is working too (same \disd+ or \di+sd)

These two chars are acceptable. Same principle is used for \l command

\lsd+ or \l+sd

What do you think about it?

I think \lsd+ command would be another postgres meme :)
BTW, are you going to provide an ability to sort by name, schema?

It has sense only for tables - probably only \dtn "n" like name

In general, this approach looks good for me.
Regarding current state of patch, I'd like to see new options documented.
Also, it would be better to replace "bool sort_size" with enum assuming
there could be other sorting orders in future.

------
Alexander Korotkov
Postgres Professional: http://www.postgrespro.com
The Russian Postgres Company

#41Pavel Stehule
pavel.stehule@gmail.com
In reply to: Alexander Korotkov (#40)
1 attachment(s)
Re: Re: proposal - psql: possibility to specify sort for describe commands, when size is printed

Hi

In general, this approach looks good for me.

Regarding current state of patch, I'd like to see new options documented.
Also, it would be better to replace "bool sort_size" with enum assuming
there could be other sorting orders in future.

I am sending updated patch with some basic doc

Regards

Pavel

Show quoted text

------
Alexander Korotkov
Postgres Professional: http://www.postgrespro.com
The Russian Postgres Company

Attachments:

psql-sortdesc-suffix-2.patchtext/x-patch; charset=US-ASCII; name=psql-sortdesc-suffix-2.patchDownload
diff --git a/doc/src/sgml/ref/psql-ref.sgml b/doc/src/sgml/ref/psql-ref.sgml
index e520cdf3ba..7d816fe701 100644
--- a/doc/src/sgml/ref/psql-ref.sgml
+++ b/doc/src/sgml/ref/psql-ref.sgml
@@ -1303,10 +1303,10 @@ testdb=&gt;
 
       <varlistentry>
         <term><literal>\dE[S+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term>
-        <term><literal>\di[S+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term>
-        <term><literal>\dm[S+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term>
+        <term><literal>\di[Ssd+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term>
+        <term><literal>\dm[Ssd+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term>
         <term><literal>\ds[S+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term>
-        <term><literal>\dt[S+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term>
+        <term><literal>\dt[Ssd+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term>
         <term><literal>\dv[S+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term>
 
         <listitem>
@@ -1328,6 +1328,13 @@ testdb=&gt;
         pattern or the <literal>S</literal> modifier to include system
         objects.
         </para>
+
+        <para>
+        When command contains <literal>s</literal>, then a result is
+        sorted by size. When command contains <literal>d</literal> then
+        result is in descend order. <literal>\dtsd+</literal> shows list
+        of tables sorted by size with descend order.
+        </para>
         </listitem>
       </varlistentry>
 
@@ -2253,7 +2260,7 @@ SELECT
 
 
       <varlistentry>
-        <term><literal>\l[+]</literal> or <literal>\list[+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term>
+        <term><literal>\l[sd+]</literal> or <literal>\list[+] [ <link linkend="app-psql-patterns"><replaceable class="parameter">pattern</replaceable></link> ]</literal></term>
         <listitem>
         <para>
         List the databases in the server and show their names, owners,
@@ -2265,6 +2272,12 @@ SELECT
         (Size information is only available for databases that the current
         user can connect to.)
         </para>
+
+        <para>
+        If <literal>s</literal> is used in command name, then the list is
+        sorted by size. When <literal>d</literal> is used there, then result
+        is in descend order.
+        </para>
         </listitem>
       </varlistentry>
 
diff --git a/src/bin/psql/command.c b/src/bin/psql/command.c
index 041b5e0c87..aae88b08b4 100644
--- a/src/bin/psql/command.c
+++ b/src/bin/psql/command.c
@@ -349,8 +349,9 @@ exec_command(const char *cmd,
 		status = exec_command_include(scan_state, active_branch, cmd);
 	else if (strcmp(cmd, "if") == 0)
 		status = exec_command_if(scan_state, cstack, query_buf);
-	else if (strcmp(cmd, "l") == 0 || strcmp(cmd, "list") == 0 ||
-			 strcmp(cmd, "l+") == 0 || strcmp(cmd, "list+") == 0)
+	else if (strcmp(cmd, "list") == 0 || strcmp(cmd, "list+") == 0 ||
+			 strcmp(cmd, "l") == 0 || strncmp(cmd, "l+", 2) == 0 ||
+			 strncmp(cmd, "ls", 2) == 0)
 		status = exec_command_list(scan_state, active_branch, cmd);
 	else if (strncmp(cmd, "lo_", 3) == 0)
 		status = exec_command_lo(scan_state, active_branch, cmd);
@@ -702,7 +703,9 @@ exec_command_d(PsqlScanState scan_state, bool active_branch, const char *cmd)
 	{
 		char	   *pattern;
 		bool		show_verbose,
-					show_system;
+					show_system,
+					sort_desc;
+		sortby_type	sortby;
 
 		/* We don't do SQLID reduction on the pattern yet */
 		pattern = psql_scan_slash_option(scan_state,
@@ -711,6 +714,9 @@ exec_command_d(PsqlScanState scan_state, bool active_branch, const char *cmd)
 		show_verbose = strchr(cmd, '+') ? true : false;
 		show_system = strchr(cmd, 'S') ? true : false;
 
+		sortby = SORTBY_SCHEMA_NAME;
+		sort_desc = false;
+
 		switch (cmd[1])
 		{
 			case '\0':
@@ -720,7 +726,8 @@ exec_command_d(PsqlScanState scan_state, bool active_branch, const char *cmd)
 					success = describeTableDetails(pattern, show_verbose, show_system);
 				else
 					/* standard listing of interesting things */
-					success = listTables("tvmsE", NULL, show_verbose, show_system);
+					success = listTables("tvmsE", NULL, show_verbose, show_system,
+										 false, false);
 				break;
 			case 'A':
 				success = describeAccessMethods(pattern, show_verbose);
@@ -789,12 +796,20 @@ exec_command_d(PsqlScanState scan_state, bool active_branch, const char *cmd)
 				success = describeTypes(pattern, show_verbose, show_system);
 				break;
 			case 't':
-			case 'v':
 			case 'm':
 			case 'i':
+				if (strlen(cmd) >= 2)
+				{
+					if (strchr(&cmd[2], 's') != NULL)
+						sortby = SORTBY_SIZE;
+					sort_desc = strchr(&cmd[2], 'd') ? true : false;
+				}
+
+			case 'v':
 			case 's':
 			case 'E':
-				success = listTables(&cmd[1], pattern, show_verbose, show_system);
+				success = listTables(&cmd[1], pattern, show_verbose, show_system,
+									 sortby, sort_desc);
 				break;
 			case 'r':
 				if (cmd[2] == 'd' && cmd[3] == 's')
@@ -1655,13 +1670,17 @@ exec_command_list(PsqlScanState scan_state, bool active_branch, const char *cmd)
 	{
 		char	   *pattern;
 		bool		show_verbose;
+		bool		sort_desc;
+		sortby_type	sortby;
 
 		pattern = psql_scan_slash_option(scan_state,
 										 OT_NORMAL, NULL, true);
 
 		show_verbose = strchr(cmd, '+') ? true : false;
+		sortby = strchr(cmd, 's') != NULL ? SORTBY_SIZE : SORTBY_NAME;
+		sort_desc = strchr(cmd, 'd') ? true : false;
 
-		success = listAllDbs(pattern, show_verbose);
+		success = listAllDbs(pattern, show_verbose, sortby, sort_desc);
 
 		if (pattern)
 			free(pattern);
diff --git a/src/bin/psql/describe.c b/src/bin/psql/describe.c
index 986172616e..8513022e09 100644
--- a/src/bin/psql/describe.c
+++ b/src/bin/psql/describe.c
@@ -782,7 +782,7 @@ describeOperators(const char *pattern, bool verbose, bool showSystem)
  * for \l, \list, and -l switch
  */
 bool
-listAllDbs(const char *pattern, bool verbose)
+listAllDbs(const char *pattern, bool verbose, sortby_type sortby, bool sort_desc)
 {
 	PGresult   *res;
 	PQExpBufferData buf;
@@ -830,7 +830,30 @@ listAllDbs(const char *pattern, bool verbose)
 		processSQLNamePattern(pset.db, &buf, pattern, false, false,
 							  NULL, "d.datname", NULL, NULL);
 
-	appendPQExpBufferStr(&buf, "ORDER BY 1;");
+	if (sortby == SORTBY_SIZE)
+	{
+		if (pset.sversion < 80200)
+		{
+			char		sverbuf[32];
+
+			psql_error("The server (version %s) does not support database size function.\n",
+					   formatPGVersionNumber(pset.sversion, false,
+											 sverbuf, sizeof(sverbuf)));
+			return true;
+		}
+
+		appendPQExpBufferStr(&buf, "ORDER BY pg_catalog.pg_database_size(d.datname)");
+
+		if (sort_desc)
+				appendPQExpBuffer(&buf, " DESC");
+
+		appendPQExpBuffer(&buf, ", 1;");
+	}
+	else
+	{
+		Assert(sortby == SORTBY_NAME);
+		appendPQExpBufferStr(&buf, "ORDER BY 1;");
+	}
 	res = PSQLexec(buf.data);
 	termPQExpBuffer(&buf);
 	if (!res)
@@ -3336,7 +3359,8 @@ listDbRoleSettings(const char *pattern, const char *pattern2)
  * (any order of the above is fine)
  */
 bool
-listTables(const char *tabtypes, const char *pattern, bool verbose, bool showSystem)
+listTables(const char *tabtypes, const char *pattern, bool verbose, bool showSystem,
+		   sortby_type sortby, bool sort_desc)
 {
 	bool		showTables = strchr(tabtypes, 't') != NULL;
 	bool		showIndexes = strchr(tabtypes, 'i') != NULL;
@@ -3457,7 +3481,37 @@ listTables(const char *tabtypes, const char *pattern, bool verbose, bool showSys
 						  "n.nspname", "c.relname", NULL,
 						  "pg_catalog.pg_table_is_visible(c.oid)");
 
-	appendPQExpBufferStr(&buf, "ORDER BY 1,2;");
+	if (sortby == SORTBY_SIZE)
+	{
+		appendPQExpBufferStr(&buf, "ORDER BY ");
+
+		/*
+		 * As of PostgreSQL 9.0, use pg_table_size() to show a more accurate
+		 * size of a table, including FSM, VM and TOAST tables.
+		 */
+		if (pset.sversion >= 90000)
+			appendPQExpBuffer(&buf, "pg_catalog.pg_table_size(c.oid)");
+		else if (pset.sversion >= 80100)
+			appendPQExpBuffer(&buf, "pg_catalog.pg_relation_size(c.oid)");
+		else
+		{
+			char		sverbuf[32];
+
+			psql_error("The server (version %s) does not support table size function.\n",
+					   formatPGVersionNumber(pset.sversion, false,
+											 sverbuf, sizeof(sverbuf)));
+			return true;
+		}
+
+		if (sort_desc)
+			appendPQExpBufferStr(&buf, "DESC");
+		appendPQExpBufferStr(&buf, " , 1,2;");
+	}
+	else
+	{
+		Assert(sortby == SORTBY_SCHEMA_NAME);
+		appendPQExpBufferStr(&buf, "ORDER BY 1,2;");
+	}
 
 	res = PSQLexec(buf.data);
 	termPQExpBuffer(&buf);
diff --git a/src/bin/psql/describe.h b/src/bin/psql/describe.h
index 14a5667f3e..37b812830d 100644
--- a/src/bin/psql/describe.h
+++ b/src/bin/psql/describe.h
@@ -8,6 +8,13 @@
 #ifndef DESCRIBE_H
 #define DESCRIBE_H
 
+/* how the result list should be sorted */
+typedef enum sortby_type
+{
+	SORTBY_NAME,
+	SORTBY_SCHEMA_NAME,
+	SORTBY_SIZE
+} sortby_type;
 
 /* \da */
 extern bool describeAggregates(const char *pattern, bool verbose, bool showSystem);
@@ -58,10 +65,11 @@ extern bool listTSDictionaries(const char *pattern, bool verbose);
 extern bool listTSTemplates(const char *pattern, bool verbose);
 
 /* \l */
-extern bool listAllDbs(const char *pattern, bool verbose);
+extern bool listAllDbs(const char *pattern, bool verbose, sortby_type sortby, bool sort_desc);
 
 /* \dt, \di, \ds, \dS, etc. */
-extern bool listTables(const char *tabtypes, const char *pattern, bool verbose, bool showSystem);
+extern bool listTables(const char *tabtypes, const char *pattern, bool verbose, bool showSystem,
+					   sortby_type sortby, bool sort_desc);
 
 /* \dD */
 extern bool listDomains(const char *pattern, bool verbose, bool showSystem);
diff --git a/src/bin/psql/help.c b/src/bin/psql/help.c
index a926c40b9b..620b8930a5 100644
--- a/src/bin/psql/help.c
+++ b/src/bin/psql/help.c
@@ -241,10 +241,10 @@ slashUsage(unsigned short int pager)
 	fprintf(output, _("  \\dFp[+] [PATTERN]      list text search parsers\n"));
 	fprintf(output, _("  \\dFt[+] [PATTERN]      list text search templates\n"));
 	fprintf(output, _("  \\dg[S+] [PATTERN]      list roles\n"));
-	fprintf(output, _("  \\di[S+] [PATTERN]      list indexes\n"));
+	fprintf(output, _("  \\di[Ssd+] [PATTERN]    list indexes\n"));
 	fprintf(output, _("  \\dl                    list large objects, same as \\lo_list\n"));
 	fprintf(output, _("  \\dL[S+] [PATTERN]      list procedural languages\n"));
-	fprintf(output, _("  \\dm[S+] [PATTERN]      list materialized views\n"));
+	fprintf(output, _("  \\dm[Ssd+] [PATTERN]    list materialized views\n"));
 	fprintf(output, _("  \\dn[S+] [PATTERN]      list schemas\n"));
 	fprintf(output, _("  \\do[S]  [PATTERN]      list operators\n"));
 	fprintf(output, _("  \\dO[S+] [PATTERN]      list collations\n"));
@@ -253,13 +253,13 @@ slashUsage(unsigned short int pager)
 	fprintf(output, _("  \\dRp[+] [PATTERN]      list replication publications\n"));
 	fprintf(output, _("  \\dRs[+] [PATTERN]      list replication subscriptions\n"));
 	fprintf(output, _("  \\ds[S+] [PATTERN]      list sequences\n"));
-	fprintf(output, _("  \\dt[S+] [PATTERN]      list tables\n"));
+	fprintf(output, _("  \\dt[Ssd+] [PATTERN]    list tables\n"));
 	fprintf(output, _("  \\dT[S+] [PATTERN]      list data types\n"));
 	fprintf(output, _("  \\du[S+] [PATTERN]      list roles\n"));
 	fprintf(output, _("  \\dv[S+] [PATTERN]      list views\n"));
 	fprintf(output, _("  \\dx[+]  [PATTERN]      list extensions\n"));
 	fprintf(output, _("  \\dy     [PATTERN]      list event triggers\n"));
-	fprintf(output, _("  \\l[+]   [PATTERN]      list databases\n"));
+	fprintf(output, _("  \\l[sd+] [PATTERN]      list databases\n"));
 	fprintf(output, _("  \\sf[+]  FUNCNAME       show a function's definition\n"));
 	fprintf(output, _("  \\sv[+]  VIEWNAME       show a view's definition\n"));
 	fprintf(output, _("  \\z      [PATTERN]      same as \\dp\n"));
#42Dean Rasheed
dean.a.rasheed@gmail.com
In reply to: Pavel Stehule (#37)
Re: [HACKERS] Re: proposal - psql: possibility to specify sort for describe commands, when size is printed

On 28 October 2017 at 13:46, Pavel Stehule <pavel.stehule@gmail.com> wrote:

I though about Alexander proposal, and I am thinking so it can be probably
best if we respect psql design. I implemented two command suffixes
(supported only when it has sense) "s" sorted by size and "d" as descent

so list of tables can be sorted with commands:

\dt+sd (in this case, the order is not strict), so command
\dtsd+ is working too (same \disd+ or \di+sd)

These two chars are acceptable. Same principle is used for \l command

\lsd+ or \l+sd

What do you think about it?

I really hate that syntax. This is going to turn into an
incomprehensible mess, and isn't easily extended to support other
options.

I agree with people who have said they would prefer this to be
available as a per-command option rather than as a variable that you
have to set, but it needs a clearer syntax. I actually like Stephen's
idea of using a user-defined SQL snippet, because that's a familiar
syntax to people, and it avoids adding an ever-increasing number of
options to these commands. Instead, the syntax could simply be:

\d[S+] [ pattern ] [ ( auxiliary sql ) ]

(and similar for the other commands)

The auxiliary SQL could be pretty much anything to allow user-defined
ordering and filtering.

I think parsing the optional auxiliary SQL snippet in parentheses at
the end should be quite straightforward, provided that psql makes no
attempt to actually parse the SQL contained in the parentheses -- it
should just add it to the SQL it sends to the backend (like \copy
does). For example, for \d+, instead of generating

SELECT n.nspname as "Schema",
c.relname as "Name",
CASE c.relkind WHEN 'r' THEN 'table' WHEN 'v' THEN 'view' WHEN 'm'
THEN 'materialized view' WHEN 'i' THEN 'index' WHEN 'S' THEN
'sequence' WHEN 's' THEN 'special' WHEN 'f' THEN 'foreign table' WHEN
'p' THEN 'table' END as "Type",
pg_catalog.pg_get_userbyid(c.relowner) as "Owner",
pg_catalog.pg_size_pretty(pg_catalog.pg_table_size(c.oid)) as "Size",
pg_catalog.obj_description(c.oid, 'pg_class') as "Description"
FROM pg_catalog.pg_class c
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind IN ('r','p','v','m','S','f','')
AND n.nspname <> 'pg_catalog'
AND n.nspname <> 'information_schema'
AND n.nspname !~ '^pg_toast'
AND pg_catalog.pg_table_is_visible(c.oid)
ORDER BY 1,2;

we could generate

SELECT schema as "Schema",
name as "Name",
type as "Type",
owner as "Owner",
pg_catalog.pg_size_pretty(size) as "Size",
description as "Description"
FROM (
SELECT n.nspname as schema,
c.relname as name,
CASE c.relkind WHEN 'r' THEN 'table' WHEN 'v' THEN 'view' WHEN 'm'
THEN 'materialized view' WHEN 'i' THEN 'index' WHEN 'S' THEN
'sequence' WHEN 's' THEN 'special' WHEN 'f' THEN 'foreign table' WHEN
'p' THEN 'table' END as type,
pg_catalog.pg_get_userbyid(c.relowner) as owner,
pg_catalog.pg_table_size(c.oid) as size,
pg_catalog.obj_description(c.oid, 'pg_class') as description
FROM pg_catalog.pg_class c
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind IN ('r','p','v','m','S','f','')
AND n.nspname <> 'pg_catalog'
AND n.nspname <> 'information_schema'
AND n.nspname !~ '^pg_toast'
AND pg_catalog.pg_table_is_visible(c.oid)
ORDER BY 1,2
) as t
<auxiliary sql>;

That would allow things like

\d+ (order by size)

which would sort by the numeric size, while displaying the pretty size
in the output.

This would also allow more complex orderings that would be hard to
achieve any other way, such as

\d+ (order by type, schema, size desc)
\dt (order by pg_total_relation_size(name::regclass))

(note the size reported by \d+ is not the total relation size, because
it excludes indexes)

Also, it would allow user-defined WHERE clauses to filter the results
shown, for example:

\d+ (where size > pg_size_bytes('1GB'))
\dv (where pg_relation_is_updatable(name::regclass, true) != 0)

and many more things are possible, without needing to learn any new
syntax, and without needing to keep adding more and more options to
the psql syntax.

Regards,
Dean

#43Magnus Hagander
magnus@hagander.net
In reply to: Dean Rasheed (#42)
Re: [HACKERS] Re: proposal - psql: possibility to specify sort for describe commands, when size is printed

On Mon, Nov 13, 2017 at 3:17 PM, Dean Rasheed <dean.a.rasheed@gmail.com>
wrote:

On 28 October 2017 at 13:46, Pavel Stehule <pavel.stehule@gmail.com>
wrote:

I though about Alexander proposal, and I am thinking so it can be

probably

best if we respect psql design. I implemented two command suffixes
(supported only when it has sense) "s" sorted by size and "d" as descent

so list of tables can be sorted with commands:

\dt+sd (in this case, the order is not strict), so command
\dtsd+ is working too (same \disd+ or \di+sd)

These two chars are acceptable. Same principle is used for \l command

\lsd+ or \l+sd

What do you think about it?

I really hate that syntax. This is going to turn into an
incomprehensible mess, and isn't easily extended to support other
options.

+1. While useful in itself, I think it's definitely a dangerous pattern to
go down, as it'll only get worse.

I agree with people who have said they would prefer this to be

available as a per-command option rather than as a variable that you
have to set, but it needs a clearer syntax. I actually like Stephen's
idea of using a user-defined SQL snippet, because that's a familiar
syntax to people, and it avoids adding an ever-increasing number of
options to these commands. Instead, the syntax could simply be:

+1 here as well. And anybody who is actually going to need this level of
control definitely will know SQL...

And if one wants to save some "standard patterns", it should be doable to
save the pattern itself in a variable and then use it with something like
"\dt :mysort" and have it expand the normal way there.

--
Magnus Hagander
Me: https://www.hagander.net/ <http://www.hagander.net/&gt;
Work: https://www.redpill-linpro.com/ <http://www.redpill-linpro.com/&gt;

#44Alexander Korotkov
a.korotkov@postgrespro.ru
In reply to: Magnus Hagander (#43)
Re: [HACKERS] Re: proposal - psql: possibility to specify sort for describe commands, when size is printed

On Tue, Nov 14, 2017 at 3:26 PM, Magnus Hagander <magnus@hagander.net>
wrote:

On Mon, Nov 13, 2017 at 3:17 PM, Dean Rasheed <dean.a.rasheed@gmail.com>
wrote:

On 28 October 2017 at 13:46, Pavel Stehule <pavel.stehule@gmail.com>
wrote:

I though about Alexander proposal, and I am thinking so it can be

probably

best if we respect psql design. I implemented two command suffixes
(supported only when it has sense) "s" sorted by size and "d" as descent

so list of tables can be sorted with commands:

\dt+sd (in this case, the order is not strict), so command
\dtsd+ is working too (same \disd+ or \di+sd)

These two chars are acceptable. Same principle is used for \l command

\lsd+ or \l+sd

What do you think about it?

I really hate that syntax. This is going to turn into an
incomprehensible mess, and isn't easily extended to support other
options.

+1. While useful in itself, I think it's definitely a dangerous pattern to
go down, as it'll only get worse.

I agree with people who have said they would prefer this to be

available as a per-command option rather than as a variable that you
have to set, but it needs a clearer syntax. I actually like Stephen's
idea of using a user-defined SQL snippet, because that's a familiar
syntax to people, and it avoids adding an ever-increasing number of
options to these commands. Instead, the syntax could simply be:

+1 here as well. And anybody who is actually going to need this level of
control definitely will know SQL...

And if one wants to save some "standard patterns", it should be doable to
save the pattern itself in a variable and then use it with something like
"\dt :mysort" and have it expand the normal way there.

+1
I agree, that would look better, especially with "standard patterns" which
could help with too long to type each time SQL snippets.

------
Alexander Korotkov
Postgres Professional: http://www.postgrespro.com
The Russian Postgres Company

#45Pavel Stehule
pavel.stehule@gmail.com
In reply to: Alexander Korotkov (#44)
Re: [HACKERS] Re: proposal - psql: possibility to specify sort for describe commands, when size is printed

2017-11-27 8:58 GMT+01:00 Alexander Korotkov <a.korotkov@postgrespro.ru>:

On Tue, Nov 14, 2017 at 3:26 PM, Magnus Hagander <magnus@hagander.net>
wrote:

On Mon, Nov 13, 2017 at 3:17 PM, Dean Rasheed <dean.a.rasheed@gmail.com>
wrote:

On 28 October 2017 at 13:46, Pavel Stehule <pavel.stehule@gmail.com>
wrote:

I though about Alexander proposal, and I am thinking so it can be

probably

best if we respect psql design. I implemented two command suffixes
(supported only when it has sense) "s" sorted by size and "d" as

descent

so list of tables can be sorted with commands:

\dt+sd (in this case, the order is not strict), so command
\dtsd+ is working too (same \disd+ or \di+sd)

These two chars are acceptable. Same principle is used for \l command

\lsd+ or \l+sd

What do you think about it?

I really hate that syntax. This is going to turn into an
incomprehensible mess, and isn't easily extended to support other
options.

+1. While useful in itself, I think it's definitely a dangerous pattern
to go down, as it'll only get worse.

I agree with people who have said they would prefer this to be

available as a per-command option rather than as a variable that you
have to set, but it needs a clearer syntax. I actually like Stephen's
idea of using a user-defined SQL snippet, because that's a familiar
syntax to people, and it avoids adding an ever-increasing number of
options to these commands. Instead, the syntax could simply be:

+1 here as well. And anybody who is actually going to need this level of
control definitely will know SQL...

And if one wants to save some "standard patterns", it should be doable to
save the pattern itself in a variable and then use it with something like
"\dt :mysort" and have it expand the normal way there.

+1
I agree, that would look better, especially with "standard patterns" which
could help with too long to type each time SQL snippets.

I though about this design more time. I see following disadvantages

1. we are not able to check all possible variants of extended query. If
there will be some custom error, then we will raise pretty ugly error
messages,

2. I don't thing so using "Size" as table size in human readable format and
"size" as table size in raw format is intuitive, but any change of "Size"
can introduce some (less probability compatibility issues),

3. What queries will contains size calculations? It is not cheap - requires
AccessShareLock

This proposal is first time, when we cannot to detect full semantic from
\xxx command. When user extend query correctly, then it is better than
before, when not it is worse than before.

Regards

Pavel

Show quoted text

------
Alexander Korotkov
Postgres Professional: http://www.postgrespro.com
The Russian Postgres Company

#46Michael Paquier
michael.paquier@gmail.com
In reply to: Pavel Stehule (#45)
Re: [HACKERS] Re: proposal - psql: possibility to specify sort for describe commands, when size is printed

On Tue, Nov 28, 2017 at 4:18 AM, Pavel Stehule <pavel.stehule@gmail.com> wrote:

This proposal is first time, when we cannot to detect full semantic from
\xxx command. When user extend query correctly, then it is better than
before, when not it is worse than before.

As the discussion is still going on, I am moving this patch to next CF.
--
Michael

#47Alexander Korotkov
a.korotkov@postgrespro.ru
In reply to: Pavel Stehule (#45)
Re: [HACKERS] Re: proposal - psql: possibility to specify sort for describe commands, when size is printed

Hi!

On Mon, Nov 27, 2017 at 10:18 PM, Pavel Stehule <pavel.stehule@gmail.com>
wrote:

I though about this design more time. I see following disadvantages

1. we are not able to check all possible variants of extended query. If
there will be some custom error, then we will raise pretty ugly error
messages,

Yes, that's an inevitable shortcoming. psql is not backend and can't
perform all the required checks on its side...

2. I don't thing so using "Size" as table size in human readable format and

"size" as table size in raw format is intuitive, but any change of "Size"
can introduce some (less probability compatibility issues),

Oh, this is surprisingly hard problem which probably have only imperative
solution...

3. What queries will contains size calculations? It is not cheap - requires

AccessShareLock

Sorry, I didn't understand this point. Yes, size calculation requires
locking, but that is already true for \dt+ and \l+. Why this is
disadvantage of proposed approach?

------
Alexander Korotkov
Postgres Professional: http://www.postgrespro.com
The Russian Postgres Company

#48Pavel Stehule
pavel.stehule@gmail.com
In reply to: Alexander Korotkov (#47)
Re: [HACKERS] Re: proposal - psql: possibility to specify sort for describe commands, when size is printed

2017-12-08 22:49 GMT+01:00 Alexander Korotkov <a.korotkov@postgrespro.ru>:

Hi!

On Mon, Nov 27, 2017 at 10:18 PM, Pavel Stehule <pavel.stehule@gmail.com>
wrote:

I though about this design more time. I see following disadvantages

1. we are not able to check all possible variants of extended query. If
there will be some custom error, then we will raise pretty ugly error
messages,

Yes, that's an inevitable shortcoming. psql is not backend and can't
perform all the required checks on its side...

2. I don't thing so using "Size" as table size in human readable format

and "size" as table size in raw format is intuitive, but any change of
"Size" can introduce some (less probability compatibility issues),

Oh, this is surprisingly hard problem which probably have only imperative
solution...

3. What queries will contains size calculations? It is not cheap -

requires AccessShareLock

Sorry, I didn't understand this point. Yes, size calculation requires
locking, but that is already true for \dt+ and \l+. Why this is
disadvantage of proposed approach?

Because you don't know the filter and sort clause (it can be generic), you
don't know, if you should to calculate or not the size. Or there should be
rule, so filter, order must be limited to displayed columns.

Regards

Pavel

Show quoted text

------
Alexander Korotkov
Postgres Professional: http://www.postgrespro.com
The Russian Postgres Company

#49Thomas Munro
thomas.munro@enterprisedb.com
In reply to: Pavel Stehule (#41)
Re: [HACKERS] Re: proposal - psql: possibility to specify sort for describe commands, when size is printed

On Thu, Nov 2, 2017 at 12:44 AM, Pavel Stehule <pavel.stehule@gmail.com> wrote:

I am sending updated patch with some basic doc

Hi Pavel,

I am not sure what the status of this patch is, but FYI:

startup.c: In function ‘main’:
startup.c:284:3: error: too few arguments to function ‘listAllDbs’
success = listAllDbs(NULL, false);
^
In file included from startup.c:21:0:
describe.h:68:13: note: declared here
extern bool listAllDbs(const char *pattern, bool verbose, sortby_type
sortby, bool sort_desc);
^

--
Thomas Munro
http://www.enterprisedb.com

#50Pavel Stehule
pavel.stehule@gmail.com
In reply to: Thomas Munro (#49)
Re: [HACKERS] Re: proposal - psql: possibility to specify sort for describe commands, when size is printed

Hi

2018-01-12 2:35 GMT+01:00 Thomas Munro <thomas.munro@enterprisedb.com>:

On Thu, Nov 2, 2017 at 12:44 AM, Pavel Stehule <pavel.stehule@gmail.com>
wrote:

I am sending updated patch with some basic doc

Hi Pavel,

I am not sure what the status of this patch is, but FYI:

startup.c: In function ‘main’:
startup.c:284:3: error: too few arguments to function ‘listAllDbs’
success = listAllDbs(NULL, false);
^
In file included from startup.c:21:0:
describe.h:68:13: note: declared here
extern bool listAllDbs(const char *pattern, bool verbose, sortby_type
sortby, bool sort_desc);
^

There are no agreement about optimal form of this feature - so I'll remove
this patch from commitfest.

Regards

Pavel

Show quoted text

--
Thomas Munro
http://www.enterprisedb.com