[RUBY] [Rails] Development with MySQL

I've been creating and learning some web applications so far, All DBs have used the default SQLite.

When creating a new application this time, if you try to set the production environment to AWS, you need to set MySQL ... So I would like to use MySQL! I'm still a beginner, so please point out any mistakes.

What is MySQL

It is the most used database in the world and has the following features.

Difference from SQLite

RDBMS used by default with Rails installed is ** SQLite ** SQLite has the following features

It seems better to use MySQL when dealing with a huge DB

Try developing with MySQL

Rails uses SQLite by default, so In order to use MySQL, I will specify it at startup

rails new application name--database=mysql

Can be omitted

rails new application name-d mysql

By doing this, it seems that RDBMS can be changed to MySQL. Check the Gemfile just in case ... If not specified

Gemfile


# Use sqlite3 as the database for Active Record
gem 'sqlite3'

On the other hand, if you specify

Gemfile


# Use mysql as the database for Active Record
gem 'mysql2', '>= 0.3.18', '< 0.5'

have become! !!

But the problem is ... rails new application name -d An error occurred when mysql was executed. .. ..

・
・
(Many logs)
・

Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

    current directory: /Users/mariko/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/mysql2-0.5.3/ext/mysql2
/Users/mariko/.rbenv/versions/2.6.5/bin/ruby -I /Users/mariko/.rbenv/versions/2.6.5/lib/ruby/2.6.0 -r ./siteconf20201104-33105-i9fwuc.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/[email protected]/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/[email protected]/lib
-----
creating Makefile

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

current directory: /Users/mariko/.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/mariko/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/mysql2-0.5.3 for inspection.
Results logged to /Users/mariko/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/extensions/x86_64-darwin-19/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
         run  bundle binstubs bundler
Could not find gem 'mysql2 (>= 0.4.4)' in any of the gem sources listed in your Gemfile.
         run  bundle exec spring binstub --all
Could not find gem 'mysql2 (>= 0.4.4)' in any of the gem sources listed in your Gemfile.
Run `bundle install` to install missing gems.
       rails  webpacker:install
Could not find gem 'mysql2 (>= 0.4.4)' in any of the gem sources listed in your Gemfile.
Run `bundle install` to install missing gems.

I will translate it for the time being "An error occurred during the installation of mysql2 (0.5.3) and Bundler cannot continue." ···do not know···. I have to beat it for the time being ...!

Solutions

For the time being, do what is written in the log

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

ERROR:  While executing gem ... (OptionParser::InvalidArgument)
    invalid argument: --source https://rubygems.org/

Install MySQL on Mac

I completely overlooked the part of installing MySQL. Install by referring to the following article! Procedure to install MySQL on Mac with Homebrew

Install with the following command

$ brew update
$ brew install mysql

Check if it is installed

$ brew info mysql

mysql: stable 8.0.22 (bottled)
Open source relational database management system
https://dev.mysql.com/doc/refman/8.0/en/
Conflicts with:
  mariadb (because mysql, mariadb, and percona install the same binaries)
  percona-server (because mysql, mariadb, and percona install the same binaries)
/usr/local/Cellar/mysql/8.0.22 (294 files, 296.5MB) *
  Poured from bottle on 2020-11-04 at 13:55:11
From: https://github.com/Homebrew/homebrew-core/blob/HEAD/Formula/mysql.rb
License: GPL-2.0
==> Dependencies
Build: cmake ✘
Required: [email protected] ✔, protobuf ✔
==> Caveats
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 have launchd start mysql now and restart at login:
  brew services start mysql
Or, if you don't want/need a background service you can just run:
  mysql.server start
==> Analytics
install: 85,249 (30 days), 214,834 (90 days), 813,126 (365 days)
install-on-request: 83,371 (30 days), 209,508 (90 days), 784,193 (365 days)
build-error: 0 (30 days)

Version 8.0.22 was installed!

Try to start MySQL

$mysql.server start
Starting MySQL
 SUCCESS! 

Connect and check the operation

$mysql -uroot

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

・ ・ ・ ・ Another error (crying) Is it useless because there is no password? I think, I will set it for the time being.

security settings

$mysql_secure_installation

Enter password for user root:(Enter password)

Do you want to set up a plugin that checks the strength of your password? "Y"

VALIDATE PASSWORD PLUGIN 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 plugin?

Press y|Y for Yes, any other key for No: y

Select a verification level.

There are three levels of password validation policy:

LOW    Length >= 8
MEDIUM Length >= 8, numeric, mixed case, and special characters
STRONG Length >= 8, numeric, mixed case, special characters and dictionary                  file

Please enter 0 = LOW, 1 = MEDIUM and 2 = STRONG: 2

Since it seems to be a production environment, select 2. If the password strength you entered earlier does not match, you will be prompted to enter it again. If you type in the password twice, is it okay to confirm it? Because it is said, "y"

Estimated strength of the password: 50 
Change the password for root ? ((Press y|Y for Yes, any other key for No) : y

New password: 

Re-enter new password: 
Estimated strength of the password: 100 
Do you wish to continue with the password provided?(Press y|Y for Yes, any other key for No) : y

Delete anonymous user (anonymous user)? "Y"

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

Prevents you from remotely logging in as the root user. Prohibit login? "Y"

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

Delete the database named test that is created by default? "Y"

Remove test database and access to it? (Press y|Y for Yes, any other key for No) : y
 - Dropping test database...
Success.
 - Removing privileges on test database...
Success.

Immediately reload the permission table for changes to take effect? "Y"

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

All done! 

For the time being, have you made the settings?

Check the operation again

$mysql -u root -p
Enter password:(password input)

Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 5
Server version: 5.7.32 Homebrew

Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.

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>

Uh, it worked! !! !! Crying

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

The test database is gone too!

Exit from mysql once ... Stop it ...

$ mysql.server stop
Shutting down MySQL
. SUCCESS! 

Go back to the app and bundle install

The same error ... crying

I proceeded with reference to the following article! [Rails] What to do if you can't bundle install MySQL2

$ brew info openssl
[email protected]: stable 1.1.1h (bottled) [keg-only]
Cryptography and SSL/TLS Toolkit
https://openssl.org/
/usr/local/Cellar/[email protected]/1.1.1g (8,059 files, 18MB)
  Poured from bottle on 2020-05-21 at 18:53:48
/usr/local/Cellar/[email protected]/1.1.1h (8,067 files, 18.5MB)
  Poured from bottle on 2020-11-01 at 12:26:48
From: https://github.com/Homebrew/homebrew-core/blob/HEAD/Formula/[email protected]
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/[email protected]/certs

and run
  /usr/local/opt/[email protected]/bin/c_rehash

[email protected] is keg-only, which means it was not symlinked into /usr/local,
because macOS provides LibreSSL.

If you need to have [email protected] first in your PATH run:
  echo 'export PATH="/usr/local/opt/[email protected]/bin:$PATH"' >> /Users/mariko/.bash_profile

For compilers to find [email protected] you may need to set:
  export LDFLAGS="-L/usr/local/opt/[email protected]/lib"
  export CPPFLAGS="-I/usr/local/opt/[email protected]/include"

For pkg-config to find [email protected] you may need to set:
  export PKG_CONFIG_PATH="/usr/local/opt/[email protected]/lib/pkgconfig"

==> Analytics
install: 835,013 (30 days), 1,906,254 (90 days), 7,237,126 (365 days)
install-on-request: 136,062 (30 days), 257,990 (90 days), 1,007,070 (365 days)
build-error: 0 (30 days)

This part seems to be important.

export LDFLAGS="-L/usr/local/opt/[email protected]/lib"
export CPPFLAGS="-I/usr/local/opt/[email protected]/include"

Execute the following two commands

$ bundle config --local build.mysql2 "--with-cppflags=-I/usr/local/opt/[email protected]/include"
You are replacing the current local value of build.mysql2, which is currently nil

$ bundle config --local build.mysql2 "--with-ldflags=-L/usr/local/opt/[email protected]/lib"
You are replacing the current local value of build.mysql2, which is currently "--with-cppflags=-I/usr/local/opt/[email protected]/include"

Bundle install again I was able to install it ...! !! !! Crying

Summary

Until I introduced MySQL to my app, I had to go back and forth. I'm sorry if it's hard to read. I hope you get used to the power of someone even a little.

Thank you very much to the authors for their reference.

There seems to be a procedure to change to SQLite on the way, so I will try it with the application I have made so far.

Recommended Posts

[Rails] Development with MySQL
Rails + MySQL environment construction with Docker
[Environment construction with Docker] Rails 6 & MySQL 8
Rails application development environment construction with Docker [Docker, Rails, Puma, Nginx, MySQL]
Rails Development Transition 2020
Deploy heroku with Rails6 (Cloud9 + Ubuntu) + MySQL
Create Rails 6 + MySQL environment with Docker compose
Deploy to heroku with Docker (Rails 6, MySQL)
[Docker] Development environment construction Rails6 / Ruby2.7 / MySQL8
Procedure for building a Rails application development environment with Docker [Rails, MySQL, Docker]
Rails deploy with Docker
Rails6 [API mode] + MySQL5.7 environment construction with Docker
[Rails 6] RuntimeError with $ rails s
Handle devise with Rails
[Rails] Learning with Rails tutorial
[Rails] Test with RSpec
Plugin development with ImageJ
[Docker] Connection with MySQL
Rails development environment created with VSCode and devcontainer
Error deploying rails5 + Mysql to heroku with Docker-compose
Supports multilingualization with Rails!
Double polymorphic with Rails
Stable development environment construction manual for "Rails6" with "Docker-compose"
Environment construction of Rails5 + MySQL8.0 + top-level volumes with docker-compose
Roughly the flow of web application development with Rails.
Build Rails (API) x MySQL x Nuxt.js environment with Docker
Rails6 development environment construction [Mac]
[Template] MySQL connection with Java
Introduced graph function with rails
[Rails] Express polymorphic with graphql-ruby
Rails6 (MySQL, Ubuntu environment, Cloud9)
[Rails] Upload videos with Rails (ActiveStorage)
Try using view_component with rails
[Vue Rails] "Hello Vue!" Displayed with Vue + Rails
Japaneseize using i18n with Rails
API creation with Rails + GraphQL
Preparation for developing with Rails
Run Rails whenever with docker
Connect to MySQL 8 with Java
Use multiple databases with Rails 6.0
[Rails] Specify format with link_to
Login function implementation with rails
[Rails / MySQL] Mac environment construction
[Ruby] REPL-driven development with pry
[Docker] Use whenever with Docker + Rails
I made a development environment with rails6 + docker + postgreSQL + Materialize.
How to build Rails, Postgres, ElasticSearch development environment with Docker
[Vagrant] Prepare LAMP development environment with Vagrant (centos + apache + MySQL + PHP)
Create portfolio with rails + postgres sql
[Rails] Push transmission with LINE Bot
Comparison of WEB application development with Rails and Java Servlet + JSP
Rails new fails to install mysql
[Rails] Make pagination compatible with Ajax
Hot deploy with Spring Boot development
Ruby on Rails development environment construction with Docker + VSCode (Remote Container)
JDBC connection with MySQL 8.x * Notes *
Prepare Java development environment with Atom
Implemented mail sending function with rails
[Rails] Creating a new project with rails new
Minimal Rails with reduced file generation
[Rails 6] API development using GraphQL (Query)