Showing posts with label postgresql. Show all posts
Showing posts with label postgresql. Show all posts

Thursday, March 4, 2021

PostgreSQL: Get a column value corresponding to the min of another column

Purpose: Get a column value corresponding to the min of another column (i.e. both values must belong to the same row)
E.g. Let's say we have columns a,b,c,b. We want a,b matching min(c) while partitioning by d.
 

crmmbqt=# create table demo (a int, b int, c int, d int);

 

crmmbqt=# insert into demo (a, b, c, d) values (1,2,1,1), (2,1,3,1), (3,4,5,2), (4,3,4,2);

INSERT 0 4

Time: 6.106 ms

crmmbqt=# select * from demo;

┌───┬───┬───┬───┐

│ a │ b │ c │ d │

├───┼───┼───┼───┤

│ 1 │ 2 │ 1 │ 1 │

│ 2 │ 1 │ 3 │ 1 │

│ 3 │ 4 │ 5 │ 2 │

│ 4 │ 3 │ 4 │ 2 │

└───┴───┴───┴───┘

(4 rows)


crmmbqt=# select first_value(a) over (partition by d order by c) as a, first_value(b) over (partition by d order by c) as b, c, d from demo;

┌───┬───┬───┬───┐

│ a │ b │ c │ d │

├───┼───┼───┼───┤

│ 1 │ 2 │ 1 │ 1 │

│ 1 │ 2 │ 3 │ 1 │

│ 4 │ 3 │ 4 │ 2 │

│ 4 │ 3 │ 5 │ 2 │

└───┴───┴───┴───┘

(4 rows)


NB: The use of first_value() is really important here.
For example, if you want to get max(c) instead of min(c), do not use last_value(a) but instead:
first_value(a) over (partition by d order by c desc)

crmmbqt=# select min(a) as a, min(b) as b, min(c), d from (select first_value(a) over (partition by d order by c) as a, first_value(b) over (partition by d order by c) as b, c, d from demo) as foo group by d;

┌───┬───┬─────┬───┐

│ a │ b │ min │ d │

├───┼───┼─────┼───┤

│ 1 │ 2 │ 1   │ 1 │

│ 4 │ 3 │ 4   │ 2 │

└───┴───┴─────┴───┘

(2 rows)


Friday, December 11, 2020

postgreSQL: see trigger dependencies of an extension

Source: How to select functions that belong in a given extension in PostgreSQL?
The StackExchange question shows this is the request to use:
SELECT e.extname, ne.nspname AS extschema, p.proname, np.nspname AS proschema
FROM pg_catalog.pg_extension AS e
    INNER JOIN pg_catalog.pg_depend AS d ON (d.refobjid = e.oid)
    INNER JOIN pg_catalog.pg_proc AS p ON (p.oid = d.objid)
    INNER JOIN pg_catalog.pg_namespace AS ne ON (ne.oid = e.extnamespace)
    INNER JOIN pg_catalog.pg_namespace AS np ON (np.oid = p.pronamespace)
WHERE d.deptype = 'e'
ORDER BY 1, 3
which led me to use
SELECT e.extname, t.tgname
FROM pg_catalog.pg_extension AS e
JOIN pg_catalog.pg_depend AS d ON (d.refobjid = e.oid)
JOIN pg_catalog.pg_trigger AS t ON (t.tgfoid = d.objid)
where e.extname = 'mbqt_shared_api'

┌─────────────────┬─────────────────────────────────────┐
│     extname     │               tgname                │
├─────────────────┼─────────────────────────────────────┤
│ mbqt_shared_api │ dt_dialdigit_after_ins_trg          │
│ mbqt_shared_api │ dt_imsi_range_before_ins_or_upd_trg │
│ mbqt_shared_api │ dt_rzgthlr_after_ins_trg            │
│ mbqt_shared_api │ dt_rzgthlr_before_del_trg           │
│ mbqt_shared_api │ dt_rzgthlr_after_upd_trg            │
│ mbqt_shared_api │ dt_dialdigit_after_upd_trg          │
│ mbqt_shared_api │ dt_tadig_after_ins_trg              │
│ mbqt_shared_api │ dt_mccmnc_after_ins_trg             │
└─────────────────┴─────────────────────────────────────┘

Monday, June 1, 2020

PostgreSQL: plpgsql_check

Source: plpgsql_check
Cannot get it to compile from Github sources on macOS 10.15.5.
So, retrieve it from pgxn.
Then compile and install it.
[jerome@jeroboam] > make
clang -Wall -Wmissing-prototypes -Wpointer-arith -Wdeclaration-after-statement -Wendif-labels -Wmissing-format-attribute -Wformat-security -fno-strict-aliasing -fwrapv -Wno-unused-command-line-argument -O2  -undefined dynamic_lookup -I/usr/local/Cellar/postgresql@9.4/9.4.26/lib/pgxs/src/makefiles/../../src/pl/plpgsql/src -I. -I./ -I/usr/local/Cellar/postgresql@9.4/9.4.26/include/server -I/usr/local/Cellar/postgresql@9.4/9.4.26/include/internal -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk   -I/usr/local/opt/gettext/include -I/usr/local/opt/openldap/include -I/usr/local/opt/openssl@1.1/include -I/usr/local/opt/readline/include -I/usr/local/opt/tcl-tk/include  -c -o plpgsql_check.o plpgsql_check.c
clang -Wall -Wmissing-prototypes -Wpointer-arith -Wdeclaration-after-statement -Wendif-labels -Wmissing-format-attribute -Wformat-security -fno-strict-aliasing -fwrapv -Wno-unused-command-line-argument -O2  -undefined dynamic_lookup -I/usr/local/Cellar/postgresql@9.4/9.4.26/lib/pgxs/src/makefiles/../../src/pl/plpgsql/src -bundle -multiply_defined suppress -o plpgsql_check.so plpgsql_check.o -L/usr/local/Cellar/postgresql@9.4/9.4.26/lib    -L/usr/local/opt/gettext/lib -L/usr/local/opt/openldap/lib -L/usr/local/opt/openssl@1.1/lib -L/usr/local/opt/readline/lib -L/usr/local/opt/tcl-tk/lib -Wl,-dead_strip_dylibs   -bundle_loader /usr/local/Cellar/postgresql@9.4/9.4.26/bin/postgres
[jerome@jeroboam] > make install
/bin/sh /usr/local/Cellar/postgresql@9.4/9.4.26/lib/pgxs/src/makefiles/../../config/install-sh -c -d '/usr/local/Cellar/postgresql@9.4/9.4.26/lib'
/bin/sh /usr/local/Cellar/postgresql@9.4/9.4.26/lib/pgxs/src/makefiles/../../config/install-sh -c -d '/usr/local/Cellar/postgresql@9.4/9.4.26/share/extension'
/bin/sh /usr/local/Cellar/postgresql@9.4/9.4.26/lib/pgxs/src/makefiles/../../config/install-sh -c -d '/usr/local/Cellar/postgresql@9.4/9.4.26/share/extension'
/usr/bin/install -c -m 755  plpgsql_check.so '/usr/local/Cellar/postgresql@9.4/9.4.26/lib/plpgsql_check.so'
/usr/bin/install -c -m 644 plpgsql_check.control '/usr/local/Cellar/postgresql@9.4/9.4.26/share/extension/'
/usr/bin/install -c -m 644 plpgsql_check--1.0.sql '/usr/local/Cellar/postgresql@9.4/9.4.26/share/extension/'
[jerome@jeroboam] > 
Then from psql:
crmmbqt=# CREATE EXTENSION plpgsql_check;
CREATE EXTENSION
Time: 317.716 ms

PostgreSQL: ERROR: could not access file "$libdir/plpython2": No such file or directory

After upgrading postgres from 9.4.18 to 9.4.26 on MacOS 10.15.5 with
[jerome@jeroboam] > brew upgrade 'postgresql@9.4'
I then discovered that plpython was gone.
[jerome@jeroboam] > make
touch sql/mbqt_post_api.out
../bin/replace_extension.pl sql/mbqt_post_api.sql
DBG> schema = mbqt_db, extension = mbqt_post_api
DBG> installed version = 1.21, new version = 1.21
CMD> cat sql/mbqt_post_api.sql > sql/mbqt_post_api--1.21.sql
CMD> /usr/bin/install -m 644 sql/mbqt_post_api--1.21.sql sql/mbqt_post_api.control /usr/local/Cellar/postgresql@9.4/9.4.26/share/postgresql@9.4/extension
CMD> psql -Upostgres -h127.0.0.1 -p5432 -dcrmmbqt -q<<END_OF_SQL
\set ON_ERROR_STOP ON
create schema if not exists mbqt_db authorization postgres;
drop extension if exists mbqt_post_api cascade;
create extension mbqt_post_api with schema mbqt_db;
END_OF_SQL
2020-06-01 14:12:47
NOTICE:  schema "mbqt_db" already exists, skipping
Time: 11.778 ms
NOTICE:  extension "mbqt_post_api" does not exist, skipping
Time: 12.900 ms
ERROR:  could not access file "$libdir/plpython2": No such file or directory
And indeed
[jerome@jeroboam] > ll -rt /usr/local/opt/postgresql\@9.4/lib/pl*
-r--r--r--  1 jerome  staff    42K Jun  1 12:41 /usr/local/opt/postgresql@9.4/lib/pltcl.so
-r--r--r--  1 jerome  staff   164K Jun  1 12:41 /usr/local/opt/postgresql@9.4/lib/plpgsql.so
-r--r--r--  1 jerome  staff    84K Jun  1 12:41 /usr/local/opt/postgresql@9.4/lib/plperl.so
I tried
[jerome@jeroboam] > brew reinstall postgresql@9.4 --with-python
But it failed with
Error: invalid option: --with-python
And indeed, as per Remove all options from Homebrew/homebrew-core formulae, they estimated that options in brew are bad from now.
Then I found out: petere / homebrew-postgresql.
So, I used
[jerome@jeroboam] > brew tap petere/postgresql
And
[jerome@jeroboam] > brew reinstall petere/postgresql/postgresql@9.4
which ended up with
configure: error: header file <perl.h> is required for Perl

If reporting this issue please do so at (not Homebrew/brew or Homebrew/core):
  https://github.com/petere/homebrew-postgresql/issues


Error: A newer Command Line Tools release is available.
Update them from Software Update in System Preferences or run:
  softwareupdate --all --install --force

If that doesn't show you an update run:
  sudo rm -rf /Library/Developer/CommandLineTools
  sudo xcode-select --install
Then let's go
[jerome@jeroboam] > sudo rm -rf /Library/Developer/CommandLineTools
[jerome@jeroboam] > sudo xcode-select --install
And finally
[jerome@jeroboam] > brew reinstall petere/postgresql/postgresql@9.4
which ended OK this time

==> Summary
🍺  /usr/local/Cellar/postgresql@9.4/9.4.26: 2,989 files, 41.0MB, built in 2 minutes 8 seconds
And guess what? plpython is back.
[jerome@jeroboam] > ll -rt /usr/local/opt/postgresql\@9.4/lib/pl*
-r--r--r--  1 jerome  staff    42K Jun  1 15:53 /usr/local/opt/postgresql@9.4/lib/pltcl.so
-r--r--r--  1 jerome  staff   108K Jun  1 15:53 /usr/local/opt/postgresql@9.4/lib/plpython2.so
-r--r--r--  1 jerome  staff   164K Jun  1 15:53 /usr/local/opt/postgresql@9.4/lib/plpgsql.so
-r--r--r--  1 jerome  staff    84K Jun  1 15:53 /usr/local/opt/postgresql@9.4/lib/plperl.so

Monday, May 25, 2020

postgreSQL: streaming replication delay

From the standby DB:
crmmbqt=# select now() - pg_last_xact_replay_timestamp() as replication_delay;
┌───────────────────────┐
│   replication_delay   │
├───────────────────────┤
│ 1 day 05:45:26.277667 │
└───────────────────────┘
or get more details with
crmmbqt=# pg_last_xlog_receive_location(), pg_last_xlog_replay_location(), pg_last_xact_replay_timestamp(), case when pg_last_xlog_receive_location() = pg_last_xlog_replay_location() then 0 else extract(epoch from now() - pg_last_xact_replay_timestamp()) end as replication_delay;

Monday, March 2, 2020

macOS: add PYTHONPATH to PostgreSQL brew service

Source: Changing the Homebrew Apache PATH variable.

Let's suppose we installed Python requests module.
On my system, requests has been installed in /usr/local/lib/python2.7/site-packages/.
Then, trying to import it from postgres like in
create or replace function tutu(o_status out int) as
$$
import sys, os
import requests, json
plpy.info(sys.version)
plpy.info(sys.path)
return (500)
$$ language plpython2u security definer;
will cause
select * from tutu()
to output
Query 1 ERROR: ERROR:  ImportError: No module named requests
By default, postgres will look in /Library/Python/2.7/site-packages/.
We then need to update PYTHONPATH.
With brew starting postgres, we will update the postgres plist file.
[jerome@jeroboam] > vi /usr/local/opt/postgresql\@9.4/homebrew.mxcl.postgresql\@9.4.plist


  KeepAlive
  
  Label
  homebrew.mxcl.postgresql@9.4
  EnvironmentVariables
  
    PYTHONPATH
    /usr/local/lib/python2.7/site-packages
  
  ProgramArguments
  
    /usr/local/opt/postgresql@9.4/bin/postgres
    -D
    /usr/local/var/postgresql@9.4
  
  RunAtLoad
  
  WorkingDirectory
  /usr/local
  StandardErrorPath
  /usr/local/var/log/postgresql@9.4.log


Then
[jerome@jeroboam] > brew services stop postgresql@9.4
[jerome@jeroboam] > brew services start postgresql@9.4
Then
select * from tutu()
outputs
INFO:  2.7.16 (default, Dec 13 2019, 18:00:32) 
[GCC 4.2.1 Compatible Apple LLVM 11.0.0 (clang-1100.0.32.4) (-macos10.15-objc-s
INFO:  ['/usr/local/lib/python2.7/site-packages', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python27.zip', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload', '/Users/jerome/Library/Python/2.7/lib/python/site-packages', '/Library/Python/2.7/site-packages', '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python', '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC']

Wednesday, February 26, 2020

macOS: ld: warning: directory not found for option '-L/Library/Developer/CommandLineTools/SDKs/MacOSX10.13.sdk/usr/lib'

If your PostgreSQL extension Makefile uses PGXS like in
PG_CONFIG = pg_config
...
PGXS := $(shell $(PG_CONFIG) --pgxs)
include $(PGXS)
And you updated MacOS since you installed PostgreSQL, you may experience the following error at compile time :
[jerome@jeroboam] > make
...
clang -Wall -Wmissing-prototypes -Wpointer-arith -Wdeclaration-after-statement -Wendif-labels -Wmissing-format-attribute -Wformat-security -fno-strict-aliasing -fwrapv -Wno-unused-command-line-argument -D_XOPEN_SOURCE  -L/usr/local/Cellar/postgresql@9.4/9.4.18/lib -L/usr/local/opt/openssl/lib -L/usr/local/opt/readline/lib -L/Library/Developer/CommandLineTools/SDKs/MacOSX10.13.sdk/usr/lib  -Wl,-dead_strip_dylibs   -bundle -bundle_loader /usr/local/Cellar/postgresql@9.4/9.4.18/bin/postgres -o src/pg_proctab.so src/pg_proctab.o
ld: warning: directory not found for option '-L/Library/Developer/CommandLineTools/SDKs/MacOSX10.13.sdk/usr/lib'
Then replace MacOSX10.13 for CPPFLAGS and LDFLAGS in
[jerome@jeroboam] > sudo vi /usr/local/Cellar/postgresql\@9.4/9.4.18/lib/pgxs/src/Makefile.global
with e.g. MacOSX10.15.

MacOS: fatal error: 'sys/vfs.h' file not found

[jerome@jeroboam] > make
clang -Wall -Wmissing-prototypes -Wpointer-arith -Wdeclaration-after-statement -Wendif-labels -Wmissing-format-attribute -Wformat-security -fno-strict-aliasing -fwrapv -Wno-unused-command-line-argument -D_XOPEN_SOURCE  -I. -I./ -I/usr/local/Cellar/postgresql@9.4/9.4.18/include/server -I/usr/local/Cellar/postgresql@9.4/9.4.18/include/internal -I/usr/local/opt/openssl/include -I/usr/local/opt/readline/include -I/Library/Developer/CommandLineTools/SDKs/MacOSX10.13.sdk/usr/include/libxml2   -c -o src/pg_proctab.o src/pg_proctab.c
src/pg_proctab.c:14:10: fatal error: 'sys/vfs.h' file not found
#include 
         ^~~~~~~~~~~
1 error generated.
make: *** [src/pg_proctab.o] Error 1
Then replace
#include <sys/vfs.h>
with
#if defined(__APPLE__)
#include <sys/mount.h>
#else
#include <sys/vfs.h>
#endif

Friday, October 18, 2019

postgreSQL: generate big data of unique numbers

Sources:
CREATE OR REPLACE FUNCTION jerome_pseudo_encrypt(VALUE int) returns int AS $$
DECLARE
l1 int;
l2 int;
r1 int;
r2 int;
i int:=0;
BEGIN
 l1:= (VALUE >> 16) & 65535;
 r1:= VALUE & 65535;
 WHILE i < 3 LOOP
   l2 := r1;
   r2 := l1 # ((((1366 * r1 + 150889) % 714025) / 714025.0) * 32767)::int;
   l1 := l2;
   r1 := r2;
   i := i + 1;
 END LOOP;
 RETURN ((r1 << 16) + l1);
END;
$$ LANGUAGE plpgsql strict immutable;
create sequence jerome_seq maxvalue 2147483647;
create table prov_db.dt_hpe_dev (hpe_dev_id bigserial, sim_id bigint, constraint dt_hpe_dev_pkey primary key (hpe_dev_id));
insert into prov_db.dt_hpe_dev (sim_id) select jerome_pseudo_encrypt(nextval('jerome_seq')::int)  from generate_series(1, 1000000);

Wednesday, September 4, 2019

PostgreSQL: distinct but only for one column

Source: Postgres: Distinct but only for one column
Problem: The following returns 2 distinct network_id for the same mccmnc_code.
with toto as (
    select mccmnc_code from (values (24024)) as x(mccmnc_code)
)
select dt_mccmnc.mccmnc_code, dt_mccmnc.network_id, dt_mccmnc.country_id
from toto
left join shared_db.dt_mccmnc 
    on dt_mccmnc.mccmnc_code = toto.mccmnc_code
    and dt_mccmnc.master_country_flg is true
    and localtimestamp(0) <@ dt_mccmnc.validity_period

-- mccmnc_code network_id country_id
-- 24024 1828 297
-- 24024 1816 297
So as to keep only one of the rows, use the following:
with toto as (
    select mccmnc_code from (values (24024)) as x(mccmnc_code)
)
select distinct on (dt_mccmnc.mccmnc_code) dt_mccmnc.mccmnc_code, dt_mccmnc.network_id, dt_mccmnc.country_id
from toto
left join shared_db.dt_mccmnc 
    on dt_mccmnc.mccmnc_code = toto.mccmnc_code
    and dt_mccmnc.master_country_flg is true
    and localtimestamp(0) <@ dt_mccmnc.validity_period

-- mccmnc_code network_id country_id
-- 24024 1828 297

Monday, August 26, 2019

PostgreSQL: create table from CSV

Import CSV data into new table.
create table shared_db.dt_ranking (ranking_id bigserial, vers text,tadig_code text ,mcc text ,mnc text ,advanced int, lite int, vplmn_rank int,
   constraint dt_ranking_pkey primary key (ranking_id)
)
 
\copy shared_db.dt_ranking (vers,tadig_code,mcc,mnc,advanced,lite,vplmn_rank) from '/tmp/ranking.csv' with (format csv, delimiter ',', header true);

Tuesday, April 23, 2019

postgreSQL: get some table statistics

select * from pg_stat_all_tables where schemaname = 'short_message_db' and relname = 'dt_msg';
select * from pg_statio_all_tables where schemaname = 'short_message_db' and relname = 'dt_msg';

Wednesday, April 3, 2019

AWS: list Aurora supported PostgreSQL versions

[jerome@jeroboam] > aws rds describe-db-engine-versions --engine aurora-postgresql --region eu-west-1
[
...
        {
            "Engine": "aurora-postgresql", 
            "DBParameterGroupFamily": "aurora-postgresql10", 
            "SupportsLogExportsToCloudwatchLogs": false, 
            "SupportsReadReplica": false, 
            "DBEngineDescription": "Aurora (PostgreSQL)", 
            "SupportedEngineModes": [
                "provisioned"
            ], 
            "EngineVersion": "10.6", 
            "DBEngineVersionDescription": "Aurora PostgreSQL (compatible with PostgreSQL 10.6)", 
            "ValidUpgradeTarget": []
        }
    ]

Friday, March 22, 2019

postgreSQL: collapse contiguous ranges

Source: Efficiently select beginning and end of multiple contiguous ranges in Postgresql query
with recursive
data as (
	select * from (
    values	('foo', 2, 3),
		   	('foo', 3, 4),
			('foo', 4, 5),
			('foo', 10, 11),
			('foo', 11, 13),
			('foo', 13, 15),
			('bar', 1, 2),
			('bar', 2, 4),
			('bar', 7, 8)
	) as baz (name, first, last)
),
recur (name, first, last) as (
    select name, first, last, last-first as span from data
    union all
    select name, data.first, data.last, recur.span+data.last-data.first as span
    from data join recur using (name)
    where data.first = recur.last
)
select name, start, start + span as end, span from (
    select name, (last-span) as start, max(span) as span from (
         select name, first, last, max(span) as span 
        from recur
        group by name, first, last
    ) as z
    group by name, (last-span)
) as z

┌──────┬───────┬─────┬──────┐
│ name │ start │ end │ span │
├──────┼───────┼─────┼──────┤
│ bar  │     1 │   4 │    3 │
│ bar  │     7 │   8 │    1 │
│ foo  │    10 │  15 │    5 │
│ foo  │     2 │   5 │    3 │
└──────┴───────┴─────┴──────┘
(4 rows)

Or if we do not have a "last" column.
with recursive
data as (
    select * from (
        values ('foo', 2),
               ('foo', 3),
               ('foo', 4),
               ('foo', 10),
               ('foo', 11),
               ('foo', 13),
               ('bar', 1),
               ('bar', 2),
               ('bar', 7)
    ) as baz (name, first)
),
recur (name, first) as (
    select name, first, 1 as span from data
    union all
    select name, data.first, recur.span+1 as span
    from data
    join recur using (name)
    where data.first = recur.first + 1
)
select name, start, start + span - 1 as end, span from (
    select name, (first+1-span) as start, max(span) as span from (
        select name, first, max(span) as span 
        from recur
        group by name, first
    ) as z
    group by name, start
) as z
order by name, start

┌──────┬───────┬─────┬──────┐
│ name │ start │ end │ span │
├──────┼───────┼─────┼──────┤
│ bar  │     1 │   2 │    2 │
│ bar  │     7 │   7 │    1 │
│ foo  │     2 │   4 │    3 │
│ foo  │    10 │  11 │    2 │
│ foo  │    13 │  13 │    1 │
└──────┴───────┴─────┴──────┘
(5 rows)

The problem is that with recursive tends to be slow when dealing with millions of rows.
How to find the boundaries of groups of contiguous sequential numbers? proposes a faster approach.
with
data as (
    select * from (
        values ('foo', 2),
               ('foo', 3),
               ('foo', 4),
               ('foo', 10),
               ('foo', 11),
               ('foo', 13),
               ('bar', 1),
               ('bar', 2),
               ('bar', 7)
    ) as baz (name, first)
),
island as (
    select first - row_number() over (order by name, first) as grp,
    name, first
    from data
)
select name, min(first) as start, max(first) as end
from island
group by name, grp
order by name, start

┌──────┬───────┬─────┐
│ name │ start │ end │
├──────┼───────┼─────┤
│ bar  │     1 │   2 │
│ bar  │     7 │   7 │
│ foo  │     2 │   4 │
│ foo  │    10 │  11 │
│ foo  │    13 │  13 │
└──────┴───────┴─────┘
(5 rows)

Thursday, March 14, 2019

macOS: terminal UTF-8 issues

If you cannot display unicode characters in psql, e.g.
[jerome@jeroboam] > psql mydb
mydb=# \d public.tap_funky 
         View "public.tap_funky"
<E2><94><8C><E2><94><80><E2><94><80><E2><94><80><E2><94><80><E2><94><80><E2><94><80><E2><94><80><E2><94><80><E2><94><80><E2><94><80><E2><94><80><E2><94><80><E2><94><80><E2><94><AC><E2><94><80><E2><94><80><E2>
<94><80><E2><94><80><E2><94><80><E2><94><80><E2><94><80><E2><94><80><E2><94><80><E2><94><80><E2><94><80><E2><94><80><E2><94><80><E2><94><80><E2><94><AC><E2><94><80><E2><94><80><E2><94><80><E2><94><80><E2><94>
<80><E2><94><80><E2><94><80><E2><94><80><E2><94><80><E2><94><80><E2><94><80><E2><94><90>
<E2><94><82>   Column    <E2><94><82>     Type     <E2><94><82> Modifiers <E2><94><82>
Then
[jerome@jeroboam] > vi ~/.bash_profile
export LANG=en_US.UTF-8
[jerome@jeroboam] > source ~/.bash_profile
And finally
mydb=# \d public.tap_funky 
         View "public.tap_funky"
┌─────────────┬──────────────┬───────────┐
│   Column    │     Type     │ Modifiers │
├─────────────┼──────────────┼───────────┤
│ oid         │ oid          │           │
│ schema      │ name         │           │
│ name        │ name         │           │
│ owner       │ name         │           │
│ args        │ text         │           │
│ returns     │ text         │           │
│ langoid     │ oid          │           │
│ is_strict   │ boolean      │           │
│ is_agg      │ boolean      │           │
│ is_definer  │ boolean      │           │
│ returns_set │ boolean      │           │
│ volatility  │ character(1) │           │
│ is_visible  │ boolean      │           │
└─────────────┴──────────────┴───────────┘

Monday, December 17, 2018

PostgreSQL: output from multi-line pl/pgsql from psql from perl

#!/usr/bin/perl

my $cmd = "psql -Xq --set ON_ERROR_STOP=on --dbname crmmbqt <<'EOS'
";
$cmd .= <<'END';
do
$$
begin
    raise notice '%', pg_is_in_recovery();
end
$$
END
$cmd .= 'EOS
';

print `$cmd`;

PostgreSQL: see the age of locks

Source: https://wiki.postgresql.org/wiki/Lock_Monitoring
select a.pid, c.relname, l.transactionid, l.mode, l.granted, a.usename, a.query, a.query_start, age(now(), a.query_start) as "age" from pg_stat_activity a join pg_locks l on l.pid = a.pid join pg_class c on c.oid = l.relation order by a.query_start

Thursday, July 5, 2018

macOS: install postgreSQL 9.4

brew install postgresql@9.4 --with-python
brew link postgresql@9.4 --force

Wednesday, June 27, 2018