github.com/shogo82148/std@v1.22.1-0.20240327122250-4e474527810c/database/sql/sql.go (about) 1 // Copyright 2011 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // sqlパッケージは、SQL(またはSQLライク)データベースを取り巻く汎用インターフェースを提供します。 6 // 7 // sqlパッケージは、データベースドライバと共に使用する必要があります。 8 // ドライバのリストについては、https://golang.org/s/sqldrivers を参照してください。 9 // 10 // コンテキストのキャンセルをサポートしていないドライバは、クエリが完了するまで戻らないことに注意してください。 11 // 12 // 使用例については、https://golang.org/s/sqlwiki のウィキページを参照してください。 13 package sql 14 15 import ( 16 "github.com/shogo82148/std/context" 17 "github.com/shogo82148/std/database/sql/driver" 18 "github.com/shogo82148/std/errors" 19 "github.com/shogo82148/std/fmt" 20 "github.com/shogo82148/std/reflect" 21 "github.com/shogo82148/std/sync" 22 "github.com/shogo82148/std/sync/atomic" 23 "github.com/shogo82148/std/time" 24 ) 25 26 // Registerは、指定された名前でデータベースドライバを利用可能にします。 27 // Registerが同じ名前で2回呼び出された場合、またはdriverがnilの場合、 28 // panicが発生します。 29 func Register(name string, driver driver.Driver) 30 31 // Driversは、登録されたドライバーの名前のソートされたリストを返します。 32 func Drivers() []string 33 34 // NamedArgは名前付き引数です。NamedArg値は、 [DB.Query] または [DB.Exec] の引数として使用でき、 35 // SQLステートメントの対応する名前付きパラメータにバインドされます。 36 // 37 // NamedArg値をより簡潔に作成する方法については、 [Named] 関数を参照してください。 38 type NamedArg struct { 39 _NamedFieldsRequired struct{} 40 41 // Nameはパラメータプレースホルダーの名前です。 42 // 43 // 空の場合、引数リストの序数が使用されます。 44 // 45 // Nameには、シンボル接頭辞を省略する必要があります。 46 Name string 47 48 // Valueはパラメータの値です。 49 // クエリ引数と同じ値型が割り当てられる可能性があります。 50 Value any 51 } 52 53 // Namedは、 [NamedArg] 値をより簡潔に作成する方法を提供します。 54 // 55 // 使用例: 56 // 57 // db.ExecContext(ctx, ` 58 // delete from Invoice 59 // where 60 // TimeCreated < @end 61 // and TimeCreated >= @start;`, 62 // sql.Named("start", startTime), 63 // sql.Named("end", endTime), 64 // ) 65 func Named(name string, value any) NamedArg 66 67 // IsolationLevelは、 [TxOptions] で使用されるトランザクション分離レベルです。 68 type IsolationLevel int 69 70 // [DB.BeginTx] でドライバーがサポートする可能性のあるさまざまな分離レベル。 71 // ドライバーが特定の分離レベルをサポートしていない場合、エラーが返される場合があります。 72 // 73 // https://en.wikipedia.org/wiki/Isolation_(database_systems)#Isolation_levels を参照してください。 74 const ( 75 LevelDefault IsolationLevel = iota 76 LevelReadUncommitted 77 LevelReadCommitted 78 LevelWriteCommitted 79 LevelRepeatableRead 80 LevelSnapshot 81 LevelSerializable 82 LevelLinearizable 83 ) 84 85 // Stringはトランザクション分離レベルの名前を返します。 86 func (i IsolationLevel) String() string 87 88 var _ fmt.Stringer = LevelDefault 89 90 // TxOptionsは、 [DB.BeginTx] で使用されるトランザクションオプションを保持します。 91 type TxOptions struct { 92 // Isolationはトランザクション分離レベルです。 93 // ゼロの場合、ドライバーまたはデータベースのデフォルトレベルが使用されます。 94 Isolation IsolationLevel 95 ReadOnly bool 96 } 97 98 // RawBytesは、データベース自体が所有するメモリへの参照を保持するバイトスライスです。 99 // RawBytesに対して [Rows.Scan] を実行した後、スライスは次の [Rows.Next]、[Rows.Scan]、または [Rows.Close] の呼び出しまでのみ有効です。 100 type RawBytes []byte 101 102 // NullStringは、nullである可能性がある文字列を表します。 103 // NullStringは [Scanner] インターフェースを実装するため、 104 // スキャン先として使用できます。 105 // 106 // var s NullString 107 // err := db.QueryRow("SELECT name FROM foo WHERE id=?", id).Scan(&s) 108 // ... 109 // if s.Valid { 110 // // use s.String 111 // } else { 112 // // NULL value 113 // } 114 type NullString struct { 115 String string 116 Valid bool 117 } 118 119 // Scanは [Scanner] インターフェースを実装します。 120 func (ns *NullString) Scan(value any) error 121 122 // Valueは、 [driver.Valuer] インターフェースを実装します。 123 func (ns NullString) Value() (driver.Value, error) 124 125 // NullInt64は、nullである可能性があるint64を表します。 126 // NullInt64はScannerインターフェースを実装するため、 127 // [NullString] と同様にスキャン先として使用できます。 128 type NullInt64 struct { 129 Int64 int64 130 Valid bool 131 } 132 133 // Scanは [Scanner] インターフェースを実装します。 134 func (n *NullInt64) Scan(value any) error 135 136 // Valueは、 [driver.Valuer] インターフェースを実装します。 137 func (n NullInt64) Value() (driver.Value, error) 138 139 // NullInt32は、nullである可能性があるint32を表します。 140 // NullInt32は [Scanner] インターフェースを実装するため、 141 // NullStringと同様にスキャン先として使用できます。 142 type NullInt32 struct { 143 Int32 int32 144 Valid bool 145 } 146 147 // Scanは [Scanner] インターフェースを実装します。 148 func (n *NullInt32) Scan(value any) error 149 150 // Valueは、 [driver.Valuer] インターフェースを実装します。 151 func (n NullInt32) Value() (driver.Value, error) 152 153 // NullInt16は、nullである可能性があるint16を表します。 154 // NullInt16は [Scanner] インターフェースを実装するため、 155 // [NullString] と同様にスキャン先として使用できます。 156 type NullInt16 struct { 157 Int16 int16 158 Valid bool 159 } 160 161 // Scanは [Scanner] インターフェースを実装します。 162 func (n *NullInt16) Scan(value any) error 163 164 // Valueは、 [driver.Valuer] インターフェースを実装します。 165 func (n NullInt16) Value() (driver.Value, error) 166 167 // NullByteは、nullである可能性があるバイトを表します。 168 // NullByteは [Scanner] インターフェースを実装するため、 169 // [NullString] と同様にスキャン先として使用できます。 170 type NullByte struct { 171 Byte byte 172 Valid bool 173 } 174 175 // Scanは [Scanner] インターフェースを実装します。 176 func (n *NullByte) Scan(value any) error 177 178 // Valueは、 [driver.Valuer] インターフェースを実装します。 179 func (n NullByte) Value() (driver.Value, error) 180 181 // NullFloat64は、nullである可能性があるfloat64を表します。 182 // NullFloat64は [Scanner] インターフェースを実装するため、 183 // [NullString] と同様にスキャン先として使用できます。 184 type NullFloat64 struct { 185 Float64 float64 186 Valid bool 187 } 188 189 // Scanは [Scanner] インターフェースを実装します。 190 func (n *NullFloat64) Scan(value any) error 191 192 // Valueは、 [driver.Valuer] インターフェースを実装します。 193 func (n NullFloat64) Value() (driver.Value, error) 194 195 // NullBoolは、nullである可能性があるboolを表します。 196 // NullBoolは [Scanner] インターフェースを実装するため、 197 // [NullString] と同様にスキャン先として使用できます。 198 type NullBool struct { 199 Bool bool 200 Valid bool 201 } 202 203 // Scanは [Scanner] インターフェースを実装します。 204 func (n *NullBool) Scan(value any) error 205 206 // Valueは、 [driver.Valuer] インターフェースを実装します。 207 func (n NullBool) Value() (driver.Value, error) 208 209 // NullTimeは、nullである可能性がある [time.Time] を表します。 210 // NullTimeは [Scanner] インターフェースを実装するため、 211 // [NullString] と同様にスキャン先として使用できます。 212 type NullTime struct { 213 Time time.Time 214 Valid bool 215 } 216 217 // Scanは [Scanner] インターフェースを実装します。 218 func (n *NullTime) Scan(value any) error 219 220 // Valueは、 [driver.Valuer] インターフェースを実装します。 221 func (n NullTime) Value() (driver.Value, error) 222 223 // Nullは、nullである可能性がある値を表します。 224 // Nullは [Scanner] インターフェースを実装するため、 225 // スキャン先として使用できます。 226 // 227 // var s Null[string] 228 // err := db.QueryRow("SELECT name FROM foo WHERE id=?", id).Scan(&s) 229 // ... 230 // if s.Valid { 231 // // use s.V 232 // } else { 233 // // NULL value 234 // } 235 type Null[T any] struct { 236 V T 237 Valid bool 238 } 239 240 func (n *Null[T]) Scan(value any) error 241 242 func (n Null[T]) Value() (driver.Value, error) 243 244 // Scanner is an interface used by [Rows.Scan]. 245 type Scanner interface { 246 Scan(src any) error 247 } 248 249 // Outは、ストアドプロシージャからOUTPUT値パラメータを取得するために使用できます。 250 // 251 // すべてのドライバーとデータベースがOUTPUT値パラメータをサポートしているわけではありません。 252 // 253 // 使用例: 254 // 255 // var outArg string 256 // _, err := db.ExecContext(ctx, "ProcName", sql.Named("Arg1", sql.Out{Dest: &outArg})) 257 type Out struct { 258 _NamedFieldsRequired struct{} 259 260 // Destは、ストアドプロシージャのOUTPUTパラメータの結果に設定される値へのポインタです。 261 Dest any 262 263 // Inは、パラメータがINOUTパラメータであるかどうかを示します。 264 // その場合、ストアドプロシージャへの入力値はDestのポインタの参照解除された値であり、 265 // その後、出力値で置き換えられます。 266 In bool 267 } 268 269 // ErrNoRowsは、 [DB.QueryRow] が行を返さない場合に [Row.Scan] によって返されます。 270 // そのような場合、QueryRowはプレースホルダー [*Row] 値を返し、 271 // このエラーはScanまで遅延されます。 272 var ErrNoRows = errors.New("sql: no rows in result set") 273 274 // DBは、ゼロ個以上の基礎接続を表すデータベースハンドルです。 275 // 複数のゴルーチンによる同時使用に対して安全です。 276 // 277 // sqlパッケージは、接続を自動的に作成および解放します。 278 // また、アイドル接続のフリープールを維持します。 279 // データベースが接続ごとの状態を持つ場合、そのような状態はトランザクション([Tx])または接続([Conn])内で信頼性が高く観察できます。 280 // [DB.Begin] が呼び出されると、返された [Tx] は単一の接続にバインドされます。 281 // [Tx.Commit] または [Tx.Rollback] が呼び出されると、そのトランザクションの接続が [DB] のアイドル接続プールに返されます。 282 // プールのサイズは [DB.SetMaxIdleConns] で制御できます。 283 type DB struct { 284 // Total time waited for new connections. 285 waitDuration atomic.Int64 286 287 connector driver.Connector 288 // numClosed is an atomic counter which represents a total number of 289 // closed connections. Stmt.openStmt checks it before cleaning closed 290 // connections in Stmt.css. 291 numClosed atomic.Uint64 292 293 mu sync.Mutex 294 freeConn []*driverConn 295 connRequests connRequestSet 296 numOpen int 297 // Used to signal the need for new connections 298 // a goroutine running connectionOpener() reads on this chan and 299 // maybeOpenNewConnections sends on the chan (one send per needed connection) 300 // It is closed during db.Close(). The close tells the connectionOpener 301 // goroutine to exit. 302 openerCh chan struct{} 303 closed bool 304 dep map[finalCloser]depSet 305 lastPut map[*driverConn]string 306 maxIdleCount int 307 maxOpen int 308 maxLifetime time.Duration 309 maxIdleTime time.Duration 310 cleanerCh chan struct{} 311 waitCount int64 312 maxIdleClosed int64 313 maxIdleTimeClosed int64 314 maxLifetimeClosed int64 315 316 stop func() 317 } 318 319 // OpenDBは、コネクタを使用してデータベースを開き、ドライバーが文字列ベースのデータソース名をバイパスできるようにします。 320 // 321 // ほとんどのユーザーは、 [*DB] を返すドライバー固有の接続ヘルパー関数を介してデータベースを開きます。 322 // Go標準ライブラリにはデータベースドライバーは含まれていません。サードパーティのドライバーのリストについては、https://golang.org/s/sqldrivers を参照してください。 323 // 324 // OpenDBは、データベースへの接続を作成せずに引数を検証する場合があります。 325 // データソース名が有効であることを確認するには、[DB.Ping] を呼び出します。 326 // 327 // 返された [DB] は、複数のゴルーチンによる同時使用に対して安全であり、アイドル接続のプールを維持します。 328 // したがって、OpenDB関数は1回だけ呼び出す必要があります。 [DB] を閉じる必要はほとんどありません。 329 func OpenDB(c driver.Connector) *DB 330 331 // Openは、データベースドライバー名とドライバー固有のデータソース名で指定されたデータベースを開きます。 332 // 通常、少なくともデータベース名と接続情報が含まれます。 333 // 334 // ほとんどのユーザーは、 [*DB] を返すドライバー固有の接続ヘルパー関数を介してデータベースを開きます。 335 // Go標準ライブラリにはデータベースドライバーは含まれていません。サードパーティのドライバーのリストについては、https://golang.org/s/sqldrivers を参照してください。 336 // 337 // Openは、データベースへの接続を作成せずに引数を検証する場合があります。 338 // データソース名が有効であることを確認するには、[DB.Ping] を呼び出します。 339 // 340 // 返された [DB] は、複数のゴルーチンによる同時使用に対して安全であり、アイドル接続のプールを維持します。 341 // したがって、Open関数は1回だけ呼び出す必要があります。 [DB] を閉じる必要はほとんどありません。 342 func Open(driverName, dataSourceName string) (*DB, error) 343 344 // PingContextは、データベースへの接続がまだ有効であることを確認し、必要に応じて接続を確立します。 345 func (db *DB) PingContext(ctx context.Context) error 346 347 // Pingは、データベースへの接続がまだ有効であることを確認し、必要に応じて接続を確立します。 348 // 349 // Pingは、内部的に [context.Background] を使用します。コンテキストを指定するには、 [DB.PingContext] を使用してください。 350 func (db *DB) Ping() error 351 352 // Closeはデータベースを閉じ、新しいクエリの開始を防止します。 353 // Closeは、サーバーで処理を開始したすべてのクエリが完了するのを待ってから終了します。 354 // 355 // [DB] ハンドルは長期間生存し、多くのゴルーチンで共有されることを意図しているため、 [DB] をCloseすることはまれです。 356 func (db *DB) Close() error 357 358 // SetMaxIdleConnsは、アイドル接続プール内の最大接続数を設定します。 359 // 360 // MaxOpenConnsが0より大きく、新しいMaxIdleConnsより小さい場合、 361 // 新しいMaxIdleConnsはMaxOpenConnsの制限に合わせて減少します。 362 // 363 // n <= 0の場合、アイドル接続は保持されません。 364 // 365 // デフォルトの最大アイドル接続数は現在2です。将来のリリースで変更される可能性があります。 366 func (db *DB) SetMaxIdleConns(n int) 367 368 // SetMaxOpenConnsは、データベースへの最大オープン接続数を設定します。 369 // 370 // MaxIdleConnsが0より大きく、新しいMaxOpenConnsより小さい場合、 371 // 新しいMaxIdleConnsはMaxOpenConnsの制限に合わせて減少します。 372 // 373 // n <= 0の場合、オープン接続数に制限はありません。 374 // デフォルトは0(無制限)です。 375 func (db *DB) SetMaxOpenConns(n int) 376 377 // SetConnMaxLifetimeは、接続が再利用される最大時間を設定します。 378 // 379 // 期限切れの接続は再利用前に遅延して閉じることができます。 380 // 381 // d <= 0の場合、接続の年齢により接続が閉じられることはありません。 382 func (db *DB) SetConnMaxLifetime(d time.Duration) 383 384 // SetConnMaxIdleTimeは、接続がアイドル状態になっている最大時間を設定します。 385 // 386 // 期限切れの接続は再利用前に遅延して閉じることができます。 387 // 388 // d <= 0の場合、接続のアイドル時間により接続が閉じられることはありません。 389 func (db *DB) SetConnMaxIdleTime(d time.Duration) 390 391 // DBStatsには、データベースの統計情報が含まれます。 392 type DBStats struct { 393 MaxOpenConnections int 394 395 // Pool Status 396 OpenConnections int 397 InUse int 398 Idle int 399 400 // Counters 401 WaitCount int64 402 WaitDuration time.Duration 403 MaxIdleClosed int64 404 MaxIdleTimeClosed int64 405 MaxLifetimeClosed int64 406 } 407 408 // Statsは、データベースの統計情報を返します。 409 func (db *DB) Stats() DBStats 410 411 // PrepareContextは、後でのクエリまたは実行のためにプリペアドステートメントを作成します。 412 // 返されたステートメントから複数のクエリまたは実行を同時に実行できます。 413 // ステートメントが不要になったら、呼び出し元はステートメントの [*Stmt.Close] メソッドを呼び出す必要があります。 414 // 415 // 提供されたコンテキストは、ステートメントの実行ではなく、ステートメントの準備に使用されます。 416 func (db *DB) PrepareContext(ctx context.Context, query string) (*Stmt, error) 417 418 // Prepareは、後でのクエリまたは実行のためにプリペアドステートメントを作成します。 419 // 返されたステートメントから複数のクエリまたは実行を同時に実行できます。 420 // ステートメントが不要になったら、呼び出し元はステートメントの [*Stmt.Close] メソッドを呼び出す必要があります。 421 // 422 // Prepareは、内部的に [context.Background] を使用します。コンテキストを指定するには、 [DB.PrepareContext] を使用してください。 423 func (db *DB) Prepare(query string) (*Stmt, error) 424 425 // ExecContextは、行を返さないクエリを実行します。 426 // argsは、クエリ内のプレースホルダーパラメーター用です。 427 func (db *DB) ExecContext(ctx context.Context, query string, args ...any) (Result, error) 428 429 // Execは、行を返さないクエリを実行します。 430 // argsは、クエリ内のプレースホルダーパラメーター用です。 431 // 432 // Execは、内部的に [context.Background] を使用します。コンテキストを指定するには、 [DB.ExecContext] を使用してください。 433 func (db *DB) Exec(query string, args ...any) (Result, error) 434 435 // QueryContextは、通常はSELECTで返される行を返すクエリを実行します。 436 // argsは、クエリ内のプレースホルダーパラメーター用です。 437 func (db *DB) QueryContext(ctx context.Context, query string, args ...any) (*Rows, error) 438 439 // QueryContextは、通常はSELECTで返される行を返すクエリを実行します。 440 // argsは、クエリ内のプレースホルダーパラメーター用です。 441 // 442 // QueryContextは、内部的に [context.Background] を使用します。コンテキストを指定するには、 [DB.QueryContext] を使用してください。 443 func (db *DB) Query(query string, args ...any) (*Rows, error) 444 445 // QueryRowContextは、最大1行を返すと予想されるクエリを実行します。 446 // QueryRowContextは常にnil以外の値を返します。エラーは [Row] のScanメソッドが呼び出されるまで遅延されます。 447 // クエリが行を選択しない場合、[*Row.Scan] は [ErrNoRows] を返します。 448 // そうでない場合、[*Row.Scan] は最初に選択された行をスキャンし、残りを破棄します。 449 func (db *DB) QueryRowContext(ctx context.Context, query string, args ...any) *Row 450 451 // QueryRowは、最大1行を返すと予想されるクエリを実行します。 452 // QueryRowは常にnil以外の値を返します。エラーは [Row] のScanメソッドが呼び出されるまで遅延されます。 453 // クエリが行を選択しない場合、[*Row.Scan] は [ErrNoRows] を返します。 454 // そうでない場合、[*Row.Scan] は最初に選択された行をスキャンし、残りを破棄します。 455 // 456 // QueryRowは、内部的に [context.Background] を使用します。コンテキストを指定するには、 [DBQueryRowContext] を使用してください。 457 func (db *DB) QueryRow(query string, args ...any) *Row 458 459 // BeginTxはトランザクションを開始します。 460 // 461 // 提供されたコンテキストは、トランザクションがコミットまたはロールバックされるまで使用されます。 462 // コンテキストがキャンセルされると、sqlパッケージはトランザクションをロールバックします。 463 // BeginTxに提供されたコンテキストがキャンセルされた場合、 [Tx.Commit] はエラーを返します。 464 // 465 // 提供された [TxOptions] はオプションであり、デフォルトを使用する場合はnilにすることができます。 466 // ドライバーがサポートしていない非デフォルトの分離レベルが使用された場合、エラーが返されます。 467 func (db *DB) BeginTx(ctx context.Context, opts *TxOptions) (*Tx, error) 468 469 // Beginはトランザクションを開始します。デフォルトの分離レベルはドライバーに依存します。 470 // 471 // Beginは、内部的に [context.Background] を使用します。コンテキストを指定するには、 [DB.BeginTx] を使用してください。 472 func (db *DB) Begin() (*Tx, error) 473 474 // Driverは、データベースの基礎となるドライバーを返します。 475 func (db *DB) Driver() driver.Driver 476 477 // ErrConnDoneは、接続プールに返された接続で実行された操作によって返されます。 478 var ErrConnDone = errors.New("sql: connection is already closed") 479 480 // Connは、新しい接続を開くか、接続プールから既存の接続を返して、単一の接続を返します。 481 // Connは、接続が返されるか、ctxがキャンセルされるまでブロックされます。 482 // 同じConnで実行されるクエリは、同じデータベースセッションで実行されます。 483 // 484 // 各Connは、 [Conn.Close] を呼び出して使用後にデータベースプールに返す必要があります。 485 func (db *DB) Conn(ctx context.Context) (*Conn, error) 486 487 // Connは、データベース接続プールではなく、単一のデータベース接続を表します。 488 // 特定の理由がない限り、クエリは [DB] から実行することをお勧めします。 489 // 490 // Connは、 [Conn.Close] を呼び出して接続をデータベースプールに返す必要があります。 491 // また、実行中のクエリと同時に呼び出すことができます。 492 // 493 // [Conn.Close] の呼び出し後、接続に対するすべての操作は [ErrConnDone] で失敗します。 494 type Conn struct { 495 db *DB 496 497 // closemu prevents the connection from closing while there 498 // is an active query. It is held for read during queries 499 // and exclusively during close. 500 closemu sync.RWMutex 501 502 // dc is owned until close, at which point 503 // it's returned to the connection pool. 504 dc *driverConn 505 506 // done transitions from false to true exactly once, on close. 507 // Once done, all operations fail with ErrConnDone. 508 done atomic.Bool 509 510 releaseConnOnce sync.Once 511 // releaseConnCache is a cache of c.closemuRUnlockCondReleaseConn 512 // to save allocations in a call to grabConn. 513 releaseConnCache releaseConn 514 } 515 516 // PingContextは、データベースへの接続がまだ有効であることを確認します。 517 func (c *Conn) PingContext(ctx context.Context) error 518 519 // ExecContextは、行を返さないクエリを実行します。 520 // argsは、クエリ内のプレースホルダーパラメーター用です。 521 func (c *Conn) ExecContext(ctx context.Context, query string, args ...any) (Result, error) 522 523 // QueryContextは、通常はSELECTで返される行を返すクエリを実行します。 524 // argsは、クエリ内のプレースホルダーパラメーター用です。 525 func (c *Conn) QueryContext(ctx context.Context, query string, args ...any) (*Rows, error) 526 527 // QueryRowContextは、最大1行を返すと予想されるクエリを実行します。 528 // QueryRowContextは常にnil以外の値を返します。エラーは [*Row.Scan] メソッドが呼び出されるまで遅延されます。 529 // クエリが行を選択しない場合、[*Row.Scan] は [ErrNoRows] を返します。 530 // そうでない場合、[*Row.Scan] は最初に選択された行をスキャンし、残りを破棄します。 531 func (c *Conn) QueryRowContext(ctx context.Context, query string, args ...any) *Row 532 533 // PrepareContextは、後でのクエリまたは実行のためにプリペアドステートメントを作成します。 534 // 返されたステートメントから複数のクエリまたは実行を同時に実行できます。 535 // ステートメントが不要になったら、呼び出し元はステートメントの [*Stmt.Close] メソッドを呼び出す必要があります。 536 // 537 // 提供されたコンテキストは、ステートメントの実行ではなく、ステートメントの準備に使用されます。 538 func (c *Conn) PrepareContext(ctx context.Context, query string) (*Stmt, error) 539 540 // Rawは、fを実行し、fの実行中に基礎となるドライバー接続を公開します。 541 // driverConnは、fの外部で使用してはいけません。 542 // 543 // fが返り、errが [driver.ErrBadConn] でない場合、 [Conn] は [Conn.Close] が呼び出されるまで使用可能です。 544 func (c *Conn) Raw(f func(driverConn any) error) (err error) 545 546 // BeginTxはトランザクションを開始します。 547 // 548 // 提供されたコンテキストは、トランザクションがコミットまたはロールバックされるまで使用されます。 549 // コンテキストがキャンセルされると、sqlパッケージはトランザクションをロールバックします。 550 // BeginTxに提供されたコンテキストがキャンセルされた場合、 [Tx.Commit] はエラーを返します。 551 // 552 // 提供された [TxOptions] はオプションであり、デフォルトを使用する場合はnilにすることができます。 553 // ドライバーがサポートしていない非デフォルトの分離レベルが使用された場合、エラーが返されます。 554 func (c *Conn) BeginTx(ctx context.Context, opts *TxOptions) (*Tx, error) 555 556 // Closeは、接続を接続プールに返します。 557 // Closeの後に行われたすべての操作は、 [ErrConnDone] で返されます。 558 // Closeは、他の操作と同時に安全に呼び出すことができ、 559 // すべての他の操作が完了するまでブロックされます。 560 // 使用されたコンテキストを最初にキャンセルしてから直接Closeを呼び出すことが役立つ場合があります。 561 func (c *Conn) Close() error 562 563 // Txは、進行中のデータベーストランザクションです。 564 // 565 // トランザクションは、 [Tx.Commit] または [Tx.Rollback] の呼び出しで終了する必要があります。 566 // 567 // [Tx.Commit] または [Tx.Rollback] の呼び出し後、トランザクション上のすべての操作は [ErrTxDone] で失敗します。 568 // 569 // トランザクションの [Tx.Prepare] または [Tx.Stmt] メソッドを呼び出して準備されたステートメントは、 [Tx.Commit] または [Tx.Rollback] の呼び出しで閉じられます。 570 type Tx struct { 571 db *DB 572 573 // closemu prevents the transaction from closing while there 574 // is an active query. It is held for read during queries 575 // and exclusively during close. 576 closemu sync.RWMutex 577 578 // dc is owned exclusively until Commit or Rollback, at which point 579 // it's returned with putConn. 580 dc *driverConn 581 txi driver.Tx 582 583 // releaseConn is called once the Tx is closed to release 584 // any held driverConn back to the pool. 585 releaseConn func(error) 586 587 // done transitions from false to true exactly once, on Commit 588 // or Rollback. once done, all operations fail with 589 // ErrTxDone. 590 done atomic.Bool 591 592 // keepConnOnRollback is true if the driver knows 593 // how to reset the connection's session and if need be discard 594 // the connection. 595 keepConnOnRollback bool 596 597 // All Stmts prepared for this transaction. These will be closed after the 598 // transaction has been committed or rolled back. 599 stmts struct { 600 sync.Mutex 601 v []*Stmt 602 } 603 604 // cancel is called after done transitions from 0 to 1. 605 cancel func() 606 607 // ctx lives for the life of the transaction. 608 ctx context.Context 609 } 610 611 // ErrTxDoneは、すでにコミットまたはロールバックされたトランザクションに対して実行された操作によって返されます。 612 var ErrTxDone = errors.New("sql: transaction has already been committed or rolled back") 613 614 // Commitはトランザクションをコミットします。 615 func (tx *Tx) Commit() error 616 617 // Rollbackはトランザクションを中止します。 618 func (tx *Tx) Rollback() error 619 620 // PrepareContextは、トランザクション内で使用するためのプリペアドステートメントを作成します。 621 // 622 // 返されたステートメントはトランザクション内で動作し、トランザクションがコミットまたはロールバックされたときに閉じられます。 623 // 624 // このトランザクションで既存のプリペアドステートメントを使用するには、 [Tx.Stmt] を参照してください。 625 // 626 // 提供されたコンテキストは、ステートメントの実行ではなく、ステートメントの準備に使用されます。 627 // 返されたステートメントはトランザクションコンテキストで実行されます。 628 func (tx *Tx) PrepareContext(ctx context.Context, query string) (*Stmt, error) 629 630 // Prepareは、トランザクション内で使用するためのプリペアドステートメントを作成します。 631 // 632 // 返されたステートメントはトランザクション内で動作し、トランザクションがコミットまたはロールバックされたときに閉じられます。 633 // 634 // このトランザクションで既存のプリペアドステートメントを使用するには、 [Tx.Stmt] を参照してください。 635 // 636 // Prepareは、内部的に [context.Background] を使用します。コンテキストを指定するには、 [Tx.PrepareContext] を使用してください。 637 func (tx *Tx) Prepare(query string) (*Stmt, error) 638 639 // StmtContextは、既存のステートメントからトランザクション固有のプリペアドステートメントを返します。 640 // 641 // 例: 642 // 643 // updateMoney, err := db.Prepare("UPDATE balance SET money=money+? WHERE id=?") 644 // ... 645 // tx, err := db.Begin() 646 // ... 647 // res, err := tx.StmtContext(ctx, updateMoney).Exec(123.45, 98293203) 648 // 649 // 提供されたコンテキストはステートメントの実行ではなく、ステートメントの準備に使用されます。 650 // 651 // 返されたステートメントはトランザクション内で動作し、トランザクションがコミットまたはロールバックされたときに閉じられます。 652 func (tx *Tx) StmtContext(ctx context.Context, stmt *Stmt) *Stmt 653 654 // Stmtは、既存のステートメントからトランザクション固有のプリペアドステートメントを返します。 655 // 656 // 例: 657 // 658 // updateMoney, err := db.Prepare("UPDATE balance SET money=money+? WHERE id=?") 659 // ... 660 // tx, err := db.Begin() 661 // ... 662 // res, err := tx.Stmt(updateMoney).Exec(123.45, 98293203) 663 // 664 // 返されたステートメントはトランザクション内で動作し、トランザクションがコミットまたはロールバックされたときに閉じられます。 665 // 666 // Stmtは、内部的に [context.Background] を使用します。コンテキストを指定するには、 [Tx.StmtContext] を使用してください。 667 func (tx *Tx) Stmt(stmt *Stmt) *Stmt 668 669 // ExecContextは、行を返さないクエリを実行します。 670 // 例えば、INSERTやUPDATEです。 671 func (tx *Tx) ExecContext(ctx context.Context, query string, args ...any) (Result, error) 672 673 // Execは、行を返さないクエリを実行します。 674 // 例えば、INSERTやUPDATEです。 675 // 676 // Execは、内部的に [context.Background] を使用します。コンテキストを指定するには、 [Tx.ExecContext] を使用してください。 677 func (tx *Tx) Exec(query string, args ...any) (Result, error) 678 679 // QueryContext executes a query that returns rows, typically a SELECT. 680 func (tx *Tx) QueryContext(ctx context.Context, query string, args ...any) (*Rows, error) 681 682 // Queryは、通常はSELECTで返される行を返すクエリを実行します。 683 // 684 // Queryは、内部的に [context.Background] を使用します。コンテキストを指定するには、 [Tx.QueryContext] を使用してください。 685 func (tx *Tx) Query(query string, args ...any) (*Rows, error) 686 687 // QueryRowContextは、最大1行を返すと予想されるクエリを実行します。 688 // QueryRowContextは常にnil以外の値を返します。エラーは [Row] のScanメソッドが呼び出されるまで遅延されます。 689 // クエリが行を選択しない場合、[*Row.Scan] は [ErrNoRows] を返します。 690 // そうでない場合、[*Row.Scan] は最初に選択された行をスキャンし、残りを破棄します。 691 func (tx *Tx) QueryRowContext(ctx context.Context, query string, args ...any) *Row 692 693 // QueryRowは、最大1行を返すと予想されるクエリを実行します。 694 // QueryRowは常にnil以外の値を返します。エラーは [Row] のScanメソッドが呼び出されるまで遅延されます。 695 // クエリが行を選択しない場合、[*Row.Scan] は [ErrNoRows] を返します。 696 // そうでない場合、[*Row.Scan] は最初に選択された行をスキャンし、残りを破棄します。 697 // 698 // QueryRowは、内部的に [context.Background] を使用します。コンテキストを指定するには、 [Tx.QueryRowContext] を使用してください。 699 func (tx *Tx) QueryRow(query string, args ...any) *Row 700 701 var ( 702 _ stmtConnGrabber = &Tx{} 703 _ stmtConnGrabber = &Conn{} 704 ) 705 706 // Stmtは、プリペアドステートメントです。 707 // Stmtは、複数のゴルーチンによる同時使用に対して安全です。 708 // 709 // Stmtが [Tx] または [Conn] で準備された場合、それは1つの基礎となる接続に永久にバインドされます。 710 // [Tx] または [Conn] が閉じられると、Stmtは使用できなくなり、すべての操作がエラーを返します。 711 // Stmtが [DB] で準備された場合、それは [DB] の寿命の間使用可能です。 712 // Stmtが新しい基礎となる接続で実行する必要がある場合、自動的に新しい接続で自己準備します。 713 type Stmt struct { 714 // Immutable: 715 db *DB 716 query string 717 stickyErr error 718 719 closemu sync.RWMutex 720 721 // If Stmt is prepared on a Tx or Conn then cg is present and will 722 // only ever grab a connection from cg. 723 // If cg is nil then the Stmt must grab an arbitrary connection 724 // from db and determine if it must prepare the stmt again by 725 // inspecting css. 726 cg stmtConnGrabber 727 cgds *driverStmt 728 729 // parentStmt is set when a transaction-specific statement 730 // is requested from an identical statement prepared on the same 731 // conn. parentStmt is used to track the dependency of this statement 732 // on its originating ("parent") statement so that parentStmt may 733 // be closed by the user without them having to know whether or not 734 // any transactions are still using it. 735 parentStmt *Stmt 736 737 mu sync.Mutex 738 closed bool 739 740 // css is a list of underlying driver statement interfaces 741 // that are valid on particular connections. This is only 742 // used if cg == nil and one is found that has idle 743 // connections. If cg != nil, cgds is always used. 744 css []connStmt 745 746 // lastNumClosed is copied from db.numClosed when Stmt is created 747 // without tx and closed connections in css are removed. 748 lastNumClosed uint64 749 } 750 751 // ExecContextは、指定された引数を使用してプリペアドステートメントを実行し、 752 // ステートメントの影響を要約する [Result] を返します。 753 func (s *Stmt) ExecContext(ctx context.Context, args ...any) (Result, error) 754 755 // Execは、指定された引数を使用してプリペアドステートメントを実行し、 756 // ステートメントの影響を要約する [Result] を返します。 757 // 758 // Execは、内部的に [context.Background] を使用します。コンテキストを指定するには、 [Stmt.ExecContext] を使用してください。 759 func (s *Stmt) Exec(args ...any) (Result, error) 760 761 // QueryContextは、指定された引数を使用してプリペアドクエリステートメントを実行し、 762 // クエリ結果を [*Rows] として返します。 763 func (s *Stmt) QueryContext(ctx context.Context, args ...any) (*Rows, error) 764 765 // Queryは、指定された引数を使用してプリペアドクエリステートメントを実行し、 766 // クエリ結果を*Rowsとして返します。 767 // 768 // Queryは、内部的に [context.Background] を使用します。コンテキストを指定するには、 [Stmt.QueryContext] を使用してください。 769 func (s *Stmt) Query(args ...any) (*Rows, error) 770 771 // QueryRowContextは、指定された引数を使用してプリペアドクエリステートメントを実行し、 772 // ステートメントの実行中にエラーが発生した場合、そのエラーは常にnil以外の [*Row] のScan呼び出しによって返されます。 773 // クエリが行を選択しない場合、[*Row.Scan] は [ErrNoRows] を返します。 774 // そうでない場合、[*Row.Scan] は最初に選択された行をスキャンし、残りを破棄します。 775 func (s *Stmt) QueryRowContext(ctx context.Context, args ...any) *Row 776 777 // QueryRowは、指定された引数を使用してプリペアドクエリステートメントを実行し、 778 // ステートメントの実行中にエラーが発生した場合、そのエラーは常にnil以外の [*Row] のScan呼び出しによって返されます。 779 // クエリが行を選択しない場合、[*Row.Scan] は [ErrNoRows] を返します。 780 // そうでない場合、[*Row.Scan] のScanは最初に選択された行をスキャンし、残りを破棄します。 781 // 782 // 使用例: 783 // 784 // var name string 785 // err := nameByUseridStmt.QueryRow(id).Scan(&name) 786 // 787 // QueryRowは、内部的に [context.Background] を使用します。コンテキストを指定するには、 [Stmt.QueryRowContext] を使用してください。 788 func (s *Stmt) QueryRow(args ...any) *Row 789 790 // Closeはステートメントを閉じます。 791 func (s *Stmt) Close() error 792 793 // Rowsはクエリの結果です。そのカーソルは、結果セットの最初の行の前に開始します。 794 // 行から行に進むには、 [Rows.Next] を使用してください。 795 type Rows struct { 796 dc *driverConn 797 releaseConn func(error) 798 rowsi driver.Rows 799 cancel func() 800 closeStmt *driverStmt 801 802 contextDone atomic.Pointer[error] 803 804 // closemu prevents Rows from closing while there 805 // is an active streaming result. It is held for read during non-close operations 806 // and exclusively during close. 807 // 808 // closemu guards lasterr and closed. 809 closemu sync.RWMutex 810 closed bool 811 lasterr error 812 813 // lastcols is only used in Scan, Next, and NextResultSet which are expected 814 // not to be called concurrently. 815 lastcols []driver.Value 816 817 // closemuScanHold is whether the previous call to Scan kept closemu RLock'ed 818 // without unlocking it. It does that when the user passes a *RawBytes scan 819 // target. In that case, we need to prevent awaitDone from closing the Rows 820 // while the user's still using the memory. See go.dev/issue/60304. 821 // 822 // It is only used by Scan, Next, and NextResultSet which are expected 823 // not to be called concurrently. 824 closemuScanHold bool 825 826 // hitEOF is whether Next hit the end of the rows without 827 // encountering an error. It's set in Next before 828 // returning. It's only used by Next and Err which are 829 // expected not to be called concurrently. 830 hitEOF bool 831 } 832 833 // Nextは、 [Rows.Scan] メソッドで読み取る次の結果行を準備します。 834 // 成功した場合はtrue、次の結果行がない場合や準備中にエラーが発生した場合はfalseを返します。 835 // 2つの場合を区別するには、 [Rows.Err] を参照する必要があります。 836 // 837 // 最初の呼び出しを含め、すべての [Rows.Scan] 呼び出しは、 [Rows.Next] の呼び出しに先立っている必要があります。 838 func (rs *Rows) Next() bool 839 840 // NextResultSetは、次の結果セットの読み取りの準備をします。 841 // さらに結果セットがある場合はtrue、それ以外の場合はfalseを報告します。 842 // または、それに進む際にエラーが発生した場合はfalseを報告します。 843 // 2つの場合を区別するには、 [Rows.Err] を参照する必要があります。 844 // 845 // NextResultSetを呼び出した後、スキャンする前に常に [Rows.Next] メソッドを呼び出す必要があります。 846 // さらに結果セットがある場合、結果セットに行がない場合があります。 847 func (rs *Rows) NextResultSet() bool 848 849 // Errは、反復中に遭遇したエラー(ある場合)を返します。 850 // 明示的または暗黙的な [Rows.Close] の後にErrを呼び出すことができます。 851 func (rs *Rows) Err() error 852 853 // Columnsは列名を返します。 854 // Rowsが閉じられている場合、Columnsはエラーを返します。 855 func (rs *Rows) Columns() ([]string, error) 856 857 // ColumnTypesは、列の型、長さ、null可能性などの列情報を返します。 858 // 一部の情報は、一部のドライバから利用できない場合があります。 859 func (rs *Rows) ColumnTypes() ([]*ColumnType, error) 860 861 // ColumnTypeは、列の名前と型を含みます。 862 type ColumnType struct { 863 name string 864 865 hasNullable bool 866 hasLength bool 867 hasPrecisionScale bool 868 869 nullable bool 870 length int64 871 databaseType string 872 precision int64 873 scale int64 874 scanType reflect.Type 875 } 876 877 // Nameは、列の名前またはエイリアスを返します。 878 func (ci *ColumnType) Name() string 879 880 // Lengthは、テキストやバイナリフィールドタイプなどの可変長カラムタイプのためのカラムタイプ長を返します。 881 // タイプ長が無制限の場合、値は [math.MaxInt64] になります(データベースの制限は引き続き適用されます)。 882 // カラムタイプが可変長でない場合、例えばintの場合、またはドライバでサポートされていない場合、okはfalseになります。 883 func (ci *ColumnType) Length() (length int64, ok bool) 884 885 // DecimalSizeは、10進数型のスケールと精度を返します。 886 // 適用できない場合やサポートされていない場合は、okがfalseになります。 887 func (ci *ColumnType) DecimalSize() (precision, scale int64, ok bool) 888 889 // ScanTypeは、 [Rows.Scan] を使用してスキャンするために適したGo型を返します。 890 // ドライバがこのプロパティをサポートしていない場合、ScanTypeは空のインターフェースの型を返します。 891 func (ci *ColumnType) ScanType() reflect.Type 892 893 // Nullableは、列がnullである可能性があるかどうかを報告します。 894 // ドライバがこのプロパティをサポートしていない場合、okはfalseになります。 895 func (ci *ColumnType) Nullable() (nullable, ok bool) 896 897 // DatabaseTypeNameは、列のデータベースシステム名を返します。 898 // 空の文字列が返された場合、ドライバの型名はサポートされていません。 899 // ドライバのデータ型のリストについては、ドライバのドキュメントを参照してください。 900 // [ColumnType.Length] 指定子は含まれません。 901 // 一般的な型名には、"VARCHAR"、"TEXT"、"NVARCHAR"、"DECIMAL"、"BOOL"、"INT"、"BIGINT"があります。 902 func (ci *ColumnType) DatabaseTypeName() string 903 904 // Scanは、現在の行の列をdestが指す値にコピーします。 905 // destの数は [Rows] の列数と同じでなければなりません。 906 // 907 // Scanは、データベースから読み取った列を、以下の共通のGoの型およびsqlパッケージで提供される特殊な型に変換します。 908 // 909 // *string 910 // *[]byte 911 // *int, *int8, *int16, *int32, *int64 912 // *uint, *uint8, *uint16, *uint32, *uint64 913 // *bool 914 // *float32, *float64 915 // *interface{} 916 // *RawBytes 917 // *Rows (カーソル値) 918 // Scanner を実装する任意の型(Scannerドキュメントを参照) 919 // 920 // 最も単純な場合、ソース列の値の型が整数、ブール、または文字列型Tで、destが型*Tの場合、Scanは単にポインタを介して値を割り当てます。 921 // 922 // Scanは、文字列と数値型の間でも変換しますが、情報が失われない場合に限ります。Scanは、数値データベース列からスキャンされたすべての数値を*stringに文字列化しますが、数値型へのスキャンはオーバーフローのチェックが行われます。例えば、値が300のfloat64または値が"300"の文字列はuint16にスキャンできますが、uint8にはスキャンできません。ただし、float64(255)または"255"はuint8にスキャンできます。一部のfloat64数値を文字列に変換するスキャンは、文字列化すると情報が失われる場合があります。一般的には、浮動小数点列を*float64にスキャンします。 923 // 924 // dest引数の型が*[]byteの場合、Scanは対応するデータのコピーをその引数に保存します。コピーは呼び出し元が所有し、修正して無期限に保持できます。コピーを回避するには、代わりに [*RawBytes] の引数を使用します。[RawBytes] の使用制限については、 [RawBytes] のドキュメントを参照してください。 925 // 926 // 引数の型が*interface{}の場合、Scanは変換せずに基礎ドライバが提供する値をコピーします。[]byte型のソース値から*interface{}にスキャンする場合、スライスのコピーが作成され、呼び出し元が結果を所有します。 927 // 928 // [time.Time] 型のソース値は、*time.Time、*interface{}、*string、または*[]byte型の値にスキャンできます。後者2つに変換する場合、[time.RFC3339Nano] が使用されます。 929 // 930 // bool型のソース値は、*bool、*interface{}、*string、*[]byte、または [*RawBytes] 型にスキャンできます。 931 // 932 // *boolにスキャンする場合、ソースはtrue、false、1、0、または [strconv.ParseBool] で解析可能な文字列入力である必要があります。 933 // 934 // Scanは、クエリから返されたカーソル(例:"select cursor(select * from my_table) from dual")を、自体からスキャンできる [*Rows] 値に変換できます。親の [*Rows] が閉じられると、親の選択クエリはカーソル [*Rows] を閉じます。 935 // 936 // 最初の引数のいずれかがエラーを返す [Scanner] を実装している場合、そのエラーは返されたエラーにラップされます。 937 func (rs *Rows) Scan(dest ...any) error 938 939 // Closeは、 [Rows] を閉じ、以降の列挙を防止します。 940 // [Rows.Next] がfalseを返し、さらに結果セットがない場合、 [Rows] は自動的に閉じられ、 [Rows.Err] の結果を確認するだけで十分です。 941 // Closeは冪等性があり、 [Rows.Err] の結果に影響を与えません。 942 func (rs *Rows) Close() error 943 944 // Rowは、単一の行を選択するために [DB.QueryRow] を呼び出した結果です。 945 type Row struct { 946 // One of these two will be non-nil: 947 err error 948 rows *Rows 949 } 950 951 // Scanは、一致する行から列をdestが指す値にコピーします。 952 // 詳細については、 [Rows.Scan] のドキュメントを参照してください。 953 // クエリに複数の行が一致する場合、Scanは最初の行を使用し、残りを破棄します。 954 // クエリに一致する行がない場合、Scanは [ErrNoRows] を返します。 955 func (r *Row) Scan(dest ...any) error 956 957 // Errは、 [Row.Scan] を呼び出さずにクエリエラーをチェックするための方法を提供します。 958 // Errは、クエリを実行する際に遭遇したエラー(ある場合)を返します。 959 // このエラーがnilでない場合、このエラーは [Row.Scan] からも返されます。 960 func (r *Row) Err() error 961 962 // Resultは、実行されたSQLコマンドを要約します。 963 type Result interface { 964 LastInsertId() (int64, error) 965 966 RowsAffected() (int64, error) 967 }