マソム自宅サーバ構築の記録
- ■
-
PostgreSQL8.3
-
作成日:08/02/28
更新日:09/08/07
前置き
PostgreSQLは何度か使っていますが、インストールの経験が余りありません。
インストールを勉強し直すことにします。バージョンは2008年2月現在の最新版 8.3.0 にします。
ユーザの作成
postgresユーザを作成しておきます。
$ su
# /usr/sbin/useradd postgres
# /usr/bin/passwd postgres
# exit
PostgreSQLのインストール
まず、ミラーサイトからダウンロード 。
私はユーザディレクトリにソース置き場を作ってあるので、そこにダウンロードします。 勿論/usr/local/srcでも良いと思います。
$ wget http://www.ring.gr.jp/pub/misc/db/postgresql/source/v8.3.0/postgresql-8.3.0.tar.gz
ソースを展開します。
$ tar xzf postgresql-8.3.0.tar.gz
ソースディレクトリに移動しコンパイルします。
$ cd postgresql-8.3.0
$ ./configure 2>&1 |tee configure.log
$ make 2>&1 |tee make.log
インストールします。
$ su
# make install 2>&1 |tee install.log
次にデータベースクラスタを置く(=データを保存する)ディレクトリを作成します。
# mkdir /usr/local/pgsql/data
# chown postgres:postgres /usr/local/pgsql/data
次に、postgresユーザになって、.bash_profileに環境変数の設定をします。
# su - postgres
$ vi .bash_profile
# .bash_profile
# Get the aliases and functions
if [ -f ~/.bashrc ]; then
. ~/.bashrc
fi
# User specific environment and startup programs
PATH=$PATH:$HOME/bin
export POSTGRES_HOME=/usr/local/pgsql
PATH=$POSTGRES_HOME/bin:$PATH
export PGDATA=$POSTGRES_HOME/data
export PATH
設定を有効にします。
$ source ./.bash_profile
postgresユーザのままで、データベースシステムの初期化を行います。
$ /usr/local/pgsql/bin/initdb -D /usr/local/pgsql/data
The files belonging to this database system will be owned by user "postgres".
This user must also own the server process.
The database cluster will be initialized with locale ja_JP.UTF-8.
The default database encoding has accordingly been set to UTF8.
initdb: could not find suitable text search configuration for locale ja_JP.UTF-8
The default text search configuration will be set to "simple".
fixing permissions on existing directory /usr/local/pgsql/data ... ok
creating subdirectories ... ok
selecting default max_connections ... 100
selecting default shared_buffers/max_fsm_pages ... 24MB/153600
creating configuration files ... ok
creating template1 database in /usr/local/pgsql/data/base/1 ... ok
initializing pg_authid ... ok
initializing dependencies ... ok
creating system views ... ok
loading system objects' descriptions ... ok
creating conversions ... ok
creating dictionaries ... ok
setting privileges on built-in objects ... ok
creating information schema ... ok
vacuuming database template1 ... ok
copying template1 to template0 ... ok
copying template1 to postgres ... ok
WARNING: enabling "trust" authentication for local connections
You can change this by editing pg_hba.conf or using the -A option the
next time you run initdb.
Success. You can now start the database server using:
/usr/local/pgsql/bin/postgres -D /usr/local/pgsql/data
or
/usr/local/pgsql/bin/pg_ctl -D /usr/local/pgsql/data -l logfile start
PostgreSQLの起動
起動します。postgresユーザで行います。
$ pg_ctl start
server starting
停止します。
$ pg_ctl stop
LOG: received smart shutdown request
LOG: autovacuum launcher shutting down
waiting for server to shut down....LOG: shutting down
LOG: database system is shut down
done
server stopped
無事起動できるようです。
ルートに戻って自動起動の設定をします。
ソースに付いている起動スクリプトcontrib/start-scripts/linuxを/etc/rc.d/init.dコピーします。
$ exit
# cp /ソース置き場/postgresql-8.3.0/contrib/start-scripts/linux /etc/rc.d/init.d/postgresql
# chmod 755 /etc/rc.d/init.d/postgresql
各rcにサービスを追加します。
# /sbin/chkconfig --add postgresql
S98、K02でシンボリックリンクが作成されました。
エラー報告とログの設定
エラーログはデフォルトでは標準エラーに出力されるようです。設定ファイルpostgresql.confを変更し、syslogに設定します。
# vi /usr/local/pgsql/data/postgresql.conf
・・・省略・・・
#------------------------------------------------------------------------------
# ERROR REPORTING AND LOGGING
#------------------------------------------------------------------------------
# - Where to Log -
#log_destination = 'stderr' # Valid values are combinations of
# stderr, csvlog, syslog and eventlog,
# depending on platform. csvlog
# requires logging_collector to be on.
log_destination = 'syslog'
・・・省略・・・
次にsyslogを設定します。syslogファシリティはPostgreSQLのデフォルト=0 にします。
# vi /etc/syslog.conf
・・・省略・・・
local0.* /var/log/postgresql.log
syslogとPostgreSQLを再起動します。
# /etc/init.d/syslog restart
カーネルロガーを停止中: [ OK ]
システムロガーを停止中: [ OK ]
システムロガーを起動中: [ OK ]
カーネルロガーを起動中: [ OK ]
# /etc/init.d/postgresql restart
Restarting PostgreSQL: LOG: received fast shutdown request
LOG: aborting any active transactions
LOG: autovacuum launcher shutting down
LOG: shutting down
LOG: database system is shut down
server stopped
ok
ログが出来ていることを確認してみます。
# cat /var/log/postgresql.log
Feb 29 15:15:13 xxxxx postgres[xxxxx]: [1-1] LOG: database system was shut down at 2008-02-29 15:15:12 JST
Feb 29 15:15:13 xxxxx postgres[xxxxx]: [1-1] LOG: autovacuum launcher started
Feb 29 15:15:13 xxxxx postgres[xxxxx]: [1-1] LOG: database system is ready to accept connections
psqlの起動
psqlはPostgreSQLの対話型インターフェースです。
postgresユーザになって、起動します。
# su - postgres
$ psql -U postgres
Welcome to psql 8.3.0, the PostgreSQL interactive terminal.
Type: \copyright for distribution terms
\h for help with SQL commands
\? for help with psql commands
\g or terminate with semicolon to execute query
\q to quit
postgres=#
スーパーロールにパスワードを設定
Ver8.1以降はデータベースユーザの変わりにデータベースロールを使うのだそうです。
postgresユーザはPostgreSQLのスーパーロールでもあります。まず、スーパーロールにパスワードを設定します。
postgres=# alter role postgres with encrypted password 'パスワード';
ALTER ROLE
postgres=# select rolname, rolpassword from pg_authid where rolname = 'postgres';
rolname | rolpassword
----------+-------------------------------------
postgres | md5xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
(1 row)
postgres=# \q
しかし、パスワードを有効にするには pg_hda.conf 設定ファイルの設定が必要でした。
デフォルトでは無条件にアクセス許可となっているのを、md5で暗号化されたパスワードを使う設定に変更します。
$ vi /usr/local/pgsql/data/pg_hba.conf
# TYPE DATABASE USER CIDR-ADDRESS METHOD
# "local" is for Unix domain socket connections only
##local all all trust
local all all md5
# IPv4 local connections:
##host all all 127.0.0.1/32 trust
host all all 127.0.0.1/32 md5
# IPv6 local connections:
##host all all ::1/128 trust
host all all ::1/128 md5
設定ファイルを再読み込みします。
$ pg_ctl reload
server signaled
パスワードが設定されたことを確認する為、psqlを起動します。パスワードを尋ねてくればOKです。パスワードを入力してログインします。
$ psql -U postgres
Password for user postgres:
データベースの作成
テスト用のデータベースを作成します。 DB名は「test_db」、持ち主はpostgres、文字コードはOSと同じUTF-8にします。
まず、psqlでSQLを使う場合は以下のようになります。
postgres=# create database test_db with owner = postgres encoding = 'UTF-8';
CREATE DATABASE
postgres=# \q
コマンドを使う場合は以下のようになります。
$ createdb -E UTF8 -U postgres test_db
作成されたか確認してみます。
pqslを起動しデータベースtest_dbに接続出来ればOKです。ついでにデータベースの一覧も表示してみます。
$ psql -U postgres test_db
test_db=# \l
List of databases
Name | Owner | Encoding
-----------+----------+----------
postgres | postgres | UTF8
template0 | postgres | UTF8
template1 | postgres | UTF8
test_db | postgres | UTF8
(4 rows)
次に、テスト用テーブルを作成します。
test_db=# create table test(
test_db(# no integer not null,
test_db(# name varchar(32) unique,
test_db(# primary key ( no ) );
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "test_pkey" for table "test"
NOTICE: CREATE TABLE / UNIQUE will create implicit index "test_name_key" for table "test"
CREATE TABLE
作成できたか確認します。
test_db=# \d test
Table "public.test"
Column | Type | Modifiers
--------+-----------------------+-----------
no | integer | not null
name | character varying(32) |
Indexes:
"test_pkey" PRIMARY KEY, btree (no)
"test_name_key" UNIQUE, btree (name)
レコードを追加します。
test_db=# insert into test values (1,'apple');
INSERT 0 1
test_db=# insert into test values (2,'grape');
INSERT 0 1
test_db=# insert into test values (3,'melon');
INSERT 0 1
レコードが出来ているが確認します。
test_db=# select * from test;
no | name
----+-------
1 | apple
2 | grape
3 | melon
(3 rows)
無事テスト用のデータベースとテーブルが出来ました。
psqlを終了します。
test_db=# \q
PHPのテスト
PHPからPostgreSQLに接続できるか確認します。
Apacheのインストールと
PHPのインストールはテスト前に済ませておきます。
データベースの内容を表示するテストプログラムpgsql_tst.phpを作成します。 ソースは以下の通り。
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>PostgreSQL接続テスト</title>
</head>
<body>
<?php
//===========================================================================
// PostgreSQL接続テスト
//===========================================================================
define("PGSQL_SERVER" ,"localhost");
define("PGSQL_USER" ,"postgres");
define("PGSQL_PASS" ,"パスワード");
define("PGSQL_DB" ,"test_db");
$dbconn = pg_connect("host=".PGSQL_SERVER." port=5432 dbname=".PGSQL_DB
." user=".PGSQL_USER." password=".PGSQL_PASS);
if ($dbconn===false) {
print("Connect failed\n");
exit();
}
$result = pg_query($dbconn, "select * from test");
if ($result===false) {
printf("Errormessage: %s\n", pg_last_error($dbconn));
} else {
print("PostgreSQL テスト接続<br>\n");
while( $ary_data=pg_fetch_array($result, NULL, PGSQL_ASSOC) ){
foreach( $ary_data as $key => $val ){
printf("%s[%s],\t", $key,$val);
}
print("<br>\n");
}
}
/* close connection */
pg_close($dbconn);
?>
</body>
</html>
ドキュメントルートに置いて、ブラウザからアクセスしてみます。
ブラウザに以下の文字列が出ました。接続できているようです。
PostgreSQL テスト接続
no[1], name[apple],
no[2], name[grape],
no[3], name[melon],
一般ロールの作成
psqlでデータベースへの接続に普段使用する、一般ロールを作成します。
phpPgAdminで使うことを想定しています。
$ psql -U postgres
postgres=# create role 一般ロール名 login createrole createdb encrypted password 'パスワード';
CREATE ROLE
postgres=# \du ロール名
List of roles
Role name | Superuser | Create role | Create DB | Connections | Member of
-----------+-----------+-------------+-----------+-------------+-----------
一般ロール名| no | yes | yes | no limit | {}
(1 row)
postgres=# \q
$ exit
# exit
phpPgAdminのインストール
PostgreSQLをphpPgAdminで管理する為にインストールします。バージョンは
http://phppgadmin.sourceforge.net/で確認して2008年3月現在の最新版 4.1.3 にしました。
サポートしているPostgreSQLのバージョンが8.2.x迄となっている点が気がかりでしたが、今のところ問題なさそうです。
PHPは PHP4.1以降で動作するようですが、phpPgAdminの機能を色々使いたいなら PHP 4.3以降がお勧めのようです。
まず、ダウンロードします。私はユーザディレクトリのソース置き場にダウンロードしましたが、任意のディレクトリで良いと思います。
$ cd /home/ユーザ名/src/
$ wget http://downloads.sourceforge.net/phppgadmin/phpPgAdmin-4.1.3.tar.gz?download
ソースを展開します。
$ tar xzf phpPgAdmin-4.1.3.tar.gz
展開したディレクトリ名をお好みに変更して、Apacheドキュメントルート以下の設置したい場所に移動します。
私はディレクトリ名をphpPgAdminとしました。
$ su
# mv phpPgAdmin-4.1.3 /ドキュメントルート以下の任意のディレクトリパス/phpPgAdmin
chownで各ファイルのオーナをドキュメントルートに合わせますが、既に合っていればchownは必要ありません。
# cd /ドキュメントルート以下の任意のディレクトリパス/
# chown -R ドキュメントルートユーザ名.ドキュメントルートグループ名 phpPgAdmin
phpPgAdminディレクトリ内に移動します。
# exit
$ cd /ドキュメントルート以下の任意のディレクトリパス/phpPgAdmin
conf/config.inc.phpを編集します。
以下は、localhost上のPostgreSQLで、ログインするロールの所有しているデーターベースにだけアクセスできる設定です。
$ vi conf/config.inc.php
# $conf['servers'][0]['host'] = '';
$conf['servers'][0]['host'] = 'localhost';
# $conf['owned_only'] = false;
$conf['owned_only'] = true;
ブラウザからインストールしたディレクトリにアクセスしてみてindex.phpが表示されればOKです。
ログインは作成しておいた一般ロールで行えます。
なお、postgresスーパーロールでログインしたい場合は、$conf['extra_login_security'] = false; も必要です。
紆余曲折Tips