Skip to content

Instantly share code, notes, and snippets.

@QuittyMR
QuittyMR / schemaClone.sql
Last active February 20, 2023 21:57
PSQL schema cloner
create view public.sys_get_references as SELECT tc.table_schema AS referencing_schema,
tc.constraint_name,
tc.table_name AS referencing_table,
kcu.column_name AS referencing_column,
pg_get_constraintdef(pc.oid) AS constraint_text
FROM information_schema.table_constraints tc
JOIN information_schema.key_column_usage kcu ON tc.constraint_name::text = kcu.constraint_name::text
JOIN pg_constraint pc ON pc.conname = tc.constraint_name::name
WHERE tc.constraint_type::text = 'FOREIGN KEY'::text;
@QuittyMR
QuittyMR / sys_get_sizes
Created July 17, 2020 09:36
Collect all entity sizes in a Postgres DB in high resolution
SELECT pg_statio_user_tables.schemaname,
pg_statio_user_tables.relname,
pg_size_pretty(pg_total_relation_size(pg_statio_user_tables.relid::regclass)) AS total_size,
pg_size_pretty(pg_relation_size(pg_statio_user_tables.relid::regclass, 'main'::text)) AS relation_size_main,
pg_size_pretty(pg_relation_size(pg_statio_user_tables.relid::regclass, 'fsm'::text)) AS relation_size_fsm,
pg_size_pretty(pg_relation_size(pg_statio_user_tables.relid::regclass, 'vm'::text)) AS relation_size_vm,
pg_size_pretty(pg_relation_size(pg_statio_user_tables.relid::regclass, 'init'::text)) AS relation_size_init,
pg_size_pretty(pg_table_size(pg_statio_user_tables.relid::regclass)) AS table_size,
pg_size_pretty(pg_total_relation_size(pg_statio_user_tables.relid::regclass) - pg_relation_size(pg_statio_user_tables.relid::regclass)) AS external_size
FROM pg_statio_user_tables
@QuittyMR
QuittyMR / sys_get_references
Created July 17, 2020 09:34
Collect all FK references in a Postgres DB
SELECT tc.constraint_name,
concat(tc.table_schema, '.', tc.table_name) AS referencing_table,
kcu.column_name AS referencing_column,
concat(ccu.table_schema, '.', ccu.table_name) AS src_table,
ccu.column_name AS src_column
FROM information_schema.table_constraints tc
JOIN information_schema.key_column_usage kcu ON tc.constraint_name::text = kcu.constraint_name::text
JOIN information_schema.constraint_column_usage ccu ON ccu.constraint_name::text = tc.constraint_name::text
WHERE tc.constraint_type::text = 'FOREIGN KEY'::text;
@QuittyMR
QuittyMR / sys_get_locks
Created July 17, 2020 09:33
Retrieve locks from a Postgres DB
SELECT pg_stat_activity.pid,
pg_stat_activity.usename,
pg_blocking_pids(pg_stat_activity.pid) AS blocked_by,
pg_stat_activity.query AS blocked_query
FROM pg_stat_activity
WHERE cardinality(pg_blocking_pids(pg_stat_activity.pid)) > 0;
@QuittyMR
QuittyMR / provision_lastpass
Created July 17, 2020 09:29
Provisioning script for LastPass's terrible enterprise API
#!/usr/bin/env bash
# Make sure both LASTPASS_ env vars are set
set -e
. /home/tomer/Scripts/f.sh
USER=${1?'Usage: recipient name group username password [URL]'}
NAME=${2?Please provide name for the entry}
GROUP=${3?Please provide folder for the entry}