#!/usr/bin/env bash
set -euo pipefail
if[$# !=2];thenecho"please enter a db host and a table suffix"exit1fiexportDBHOST=$1exportTSUFF=$2psql \
-X \
-U user \
-h $DBHOST\
-f /path/to/sql/file.sql \
--echo-all \
--set AUTOCOMMIT=off \
--set ON_ERROR_STOP=on \
--set TSUFF=$TSUFF\
--set QTSTUFF=\'$TSUFF\'\
mydatabase
psql_exit_status=$?if[$psql_exit_status !=0];thenecho"psql failed while trying to run this sql script" 1>&2exit$psql_exit_statusfiecho"sql script successful"exit0
begin;dropindexthis_index_:TSUFF;commit;begin;createtablenew_table_:TSUFF(greetingtextnotnulldefault'');commit;begin;insertintonew_table_:TSUFF(greeting)values('Hello from table '||:QTSUFF);commit;
#!/bin/bash
set -euo pipefail
# Set these environmental variables to override them,# but they have safe defaults.exportPGHOST=${PGHOST-localhost}exportPGPORT=${PGPORT-5432}exportPGDATABASE=${PGDATABASE-my_database}exportPGUSER=${PGUSER-my_user}exportPGPASSWORD=${PGPASSWORD-my_password}RUN_PSQL="psql -X --set AUTOCOMMIT=off --set ON_ERROR_STOP=on "${RUN_PSQL}<<SQL
select blah_column
from blahs
where blah_column = 'foo';
rollback;
SQL
CREATE_MY_TABLE_SQL=$(cat <<EOF
create table foo (
id bigint not null,
name text not null
);
EOF)$RUN_ON_MYDB<<SQL
$CREATE_MY_TABLE_SQLcommit;SQL
如何将单个SELECT标量结果赋值给Bash变量
CURRENT_ID=$($PSQL -X -U $PROD_USER -h myhost -P t -P format=unaligned $PROD_DB -c "select max(id) from users")letNEXT_ID=CURRENT_ID+1
echo"next user.id is $NEXT_ID"echo"about to reset user id sequence on other database"$PSQL -X -U $DEV_USER$DEV_DB -c "alter sequence user_ids restart with $NEXT_ID"
#!/usr/bin/env bash
set -euo pipefail
if[ -z "$1"];thenecho"Usage: $0 table [db]"exit1fiSCMTBL="$1"SCHEMANAME="${SCMTBL%%.*}"# everything before the dot (or SCMTBL if there is no dot)TABLENAME="${SCMTBL#*.}"# everything after the dot (or SCMTBL if there is no dot)if["${SCHEMANAME}"="${TABLENAME}"];thenSCHEMANAME="public"fiif[ -n "$2"];thenDB="$2"elseDB="my_default_db"fiPSQL="psql -U my_default_user -h my_default_host -d $DB -x -c "$PSQL"
select '-----------' as \"-------------\",
schemaname,
tablename,
attname,
null_frac,
avg_width,
n_distinct,
correlation,
most_common_vals,
most_common_freqs,
histogram_bounds
from pg_stats
where schemaname='$SCHEMANAME'
and tablename='$TABLENAME';
"| grep -v "\-\[ RECORD "
使用方式
./table-stats.sh myschema.mytable
对于public模式中的表
./table-stats.sh mytable
连接其他数据库
./table-stats.sh mytable myotherdb
将psql的默认输出转换为Markdown表格
aliaspg2md=' sed '\''s/+/|/g'\'' | sed '\''s/^/|/'\'' | sed '\''s/$/|/'\'' | grep -v rows | grep -v '\''||'\'''# Usagepsql -c 'SELECT * FROM pg_database'| pg2md