ためすう
読み取り専用ユーザーを作成する (MySQL)
2020-03-29やったこと
MySQL で読み取りだけ実行可能なユーザーを作成します。
確認環境
$ mysql --version
mysql Ver 14.14 Distrib 5.6.25, for Linux (x86_64) using EditLine wrapper
調査
ユーザーを検索します。
mysql> SELECT user, host FROM mysql.user;
+------+-----------------------+
| user | host |
+------+-----------------------+
| root | 127.0.0.1 |
| root | ::1 |
| root | localhost |
| root | localhost.localdomain |
+------+-----------------------+
4 rows in set (0.00 sec)
SELECT 権限を持つユーザーを作成します。
mysql> GRANT SELECT ON test.* TO read1@localhost IDENTIFIED BY 'hogehoge';
Query OK, 0 rows affected (0.00 sec)
mysql> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.00 sec)
read1
ユーザーが作成されていることを確認します。
mysql> SELECT user, host FROM mysql.user;
+-------+-----------------------+
| user | host |
+-------+-----------------------+
| root | 127.0.0.1 |
| root | ::1 |
| read1 | localhost |
| root | localhost |
| root | localhost.localdomain |
+-------+-----------------------+
5 rows in set (0.00 sec)
ここで、read1
ユーザーで MySQL に再接続します。
$ mysql -u read1 -p test
SELECT は実行できます。
mysql> select * from test_table;
+----+------+------+------+
| id | col1 | col2 | col3 |
+----+------+------+------+
| 1 | 2 | 3 | 4 |
| 2 | 2 | 3 | 4 |
+----+------+------+------+
2 rows in set (0.00 sec)
権限がないので INSERT はエラーになりました。
mysql> insert into test_table values (3, 2, 3, 4);
ERROR 1142 (42000): INSERT command denied to user 'read1'@'localhost' for table 'test_table'
ユーザー削除 (root ユーザーで実行)
mysql> DROP USER 'read1'@'localhost';
Query OK, 0 rows affected (0.00 sec)
参考
emplace_back を使ってみる (C++)
2020-03-29確認環境
$ g++ --version
g++ (Homebrew GCC 9.2.0) 9.2.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
調査
test.cpp
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<ll, string> P;
typedef tuple<ll, ll, string> T;
int main() {
vector<P> v;
v.push_back(P(1, "aaa"));
v.emplace_back(2, "bbb");
cout << "pair" << endl;
for (int i = 0; i < v.size(); i++) {
cout << v[i].first << " " << v[i].second << endl;
}
vector<T> v2;
v2.push_back(T(1, 100, "mmm"));
v2.emplace_back(2, 200, "nnn");
cout << "tupple" << endl;
for (int i = 0; i < v2.size(); i++) {
cout << get<0>(v2[i]) << " " << get<1>(v2[i]) << " " << get<2>(v2[i]) << endl;
}
}
出力結果
pair
1 aaa
2 bbb
tupple
1 100 mmm
2 200 nnn
参考
octopus を使ってみる (Rails)
2020-03-28やったこと
octopus をインストールして使ってみます。
確認環境
$ ruby --version
ruby 2.6.3p62 (2019-04-16 revision 67580) [x86_64-darwin17]
$ rails --version
Rails 5.2.3
$ sqlite3 --version
3.20.1 2017-08-24 16:21:36 8d3a7ea6c5690d6b7c3767558f4f01b511c55463e3f9e64506801fe9b74dce34
調査
今回 octopus
という gem を使います。
octopus は下記機能を提供しています。
- Sharding (with multiple shards, and grouped shards).
- Replication (Master/slave support, with multiple slaves).
- Moving data between shards with migrations.
- Tools to manage database configurations. (soon)
Replication について動きを確かめてみます。
インストール
Gemfile
gem 'ar-octopus'
config
config/shards.yml
octopus:
replicated: true
environments:
- development
development:
shard1:
adapter: sqlite3
database: db/development.slave1.sqlite3
shard2:
adapter: sqlite3
database: db/development.slave2.sqlite3
アクセスしてみる
別々にアクセスしていることを確認するため、 使用するテーブルの最終行にデータを入れました。
development.slave1.sqlite3
development.slave2.sqlite3
$ rails c
Running via Spring preloader in process 74218
Loading development environment (Rails 5.2.4.1)
irb(main):001:0> Book.last
[Shard: shard2] Book Load (0.4ms) SELECT "books".* FROM "books" ORDER BY "books"."id" DESC LIMIT ? [["LIMIT", 1]]
=> #<Book id: 4, title: "222", status: nil, created_at: "2020-03-15 07:58:57", updated_at: "2020-03-15 07:58:57">
irb(main):002:0> Book.last
[Shard: shard1] Book Load (0.1ms) SELECT "books".* FROM "books" ORDER BY "books"."id" DESC LIMIT ? [["LIMIT", 1]]
=> #<Book id: 5, title: "123", status: 1, created_at: "2020-03-28 00:00:00", updated_at: "2020-03-28 00:00:00">
shard1、shard2 によって、異なるデータを取得していることが分かります。
最後に
Octopus will enter into maintainance mode once Rails 6 is released
Rails6 がリリースされているので、メンテナンスモードになっているようです。
sqrt、sqrtf、sqrtl を使ってみる (C++)
2020-03-28確認環境
$ g++ --version
g++ (Homebrew GCC 9.2.0) 9.2.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
調査
3の平方根を計算してみます。
今回は下記の関数を使ってみます。
- sqrtf (float)
- sqrt (double)
- sqrtl (long double)
test.cpp
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int main() {
printf("%.80f\n", sqrtf((float)3));
printf("%.80f\n", sqrt(3));
printf("%.80Lf\n", sqrtl((long double)3));
}
出力結果
1.73205077648162841796875000000000000000000000000000000000000000000000000000000000
1.73205080756887719317660412343684583902359008789062500000000000000000000000000000
1.73205080756887729357372529559455642811371944844722747802734375000000000000000000
参考
stderr を使ってみる (C++)
2020-03-22確認環境
$ g++ --version
g++ (Homebrew GCC 9.2.0) 9.2.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
調査
test.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
fprintf(stderr, "message: %s\n", "error happended");
}
出力結果
message: error happended
fprintf で出力先を stderr にして使います。
stderr can be used as an argument for any function that takes an argument of type FILE* expecting an output stream, like fputs or fprintf.
参考
fabs を使ってみる (C++)
2020-03-22確認環境
$ g++ --version
g++ (Homebrew GCC 9.2.0) 9.2.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
調査
test.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
cout << fabs(12.3) << endl;
cout << fabs(-12.3) << endl;
cout << abs(12.3) << endl;
cout << abs(-12.3) << endl;
}
出力結果
12.3
12.3
12.3
12.3
fabs
戻り値は正確で、現在の丸め方式には依存しない。
abs
任意の整数型に対するオーバーロードが C++11 で追加されたが、ある種の問題を引き起こすことから、今後削除される可能性がある。Validity and return type of std::abs(0u) is unclear 参照。
abs を使っても同じ結果を取得できましたが、とあるので、fabs を使った方が良さそうです。
参考
ActiveRecord のコールバックが呼ばれるタイミングを調べる (Rails)
2020-03-15やったこと
ActiveRecord のコールバックが呼ばれるタイミングを調べてみます。
確認環境
$ ruby --version
ruby 2.6.3p62 (2019-04-16 revision 67580) [x86_64-darwin17]
$ rails --version
Rails 5.2.3
$ sqlite3 --version
3.20.1 2017-08-24 16:21:36 8d3a7ea6c5690d6b7c3767558f4f01b511c55463e3f9e64506801fe9b74dce34
調査
テーブル確認
sqlite> .schema books
CREATE TABLE IF NOT EXISTS "books" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "title" varchar, "status" integer, "created_at" datetime NOT NULL, "updated_at" datetime NOT NULL);
app/models/book.rb
class Book < ApplicationRecord
before_validation Proc.new {
Rails.logger.fatal('call before_validation')
}
after_validation Proc.new {
Rails.logger.fatal('call after_validation')
}
before_create Proc.new {
Rails.logger.fatal('call before_create')
}
around_create Proc.new {
Rails.logger.fatal('call around_create')
}
after_create Proc.new {
Rails.logger.fatal('call after_create')
}
after_commit Proc.new {
p 'p after_commit'
Rails.logger.fatal('call after_commit')
}
### around_save Proc.new {
### Rails.logger.fatal('call afround_save')
### }
before_save Proc.new {
Rails.logger.fatal('call before_save')
}
after_save Proc.new {
Rails.logger.fatal('call after_save')
}
end
出力結果 (コンソール)
irb(main):001:0> Book.create(title: 33)
(0.0ms) begin transaction
call before_validation
call after_validation
call before_save
call before_create
call around_create
call after_create
call after_save
(0.0ms) commit transaction
=> #<Book id: nil, title: "33", status: nil, created_at: "2020-03-15 08:18:52", updated_at: "2020-03-15 08:18:52">
Rails5 では after_commit は、動かないようので要注意です。
参考
struct で operator を定義してみる (C++)
2020-03-14確認環境
$ g++ --version
g++ (Homebrew GCC 9.2.0) 9.2.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
調査
test.cpp
#include <bits/stdc++.h>
using namespace std;
struct edge {
int cost, hoge1, hoge2;
bool operator<(const edge& rhs) const {
return cost > rhs.cost;
}
};
int main() {
priority_queue<edge> pq;
for (int i = 0; i < 5; i++) {
pq.push({10 + i, 2, 3});
}
while (!pq.empty()) {
edge e = pq.top();
pq.pop();
cout << e.cost << " " << e.hoge1 << " " << e.hoge2 << endl;
}
}
出力結果
10 2 3
11 2 3
12 2 3
13 2 3
14 2 3
参考
ActiveRecord の enum を使ってみる (Rails)
2020-03-14やったこと
ActiveRecord の enum を使ってみます。
確認環境
$ ruby --version
ruby 2.6.3p62 (2019-04-16 revision 67580) [x86_64-darwin17]
$ rails --version
Rails 5.2.3
調査
準備
$ rails g model book title:string status:integer
$ rails db:migrate
enum の項目だけ定義する場合
app/models/book.rb
class Book < ApplicationRecord
enum status: [ :nothing, :doing, :done ]
end
コンソール
irb(main):004:0> Book.statuses
=> {"nothing"=>0, "doing"=>1, "done"=>2}
-- データ作成
irb(main):005:0> Book.create(title: 'book1', status: 1)
(0.1ms) begin transaction
Book Create (0.8ms) INSERT INTO "books" ("title", "status", "created_at", "updated_at") VALUES (?, ?, ?, ?) [["title", "book1"], ["status", 1], ["created_at", "2020-03-14 07:35:38.468498"], ["updated_at", "2020-03-14 07:35:38.468498"]]
(1.5ms) commit transaction
=> #<Book id: 1, title: "book1", status: "doing", created_at: "2020-03-14 07:35:38", updated_at: "2020-03-14 07:35:38">
-- データ取得
irb(main):006:0> b = Book.find(1)
Book Load (0.2ms) SELECT "books".* FROM "books" WHERE "books"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
=> #<Book id: 1, title: "book1", status: "doing", created_at: "2020-03-14 07:35:38", updated_at: "2020-03-14 07:35:38">
-- stauts を更新
irb(main):007:0> b.done!
(0.1ms) begin transaction
Book Update (0.6ms) UPDATE "books" SET "status" = ?, "updated_at" = ? WHERE "books"."id" = ? [["status", 2], ["updated_at", "2020-03-14 07:38:35.150818"], ["id", 1]]
(0.9ms) commit transaction
=> true
enum で key と value を定義する場合
app/models/book.rb
class Book < ApplicationRecord
enum status: { nothing: 0, doing: 2, done: 4 }
end
コンソール
-- データ取得
irb(main):011:0> b = Book.find(1)
Book Load (0.1ms) SELECT "books".* FROM "books" WHERE "books"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
=> #<Book id: 1, title: "book1", status: "doing", created_at: "2020-03-14 07:35:38", updated_at: "2020-03-14 07:38:35">
irb(main):012:0> b.status
=> "doing"
-- データ更新
irb(main):013:0> b.done!
(0.1ms) begin transaction
Book Update (0.3ms) UPDATE "books" SET "status" = ?, "updated_at" = ? WHERE "books"."id" = ? [["status", 4], ["updated_at", "2020-03-14 07:42:16.748137"], ["id", 1]]
(1.0ms) commit transaction
=> true
enum をメソッドみたいに使えるの知りませんでした。
参考
minitest を行数指定で使う (Rails)
2020-03-07やったこと
minitest を行数指定で実行します。
確認環境
$ ruby --version
ruby 2.6.3p62 (2019-04-16 revision 67580) [x86_64-darwin17]
$ rails --version
Rails 5.2.3
調査
準備
$ rails g model book title:string status:integer
$ rails db:migrate
test/models/book_test.rb
require 'test_helper'
class BookTest < ActiveSupport::TestCase
test "the truth" do
assert true
end
test "the truth222" do
assert true
end
end
テストを実行する
$ rails test test/models/book_test.rb:8
Running via Spring preloader in process 46538
Run options: --seed 24522
# Running:
.
Finished in 0.011685s, 85.5798 runs/s, 85.5798 assertions/s.
1 runs, 1 assertions, 0 failures, 0 errors, 0 skips