GoのentでDBへの接続確認のためPingする方法
entでDBへの接続を確認する方法
GoのDBのPingで接続確認をすることは、安全なアプリケーションを作るために重要です。
database/sqlパッケージではPingをすることが可能なのですが、ent自体にはその機能がないため、database/sqlパッケージを使ってDBへの接続を確認する必要があります。
これは、ent公式リポジトリのIssue #661で議論に基づいています。
なぜ接続確認が重要なのか
アプリケーション起動時にデータベース接続を確認することには、以下のような利点があります
- 早期にエラーを検出できるため、DB接続に関するトラブルシューティングが容易になる。
- 接続パラメータに問題があればinit時に即座に気づける。
実装例
以下はentでDB接続を確認するための実装例です。
DBはMySQLを使用しています。
func main() {
// MySQLに接続
db, err := sql.Open("mysql", config.DB())
if err != nil {
log.Panicf("failed to open database: %v", err)
}
// 接続確認
if err := db.Ping(); err != nil {
log.Panicf("failed to connect to mysql: %v", err)
}
log.Println("connected to mysql")
// entドライバーを作成
drv := entsql.OpenDB("mysql", db)
defer drv.Close()
// entクライアントを初期化
client := ent.NewClient(ent.Driver(drv))
client = client.Debug()
defer client.Close()
// ...
}
GitHub Issue #661の議論
entでのDB接続確認について、Issue #661では、entクライアントに直接Ping機能を追加するべきかという提案が検討されました。
Issue #661の主な内容を引用すると:
[...] I usually check if the connection is made right after I make a DB connection when starting the server. In Ent, it seems that I can't check whether the connection with the DB is properly.
in database/sql, comment on Open() says "Open may just validate its arguments without creating a connection to the database. To verify that the data source name is valid, call Ping." So, If the ping method is added to the client, it will be able to perform the desired function. [...]
という内容で、entクライアントにPingメソッドを追加することが提案されました。
しかし、この提案に対して、entのメンテナーからは
「database/sql.DBにPingメソッドがあるので、ent自体にそれが必要かどうかはわからない」という回答がありました。
公式ドキュメント(ent - sql.DB Integration)にもあるように sql.DB
objectを使用することで可能なことはそれでやってほしいということみたいです。
Discussion