postgresqlを使うときのためのメモ
環境
CentOS 4.3
インストール
yumでpostgresをインストール
yum -y install postgresql-server
postgresを起動
/etc/rc.d/init.d/postgresql start
設定
postgresqlの設定ファイル(/var/lib/pgsql/data/postgresql.conf)
listen_addresses='*' #↑TCP/IP経由でのデータベース接続許可
postgresqlの認証設定ファイル(/var/lib/pgsql/data/pg_hba.conf)
local all all trust #↑追加(ローカルからのアクセスは無条件に許可) host all all 192.168.1.0/24 trust #↑追加(内部からのアクセスは無条件に許可) host all all 0.0.0.0 0.0.0.0 password md5 #↑追加(上記以外からのアクセスはパスワード認証により許可)
psqlでログイン
psql -U postgres -d postgres ←ユーザpostgresでデータベースpostgresに接続要求
プロンプトの表示
postgres=# ←新規コマンド入力開始 postgres-# ←コマンド入力途中 postgres=> ←一般ユーザで接続時 postgres=# ←スーパーユーザで接続時 ※postgresはデータベース名
シーケンス
シーケンスの作成とオートインクリメントの設定
CREATE SEQUENCE company_id_seq; CREATE TABLE company ( id INTEGER DEFAULT nextval('company_id_seq') PRIMARY KEY, name VARCHAR(255) NOT NULL, ... )
シーケンスのリセット
SELECT setval('company_id_set', 1, FALSE);
知っておくと便利なクエリ
カラム一覧
SELECT * FROM infromation_schema.columns WHERE table_catalog='データベース名' AND table_name='テーブル名' ORDER BY ordinal_position;
プライマリー情報取得
SELECT ccu.column_name as COLUMN_NAME FROM information_schema.table_constraints tc ,information_schema.constraint_column_usage ccu WHERE tc.table_catalog='データベース名' AND tc.table_name='テーブル名' AND tc.constraint_type='PRIMARY KEY' AND tc.table_catalog=ccu.table_catalog AND tc.table_schema=ccu.table_schema AND tc.table_name=ccu.table_name AND tc.constraint_name=ccu.constraint_name