( connectionOptions: Mysql.ConnectionOptions, conn: Mysql.PoolConnection, permit: Semaphore.Semaphore, sql: string, params?: ReadonlyArray<any> )
| 620 | } |
| 621 | |
| 622 | function queryStream( |
| 623 | connectionOptions: Mysql.ConnectionOptions, |
| 624 | conn: Mysql.PoolConnection, |
| 625 | permit: Semaphore.Semaphore, |
| 626 | sql: string, |
| 627 | params?: ReadonlyArray<any> |
| 628 | ) { |
| 629 | return asyncPauseResume<any, SqlError>(Effect.fnUntraced(function*(emit) { |
| 630 | const statement = new ActiveStatement(connectionOptions, conn) |
| 631 | let query: any |
| 632 | // The permit is returned as soon as the statement settles, because the |
| 633 | // consumer may run its own statements on this connection before the |
| 634 | // stream ends. When the stream is cancelled, it is kept until the statement |
| 635 | // has been killed and seen to settle. |
| 636 | let owned = true |
| 637 | const release = Effect.suspend(() => { |
| 638 | if (!owned) return Effect.void |
| 639 | owned = false |
| 640 | return permit.release(1) |
| 641 | }) |
| 642 | // Taking the permit also installs the cleanup, so once the command starts |
| 643 | // below there is no point at which interruption could leave it running. |
| 644 | yield* Effect.acquireRelease( |
| 645 | permit.take(1), |
| 646 | () => |
| 647 | Effect.ensuring( |
| 648 | Effect.suspend(() => { |
| 649 | if (query === undefined) return Effect.void |
| 650 | // Destroying the stream resumes a paused connection, so the |
| 651 | // remaining rows are read and discarded while the statement is |
| 652 | // killed. Rows that were already buffered are replayed |
| 653 | // synchronously and can settle the statement before `destroy` |
| 654 | // returns, in which case nothing is killed. |
| 655 | query.destroy() |
| 656 | return statement.cancel |
| 657 | }), |
| 658 | release |
| 659 | ), |
| 660 | { interruptible: true } |
| 661 | ) |
| 662 | const command = (conn as any).query(sql, params) |
| 663 | query = command.stream() |
| 664 | // The command, unlike its stream, reports when the server is done with the |
| 665 | // statement, even after the stream has been destroyed. |
| 666 | const settle = () => { |
| 667 | if (statement.settle()) Effect.runSync(release) |
| 668 | } |
| 669 | command.once("end", settle) |
| 670 | command.once("error", settle) |
| 671 | |
| 672 | let buffer: Array<any> = [] |
| 673 | let taskPending = false |
| 674 | query.on( |
| 675 | "error", |
| 676 | (cause: unknown) => |
| 677 | emit.fail(new SqlError({ reason: classifyError(cause, "Failed to stream statement", "stream") })) |
| 678 | ) |
| 679 | query.on("data", (row: any) => { |
no test coverage detected