node.jsからPostgresqlを使ってみました

普段DBはPostgresqlを使っています。

MySQLはほぼWordPressのときのみ(^^;

今回はnode.jsからPostgreSQLを使ってみました。

インターフェースをインストールします。

$ npm install pg
[email protected] /home/vagrant/nodej/exapp
└─┬ [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├─┬ [email protected]
│ ├── [email protected]
│ └── [email protected]
├─┬ [email protected]
│ ├── [email protected]
│ ├── [email protected]
│ ├── [email protected]
│ ├── [email protected]
│ └─┬ [email protected]
│ └── [email protected]
├─┬ [email protected]
│ └─┬ [email protected]
│ └── [email protected]
└── [email protected]

テスト用のテーブルを作成します。

-bash-4.2$ createuser -P datauser
Enter password for new role: datapass
Enter it again:
Password: postgresのパスワード

postgres=# \du
List of roles
Role name | Attributes | Member of
———–+————————————————————+———–
datauser | | {}
postgres | Superuser, Create role, Create DB, Replication, Bypass RLS | {}

-bash-4.2$ createdb test_db -O datauser
Password:
-bash-4.2$ psql -l
Password:
List of databases
Name | Owner | Encoding | Collate | Ctype | Access privileges
———–+———-+———-+———+——-+———————–
postgres | postgres | UTF8 | C | C |
tdetestdb | postgres | UTF8 | C | C |
template0 | postgres | UTF8 | C | C | =c/postgres +
| | | | | postgres=CTc/postgres
template1 | postgres | UTF8 | C | C | =c/postgres +
| | | | | postgres=CTc/postgres
test_db | datauser | UTF8 | C | C |
(5 rows)

-bash-4.2$ psql -U datauser test_db
Password for user datauser:
test_db=> create table mydata (
test_db(> id serial primary key,
test_db(> name varchar(50),
test_db(> mail varchar(100),
test_db(> memo varchar(255)
test_db(> );
CREATE TABLE
test_db=> \dp
Access privileges
Schema | Name | Type | Access privileges | Column privileges | Policies
——–+—————+———-+——————-+——————-+———-
public | mydata | table | | |
public | mydata_id_seq | sequence | | |
(2 rows)

test_db=> \d
List of relations
Schema | Name | Type | Owner
——–+—————+———-+———-
public | mydata | table | datauser
public | mydata_id_seq | sequence | datauser
(2 rows)

サンプルソースです

create.js

SQLをそのまま使えるのがありがたいかもです(^^;
ORマッパーはあるのかな???

Follow me!

コメントを残す

メールアドレスが公開されることはありません。 ※ が付いている欄は必須項目です

CAPTCHA