JavaScript: Node.jsでWebアプリケーションを作る際の、データベース(MySQL)準備の備忘録

前々回の下記記事でNode.jsの準備とサーバー起動までをまとめた。

今回の目的:データベースの設定

引き続きWebアプリケーションとして、買い物に使う様なリストを作っているが、この様なリストアプリの肝のデータベース設定の流れを備忘録として。
当方の環境はMacOS。

MySQLの確認とインストール

まずはMySQLをインストールする所から。

下記コマンドを入れてcommand not found: mysqlと出れば入っていないので入れる。

% mysql --version
zsh: command not found: mysql

この様にバージョン情報が出てくれば既に入っているのでmysqlのインストールは不要。

% mysql --version   
mysql  Ver 8.0.27 for macos11.6 on x86_64 (Homebrew)

インストールにあたってはHomebrewを使用。

% brew install mysql
(中略)
==> Summary
🍺  /usr/local/Cellar/mysql/8.0.27: 304 files, 294MB
==> Caveats
==> mysql
We've installed your MySQL database without a root password. To secure it run:
    mysql_secure_installation

MySQL is configured to only allow connections from localhost by default

To connect run:
    mysql -uroot

To restart mysql after an upgrade:
  brew services restart mysql
Or, if you don't want/need a background service you can just run:
  /usr/local/opt/mysql/bin/mysqld_safe --datadir=/usr/local/var/mysql

終わった後、またバージョンを確認して出てくれば無事入っている。

セキュリティ設定:rootユーザーへのパスワードの設定

インストール時の情報には

We’ve installed your MySQL database without a root password. To secure it run:
mysql_secure_installation

と有る。
デフォルトではrootユーザーにパスワードが設定されていないとの事、
個人がテストで使用するなら不要と思われるが、
パスワードを設定したいなら、mysql_secure_installationと入力して指示に従う。

因みに、最初に”VALIDATE PASSWORD COMPONENT”を設定するか聞かれるが、これはしっかりしたパスワード管理の仕組みでインストールするとアクセスの都度大変な気がするので、本番環境でもないし不要、と思われる人は入れない方が良さそう。
不要なら”y”か”Y”以外を入力。

% mysql_secure_installation

Securing the MySQL server deployment.

Connecting to MySQL using a blank password.

VALIDATE PASSWORD COMPONENT can be used to test passwords
and improve security. It checks the strength of password
and allows the users to set only those passwords which are
secure enough. Would you like to setup VALIDATE PASSWORD component?

Press y|Y for Yes, any other key for No: 
Please set the password for root here.

New password: 

Re-enter new password: 
By default, a MySQL installation has an anonymous user,
allowing anyone to log into MySQL without having to have
a user account created for them. This is intended only for
testing, and to make the installation go a bit smoother.
You should remove them before moving into a production
environment.

Remove anonymous users? (Press y|Y for Yes, any other key for No) : 

 ... skipping.


Normally, root should only be allowed to connect from
'localhost'. This ensures that someone cannot guess at
the root password from the network.

Disallow root login remotely? (Press y|Y for Yes, any other key for No) : 

 ... skipping.
By default, MySQL comes with a database named 'test' that
anyone can access. This is also intended only for testing,
and should be removed before moving into a production
environment.


Remove test database and access to it? (Press y|Y for Yes, any other key for No) : 

 ... skipping.
Reloading the privilege tables will ensure that all changes
made so far will take effect immediately.

Reload privilege tables now? (Press y|Y for Yes, any other key for No) : 

 ... skipping.
All done! 

当方はVALIDATE PASSWORD COMPONENTは設定しなかったが、rootにはパスワードを設定した。
以降は設定したとして進める。

セキュリティ設定:その他のセキュリティー上の設定

mysql_secure_installationではそれ以外のセキュリティ上の設定も行う。

  • anonymous userの削除について:テスト用のいわゆる匿名ユーザーが設定されているが、これを削除するかどうか。本番環境に入る前には削除するべき、との事。
  • localhostの外から(remotely)アクセスできるrootアカウントの削除について
  • testデータベースの削除について:誰でもアクセスできるtestと言う名のデータベースがあり、これを削除するかどうか。これも本番環境に入る前には削除するべき、との事。

こちらは今回全てNoとした。2つ目のlocalhostの外からアクセスできるrootアカウントの削除は、Yesを選択している人も多い様ですが、今の所Noとしました。

このrootアカウントについて、デフォルトではlocalhostからの設定のみ受け入れてくれるが、この設定を変えたい時は別途調整をする必要がありそう。
しかし、これは今日のトピックの趣旨と異なるので割愛。

セキュリティ設定が終わったのでMySQLを起動する。

MySQLの起動と終了:MySQL起動の前にサーバーを起動させる事

mysqlを起動する前に、まずはサーバを起動。

% brew services start mysql
==> Successfully started `mysql` (label: homebrew.mxcl.mysql)

続いて”mysql -u root -p”と入力してmysqlを起動。

このコマンド
mysql -u root -p

“-u:ユーザー”はroot、”-p:パスワード”は設定したパスワード、で起動を意味している。
パスワードを設定していなければ、”mysql -u root”で起動できる。

すると起動して下記画面になる。

% mysql -u root -p         
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 8
Server version: 8.0.27 Homebrew

Copyright (c) 2000, 2021, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> 

因みに、
パスワードについて、今回の様に”-p”と入力したらパスワードを聞かれ、マスクされた、入力文字が見えない状況で入力する。
他にも”–password=”もあり、
% mysql -u root –password=(設定したパスワード直打ち)
と入力しても起動できる。
しかし、これは安全性が低下するのでお勧めしない。

出るにはexitと入力。

mysql> exit
Bye

Bye と出たら無事mysqlから出ている。

サーバーをストップするにはbrew services stop mysql。

% brew services stop mysql    
Stopping `mysql`... (might take a while)
==> Successfully stopped `mysql` (label: homebrew.mxcl.mysql)

因みに、サーバを起動しないままにmysqlを起動するとエラ〜メッセージが出る。
mysqlはサーバを起動してからの起動で。

% mysql -u root -p
Enter password: 
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

データベースの中身の準備

もう一度mysqlに入り直してデータベースの中身を準備。

今あるデータベースをSHOW databasesで表示。今あるのは下記4つ。

mysql> SHOW databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
4 rows in set (0.03 sec)

新規データベースの作成

早速CREATE DATABASEでitem_listと言うデータベースを作る。

mysql> CREATE DATABASE item_list;
Query OK, 1 row affected (0.01 sec)

データベースを選択、テーブルを作る(USE/CREATE TABLE)

続いて、そのままTABLE(テーブル)を作ろうとCREATE TABEのコマンドを入れたらエラーが出た。

mysql> CREATE TABLE items (id INT AUTO_INCREMENT, name TEXT, PRIMARY KEY (id)) DEFAULT CHARSET=utf8;
ERROR 1046 (3D000): No database selected

おっと、データベースを作っただけで選んでいないと作業ができない様だ。
コマンド”USE (データベース名)”でデータベースを選ぶ。
データベース名は勿論先程作ったデータベース名item_listで。

mysql> USE item_list
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed

選んだ後に”items”と言う名のテーブルを作る。
カラム(欄)はINT(数字)属性のid、このidは自動採番(AUTO_INCREMENT)、そしてTEXT(テキスト)属性のname。
プライマリキー(PRIMARY KEY)はid、自動採番のキーに設定すると良い。

mysql> CREATE TABLE items (id INT AUTO_INCREMENT, name TEXT, PRIMARY KEY (id)) DEFAULT CHARSET=utf8;
Query OK, 0 rows affected, 1 warning (0.01 sec)

Query OKと出ているので上手く出来た様だ。

データを入れて確認(INSERT/SELECT)

次にデータベースのテーブルにデータを入れる(INSERT)。

複数まとめて入れる場合には、カラム(欄)に合わせた組み合わせをVALUESの後にカンマで区切って繋げれば良い。
今回はidが自動裁判なのでnameしかないので分かり辛いけれど。

データをINSERTした後はSELECT * FROM テーブル名で見るときちんと入ったか分かる。

mysql> INSERT INTO items (name) VALUES ("きゅうり"), ("とまと"), ("じゃがいも"), ("なす");
Query OK, 4 rows affected (0.02 sec)
Records: 4  Duplicates: 0  Warnings: 0

mysql> SELECT * from items;
+----+-----------------+
| id | name            |
+----+-----------------+
|  1 | きゅうり        |
|  2 | とまと          |
|  3 | じゃがいも      |
|  4 | なす            |
+----+-----------------+
4 rows in set (0.01 sec)

これでアプリで使うアイテムリストのデータベース部分は準備できた。
現状を確認する。

データベース情報の確認

現在データベースは下記5つ、インストール時に元々あった4つに追加して、新しいitem_listが出来ている。

mysql> SHOW databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| item_list          |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
5 rows in set (0.00 sec)

データベースitem_listを選択の上、テーブルリストを出すと、テーブルitemsが出来ている。

mysql> SHOW tables;
+---------------------+
| Tables_in_item_list |
+---------------------+
| items               |
+---------------------+
1 row in set (0.00 sec)

テーブルの設定はDESCRIBE テーブル名で確認。

mysql> DESCRIBE items;
+-------+------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra          |
+-------+------+------+-----+---------+----------------+
| id    | int  | NO   | PRI | NULL    | auto_increment |
| name  | text | YES  |     | NULL    |                |
+-------+------+------+-----+---------+----------------+
2 rows in set (0.00 sec)

今さっき出力したけれど、テーブルのデータはSELECT文で確認。

mysql> SELECT * from items;
+----+-----------------+
| id | name            |
+----+-----------------+
|  1 | きゅうり        |
|  2 | とまと          |
|  3 | じゃがいも      |
|  4 | なす            |
+----+-----------------+
4 rows in set (0.01 sec)</pre>

このデータベースのユーザーとホストのリストもSELECT文で確認。
初めてMySQLを入れた時点では多分皆こんな感じ。

mysql> SELECT User, Host FROM mysql.user;
+------------------+-----------+
| User             | Host      |
+------------------+-----------+
| mysql.infoschema | localhost |
| mysql.session    | localhost |
| mysql.sys        | localhost |
| root             | localhost |
+------------------+-----------+
4 rows in set (0.00 sec)

以上がデータベース側の準備。

次はNode.js側の準備をする。

「マスタリングTCP/IP 入門編(第6版)」
TCP/IPの基礎的な情報が分かり易く書かかれた入門書
第6版まで出版されている事からも内容の確かさが窺える
情報量も多く、リフロー型なので資料として便利
現時点で中古本が1,950円以下である様だが、送料と使い勝手を考えるとKindle版に一票

コメント

  1. […] Node.jsでWebアプリケーションを作る際の、データベース(MySQL)準備の備忘録 […]

  2. […] […]

タイトルとURLをコピーしました