初めての Rast (4) つーか、初めての PostgreSQL だなこりゃ
8/1のつづき〜。休み時間とか定時後にやっているので、忙しいとどうもイカン。
DB は PostgreSQL でやります。最近 MySQL しか触ってないのでリハビリ。
$ COLUMNS=100 dpkg -l | egrep "(postgresql|pgsql)" ii libpgsql-ruby 0.7.1-3 ii libpgsql-ruby1.8 0.7.1-3 ii postgresql 7.4.7-6sarge1 ii postgresql-client 7.4.7-6sarge1
PostgreSQL 関連のパッケージはこんなかんじ。
データベース作りましょ。
$ sudo su - postgres
$ createdb -E UNICODE rastdb
CREATE DATABASE
$ psql rastdb
Welcome to psql 7.4.7, the PostgreSQL interactive terminal.
...
rastdb=# \l
List of databases
Name | Owner | Encoding
-----------+-------------+----------
rastdb | postgres | UNICODE
template0 | postgres | EUC_JP
(2 rows)Rast に合わせて、Unicode (多分 UTF-8) でデータベースを作っておく。こっちは EUC-JP コッチは UTF-8 じゃ、ややこしいので。
実は、-E オプションを入れるのを忘れていたので、
DROP DATABASE
して作り直した。
テーブル作る。
rastdb=# CREATE TABLE Items (
rastdb(# id SERIAL PRIMARY KEY,
rastdb(# name TEXT,
rastdb(# description TEXT
rastdb(# );
...
rastdb=# \d
List of relations
Schema | Name | Type | Owner
--------+--------------+----------+----------
public | items | table | postgres
public | items_id_seq | sequence | postgres
(2 rows)
rastdb=# \d Items
Table "public.items"
Column | Type | Modifiers
-------------+---------+--------------------------------------
id | integer | not null default
| | nextval('public.items_id_seq'::text)
name | text |
description | text |
Indexes:
"items_pkey" primary key, btree (id)
できたできた。
実は、テーブル名を Item (単数形) にしていたので、ALTER TABLE Item RENAME TO Items; して直した。
一々作り直さなくても、
app/models/item.rb に
table_name :item
でもいいし、
config/enviroment.rb に
ActiveRecord::Base.pluralize_table_names = false
でもいいんだけど…。
さらに、id のデータ型を INT にしてしまったので、SERIAL で作り直した。
CREATE SEQUENCE items_id_sql;
ALTER TABLE Items ALTER id SET DEFAULT nextval('items_id_seq'); で消さなくても変更できるはず。)
ユーザーも作っておこう。
rastdb=# CREATE USER rastuser WITH PASSWORD 'rastuser-passwd'; CREATE USER rastdb=# GRANT ALL ON Items TO rastuser; GRANT rastdb=# GRANT ALL ON items_id_seq TO rastuser; GRANT
(sequence の方は権限付与を忘れがち。)
弾かれないように。
$ sudo view /etc/postgresql/pg_hba.conf # Database administrative login by UNIX sockets local rastdb rastuser password ... # All IPv4 connections from localhost host rastdb rastuser 127.0.0.1 255.255.255.255 password ...
(/etc/init.d/postgresql reload を忘れないように。)
アクセスできるかな?
$ psql -d rastdb -U rastuser -W (rastuser-passwd と入力)
これで PostgreSQL は終了。