MySQLについて

MySQLについて

GitHubからリポジトリをクローンして環境構築をする際にMySQLの導入や使い方で、ハマってしまったので、こちらにまとめます

MySQLは、リレーショナルデータベース管理システムのことである
MySQLは、Railsアプリケーションとやり取りをしてデータベースを操作してくれる
MySQLRailsアプリケーションは、それぞれのソケットを接続口としてやり取りする(ソケット: プログラムとネットワークとの接続口の事)
ローカル環境でMySQLを実行する際は、Unixドメインソケットが必要で、このソケットファイルの入出力を通じてクライアントとサーバーがやり取りできる
MySQLを使うためには、大まかに以下のような手順になる

  1. MySQLをインストールする

  2. MySQLのサーバーを起動する

  3. MySQLにログインする

今回発生したエラーを時系列ごとに以下に示します

[Gemfile]にmysql2を記述して、bundle installしたところ、以下のようになりました

higmonta@higuchimiyukiyuunoMacBook-Pro sql_active_record_practice % bundle
Fetching gem metadata from https://rubygems.org/............
Fetching rake 13.0.6
Installing rake 13.0.6
Using minitest 5.14.0
Using thread_safe 0.3.6
Using builder 3.2.4
Using erubi 1.9.0
Using websocket-extensions 0.1.4
Using mini_mime 1.0.2
Using bindex 0.8.1
Using crass 1.0.6
Using bundler 2.2.6
Fetching concurrent-ruby 1.1.6
Fetching zeitwerk 2.3.0
Fetching byebug 11.1.1
Fetching msgpack 1.3.3
Fetching mini_portile2 2.6.1
Fetching rack 2.2.2
Fetching racc 1.5.2
Fetching nio4r 2.5.8
Installing zeitwerk 2.3.0
Installing mini_portile2 2.6.1
Installing byebug 11.1.1 with native extensions
Installing msgpack 1.3.3 with native extensions
Installing nio4r 2.5.8 with native extensions
Installing rack 2.2.2
Installing concurrent-ruby 1.1.6
Installing racc 1.5.2 with native extensions
Fetching ffi 1.15.3
Fetching hirb 0.7.3
Installing ffi 1.15.3 with native extensions
Installing hirb 0.7.3
Using rb-fsevent 0.10.3
Using method_source 0.9.2
Using thor 1.0.1
Using tilt 2.0.10
Using spring 2.1.0
Using tzinfo 1.2.6
Using websocket-driver 0.7.1
Using mail 2.7.1
Using rack-test 1.1.0
Fetching ruby_dep 1.5.0
Fetching mysql2 0.5.3
Using sprockets 4.0.0
Installing ruby_dep 1.5.0
Installing mysql2 0.5.3 with native extensions
Fetching i18n 1.8.2
Installing i18n 1.8.2
Fetching puma 4.3.8
Using rb-inotify 0.10.1
Installing puma 4.3.8 with native extensions
Fetching nokogiri 1.12.3 (x86_64-darwin)
Fetching bootsnap 1.4.6
Fetching listen 3.1.5
Fetching activesupport 6.0.2.1
Installing bootsnap 1.4.6 with native extensions
Installing listen 3.1.5
Installing activesupport 6.0.2.1
Using globalid 0.4.2
Installing nokogiri 1.12.3 (x86_64-darwin)
Using rails-dom-testing 2.0.3
Using loofah 2.4.0
Using mimemagic 0.3.10
Using rails-html-sanitizer 1.3.0
Using marcel 0.3.3
Fetching spring-watcher-listen 2.0.1
Installing spring-watcher-listen 2.0.1
Fetching jbuilder 2.10.0
Fetching activemodel 6.0.2.1
Fetching actionview 6.0.2.1
Fetching activejob 6.0.2.1
Fetching sassc 2.4.0
Installing activemodel 6.0.2.1
Installing jbuilder 2.10.0
Installing activejob 6.0.2.1
Installing actionview 6.0.2.1
Installing sassc 2.4.0 with native extensions
Fetching activerecord 6.0.2.1
Installing activerecord 6.0.2.1
Fetching actionpack 6.0.2.1
Installing actionpack 6.0.2.1
Using sprockets-rails 3.2.1
Fetching railties 6.0.2.1
Fetching actionmailer 6.0.2.1
Fetching actioncable 6.0.2.1
Fetching activestorage 6.0.2.1
Installing actionmailer 6.0.2.1
Installing activestorage 6.0.2.1
Installing actioncable 6.0.2.1
Installing railties 6.0.2.1
Fetching actionmailbox 6.0.2.1
Fetching actiontext 6.0.2.1
Installing actiontext 6.0.2.1
Installing actionmailbox 6.0.2.1
Gem::Ext::BuildError: ERROR: Failed to build gem native extension.  ①

    current directory: /Users/higmonta/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/mysql2-0.5.3/ext/mysql2
/Users/higmonta/.rbenv/versions/2.6.5/bin/ruby -I /Users/higmonta/.rbenv/versions/2.6.5/lib/ruby/2.6.0 -r ./siteconf20210908-34706-z00lo0.rb extconf.rb
checking for rb_absint_size()... yes
checking for rb_absint_singlebit_p()... yes
checking for rb_wait_for_single_fd()... yes
-----
Using mysql_config at /usr/local/opt/mysql@5.7/bin/mysql_config
-----
checking for mysql.h... yes
checking for errmsg.h... yes
checking for SSL_MODE_DISABLED in mysql.h... yes
checking for SSL_MODE_PREFERRED in mysql.h... yes
checking for SSL_MODE_REQUIRED in mysql.h... yes
checking for SSL_MODE_VERIFY_CA in mysql.h... yes
checking for SSL_MODE_VERIFY_IDENTITY in mysql.h... yes
checking for MYSQL.net.vio in mysql.h... yes
checking for MYSQL.net.pvio in mysql.h... no
checking for MYSQL_ENABLE_CLEARTEXT_PLUGIN in mysql.h... yes
checking for SERVER_QUERY_NO_GOOD_INDEX_USED in mysql.h... yes
checking for SERVER_QUERY_NO_INDEX_USED in mysql.h... yes
checking for SERVER_QUERY_WAS_SLOW in mysql.h... yes
checking for MYSQL_OPTION_MULTI_STATEMENTS_ON in mysql.h... yes
checking for MYSQL_OPTION_MULTI_STATEMENTS_OFF in mysql.h... yes
checking for my_bool in mysql.h... yes
-----
Don't know how to set rpath on your system, if MySQL libraries are not in path mysql2 may not load
-----
-----
Setting libpath to /usr/local/opt/mysql@5.7/lib
-----
creating Makefile

current directory: /Users/higmonta/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/mysql2-0.5.3/ext/mysql2
make "DESTDIR=" clean

current directory: /Users/higmonta/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/mysql2-0.5.3/ext/mysql2
make "DESTDIR="
compiling client.c
compiling infile.c
compiling mysql2_ext.c
compiling result.c
compiling statement.c
linking shared-object mysql2/mysql2.bundle
ld: library not found for -lssl     ②
clang: error: linker command failed with exit code 1 (use -v to see invocation)    ②
make: *** [mysql2.bundle] Error 1

make failed, exit code 2

Gem files will remain installed in /Users/higmonta/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/mysql2-0.5.3 for inspection.
Results logged to /Users/higmonta/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/extensions/x86_64-darwin-20/2.6.0/mysql2-0.5.3/gem_make.out

An error occurred while installing mysql2 (0.5.3), and Bundler cannot continue.
Make sure that `gem install mysql2 -v '0.5.3' --source 'https://rubygems.org/'` succeeds before bundling.  ③

In Gemfile:
  mysql2

①のエラーについては、下記記事を参考に以下のようにして解消できた(mimemagicのライセンス問題のよう)

【Ruby】bundle installでGem::Ext::BuildError: ERROR: Failed to build gem native extension (mimemagic)エラーが出る - Qiita

$ brew install shared-mime-info

$ bundle install

③の記載通り以下を実行したが、以下のようになり何もならなかった

$ gem install mysql2 -v '0.5.3' -source 'https://rubygems.org/
quote> 

②の部分で何か情報が無いかと思い、以下の記事を参考に下記を実行しました

【Rails】MySQL2がbundle installできない時の対応方法 - Qiita

higmonta@higuchimiyukiyuunoMacBook-Pro sql_active_record_practice % brew info openssl
openssl@1.1: stable 1.1.1l (bottled) [keg-only]
Cryptography and SSL/TLS Toolkit
https://openssl.org/
/usr/local/Cellar/openssl@1.1/1.1.1k (8,071 files, 18.5MB)
  Poured from bottle on 2021-03-30 at 21:47:31
From: https://github.com/Homebrew/homebrew-core/blob/HEAD/Formula/openssl@1.1.rb
License: OpenSSL
==> Caveats
A CA file has been bootstrapped using certificates from the system
keychain. To add additional certificates, place .pem files in
  /usr/local/etc/openssl@1.1/certs

and run
  /usr/local/opt/openssl@1.1/bin/c_rehash

openssl@1.1 is keg-only, which means it was not symlinked into /usr/local,
because macOS provides LibreSSL.

==> Analytics
install: 918,540 (30 days), 2,012,009 (90 days), 9,012,699 (365 days)
install-on-request: 69,086 (30 days), 146,620 (90 days), 1,031,017 (365 days)
build-error: 0 (30 days) ①

①で[build-error]となってしまい、下記記事を参考に[build-error]が何なのか調べたところ、実行ファイルが作成できないとのこと

エラーについて | Programming Place Plus 新C++編

opensslの[build-error]について下記記事を参考に、opensslというものがそもそもインストールされていないのではないかと思い、以下を実行しました
※OpenSSL: インターネット上で標準的に利用される暗号通信プロトコルであるSSLおよびTLSの機能を実装した、オープンソースのライブラリ

MacのhomebrewでOpenSSLがビルドエラーになる場合の対処方法|TechRacho by BPS株式会社

$ brew install openssl

上記の実行がうまくいき、opensslをインストールできました
opensslがインストールできたので、下記記事を参考に以下を実行しました

【Rails】MySQL2がbundle installできない時の対応方法 - Qiita

higmonta@higuchimiyukiyuunoMacBook-Pro sql_active_record_practice % brew info openssl   

openssl@1.1: stable 1.1.1l (bottled) [keg-only]
Cryptography and SSL/TLS Toolkit
https://openssl.org/
/usr/local/Cellar/openssl@1.1/1.1.1l (8,073 files, 18.5MB)
  Poured from bottle on 2021-09-09 at 19:59:37
From: https://github.com/Homebrew/homebrew-core/blob/HEAD/Formula/openssl@1.1.rb
License: OpenSSL
==> Caveats
A CA file has been bootstrapped using certificates from the system
keychain. To add additional certificates, place .pem files in
  /usr/local/etc/openssl@1.1/certs

and run
  /usr/local/opt/openssl@1.1/bin/c_rehash

openssl@1.1 is keg-only, which means it was not symlinked into /usr/local,
because macOS provides LibreSSL.

If you need to have openssl@1.1 first in your PATH, run:
  echo 'export PATH="/usr/local/opt/openssl@1.1/bin:$PATH"' >> ~/.zshrc

For compilers to find openssl@1.1 you may need to set:
  export LDFLAGS="-L/usr/local/opt/openssl@1.1/lib"         ①
  export CPPFLAGS="-I/usr/local/opt/openssl@1.1/include"  ②

For pkg-config to find openssl@1.1 you may need to set:
  export PKG_CONFIG_PATH="/usr/local/opt/openssl@1.1/lib/pkgconfig"

==> Analytics
install: 918,540 (30 days), 2,012,009 (90 days), 9,012,699 (365 days)
install-on-request: 69,086 (30 days), 146,620 (90 days), 1,031,017 (365 days)
build-error: 0 (30 days)

参考記事通りに上記の①、②でパスが出力されました
パスが出力されたので、参考記事通りに以下を実行しました

higmonta@higuchimiyukiyuunoMacBook-Pro sql_active_record_practice % bundle config --local build.mysql2 "--with-cppflags=-I/usr/local/opt/openssl@1.1/include"

higmonta@higuchimiyukiyuunoMacBook-Pro sql_active_record_practice % bundle config --local build.mysql2 "--with-ldflags=-L/usr/local/opt/openssl@1.1/lib"
-L/usr/local/opt/openssl@1.1/lib"
You are replacing the current local value of build.mysql2, which is currently "--with-cppflags=-I/usr/local/opt/openssl@1.1/include"

参考記事通りに実行したので、以下のようにbundle installを実行したところ今度は、うまくいきました
今までやった過程を整理すると、MySQLをインストールするのには、暗号化通信(SSL)を利用するため、OpenSSLをインストールし、MySQLをローカルにインストールする場所が不明だったため、パスを指定したということ?なのかと思いました。

$ bundle install

クローンしたリポジトリのREADME通りに次は、[bundle exec rails db:create]を実行しましたが、またもエラーになってしまいました

higmonta@higuchimiyukiyuunoMacBook-Pro sql_active_record_practice % bundle exec rails db:create
bundle exec rails db:create
Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)    ①
Couldn't create 'sakila_rails_development' database. Please check your configuration.
rails aborted!
Mysql2::Error::ConnectionError: Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)
/Users/higmonta/workspace/runteq/application_tasks/sql_active_record_practice/bin/rails:9:in `<top (required)>'
/Users/higmonta/workspace/runteq/application_tasks/sql_active_record_practice/bin/spring:15:in `require'
/Users/higmonta/workspace/runteq/application_tasks/sql_active_record_practice/bin/spring:15:in `<top (required)>'
bin/rails:3:in `load'
bin/rails:3:in `<main>'
Tasks: TOP => db:create
(See full trace by running task with --trace)

①で、ローカルのMySQLサーバーにソケット'/tmp/mysql.sock'を介して接続できません。となっています
以下の参考記事を参考に権限を変えましたが、ファイルが無いとなってしまいうまくいきませんでした

MySQLが起動しない ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2) - Qiita

higmonta@higuchimiyukiyuunoMacBook-Pro ~ % sudo chown higmonta /tmp/mysql.sock

Password:
chown: /tmp/mysql.sock: No such file or directory

下記コマンドでファイルを調べたところ、確かに[/tmp]フォルダ以下に[mysql.sock]ファイルがありませんでした。

higmonta@higuchimiyukiyuunoMacBook-Pro /tmp % ls

com.apple.launchd.2zs9YAoLX2    tmp8b0ymce2cacert.pem   

下記記事を参考に以下コマンドで[mysql.sock]ファイルを作成しました

mysqlが起動できない(Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)) - Qiita

higmonta@higuchimiyukiyuunoMacBook-Pro /tmp % ls
com.apple.launchd.2zs9YAoLX2    powerlog                        tmp8b0ymce2cacert.pem           tmpzxo91tzpcacert.pem
higmonta@higuchimiyukiyuunoMacBook-Pro /tmp % touch mysql.sock

ローカルPC上でプロセス同士で通信をする際は、UNIXドメインソケット([/tmp/mysql.sock]ファイルのこと)が必要という事が分かり、また、そのソケットはtouchコマンドで自分で空のファイルを作るだけで大丈夫ということが分かりました。
また、MySQLを動かす際には(データベース作成など)MySQLのサーバーを起動しなければいけないということも分かりました。
以下でMySQLのサーバーを起動して、実行したところうまくいきました。

higmonta@higuchimiyukiyuunoMacBook-Pro sql_active_record_practice % mysql.server start
Starting MySQL
.. SUCCESS! 

higmonta@higuchimiyukiyuunoMacBook-Pro sql_active_record_practice % bundle exec rails db:create
Created database 'sakila_rails_development'
Created database 'skila_rals_test'

higmonta@higuchimiyukiyuunoMacBook-Pro sql_active_record_practice % bundle exec rails db < db/seed.sql

ここまでで、MySQLのインストールとMySQLのサーバーを起動できるようになったので、MySQLにログインしてみます。
ここでもハマってしまったので、こちらにまとめます

MySQLへのログイン方法を調べると以下のようになっていました
[mysql -u ユーザー名 -p]を実行するとパスワード入力欄が出てくるので、そこにパスワードを入力
MySQLのアカウントを作成とかしていないしユーザー名ってのは、PCのユーザー名でパスワードもPCのパスワードのこと?と思い以下を実行しました

higmonta@higuchimiyukiyuunoMacBook-Pro sql_active_record_practice % mysql -u higmonta -p
Enter password: 
ERROR 1045 (28000): Access denied for user 'higmonta'@'localhost' (using password: YES)

higmonta@higuchimiyukiyuunoMacBook-Pro sql_active_record_practice % mysql -u higmonta   
ERROR 1045 (28000): Access denied for user 'higmonta'@'localhost' (using password: NO)

上記のようになってしまい、ログインできませんでした

下記の参考記事を参考に、PCにログインしているユーザーアカウントとMySQLのアカウントは別で、MySQLにアカウントを作らなければいけないという事が分かりました。
まずrootユーザーでMySQLにログインして指定したユーザーのアカウントを作ろうと以下を実行しうまくいきました。

よく使うMySQLコマンド&構文集 - Qiita

higmonta@higuchimiyukiyuunoMacBook-Pro sql_active_record_practice % mysql -u root   
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 9
Server version: 5.7.35 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> create user `(ユーザー名)`@`localhost` IDENTIFIED BY '(パスワード)';
Query OK, 0 rows affected (0.01 sec)

mysql> quit
Bye

作成したユーザーでログインして、データベースを作成したらエラーになったが、これは作成したユーザーがデータベース作成の権限がなかったため

higmonta@higuchimiyukiyuunoMacBook-Pro sql_active_record_practice % mysql -u higmonta -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 10
Server version: 5.7.35 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> create database runteq_study;
ERROR 1044 (42000): Access denied for user 'higmonta'@'localhost' to database 'runteq_study'

下記のようにrootユーザーでログインして、データベースを作成したいユーザーにデータベースの全権限を付与した

igmonta@higuchimiyukiyuunoMacBook-Pro sql_active_record_practice % mysql -u root       
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 11
Server version: 5.7.35 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> GRANT ALL ON *.* TO '(ユーザー名)'@'localhost' IDENTIFIED BY '(パスワード)';
Query OK, 0 rows affected, 1 warning (0.00 sec)

MySQLでよく使うコマンド

MySQLのサーバー起動

$ mysql.server restart

MySQLのサーバーの停止

$ mysql.server stop

・ログイン

# -p オプションはパスワード設定しているときのみ付与する

$ mysql -u [ユーザー名] -p
# localhostのMySQLサーバに接続する場合

$ mysql -u [ユーザー名] -p -h [host名] -P [ポート番号]
# 外部MySQLサーバに接続する場合

・ログアウト

mysql > \q
mysql > quit
mysql > exit

・ユーザー情報を取得

mysql > select user, host from mysql.user;

・ユーザーの追加(ログインしているユーザーがユーザーの追加権限を持っていないとできない(最初は、rootユーザーでやる))

mysql > create user `testtest`@`localhost` IDENTIFIED BY 'password';

# ユーザー名: testtest
   パスワード: password
 ホスト名: localhost

・ユーザーへ権限を付与(ログインしているユーザーがユーザーへの権限付与の権限を持っていないとできない(最初は、rootユーザーでやる))(以下は、ALLで全ての権限を付与している例)

mysql > grant all privileges on test_db.* to testtest@localhost IDENTIFIED BY 'password';
# 対象: testtest@localhost
    対象のパスワード: password
    操作できるデータベース名: test_db

・データベース一覧の表示

mysql > show databases;

・データベースの選択

mysql > use test_db;

・データベースの追加

mysql > create database test_db;

・テーブル一覧の表示

mysql > show tables;

SQLコマンドでデータを取得(以下が例)したり、テーブルを作成したり、テーブルにデータを入れたり、データを更新したり、データを削除したりなどできる

mysql> select * from board;
+----+-------+------------------+---------+
| id | title | body             | user_id |
+----+-------+------------------+---------+
|  1 | hoge  | hogehogehogehoge |       1 |
|  2 | fuga  | fugafugafugafuga |       1 |
|  3 | bar   | barbarbarbar     |       2 |
+----+-------+------------------+---------+
3 rows in set (0.00 sec)

※ポイント

MySQLを実際に使用する際の手順は、以下のようになります

  1. MySQLのサーバーを起動
$ mysql.server restart
  1. 対象のユーザーでログイン
# -p オプションはパスワード設定しているときのみ付与する

$ mysql -u [ユーザー名] -p
# localhostのMySQLサーバに接続する場合

$ mysql -u [ユーザー名] -p -h [host名] -P [ポート番号]
# 外部MySQLサーバに接続する場合
  1. データベースの一覧を表示して、使用するデータベースを選択する
mysql > show databases;
# データベースの一覧を表示

mysql > use test_db;
# 使用するデータベースを選択

参考記事

【Rails】MySQL2がbundle installできない時の対応方法 - Qiita

OpenSSLの仕組みとは?初歩から解説! | CodeCampus

MySQL起動エラーの対処の仕方【Can't connect to local MySQL server through socket '/tmp/mysql.sock' (38)】 - Qiita

[2002] MySQLのソケットエラー の原因と対処法 | 株式会社ビヨンド

MySQL|ユーザーアカウントの確認、作成、変更 - わくわくBank

MySQLで新規にデータベースを作成・削除する方法 | サービス | プロエンジニア

MySQLサーバの起動と停止 – OpenGroove

MySQL | ユーザーに設定できる権限の種類と一覧

MySQL | AUTO_INCREMENTを設定する(連続した数値を自動でカラムに格納する)

よく使うMySQLコマンド&構文集 - Qiita

MySQLで新しいユーザーを作成して権限を付与する方法 | DigitalOcean