I'm looking for a solution to generate postgreSQL database statistics programmatically. The psql commmand "\d+" is exactly what I need (output-wise), but so far I didn't find a way to retrieve this same data programmatically (by using C# and npgsql.dll). Any suggestions? Thanks in advance!
Asked
Active
Viewed 929 times
1
-
4You can run `psql` with the `-E` option, that will show you the statements that are being used. – Jan 15 '14 at 11:56
2 Answers
0
The answer is here: http://wiki.postgresql.org/wiki/Disk_Usage
I find it useful to have a function: https://gist.github.com/ArtemGr/8434901
See also: PostgreSQL "DESCRIBE TABLE"
0
Apparently the canonical way to find this out is to start psql with the -E
option.
Then it spits out the queries it is using (or any query it runs internally). In this case, it spits out this:
=> \d test_int;
********* QUERY **********
SELECT c.oid,
n.nspname,
c.relname
FROM pg_catalog.pg_class c
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE c.relname ~ '^(test_int)$'
AND pg_catalog.pg_table_is_visible(c.oid)
ORDER BY 2, 3;
**************************
********* QUERY **********
SELECT c.relchecks, c.relkind, c.relhasindex, c.relhasrules, c.relhastriggers, c.relhasoids, '', c.reltablespace, CASE WHEN c.reloftype = 0 THEN '' ELSE c.reloftype::pg_catalog.regtype::pg_catalog.text END, c.relpersistence
FROM pg_catalog.pg_class c
LEFT JOIN pg_catalog.pg_class tc ON (c.reltoastrelid = tc.oid)
WHERE c.oid = '57695';
**************************
********* QUERY **********
SELECT a.attname,
pg_catalog.format_type(a.atttypid, a.atttypmod),
(SELECT substring(pg_catalog.pg_get_expr(d.adbin, d.adrelid) for 128)
FROM pg_catalog.pg_attrdef d
WHERE d.adrelid = a.attrelid AND d.adnum = a.attnum AND a.atthasdef),
a.attnotnull, a.attnum,
(SELECT c.collname FROM pg_catalog.pg_collation c, pg_catalog.pg_type t
WHERE c.oid = a.attcollation AND t.oid = a.atttypid AND a.attcollation <> t.typcollation) AS attcollation,
NULL AS indexdef,
NULL AS attfdwoptions
FROM pg_catalog.pg_attribute a
WHERE a.attrelid = '57695' AND a.attnum > 0 AND NOT a.attisdropped
ORDER BY a.attnum;
**************************
********* QUERY **********
SELECT c.oid::pg_catalog.regclass FROM pg_catalog.pg_class c, pg_catalog.pg_inherits i WHERE c.oid=i.inhparent AND i.inhrelid = '57695' ORDER BY inhseqno;
**************************
********* QUERY **********
SELECT c.oid::pg_catalog.regclass FROM pg_catalog.pg_class c, pg_catalog.pg_inherits i WHERE c.oid=i.inhrelid AND i.inhparent = '57695' ORDER BY c.oid::pg_catalog.regclass::pg_catalog.text;
**************************
Table "name_space.test_int"
Column | Type | Modifiers
--------+---------+-----------
yo | integer |
Which implies that it is getting the oid
of the table from the first query, then using it to lookup various attributes in the rest of the queries.

rogerdpack
- 62,887
- 36
- 269
- 388