0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Go】pgxでErrNoRowsのエラーを判定する

Posted at

概要

Go のちょっと変わったORM sqlc の紹介の記事で紹介されているsqlcですが、PostgreSQLで使用する際はドライバーのライブラリはGetting started with PostgreSQLの公式ページで紹介されている通り、pgxの使用が推奨されています。
そのpgxでクエリの結果を取得した際に、1件もなかった時の判定をする際のメモ書きです。

前提

  • 使用したpgxのバージョンはv5.7.4です。

判定方法

:one without results is supposed to return "sql: no rows in result set" which is the same as database/sql.ErrNoRows but returning "no rows in result set"のissueで言及されている通り、エラーはsql.ErrNoRowsではなくpgx.ErrNoRowsで返ってきます。ので、判定方法としてもpgx.ErrNoRowsと比較する形となります。

実装サンプル

pgxを設定した際のsqlcで、クエリ発行時のErrNoRowsの判定実装サンプルです。

// ユーザIDが重複してるかチェック
func CheckUserAccountTest(ctx context.Context, queries *db.Queries, input model.NewUserAccount) error {
	// ユーザIDを条件にクエリを実行
	_, err := queries.SelectUserAccountByUserSettingId(ctx, input.UserSettingID)
	if err != nil {
		// pgxのErrNoRowで0件エラーか判定
		if err != pgx.ErrNoRows {
			return err
		}
	} else {
		// ユーザが取得できていたら重複エラー
		return &gqlerror.Error{
			Message: "Dupilicate userSettingId",
			Extensions: map[string]any{
				"code": 400,
			}}
	}

	return nil
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?