20201204のMySQLに関する記事は12件です。

MySQL接続エラー <自分メモ>

環境

mac os 11.0.1
appコンテナ php:7.4-apache
dbコンテナ mysql:5.5(MySQLのバージョンはHerokuアドオンのClearDBに合わせている)

エラー内容

Warning: mysqli_connect(): (HY000/2002): php_network_getaddresses:
getaddrinfo failed: Name or service not known in /var/www/html/book_log.php on line 3

ここはホスト名が、localhostだったのでエラーになったみたいです。

参考記事
DockerのLAMP環境でPHPからMySQL接続に詰まった話
Dockerで動かしているMySQLに作成したユーザーでPHPから接続できないときの対処方法

再度エラー

Warning: mysqli_connect(): (HY000/2002): php_network_getaddresses: 
getaddrinfo failed: Name or service not known in /var/www/html/book_log.php on line 3

翻訳
php_network_getaddresses:getaddrinfoが失敗しました:3行目の/var/www/html/book_log.phpで名前またはサービスが不明です

名前とサービス名が間違えているのか!

host名を、mysqlからdbに変更したが、またしてもエラー

Access denied for user 'book_log'@'172.20.0.3' 
(using password: NO) in /var/www/html/book_log.php on line 3

接続の際に,パスワードを入力していなかったので、$passwdの部分を追加!

書式
mysqli_connect($host,$username,$passwd,$dbname,$port,$socket)

今回は、$link = mysqli_connect('サーバー名','ユーザー名','パスワード')の部分まで入力!

これで無事接続できました!

何かお気づきの点がありましたらコメントやアドバイスいただけますとありがたいです!!

参考にさせていだきました。
ありがとうございます!

PHPからMySQLに接続する方法を簡単に解説

DockerでPHPエラー「php_network_getaddresses: getaddrinfo failed: Name or service not known」

  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

EC2上のCakephp4でRDSを使う

前提

EC2(Amazon Linux 2 AMI)にCakePHP4をインストールしてあることを前提としています。
今回、PHPのversionは7.4とします。
基本的に前回の投稿の続きです。

RDSの立ち上げ

RDSの立ち上げは公式サイトにもありますのでここでは省略します。
初心者の方はこちらがおすすめです。

MySQLとPHP拡張モジュールのインストール

MySQLとそれに繋ぐためのPHP拡張モジュールをインストールします。

$ sudo yum install -y mysql
$ sudo yum install -y mysql57-server php74-mysqlnd

以下のコマンドで先ほど立ち上げたRDSに接続できると思います。

$ mysql -h db-resume.crcdiqvbtctf.ap-northeast-1.rds.amazonaws.com -P 3306 -u admin -p
Enter password: (パスワードを入力)
Server version: 8.0.20 Source distribution

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

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

MySQL [(none)]> 

Cakephp接続設定

git管理下にあるconfig/app.phpにデータベースのパスワードやらをのせるのはまずいと思いますので、
接続情報は app.php ではなく、デフォルトでgitignoreされている app_local.php に書いておくのが無難だと思います。

<?php
return [
    // 他の設定
    'Datasources' => [
        'default' => [
            'className' => 'Cake\Database\Connection',
            'driver' => 'Cake\Database\Driver\Mysql',
            'persistent' => false,
            'host' => 'testdb.abcdefghijkl.ap-northeast-1.rds.amazonaws.com',
            'username' => 'cakephp',
            'password' => 'secret',
            'database' => 'testdb',
            'encoding' => 'utf8mb4',
            'timezone' => 'Asia/Tokyo',
            'cacheMetadata' => true,
        ],
    ],
    // 他の設定
];

port番号を設定しなくても自動で探してくれるらしいです。

  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

【AmazonLinux2】Railsアプリケーション新規作成 rake db:createまで

初めに

AmazonLinux2でRailsアプリケーションを新規作成した際に、いろいろとエラーにハマったため、黙示録として書いています。

環境

OS:AmazonLinux2
Ruby:ruby 2.6.3p62 (2019-04-16 revision 67580) [x86_64-linux]
Rails:Rails 5.0.0
DB:Mariadb

手順

前提として今回は、AWS(cloud9)でAmazonLinux2での開発を想定してます。またAWSのenvironmentの作成はできているものとします。

Ruby, Railsのバージョンの確認(AWSでは環境構築がされているため)
$ ruby -v
ruby 2.6.3p62 (2019-04-16 revision 67580) [x86_64-linux]

$ rails -v
Rails 5.0.0
RubyのライブラリであるGemを管理するためのGem(bundler)をinstallする
$ gem install bundler
Fetching bundler-2.1.4.gem
Successfully installed bundler-2.1.4
Parsing documentation for bundler-2.1.4
Installing ri documentation for bundler-2.1.4
Done installing documentation for bundler after 3 seconds
1 gem installed
Marinadbを使用するために必要なパッケージをインストール

DBサーバーインストール

$ sudo yum install mariadb-server
Loaded plugins: extras_suggestions, langpacks, priorities, update-motd
amzn2-core                                                                                                                                                               | 3.7 kB  00:00:00     
220 packages excluded due to repository priority protections
Resolving Dependencies
--> Running transaction check
---> Package mariadb-server.x86_64 3:10.2.10-2.amzn2.0.3 will be installed
--> Processing Dependency: mariadb-tokudb-engine(x86-64) = 3:10.2.10-2.amzn2.0.3 for package: 3:mariadb-server-10.2.10-2.amzn2.0.3.x86_64
--> Processing Dependency: mariadb-server-utils(x86-64) = 3:10.2.10-2.amzn2.0.3 for package: 3:mariadb-server-10.2.10-2.amzn2.0.3.x86_64
--> Processing Dependency: mariadb-rocksdb-engine(x86-64) = 3:10.2.10-2.amzn2.0.3 for package: 3:mariadb-server-10.2.10-2.amzn2.0.3.x86_64
--> Processing Dependency: mariadb-gssapi-server(x86-64) = 3:10.2.10-2.amzn2.0.3 for package: 3:mariadb-server-10.2.10-2.amzn2.0.3.x86_64
--> Processing Dependency: mariadb-errmsg(x86-64) = 3:10.2.10-2.amzn2.0.3 for package: 3:mariadb-server-10.2.10-2.amzn2.0.3.x86_64
--> Processing Dependency: mariadb-cracklib-password-check(x86-64) = 3:10.2.10-2.amzn2.0.3 for package: 3:mariadb-server-10.2.10-2.amzn2.0.3.x86_64
--> Processing Dependency: mariadb-backup(x86-64) = 3:10.2.10-2.amzn2.0.3 for package: 3:mariadb-server-10.2.10-2.amzn2.0.3.x86_64
--> Running transaction check
---> Package mariadb-backup.x86_64 3:10.2.10-2.amzn2.0.3 will be installed
---> Package mariadb-cracklib-password-check.x86_64 3:10.2.10-2.amzn2.0.3 will be installed
---> Package mariadb-errmsg.x86_64 3:10.2.10-2.amzn2.0.3 will be installed
---> Package mariadb-gssapi-server.x86_64 3:10.2.10-2.amzn2.0.3 will be installed
---> Package mariadb-rocksdb-engine.x86_64 3:10.2.10-2.amzn2.0.3 will be installed
---> Package mariadb-server-utils.x86_64 3:10.2.10-2.amzn2.0.3 will be installed
--> Processing Dependency: perl(DBI) for package: 3:mariadb-server-utils-10.2.10-2.amzn2.0.3.x86_64
--> Processing Dependency: perl(DBI) for package: 3:mariadb-server-utils-10.2.10-2.amzn2.0.3.x86_64
--> Processing Dependency: perl(DBD::mysql) for package: 3:mariadb-server-utils-10.2.10-2.amzn2.0.3.x86_64
---> Package mariadb-tokudb-engine.x86_64 3:10.2.10-2.amzn2.0.3 will be installed
--> Processing Dependency: libjemalloc.so.1()(64bit) for package: 3:mariadb-tokudb-engine-10.2.10-2.amzn2.0.3.x86_64
--> Running transaction check
---> Package jemalloc.x86_64 0:3.6.0-1.amzn2.0.1 will be installed
---> Package perl-DBD-MySQL.x86_64 0:4.023-6.amzn2 will be installed
---> Package perl-DBI.x86_64 0:1.627-4.amzn2.0.2 will be installed
--> Processing Dependency: perl(RPC::PlServer) >= 0.2001 for package: perl-DBI-1.627-4.amzn2.0.2.x86_64
--> Processing Dependency: perl(RPC::PlClient) >= 0.2000 for package: perl-DBI-1.627-4.amzn2.0.2.x86_64
--> Running transaction check
---> Package perl-PlRPC.noarch 0:0.2020-14.amzn2 will be installed
--> Processing Dependency: perl(Net::Daemon) >= 0.13 for package: perl-PlRPC-0.2020-14.amzn2.noarch
--> Processing Dependency: perl(Net::Daemon::Test) for package: perl-PlRPC-0.2020-14.amzn2.noarch
--> Processing Dependency: perl(Net::Daemon::Log) for package: perl-PlRPC-0.2020-14.amzn2.noarch
--> Processing Dependency: perl(Compress::Zlib) for package: perl-PlRPC-0.2020-14.amzn2.noarch
--> Running transaction check
---> Package perl-IO-Compress.noarch 0:2.061-2.amzn2 will be installed
--> Processing Dependency: perl(Compress::Raw::Zlib) >= 2.061 for package: perl-IO-Compress-2.061-2.amzn2.noarch
--> Processing Dependency: perl(Compress::Raw::Bzip2) >= 2.061 for package: perl-IO-Compress-2.061-2.amzn2.noarch
---> Package perl-Net-Daemon.noarch 0:0.48-5.amzn2 will be installed
--> Running transaction check
---> Package perl-Compress-Raw-Bzip2.x86_64 0:2.061-3.amzn2.0.2 will be installed
---> Package perl-Compress-Raw-Zlib.x86_64 1:2.061-4.amzn2.0.2 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

================================================================================================================================================================================================
 Package                                               Arch                         Version                                      Repository                                                Size
================================================================================================================================================================================================
Installing:
 mariadb-server                                        x86_64                       3:10.2.10-2.amzn2.0.3                        amzn2extra-lamp-mariadb10.2-php7.2                        17 M
Installing for dependencies:
 jemalloc                                              x86_64                       3.6.0-1.amzn2.0.1                            amzn2extra-lamp-mariadb10.2-php7.2                       109 k
 mariadb-backup                                        x86_64                       3:10.2.10-2.amzn2.0.3                        amzn2extra-lamp-mariadb10.2-php7.2                       5.9 M
 mariadb-cracklib-password-check                       x86_64                       3:10.2.10-2.amzn2.0.3                        amzn2extra-lamp-mariadb10.2-php7.2                        36 k
 mariadb-errmsg                                        x86_64                       3:10.2.10-2.amzn2.0.3                        amzn2extra-lamp-mariadb10.2-php7.2                       221 k
 mariadb-gssapi-server                                 x86_64                       3:10.2.10-2.amzn2.0.3                        amzn2extra-lamp-mariadb10.2-php7.2                        39 k
 mariadb-rocksdb-engine                                x86_64                       3:10.2.10-2.amzn2.0.3                        amzn2extra-lamp-mariadb10.2-php7.2                       4.0 M
 mariadb-server-utils                                  x86_64                       3:10.2.10-2.amzn2.0.3                        amzn2extra-lamp-mariadb10.2-php7.2                       1.6 M
 mariadb-tokudb-engine                                 x86_64                       3:10.2.10-2.amzn2.0.3                        amzn2extra-lamp-mariadb10.2-php7.2                       818 k
 perl-Compress-Raw-Bzip2                               x86_64                       2.061-3.amzn2.0.2                            amzn2-core                                                32 k
 perl-Compress-Raw-Zlib                                x86_64                       1:2.061-4.amzn2.0.2                          amzn2-core                                                58 k
 perl-DBD-MySQL                                        x86_64                       4.023-6.amzn2                                amzn2-core                                               141 k
 perl-DBI                                              x86_64                       1.627-4.amzn2.0.2                            amzn2-core                                               804 k
 perl-IO-Compress                                      noarch                       2.061-2.amzn2                                amzn2-core                                               260 k
 perl-Net-Daemon                                       noarch                       0.48-5.amzn2                                 amzn2-core                                                51 k
 perl-PlRPC                                            noarch                       0.2020-14.amzn2                              amzn2-core                                                36 k

Transaction Summary
================================================================================================================================================================================================
Install  1 Package (+15 Dependent packages)

Total download size: 31 M
Installed size: 136 M
Is this ok [y/d/N]: y
Downloading packages:
(1/16): jemalloc-3.6.0-1.amzn2.0.1.x86_64.rpm                                                                                                                            | 109 kB  00:00:00     
(2/16): mariadb-cracklib-password-check-10.2.10-2.amzn2.0.3.x86_64.rpm                                                                                                   |  36 kB  00:00:00     
(3/16): mariadb-errmsg-10.2.10-2.amzn2.0.3.x86_64.rpm                                                                                                                    | 221 kB  00:00:00     
(4/16): mariadb-backup-10.2.10-2.amzn2.0.3.x86_64.rpm                                                                                                                    | 5.9 MB  00:00:00     
(5/16): mariadb-gssapi-server-10.2.10-2.amzn2.0.3.x86_64.rpm                                                                                                             |  39 kB  00:00:00     
(6/16): mariadb-rocksdb-engine-10.2.10-2.amzn2.0.3.x86_64.rpm                                                                                                            | 4.0 MB  00:00:00     
(7/16): mariadb-server-utils-10.2.10-2.amzn2.0.3.x86_64.rpm                                                                                                              | 1.6 MB  00:00:00     
(8/16): mariadb-tokudb-engine-10.2.10-2.amzn2.0.3.x86_64.rpm                                                                                                             | 818 kB  00:00:00     
(9/16): mariadb-server-10.2.10-2.amzn2.0.3.x86_64.rpm                                                                                                                    |  17 MB  00:00:00     
(10/16): perl-Compress-Raw-Bzip2-2.061-3.amzn2.0.2.x86_64.rpm                                                                                                            |  32 kB  00:00:00     
(11/16): perl-Compress-Raw-Zlib-2.061-4.amzn2.0.2.x86_64.rpm                                                                                                             |  58 kB  00:00:00     
(12/16): perl-DBD-MySQL-4.023-6.amzn2.x86_64.rpm                                                                                                                         | 141 kB  00:00:00     
(13/16): perl-IO-Compress-2.061-2.amzn2.noarch.rpm                                                                                                                       | 260 kB  00:00:00     
(14/16): perl-Net-Daemon-0.48-5.amzn2.noarch.rpm                                                                                                                         |  51 kB  00:00:00     
(15/16): perl-PlRPC-0.2020-14.amzn2.noarch.rpm                                                                                                                           |  36 kB  00:00:00     
(16/16): perl-DBI-1.627-4.amzn2.0.2.x86_64.rpm                                                                                                                           | 804 kB  00:00:00     
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Total                                                                                                                                                            32 MB/s |  31 MB  00:00:00     
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  Installing : 3:mariadb-errmsg-10.2.10-2.amzn2.0.3.x86_64                                                                                                                                 1/16 
  Installing : jemalloc-3.6.0-1.amzn2.0.1.x86_64                                                                                                                                           2/16 
  Installing : perl-Compress-Raw-Bzip2-2.061-3.amzn2.0.2.x86_64                                                                                                                            3/16 
  Installing : perl-Net-Daemon-0.48-5.amzn2.noarch                                                                                                                                         4/16 
  Installing : 1:perl-Compress-Raw-Zlib-2.061-4.amzn2.0.2.x86_64                                                                                                                           5/16 
  Installing : perl-IO-Compress-2.061-2.amzn2.noarch                                                                                                                                       6/16 
  Installing : perl-PlRPC-0.2020-14.amzn2.noarch                                                                                                                                           7/16 
  Installing : perl-DBI-1.627-4.amzn2.0.2.x86_64                                                                                                                                           8/16 
  Installing : perl-DBD-MySQL-4.023-6.amzn2.x86_64                                                                                                                                         9/16 
  Installing : 3:mariadb-tokudb-engine-10.2.10-2.amzn2.0.3.x86_64                                                                                                                         10/16 
  Installing : 3:mariadb-rocksdb-engine-10.2.10-2.amzn2.0.3.x86_64                                                                                                                        11/16 
  Installing : 3:mariadb-backup-10.2.10-2.amzn2.0.3.x86_64                                                                                                                                12/16 
  Installing : 3:mariadb-cracklib-password-check-10.2.10-2.amzn2.0.3.x86_64                                                                                                               13/16 
  Installing : 3:mariadb-gssapi-server-10.2.10-2.amzn2.0.3.x86_64                                                                                                                         14/16 
  Installing : 3:mariadb-server-10.2.10-2.amzn2.0.3.x86_64                                                                                                                                15/16 
  Installing : 3:mariadb-server-utils-10.2.10-2.amzn2.0.3.x86_64                                                                                                                          16/16 
  Verifying  : 1:perl-Compress-Raw-Zlib-2.061-4.amzn2.0.2.x86_64                                                                                                                           1/16 
  Verifying  : 3:mariadb-tokudb-engine-10.2.10-2.amzn2.0.3.x86_64                                                                                                                          2/16 
  Verifying  : perl-Net-Daemon-0.48-5.amzn2.noarch                                                                                                                                         3/16 
  Verifying  : 3:mariadb-rocksdb-engine-10.2.10-2.amzn2.0.3.x86_64                                                                                                                         4/16 
  Verifying  : perl-DBD-MySQL-4.023-6.amzn2.x86_64                                                                                                                                         5/16 
  Verifying  : 3:mariadb-backup-10.2.10-2.amzn2.0.3.x86_64                                                                                                                                 6/16 
  Verifying  : 3:mariadb-server-utils-10.2.10-2.amzn2.0.3.x86_64                                                                                                                           7/16 
  Verifying  : 3:mariadb-cracklib-password-check-10.2.10-2.amzn2.0.3.x86_64                                                                                                                8/16 
  Verifying  : perl-IO-Compress-2.061-2.amzn2.noarch                                                                                                                                       9/16 
  Verifying  : 3:mariadb-gssapi-server-10.2.10-2.amzn2.0.3.x86_64                                                                                                                         10/16 
  Verifying  : perl-Compress-Raw-Bzip2-2.061-3.amzn2.0.2.x86_64                                                                                                                           11/16 
  Verifying  : jemalloc-3.6.0-1.amzn2.0.1.x86_64                                                                                                                                          12/16 
  Verifying  : perl-DBI-1.627-4.amzn2.0.2.x86_64                                                                                                                                          13/16 
  Verifying  : perl-PlRPC-0.2020-14.amzn2.noarch                                                                                                                                          14/16 
  Verifying  : 3:mariadb-errmsg-10.2.10-2.amzn2.0.3.x86_64                                                                                                                                15/16 
  Verifying  : 3:mariadb-server-10.2.10-2.amzn2.0.3.x86_64                                                                                                                                16/16 

Installed:
  mariadb-server.x86_64 3:10.2.10-2.amzn2.0.3                                                                                                                                                   

Dependency Installed:
  jemalloc.x86_64 0:3.6.0-1.amzn2.0.1                        mariadb-backup.x86_64 3:10.2.10-2.amzn2.0.3                 mariadb-cracklib-password-check.x86_64 3:10.2.10-2.amzn2.0.3         
  mariadb-errmsg.x86_64 3:10.2.10-2.amzn2.0.3                mariadb-gssapi-server.x86_64 3:10.2.10-2.amzn2.0.3          mariadb-rocksdb-engine.x86_64 3:10.2.10-2.amzn2.0.3                  
  mariadb-server-utils.x86_64 3:10.2.10-2.amzn2.0.3          mariadb-tokudb-engine.x86_64 3:10.2.10-2.amzn2.0.3          perl-Compress-Raw-Bzip2.x86_64 0:2.061-3.amzn2.0.2                   
  perl-Compress-Raw-Zlib.x86_64 1:2.061-4.amzn2.0.2          perl-DBD-MySQL.x86_64 0:4.023-6.amzn2                       perl-DBI.x86_64 0:1.627-4.amzn2.0.2                                  
  perl-IO-Compress.noarch 0:2.061-2.amzn2                    perl-Net-Daemon.noarch 0:0.48-5.amzn2                       perl-PlRPC.noarch 0:0.2020-14.amzn2                                  

Complete!

DBクライアントインストール

$ sudo yum install mariadb-devel
Loaded plugins: extras_suggestions, langpacks, priorities, update-motd
220 packages excluded due to repository priority protections
Resolving Dependencies
--> Running transaction check
---> Package mariadb-devel.x86_64 3:10.2.10-2.amzn2.0.3 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

================================================================================================================================================================================================
 Package                                 Arch                             Version                                            Repository                                                    Size
================================================================================================================================================================================================
Installing:
 mariadb-devel                           x86_64                           3:10.2.10-2.amzn2.0.3                              amzn2extra-lamp-mariadb10.2-php7.2                           1.0 M

Transaction Summary
================================================================================================================================================================================================
Install  1 Package

Total download size: 1.0 M
Installed size: 4.5 M
Is this ok [y/d/N]: y
Downloading packages:
mariadb-devel-10.2.10-2.amzn2.0.3.x86_64.rpm                                                                                                                             | 1.0 MB  00:00:00     
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  Installing : 3:mariadb-devel-10.2.10-2.amzn2.0.3.x86_64                                                                                                                                   1/1 
  Verifying  : 3:mariadb-devel-10.2.10-2.amzn2.0.3.x86_64                                                                                                                                   1/1 

Installed:
  mariadb-devel.x86_64 3:10.2.10-2.amzn2.0.3                                                                                                                                                    

Complete!
データベースサーバーの起動
$ sudo systemctl start mariadb
サーバーの起動状況を確認
$ sudo systemctl status mariadb
● mariadb.service - MariaDB 10.2 database server
   Loaded: loaded (/usr/lib/systemd/system/mariadb.service; disabled; vendor preset: disabled)
   Active: active (running) since Thu 2020-12-03 15:35:26 UTC; 8s ago
  Process: 860 ExecStartPost=/usr/libexec/mysql-check-upgrade (code=exited, status=0/SUCCESS)
  Process: 638 ExecStartPre=/usr/libexec/mysql-prepare-db-dir %n (code=exited, status=0/SUCCESS)
  Process: 582 ExecStartPre=/usr/libexec/mysql-check-socket (code=exited, status=0/SUCCESS)
 Main PID: 778 (mysqld)
   Status: "Taking your SQL requests now..."
    Tasks: 45
   Memory: 169.8M
   CGroup: /system.slice/mariadb.service
           └─778 /usr/libexec/mysqld --basedir=/usr

Dec 03 15:35:25 ip-172-31-19-99.us-east-2.compute.internal mysql-prepare-db-dir[638]: MySQL manual for more instructions.
Dec 03 15:35:25 ip-172-31-19-99.us-east-2.compute.internal mysql-prepare-db-dir[638]: Please report any problems at http://mariadb.org/jira
Dec 03 15:35:25 ip-172-31-19-99.us-east-2.compute.internal mysql-prepare-db-dir[638]: The latest information about MariaDB is available at http://mariadb.org/.
Dec 03 15:35:25 ip-172-31-19-99.us-east-2.compute.internal mysql-prepare-db-dir[638]: You can find additional information about the MySQL part at:
Dec 03 15:35:25 ip-172-31-19-99.us-east-2.compute.internal mysql-prepare-db-dir[638]: http://dev.mysql.com
Dec 03 15:35:25 ip-172-31-19-99.us-east-2.compute.internal mysql-prepare-db-dir[638]: Consider joining MariaDB's strong and vibrant community:
Dec 03 15:35:25 ip-172-31-19-99.us-east-2.compute.internal mysql-prepare-db-dir[638]: https://mariadb.org/get-involved/
Dec 03 15:35:26 ip-172-31-19-99.us-east-2.compute.internal mysqld[778]: 2020-12-03 15:35:26 140397484732224 [Note] /usr/libexec/mysqld (mysqld 10.2.10-MariaDB) starting as process 778 ...
Dec 03 15:35:26 ip-172-31-19-99.us-east-2.compute.internal mysqld[778]: 2020-12-03 15:35:26 140397484732224 [Warning] Changed limits: max_open_files: 1024  max_connections: 151  ta...ache: 431
Dec 03 15:35:26 ip-172-31-19-99.us-east-2.compute.internal systemd[1]: Started MariaDB 10.2 database server.
Hint: Some lines were ellipsized, use -l to show in full.
OS起動時に自動的に起動するように設定
$ sudo systemctl enable mariadb
Created symlink from /etc/systemd/system/multi-user.target.wants/mariadb.service to /usr/lib/systemd/system/mariadb.service.
アプリケーション新規作成

ここでようやくアプリケーションを新規作成します。今回データベースはmysqlを指定するので、以下コマンドを打ち込みます。例としてアプリケーション名は"shift-management"としています。

$ rails new shift-management -d mysql
      create  
      create  README.md
      create  Rakefile
      create  config.ru
      create  .gitignore
      create  Gemfile
      create  app
      create  app/assets/config/manifest.js
      create  app/assets/javascripts/application.js
      create  app/assets/javascripts/cable.js
      create  app/assets/stylesheets/application.css
      create  app/channels/application_cable/channel.rb
      create  app/channels/application_cable/connection.rb
      create  app/controllers/application_controller.rb
      create  app/helpers/application_helper.rb
      create  app/jobs/application_job.rb
      create  app/mailers/application_mailer.rb
      create  app/models/application_record.rb
      create  app/views/layouts/application.html.erb
      create  app/views/layouts/mailer.html.erb
      create  app/views/layouts/mailer.text.erb
      create  app/assets/images/.keep
      create  app/assets/javascripts/channels
      create  app/assets/javascripts/channels/.keep
      create  app/controllers/concerns/.keep
      create  app/models/concerns/.keep
      create  bin
      create  bin/bundle
      create  bin/rails
      create  bin/rake
      create  bin/setup
      create  bin/update
      create  config
      create  config/routes.rb
      create  config/application.rb
      create  config/environment.rb
      create  config/secrets.yml
      create  config/cable.yml
      create  config/puma.rb
      create  config/spring.rb
      create  config/environments
      create  config/environments/development.rb
      create  config/environments/production.rb
      create  config/environments/test.rb
      create  config/initializers
      create  config/initializers/application_controller_renderer.rb
      create  config/initializers/assets.rb
      create  config/initializers/backtrace_silencers.rb
      create  config/initializers/cookies_serializer.rb
      create  config/initializers/cors.rb
      create  config/initializers/filter_parameter_logging.rb
      create  config/initializers/inflections.rb
      create  config/initializers/mime_types.rb
      create  config/initializers/new_framework_defaults.rb
      create  config/initializers/session_store.rb
      create  config/initializers/wrap_parameters.rb
      create  config/locales
      create  config/locales/en.yml
      create  config/boot.rb
      create  config/database.yml
      create  db
      create  db/seeds.rb
      create  lib
      create  lib/tasks
      create  lib/tasks/.keep
      create  lib/assets
      create  lib/assets/.keep
      create  log
      create  log/.keep
      create  public
      create  public/404.html
      create  public/422.html
      create  public/500.html
      create  public/apple-touch-icon-precomposed.png
      create  public/apple-touch-icon.png
      create  public/favicon.ico
      create  public/robots.txt
      create  test/fixtures
      create  test/fixtures/.keep
      create  test/fixtures/files
      create  test/fixtures/files/.keep
      create  test/controllers
      create  test/controllers/.keep
      create  test/mailers
      create  test/mailers/.keep
      create  test/models
      create  test/models/.keep
      create  test/helpers
      create  test/helpers/.keep
      create  test/integration
      create  test/integration/.keep
      create  test/test_helper.rb
      create  tmp
      create  tmp/.keep
      create  tmp/cache
      create  tmp/cache/assets
      create  vendor/assets/javascripts
      create  vendor/assets/javascripts/.keep
      create  vendor/assets/stylesheets
      create  vendor/assets/stylesheets/.keep
      remove  config/initializers/cors.rb
         run  bundle install
[DEPRECATED] `Bundler.with_clean_env` has been deprecated in favor of `Bundler.with_unbundled_env`. If you instead want the environment before bundler was originally loaded, use `Bundler.with_original_env` (called at /home/ec2-user/.rvm/gems/ruby-2.6.3/gems/railties-5.0.0/lib/rails/generators/app_base.rb:374)
The dependency tzinfo-data (>= 0) will be unused by any of the platforms Bundler is installing for. Bundler is installing for ruby but the dependency is only for x86-mingw32, x86-mswin32, x64-mingw32, java. To add those platforms to the bundle, run `bundle lock --add-platform x86-mingw32 x86-mswin32 x64-mingw32 java`.
Fetching gem metadata from https://rubygems.org/............
Fetching gem metadata from https://rubygems.org/.
Resolving dependencies....
Fetching rake 13.0.1
Installing rake 13.0.1
Using concurrent-ruby 1.1.7
Fetching i18n 1.8.5
Installing i18n 1.8.5
Fetching minitest 5.14.2
Installing minitest 5.14.2
Using thread_safe 0.3.6
Fetching tzinfo 1.2.8
Installing tzinfo 1.2.8
Fetching activesupport 5.0.7.2
Installing activesupport 5.0.7.2
Using builder 3.2.4
Using erubis 2.7.0
Using mini_portile2 2.4.0
Using nokogiri 1.10.10
Using rails-dom-testing 2.0.3
Using crass 1.0.6
Fetching loofah 2.8.0
Installing loofah 2.8.0
Using rails-html-sanitizer 1.3.0
Fetching actionview 5.0.7.2
Installing actionview 5.0.7.2
Using rack 2.2.3
Using rack-test 0.6.3
Fetching actionpack 5.0.7.2
Installing actionpack 5.0.7.2
Fetching nio4r 2.5.4
Installing nio4r 2.5.4 with native extensions
Using websocket-extensions 0.1.5
Using websocket-driver 0.6.5
Fetching actioncable 5.0.7.2
Installing actioncable 5.0.7.2
Using globalid 0.4.2
Fetching activejob 5.0.7.2
Installing activejob 5.0.7.2
Using mini_mime 1.0.2
Using mail 2.7.1
Fetching actionmailer 5.0.7.2
Installing actionmailer 5.0.7.2
Fetching activemodel 5.0.7.2
Installing activemodel 5.0.7.2
Using arel 7.1.4
Fetching activerecord 5.0.7.2
Installing activerecord 5.0.7.2
Fetching bindex 0.8.1
Installing bindex 0.8.1 with native extensions
Using bundler 2.1.4
Fetching byebug 11.1.3
Installing byebug 11.1.3 with native extensions
Fetching coffee-script-source 1.12.2
Installing coffee-script-source 1.12.2
Fetching execjs 2.7.0
Installing execjs 2.7.0
Fetching coffee-script 2.4.1
Installing coffee-script 2.4.1
Using method_source 1.0.0
Using thor 1.0.1
Fetching railties 5.0.7.2
Installing railties 5.0.7.2
Fetching coffee-rails 4.2.2
Installing coffee-rails 4.2.2
Fetching ffi 1.13.1
Installing ffi 1.13.1 with native extensions
Fetching jbuilder 2.10.1
Installing jbuilder 2.10.1
Fetching jquery-rails 4.4.0
Installing jquery-rails 4.4.0
Fetching rb-fsevent 0.10.4
Installing rb-fsevent 0.10.4
Fetching rb-inotify 0.10.1
Installing rb-inotify 0.10.1
Fetching listen 3.0.8
Installing listen 3.0.8
Fetching mysql2 0.4.10
Installing mysql2 0.4.10 with native extensions
Fetching puma 3.12.6
Installing puma 3.12.6 with native extensions
Fetching sprockets 3.7.2
Installing sprockets 3.7.2
Using sprockets-rails 3.2.2
Fetching rails 5.0.7.2
Installing rails 5.0.7.2
Fetching sass-listen 4.0.0
Installing sass-listen 4.0.0
Fetching sass 3.7.4
Installing sass 3.7.4
Fetching tilt 2.0.10
Installing tilt 2.0.10
Fetching sass-rails 5.0.7
Installing sass-rails 5.0.7
Fetching spring 2.1.1
Installing spring 2.1.1
Fetching spring-watcher-listen 2.0.1
Installing spring-watcher-listen 2.0.1
Fetching turbolinks-source 5.2.0
Installing turbolinks-source 5.2.0
Fetching turbolinks 5.2.1
Installing turbolinks 5.2.1
Fetching uglifier 4.2.0
Installing uglifier 4.2.0
Fetching web-console 3.7.0
Installing web-console 3.7.0
Bundle complete! 15 Gemfile dependencies, 62 gems now installed.
Use `bundle info [gemname]` to see where a bundled gem is installed.
Post-install message from i18n:

HEADS UP! i18n 1.1 changed fallbacks to exclude default locale.
But that may break your application.

If you are upgrading your Rails application from an older version of Rails:

Please check your Rails app for 'config.i18n.fallbacks = true'.
If you're using I18n (>= 1.1.0) and Rails (< 5.2.2), this should be
'config.i18n.fallbacks = [I18n.default_locale]'.
If not, fallbacks will be broken in your app by I18n 1.1.x.

If you are starting a NEW Rails application, you can ignore this notice.

For more info see:
https://github.com/svenfuchs/i18n/releases/tag/v1.1.0

Post-install message from sass:

Ruby Sass has reached end-of-life and should no longer be used.

* If you use Sass as a command-line tool, we recommend using Dart Sass, the new
  primary implementation: https://sass-lang.com/install

* If you use Sass as a plug-in for a Ruby web framework, we recommend using the
  sassc gem: https://github.com/sass/sassc-ruby#readme

* For more details, please refer to the Sass blog:
  https://sass-lang.com/blog/posts/7828841

         run  bundle exec spring binstub --all
* bin/rake: Spring inserted
* bin/rails: Spring inserted
データベースの作成
$ rake db:create
The dependency tzinfo-data (>= 0) will be unused by any of the platforms Bundler is installing for. Bundler is installing for ruby but the dependency is only for x86-mingw32, x86-mswin32, x64-mingw32, java. To add those platforms to the bundle, run `bundle lock --add-platform x86-mingw32 x86-mswin32 x64-mingw32 java`.
Created database 'shift-management_development'
Created database 'shift-management_test'

今回はここまで。

よくあるエラー

Railsで新規アプリケーションを作成した際、mysql2のインストール中にエラーが発生した時の解決策

  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

ExcelやcsvでもらったマスタデータをLaravelのseederでデータ登録する

区分値だったりデータベース上で管理するマスタデータをexcelやcsvで共有されることが多いです。

マスタデータなどはLaravelのSeeder機能を使ってレコード追加していきたいので少し工夫してみたという記録です

例えば都道府県の登録
以下のようなcsvがあるとします。
これをいちいち登録するのはうんざりする作業なのでcsvからLaravelのSeederを使って登録したいです

todofuken.csv

1,北海道
2,青森県
3,岩手県
4,宮城県
5,秋田県
6,山形県
7,福島県
8,茨城県
9,栃木県
10,群馬県
11,埼玉県
12,千葉県
13,東京都
14,神奈川県
15,新潟県
16,富山県
17,石川県
18,福井県
19,山梨県
20,長野県
21,岐阜県
22,静岡県
23,愛知県
24,三重県
25,滋賀県
26,京都府
27,大阪府
28,兵庫県
29,奈良県
30,和歌山県
31,鳥取県
32,島根県
33,岡山県
34,広島県
35,山口県
36,徳島県
37,香川県
38,愛媛県
39,高知県
40,福岡県
41,佐賀県
42,長崎県
43,熊本県
44,大分県
45,宮崎県
46,鹿児島県
47,沖縄県

単純な話でただcsvを一行ずつ読んで
insertしていくスクリプトを書くだけです。

<?php

use Illuminate\Database\Seeder;

class Area1TableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        if (($handle = fopen(__DIR__ . './todofuken.csv', 'r')) !== false) {
            while (($data = fgetcsv($handle))) {
                DB::table('m_todofuken')->insert([
                    'id'   => $data[0],
                    'name' => $data[1],
                ]);
            }
            fclose($handle);
        }
    }
}

csvファイルもリポジトリで管理しておけばマスタデータが変わったよなんて言うときにも
csvを編集してseedを実行してあげればいいので楽ちんですね

終わり

  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

MYSQLWorkbenchからawsのRDSに作ったDBインスタンスに接続できなくなった問題と解決法

・事象
image.png

・解決法
別のwifiに接続を切り替える。おそらくパブリックIPアドレスが変わってしまうのでDBインスタンス作成の際のwifiに合わせないといけない?

  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Laravel ログインテスト

Laravel Unitテスト

 ポートフォリオを作成して、ユニットテストを実行するまでの一連の流れを備忘録として記述します。
 作成したポートフォリオでは初期画面からホーム画面に遷移するのにログインする必要があるシステムでした。コントローラーのテストで下記のように実行してもエラーが表示された為、ログインテストを別で作成してモデルのテストを実行しました。

pubulic function testBasicTest() {
    $this->get('/home')->assertStatusOk();
    /// /homeにはログインが必要な為アクセスできない
}

1.テスト用のDatabaseの準備

今回はMySQLを使用しました。使用するデータベースに応じてテスト用のデータベースを準備。

$ mysql -uroot -p
$ ?(password入力)
mysql> create database データベース名
mysql> show databases
    今回作成したデータベースがあるか確認
mysql> exit

Config/database.phpの'connections'にテスト用のデータベースの設定を追加。

'testing' => [
            'driver' => 'mysql',
            'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => "作成したデータベース名",
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'prefix_indexes' => true,
            'strict' => true,
            'engine' => null,
            'options' => extension_loaded('pdo_mysql') ? array_filter([
                PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
            ]) : [],
        ],

phpunit.xmlのタグ内に下記を追加。

    <server name="DB_CONNECTION" value="mysql"/>
    <server name="DB_DATABASE" value="[データベース名]"/>

2.ファクトリーを準備する

 今回作ったポートフォリオはLaravelに標準で準備されているUserテーブルを使用した為、変更しませんが追加などしている場合は変更する。(database/factories/UserFactory.php)

3.テスト用ファイルの作成

下記コマンドを実行するとtests/Featureにテスト用ファイルが作成されます。

$ php artisan make:test LoginTest

作成されたLoginTest.phpを下記に変更

<?php

namespace Tests\Feature;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Tests\TestCase;
use App\User;
use Auth;

class LoginTest extends TestCase
{
    /**
     * A basic feature test example.
     *
     * @return void
     */
    public function testExample()
    {
        $user = factory(User::class)->create([
            'password'  => bcrypt('laraveltest123')
            //パスワードは好きな言葉で大丈夫です
        ]);

        // 認証されないことを確認
        $this->assertFalse(Auth::check());

        // ログインを実行
        $response = $this->post('login', [
            'email'    => $user->email,
            'password' => 'laraveltest123'
            //先ほど設定したパスワードを入力
        ]);

        // 認証されていることを確認
        $this->assertTrue(Auth::check());

        // ログイン後にホームページにリダイレクトされるのを確認
        $response->assertRedirect('home');
     //作成したサイトでログイン後にリダイレクトされるルート情報を記述
    }
}

4.マイグレーションの実行

 下記コマンドを実行するとテスト用のデータベースにテーブルが作成されます。
--database==testingを忘れないでください。この記述によりdatabase.phpに用意したtesing設定で実行されます。

$ php artisan migrate:refresh --database==testing

5.テストの実行

$ vendor/bin/phpunit

以上でテスト完了です!
作成したデータベースのUserテーブルには新規レコードが登録されていて正しくログイン出来ています。

  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

mysql 起動しているサービスを探すコマンド

netstat -ano | find ":3306"

  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Railsで新規アプリケーションを作成した際、mysql2のインストール中にエラーが発生した時の解決策

環境

OS:AmazonLinux2
Ryby:ruby 2.6.3p62 (2019-04-16 revision 67580) [x86_64-linux]
Rails:Rails 5.0.0

問題

データベースをmysqlに指定してRailsアプリケーションを新規作成した際、mysql2のGemのインストール中にエラーが発生した。

結論

DBクライアントというパッケージをインストールしていなかったことが原因だった。

やったこと

以下コマンドで、データベースをmysqlに指定して、新規アプリケーションを作成
$ rails new (アプリケーション名) -d mysql

$ rails new shift-management -d mysql
      create  
      create  README.md
      create  Rakefile
      create  config.ru
      create  .gitignore
      create  Gemfile
      create  app
      create  app/assets/config/manifest.js
      create  app/assets/javascripts/application.js
      create  app/assets/javascripts/cable.js
      create  app/assets/stylesheets/application.css
      create  app/channels/application_cable/channel.rb
      create  app/channels/application_cable/connection.rb
      create  app/controllers/application_controller.rb
      create  app/helpers/application_helper.rb
      create  app/jobs/application_job.rb
      create  app/mailers/application_mailer.rb
      create  app/models/application_record.rb
      create  app/views/layouts/application.html.erb
      create  app/views/layouts/mailer.html.erb
      create  app/views/layouts/mailer.text.erb
      create  app/assets/images/.keep
      create  app/assets/javascripts/channels
      create  app/assets/javascripts/channels/.keep
      create  app/controllers/concerns/.keep
      create  app/models/concerns/.keep
      create  bin
      create  bin/bundle
      create  bin/rails
      create  bin/rake
      create  bin/setup
      create  bin/update
      create  config
      create  config/routes.rb
      create  config/application.rb
      create  config/environment.rb
      create  config/secrets.yml
      create  config/cable.yml
      create  config/puma.rb
      create  config/spring.rb
      create  config/environments
      create  config/environments/development.rb
      create  config/environments/production.rb
      create  config/environments/test.rb
      create  config/initializers
      create  config/initializers/application_controller_renderer.rb
      create  config/initializers/assets.rb
      create  config/initializers/backtrace_silencers.rb
      create  config/initializers/cookies_serializer.rb
      create  config/initializers/cors.rb
      create  config/initializers/filter_parameter_logging.rb
      create  config/initializers/inflections.rb
      create  config/initializers/mime_types.rb
      create  config/initializers/new_framework_defaults.rb
      create  config/initializers/session_store.rb
      create  config/initializers/wrap_parameters.rb
      create  config/locales
      create  config/locales/en.yml
      create  config/boot.rb
      create  config/database.yml
      create  db
      create  db/seeds.rb
      create  lib
      create  lib/tasks
      create  lib/tasks/.keep
      create  lib/assets
      create  lib/assets/.keep
      create  log
      create  log/.keep
      create  public
      create  public/404.html
      create  public/422.html
      create  public/500.html
      create  public/apple-touch-icon-precomposed.png
      create  public/apple-touch-icon.png
      create  public/favicon.ico
      create  public/robots.txt
      create  test/fixtures
      create  test/fixtures/.keep
      create  test/fixtures/files
      create  test/fixtures/files/.keep
      create  test/controllers
      create  test/controllers/.keep
      create  test/mailers
      create  test/mailers/.keep
      create  test/models
      create  test/models/.keep
      create  test/helpers
      create  test/helpers/.keep
      create  test/integration
      create  test/integration/.keep
      create  test/test_helper.rb
      create  tmp
      create  tmp/.keep
      create  tmp/cache
      create  tmp/cache/assets
      create  vendor/assets/javascripts
      create  vendor/assets/javascripts/.keep
      create  vendor/assets/stylesheets
      create  vendor/assets/stylesheets/.keep
      remove  config/initializers/cors.rb
         run  bundle install
The dependency tzinfo-data (>= 0) will be unused by any of the platforms Bundler is installing for. Bundler is installing for ruby but the dependency is only for x86-mingw32, x86-mswin32, x64-mingw32, java. To add those platforms to the bundle, run `bundle lock --add-platform x86-mingw32 x86-mswin32 x64-mingw32 java`.
Fetching gem metadata from https://rubygems.org/............
Fetching gem metadata from https://rubygems.org/.
Resolving dependencies....
Fetching rake 13.0.1
Installing rake 13.0.1
Using concurrent-ruby 1.1.7
Fetching i18n 1.8.5
Installing i18n 1.8.5
Fetching minitest 5.14.2
Installing minitest 5.14.2
Using thread_safe 0.3.6
Fetching tzinfo 1.2.8
Installing tzinfo 1.2.8
Fetching activesupport 5.0.7.2
Installing activesupport 5.0.7.2
Using builder 3.2.4
Using erubis 2.7.0
Using mini_portile2 2.4.0
Using nokogiri 1.10.10
Using rails-dom-testing 2.0.3
Using crass 1.0.6
Fetching loofah 2.8.0
Installing loofah 2.8.0
Using rails-html-sanitizer 1.3.0
Fetching actionview 5.0.7.2
Installing actionview 5.0.7.2
Using rack 2.2.3
Using rack-test 0.6.3
Fetching actionpack 5.0.7.2
Installing actionpack 5.0.7.2
Fetching nio4r 2.5.4
Installing nio4r 2.5.4 with native extensions
Using websocket-extensions 0.1.5
Using websocket-driver 0.6.5
Fetching actioncable 5.0.7.2
Installing actioncable 5.0.7.2
Using globalid 0.4.2
Fetching activejob 5.0.7.2
Installing activejob 5.0.7.2
Using mini_mime 1.0.2
Using mail 2.7.1
Fetching actionmailer 5.0.7.2
Installing actionmailer 5.0.7.2
Fetching activemodel 5.0.7.2
Installing activemodel 5.0.7.2
Using arel 7.1.4
Fetching activerecord 5.0.7.2
Installing activerecord 5.0.7.2
Fetching bindex 0.8.1
Installing bindex 0.8.1 with native extensions
Using bundler 1.17.3
Fetching byebug 11.1.3
Installing byebug 11.1.3 with native extensions
Fetching coffee-script-source 1.12.2
Installing coffee-script-source 1.12.2
Fetching execjs 2.7.0
Installing execjs 2.7.0
Fetching coffee-script 2.4.1
Installing coffee-script 2.4.1
Using method_source 1.0.0
Using thor 1.0.1
Fetching railties 5.0.7.2
Installing railties 5.0.7.2
Fetching coffee-rails 4.2.2
Installing coffee-rails 4.2.2
Fetching ffi 1.13.1
Installing ffi 1.13.1 with native extensions
Fetching jbuilder 2.10.1
Installing jbuilder 2.10.1
Fetching jquery-rails 4.4.0
Installing jquery-rails 4.4.0
Fetching rb-fsevent 0.10.4
Installing rb-fsevent 0.10.4
Fetching rb-inotify 0.10.1
Installing rb-inotify 0.10.1
Fetching listen 3.0.8
Installing listen 3.0.8
Fetching mysql2 0.4.10
Installing mysql2 0.4.10 with native extensions
Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

    current directory: /home/ec2-user/.rvm/gems/ruby-2.6.3/gems/mysql2-0.4.10/ext/mysql2
/home/ec2-user/.rvm/rubies/ruby-2.6.3/bin/ruby -I /home/ec2-user/.rvm/rubies/ruby-2.6.3/lib/ruby/site_ruby/2.6.0 -r ./siteconf20201203-7896-3nmivb.rb extconf.rb
checking for rb_absint_size()... yes
checking for rb_absint_singlebit_p()... yes
checking for ruby/thread.h... yes
checking for rb_thread_call_without_gvl() in ruby/thread.h... yes
checking for rb_thread_blocking_region()... no
checking for rb_wait_for_single_fd()... yes
checking for rb_hash_dup()... yes
checking for rb_intern3()... yes
checking for rb_big_cmp()... yes
checking for mysql_query() in -lmysqlclient... yes
checking for mysql.h... no
checking for mysql/mysql.h... no
-----
mysql.h is missing. You may need to 'apt-get install libmysqlclient-dev' or 'yum install mysql-devel', and try again.
-----
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers.  Check the mkmf.log file for more details.  You may
need configuration options.

Provided configuration options:
        --with-opt-dir
        --without-opt-dir
        --with-opt-include
        --without-opt-include=${opt-dir}/include
        --with-opt-lib
        --without-opt-lib=${opt-dir}/lib
        --with-make-prog
        --without-make-prog
        --srcdir=.
        --curdir
        --ruby=/home/ec2-user/.rvm/rubies/ruby-2.6.3/bin/$(RUBY_BASE_NAME)
        --with-mysql-dir
        --without-mysql-dir
        --with-mysql-include
        --without-mysql-include=${mysql-dir}/include
        --with-mysql-lib
        --without-mysql-lib=${mysql-dir}/lib
        --with-mysql-config
        --without-mysql-config
        --with-mysql-dir
        --without-mysql-dir
        --with-mysql-include
        --without-mysql-include=${mysql-dir}/include
        --with-mysql-lib
        --without-mysql-lib=${mysql-dir}/lib
        --with-mysqlclientlib
        --without-mysqlclientlib

To see why this extension failed to compile, please check the mkmf.log which can be found here:

  /home/ec2-user/.rvm/gems/ruby-2.6.3/extensions/x86_64-linux/2.6.0/mysql2-0.4.10/mkmf.log

extconf failed, exit code 1

Gem files will remain installed in /home/ec2-user/.rvm/gems/ruby-2.6.3/gems/mysql2-0.4.10 for inspection.
Results logged to /home/ec2-user/.rvm/gems/ruby-2.6.3/extensions/x86_64-linux/2.6.0/mysql2-0.4.10/gem_make.out

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

In Gemfile:
  mysql2
         run  bundle exec spring binstub --all
bundler: command not found: spring
Install missing gem executables with `bundle install`

mysql2がインストールできないと言われる

原因

どうやらDBクライアントをインストールしていないことが原因だった
参考:AmazonLinux2にMariaDBをインストールする

解決策

DBクライアントをインストール(パッケージインストール)

$ sudo yum install mariadb-devel
Loaded plugins: extras_suggestions, langpacks, priorities, update-motd
220 packages excluded due to repository priority protections
Resolving Dependencies
--> Running transaction check
---> Package mariadb-devel.x86_64 3:10.2.10-2.amzn2.0.3 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

================================================================================================================================================================================================
 Package                                 Arch                             Version                                            Repository                                                    Size
================================================================================================================================================================================================
Installing:
 mariadb-devel                           x86_64                           3:10.2.10-2.amzn2.0.3                              amzn2extra-lamp-mariadb10.2-php7.2                           1.0 M

Transaction Summary
================================================================================================================================================================================================
Install  1 Package

Total download size: 1.0 M
Installed size: 4.5 M
Is this ok [y/d/N]: y
Downloading packages:
mariadb-devel-10.2.10-2.amzn2.0.3.x86_64.rpm                                                                                                                             | 1.0 MB  00:00:00     
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  Installing : 3:mariadb-devel-10.2.10-2.amzn2.0.3.x86_64                                                                                                                                   1/1 
  Verifying  : 3:mariadb-devel-10.2.10-2.amzn2.0.3.x86_64                                                                                                                                   1/1 

Installed:
  mariadb-devel.x86_64 3:10.2.10-2.amzn2.0.3                                                                                                                                                    

Complete!

インストール完了(mysql-develでも同じみたい)

もう一度bundle installすると

$ bundle install 
The dependency tzinfo-data (>= 0) will be unused by any of the platforms Bundler is installing for. Bundler is installing for ruby but the dependency is only for x86-mingw32, x86-mswin32, x64-mingw32, java. To add those platforms to the bundle, run `bundle lock --add-platform x86-mingw32 x86-mswin32 x64-mingw32 java`.
Fetching gem metadata from https://rubygems.org/............
Fetching gem metadata from https://rubygems.org/.
Resolving dependencies....
Using rake 13.0.1
Using concurrent-ruby 1.1.7
Using i18n 1.8.5
Using minitest 5.14.2
Using thread_safe 0.3.6
Using tzinfo 1.2.8
Using activesupport 5.0.7.2
Using builder 3.2.4
Using erubis 2.7.0
Using mini_portile2 2.4.0
Using nokogiri 1.10.10
Using rails-dom-testing 2.0.3
Using crass 1.0.6
Using loofah 2.8.0
Using rails-html-sanitizer 1.3.0
Using actionview 5.0.7.2
Using rack 2.2.3
Using rack-test 0.6.3
Using actionpack 5.0.7.2
Using nio4r 2.5.4
Using websocket-extensions 0.1.5
Using websocket-driver 0.6.5
Using actioncable 5.0.7.2
Using globalid 0.4.2
Using activejob 5.0.7.2
Using mini_mime 1.0.2
Using mail 2.7.1
Using actionmailer 5.0.7.2
Using activemodel 5.0.7.2
Using arel 7.1.4
Using activerecord 5.0.7.2
Using bindex 0.8.1
Using bundler 1.17.3
Using byebug 11.1.3
Using coffee-script-source 1.12.2
Using execjs 2.7.0
Using coffee-script 2.4.1
Using method_source 1.0.0
Using thor 1.0.1
Using railties 5.0.7.2
Using coffee-rails 4.2.2
Using ffi 1.13.1
Using jbuilder 2.10.1
Using jquery-rails 4.4.0
Using rb-fsevent 0.10.4
Using rb-inotify 0.10.1
Using listen 3.0.8
Fetching mysql2 0.4.10
Installing mysql2 0.4.10 with native extensions
Fetching puma 3.12.6
Installing puma 3.12.6 with native extensions
Fetching sprockets 3.7.2
Installing sprockets 3.7.2
Using sprockets-rails 3.2.2
Fetching rails 5.0.7.2
Installing rails 5.0.7.2
Fetching sass-listen 4.0.0
Installing sass-listen 4.0.0
Fetching sass 3.7.4
Installing sass 3.7.4
Fetching tilt 2.0.10
Installing tilt 2.0.10
Fetching sass-rails 5.0.7
Installing sass-rails 5.0.7
Fetching spring 2.1.1
Installing spring 2.1.1
Fetching spring-watcher-listen 2.0.1
Installing spring-watcher-listen 2.0.1
Fetching turbolinks-source 5.2.0
Installing turbolinks-source 5.2.0
Fetching turbolinks 5.2.1
Installing turbolinks 5.2.1
Fetching uglifier 4.2.0
Installing uglifier 4.2.0
Fetching web-console 3.7.0
Installing web-console 3.7.0
Bundle complete! 15 Gemfile dependencies, 62 gems now installed.
Use `bundle info [gemname]` to see where a bundled gem is installed.
Post-install message from sass:

Ruby Sass has reached end-of-life and should no longer be used.

* If you use Sass as a command-line tool, we recommend using Dart Sass, the new
  primary implementation: https://sass-lang.com/install

* If you use Sass as a plug-in for a Ruby web framework, we recommend using the
  sassc gem: https://github.com/sass/sassc-ruby#readme

* For more details, please refer to the Sass blog:
  https://sass-lang.com/blog/posts/7828841

無事mysql2がインストールされました。
以下に、Railsアプリケーションの作成時の手順を書いているので参考にしてみてください

【AmazonLinux2】Railsアプリケーション新規作成 rake db:createまで

  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

MySQLでFNVハッシュ関数を組み込んで使う

はじめに

DBに変更を加え、それを別DBに移行するような場合、簡単な方法としてはdumpして流し込むことで反映されられます。
ただし、元々のデータ量が多くて差分が少ない場合には、全て入れ直そうとすると時間がかかるので、差分のあるテーブルやデータに対してのみ変更をかけると良さそうです。

差分のあるデータの特定にあたって、軽量なハッシュ関数が使えるとより処理が早くなると思われる箇所があったので、この記事では標準関数にないFNVのハッシュ関数をUDF(ユーザー定義関数)として組み込んで使えるようにしてみます。

差分のある箇所の特定

テーブル単位でのハッシュは以下のようにして取れるので、DB間でハッシュ値が違うテーブルのみをdumpの対象にすれば処理が少なくて済みます。

CHECKSUM TABLE table_1, table_2, ... , table_n;

行単位でのハッシュは例えば以下のようにして取れるので、DB間でidなどのプライマリキーに対してハッシュ値が違う行のみを変更対象にすれば処理が少なくて済みます。
特に、行単位でのデータ量が大きい場合には、元のデータを全件そのまま取得して比較するよりもDBとの通信にかかるリソースが少なくて済みます。

SELECT id, MD5(CONCAT_WS(",", col1, col2, ... , coln)) hash FROM table_name;

改善ポイント

この行単位のハッシュ化の方法について、

  • md5より軽量なハッシュ関数が使えないか
  • わざわざ文字列結合せずに直接引数として渡せないか

という点が気になりました。

前者に関しては、より出力される桁数が少ない・処理が少ないアルゴリズムに置き換えられるならそちらを使った方が効率が良さそうです。
後者に関しては、一度全てを連結した文字列を作ってからmd5関数に渡しているので、この文字列連結の手順がなければより効率的に処理できそうです。

ただし、標準で実装されている関数にはmd5より軽量そうなハッシュ関数や可変長の引数をまとめて受け取ってくれる関数が実装されていないようすなので、今回はFNVというハッシュ関数をMySQLのUDF(ユーザー定義関数)として追加してどのくらい効果があるか見てみます。

FNVを選んだ理由は、phpでの速度比較記事で速度面で優位そうだったのと、擬似コードがやたら短くてよさそうという雑な理由です。

FNV関数の導入

MySQLでのFNVの実装について調べると以下のような内容が見つかりました。

特に2つ目の内容に関しては、引数を複数扱えるように実装しているようで自分が出した2つの要件を両方とも満たせるため、今回は2つ目の内容をやってみることにしました。

UDFの追加でやることはざっくり

の3ステップです。

今回は上記記事の内容にある通り、Maatkitというツール内で実装されているものを利用しました。
以下はMacでの手順です。brewでインストールしたMySQLに組み込んでいるので、各自のマシンに合わせてバージョンやパスを適宜置き換えてください。

# DL&解凍
curl -0 https://storage.googleapis.com/google-code-archive-downloads/v2/code.google.com/maatkit/maatkit-7540.tar.gz > maatkit-7540.tar.gz
tar -zxvf maatkit-7540.tar.gz
cp maatkit-7540/udf/fnv_udf.cc ./
# コンパイル&配置
gcc -fPIC -Wall -I/usr/local/Cellar/mysql@5.6/5.6.43/include/mysql -dynamiclib -o fnv_udf.so fnv_udf.cc -lstdc++
cp fnv_udf.so /usr/local/Cellar/mysql@5.6/5.6.43/lib/plugin/
# 関数の読み込み
mysql mysql -e "CREATE FUNCTION fnv_64 RETURNS INTEGER SONAME 'fnv_udf.so'"

MacとLinuxでビルドオプションが違うので、例えばMySQLの公式dockerイメージ内でビルドする場合は以下のようにします。

gcc -fPIC -Wall -I/usr/include/mysql -shared -o fnv_udf.so fnv_udf.cc
cp fnv_udc.so /usr/lib/mysql/plugin/

MySQLでの読み込みが完了すると、 FNV_64 関数が使用可能になります。

mysql> select fnv_64();
ERROR 1123 (HY000): Can't initialize function 'fnv_64'; FNV_64 requires at least one argument
mysql> select fnv_64(1);
+----------------------+
| fnv_64(1)            |
+----------------------+
| -6320923009900088257 |
+----------------------+
1 row in set (0.01 sec)

mysql> select fnv_64(null);
+----------------------+
| fnv_64(null)         |
+----------------------+
| -5259373969131113000 |
+----------------------+
1 row in set (0.00 sec)

mysql> select fnv_64("hoge", "fuga");
+------------------------+
| fnv_64("hoge", "fuga") |
+------------------------+
|     540658518371715184 |
+------------------------+
1 row in set (0.01 sec)

今回使わせてもらった実装の特徴として、複数引数が扱えることだけでなく、 NULL 値も扱えるようになっています。
記事冒頭に書いたような CONCAT_WS 関数を使用した場合、NULLが無視される挙動になるため、場合によっては空文字と被らない別の文字として扱うように回避する必要があります。このUDFではNULLの代わりとして 0x0a0b0c0d という値が指定されています。

#define HASH_NULL_DEFAULT 0x0a0b0c0d

ちなみに、引数を何も指定しなかった場合に表示されている FNV_64 requires at least one argument という文字列も、UDFを作る上での必須実装関数の fnv_64_init にて指定されている文字列です。組み込んだものがちゃんと実装通りになっている実感があっていいですね。

my_bool
fnv_64_init( UDF_INIT* initid, UDF_ARGS* args, char* message ) {
   if (args->arg_count == 0 ) {
      strcpy(message,"FNV_64 requires at least one argument");
      return 1;
   }
   initid->maybe_null = 0;      /* The result will never be NULL */
   return 0;
}

速度比較

MySQLのサンプルデータの sakila (レンタルビデオ店風のデータ)から良さげなテーブルを使って、よさげな件数の実験用テーブルを作って実験してみました。 film_text というテーブルが多少バラツキのある文字数が入っていて1000レコードあったので、このテーブル自身を CROSS JOIN して 1,000,000 レコードのテーブルを用意しました。

mysql> select table_name, table_rows, avg_row_length from information_schema.tables where table_schema = "sakila" and table_type = 'BASE TABLE';
+---------------+------------+----------------+
| table_name    | table_rows | avg_row_length |
+---------------+------------+----------------+
| actor         |        200 |             81 |
| address       |        603 |            163 |
| category      |         16 |           1024 |
| city          |        600 |             81 |
| country       |        109 |            150 |
| customer      |        599 |            136 |
| film          |       1000 |            196 |
| film_actor    |       5462 |             35 |
| film_category |       1000 |             65 |
| film_text     |       1000 |            180 |
| inventory     |       4581 |             39 |
| language      |          6 |           2730 |
| payment       |      16086 |             98 |
| rental        |      16005 |             99 |
| staff         |          2 |          32768 |
| store         |          2 |           8192 |
+---------------+------------+----------------+

mysql> select * from film_text limit 5;
+---------+------------------+-----------------------------------------------------------------------------------------------------------------------+
| film_id | title            | description                                                                                                           |
+---------+------------------+-----------------------------------------------------------------------------------------------------------------------+
|       1 | ACADEMY DINOSAUR | A Epic Drama of a Feminist And a Mad Scientist who must Battle a Teacher in The Canadian Rockies                      |
|       2 | ACE GOLDFINGER   | A Astounding Epistle of a Database Administrator And a Explorer who must Find a Car in Ancient China                  |
|       3 | ADAPTATION HOLES | A Astounding Reflection of a Lumberjack And a Car who must Sink a Lumberjack in A Baloon Factory                      |
|       4 | AFFAIR PREJUDICE | A Fanciful Documentary of a Frisbee And a Lumberjack who must Chase a Monkey in A Shark Tank                          |
|       5 | AFRICAN EGG      | A Fast-Paced Documentary of a Pastry Chef And a Dentist who must Pursue a Forensic Psychologist in The Gulf of Mexico |
+---------+------------------+-----------------------------------------------------------------------------------------------------------------------+
5 rows in set (0.01 sec)

mysql> show create table film_text;
+-----------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table     | Create Table                                                                                                                                                                                                                                          |
+-----------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| film_text | CREATE TABLE `film_text` (
  `film_id` smallint(6) NOT NULL,
  `title` varchar(255) NOT NULL,
  `description` text,
  PRIMARY KEY (`film_id`),
  FULLTEXT KEY `idx_title_description` (`title`,`description`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 |
+-----------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

mysql> CREATE TABLE `film_text_cross` (
    ->   `film_id1` smallint(6) NOT NULL,
    ->   `title1` varchar(255) NOT NULL,
    ->   `description1` text,
    ->   `film_id2` smallint(6) NOT NULL,
    ->   `title2` varchar(255) NOT NULL,
    ->   `description2` text,
    ->   PRIMARY KEY (`film_id1`,`film_id2`)
    -> ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
    -> ;
Query OK, 0 rows affected (0.09 sec)

mysql> insert into film_text_cross (select t1.film_id film_id1, t1.title title1, t1.description description1, t2.film_id film_id2, t2.title title2, t2.description description2 from film_text t1 cross join film_text t2);
Query OK, 1000000 rows affected (42.75 sec)
Records: 1000000  Duplicates: 0  Warnings: 0

それなりのデータが準備できたので、以下の3種類のクエリを投げてみます。

# md5 + concat_ws
select film_id1, film_id2, md5(concat_ws(",", film_id1, title1, description1, film_id2, title2, description2)) hash from film_text_cross;
# fnv_64 + concat_ws
select film_id1, film_id2, fnv_64(concat_ws(",", film_id1, title1, description1, film_id2, title2, description2)) from film_text_cross;
# fnv_64
select film_id1, film_id2, fnv_64(film_id1, title1, description1, film_id2, title2, description2) hash from film_text_cross;

結果はこのようになりました。

クエリ 実行時間
md5 + concat_ws 1.64 sec
fnv_64 + concat_ws 1.97 sec
fnv_64 1.85 sec

予想に反してUDF使った方が若干遅くなってしまいました...。

拡張の関数の呼び出しが遅いのか、最適化不足なのかもしれないと思い、
とりあえす最適化オプション -O2 をつけてコンパイルし直してもう一度やってみました。

クエリ 実行時間
md5 + concat_ws 1.62 sec
fnv_64 + concat_ws 1.44 sec
fnv_64 1.32 sec

期待していた通りに、UDFをうまく使った方がより実行時間が短くなるようになりました。
最適化については、md5のようなアルゴリズムは同じビット演算を数十回繰り返し行ったりしている箇所もあったりするんですが、
いつしかマイニングツールのハッシュ値計算の処理を覗いた時に #pragma unroll みたいな記述を見たことがあり、最適化をかけられるポイントがあるみたいです。
FNVみたいに処理自体が少ないものでも最適化かけないとそれより遅くなることもあるんだなと思いました。

さいごに

より軽量な関数を組み込むことで高速化が図れそうなことがわかりました。
自作関数の実装は、簡単な処理の関数1つ追加する程度なら 100 行ほどで実装できるようで、意外と敷居が低いのかなという印象を持ちました。
実際に運用することを考えると素人のポインタ操作によって影響が出るかもしれないのでそこの考慮は必要ですが...。

  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

RailsのDBをmysqlに変える(メモ)

RailsでデフォルトのDB'SQlite'から'mysql'(ver8.0.22)に変更する際に詰まったので、
mysqlインストールから実際にDB作成をするところまでの手順をメモ。

1.mysqlインストーラでmysqlをインストール。
http://dev.mysql.com/downloads/installer/
からインストーラをダウンロード。
mysqlインストーラ.PNG

2.ダウンロードしたインストーラを起動。
あとは流れに沿ってインストールしていく。(rootのパスワード設定等。)
そして、この流れの中で後にRailsからmysqlを起動しようとするとErrorになってしまう設定項目があった。それがこの設定。
Authenticate.png

ここで上の認証方式を選択してしまうと、認証方式が'caching_sha2_password'になるが、Railsではこの認証方式に対応していないらしい。(この認証方式はmysql8で使用可能。)
なので、下の設定を選択して認証方式を'mysql_native_password'にする必要があった。

3.gemファイルでmysqlをinstall。

Gemfile
# Use mysql as the database for Active Record
gem "mysql2"
bundel install

4.railsアプリケーションのDB設定

config/database.yml
default: &default
  adapter: mysql2
  encoding: utf8
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  username: root
  password:
  host: localhost
  timeout: 5000

development:
  adapter: mysql2
  encoding: utf8
  reconnect: false
  database: <%= ENV['DATABASE_DEV_NAME'] %>
  pool: 5
  username: <%= ENV['DATABASE_DEV_USER'] %>
  password: <%= ENV['DATABASE_DEV_PASSWORD'] %>
  host: <%= ENV['DATABASE_DEV_HOST'] %>

# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
  adapter: mysql2
  encoding: utf8
  reconnect: false
  database: アプリケーション名_test
  pool: 5
  username: root
  password: <%= ENV['DATABASE_TST_PASSWORD'] %>
  host: localhost

production:
  adapter: mysql2
  encoding: utf8
  reconnect: false
  database: アプリケーション名_production
  pool: 5
  username: アプリケーション名
  password: <%= ENV['アプリケーション名_DATABASE_PASSWORD'] %>
  host: localhost

のように変更。

5.パスワードを環境変数で管理する。
dotenvというgemをinstall。

Gemfile
gem "dotenv-rails"
bundle install

アプリケーションのルートディレクトリに.envファイルを作成し、その中に環境変数を設定する。

.env
 DATABASE_DEV_NAME = 'アプリケーション名_development'
 DATABASE_DEV_PASSWORD = 'パスワードを記入'
 DATABASE_DEV_USER = 'MySQLユーザー名を記入'
 DATABASE_DEV_HOST = 'localhost'
 DATABASE_TST_PASSWORD = 'パスワードを記入'

.gitignoreファイルに.envを追加する。

.gitignore
# Ignore env config
/.env

※mysqlユーザを作成しておく。

ここで

rails db:create

完了。

※mysqlユーザを作成する。

1.mysqlに接続する。
コマンドプロンプトを管理者権限で開き、以下を実行する。

net start mysql80
mysql -u root -p

mysqlインストール時に設定したパスワードを入力。

2.実際にmysqlユーザを作成する。

mysql> create user 'test-user'@'localhost' identified by 'password';

3.mysqlユーザに権限を与える。

mysql> grant all on *.* to 'test-user'@'localhost';
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

uminにwordpressを導入してみた

先日umin.ac.jpにwordpressを導入して欲しいとの依頼を受けました。
色々と勉強になったのでメモがてらQiitaに記載することにしました。

uminとは

生物系、医療系研究職のためのネットワークサービスだそうです。
正直今まで全然知らなかったのですが、医療系ではかなり利用している方が多いとか。
研究支援のために様々なサービスを展開しているようです。
(正直私もイマイチわかっていないw)

wordpress導入の背景

とある教授の研究紹介サイトがumin上にありました。それをリニューアルしたいとのご相談を受けました。
というのも、自分で更新が出来ないようです。
それは大変ですね、自分で情報が更新できない研究サイトってもはや正直何のための研究サイトなのかよくわかりません。
どんどん情報をアップデートしてこそホームページの意味があると思うので引き受けることにしました。
無料で使えてコーデイングの知識がない人でも簡単に更新できると言えばwordpress!
なので今回はuminにwordpressを導入することにしました。

uminにwordpress導入までの大まかな流れ

ざっくりとした流れとしては
1. uminにssh接続
2. mysql導入のための準備
3. mysqlインストール
4. mysql起動
5. mysql初期設定
6. db作成とwordpress導入

wordpress導入するために参考にしたサイト

https://plaza.umin.ac.jp/kikkenlab/note/umin-wordpress/
https://plaza.umin.ac.jp/shoei05/wp/index.php/2020/10/13/6/#datadir%E3%81%AE%E8%A8%AD%E7%BD%AE

正直これらのサイトにかなり丁寧に導入方法は記載があったのでこれらを見ながら導入しました。

uminへのwordpress導入で詰まった点

上記サイトを見ながら実施して私自身が最も詰まったのは、
4. mysql起動
までの肯定です。
ここまで出来れば後は非常にスムーズでした。

/mysql.server start

を叩いても

Starting MySQL. SUCCESS!

が出てこない・・・
という部分で半日ほど詰まりました・・・
その時のエラー文がこちら

Starting MySQL.. ERROR! The server quit without updating PID file (/home/{your account}/tmp/mysql.pid).

私のあかん所ですが、このエラー文を読んで、
「あっPIDファイルがなんか変なんか」と
思い込んでしまい、
PIDファイルについて調べまくってその部分だけをあーだこうだ修正していました。
このエラー文ググってしらべまくりました。

しかし何回しても上手くいかず、
mysqlが入っているディレクションを全部消してまた入れるという作業も何回か実施しましたが、
それでもダメで・・・

そこで気付いたのがエラーログです!!
このエラーどこでふいてるんや?
と調べてみると、

/mysql_data/mysqld/ 

配下にありました。
そのログの中身を見てみると・・・・
エラー文章発見!!

エラー文章のスクショ撮るの忘れましたが、
要するに
port番号#### (私が記載した番号)で大丈夫?
というようなエラー内容でした。

全然PIDファイルちゃうやん!!
というのが私の率直な感想ww

uminは自分でport番号を設定しなくてはいけないのですが、

$ netstat -nat | grep LISTEN | awk '{print $4}'

で既に使われているport番号を調べてまだ使われていないport番号を入力しなくてはいけないんですよね。

ここのport番号が既に使われている番号を使用していたのが大きな原因でした。

ざっと見て大丈夫そうなport番号を入力したのですが、
結果的にはその適当に選んだport番号が既に使われているport番号やったからサーバーが起動しなかったのです。

このport番号をちゃんと調べるのがまぁ意外と面倒くさくて、
既に使われているport番号が一覧で表示されるのですが、数字の順番とかではなくランダムなんです。
つまり被らないport番号を見つけるために、
私は一旦exelに落として、数字順番に並び替えて番号を調べました。

そしてport番号を入れ直すと、

Starting MySQL. SUCCESS!

やっと出た!!
mysqlだけ入れば後はもうスイスイです。

こんな些細なことに半日も時間費やしたのがもったいなくて・・・
気づいた時逆に落ち込みましたw

エラーが出た時はログを見るという当たり前の行為を忘れないようにしなくてはいけませんね・・・
深く反省・・・

  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

MySQLでquit;コマンドで終了した際に、root@以下省略が表示されてしまい元のディレクトリに戻れない

環境

mac OS Big Sur
docker上でMySQLを起動
(何か間違えていましたらすみません)

状況

MySQLをターミナル上で終了しようとした際にroot@が表示されてしまう

MySQL [book_log]> quit;
Bye
root@ebe3e64de4d6:/var/www/html#

何か押してしまってroot@が表示されてしまったのだろうか

exitコマンドで抜け出せました!

root@ebe3e64de4d6:/var/www/html# exit;
exit
ss@saaaMPro part2 %

rootが表示され、かなり焦りました笑

参考にさせていただきました。ありがとうございます!
ターミナルにて、mysqlからexitできない

  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む