* Prepared statements for one connection, keyed by result format, parameter * OIDs, and SQL text. Text-format runs are keyed separately because cached * descriptions hold format-specific column readers. * * The cache is bounded and evicts least-recently-used. An evicted statement is * closed on
| 1475 | * out rather than taking a round trip of its own. |
| 1476 | */ |
| 1477 | class PreparedCache { |
| 1478 | readonly max: number |
| 1479 | private readonly statements = new Map<string, Prepared>() |
| 1480 | private readonly namespace = randomBytes(8).toString("hex") |
| 1481 | private closes: Array<Uint8Array> | undefined |
| 1482 | private counter = 0 |
| 1483 | |
| 1484 | constructor(max: number) { |
| 1485 | this.max = max |
| 1486 | } |
| 1487 | |
| 1488 | get(sql: string, parameterTypes: ReadonlyArray<number>, textResults: boolean): Prepared { |
| 1489 | const key = `${textResults ? "T" : "B"}\u0000${parameterTypes.join(",")}\u0000${sql}` |
| 1490 | const found = this.statements.get(key) |
| 1491 | if (found !== undefined) { |
| 1492 | // Re-insert to move it to the end: `Map` iterates in insertion order, so |
| 1493 | // the first key is the least recently used one. |
| 1494 | this.statements.delete(key) |
| 1495 | this.statements.set(key, found) |
| 1496 | this.trim(found) |
| 1497 | return found |
| 1498 | } |
| 1499 | const prepared: Prepared = { |
| 1500 | name: `effect_${this.namespace}_${++this.counter}`, |
| 1501 | key, |
| 1502 | ready: false, |
| 1503 | parsing: false, |
| 1504 | description: undefined |
| 1505 | } |
| 1506 | this.statements.set(key, prepared) |
| 1507 | this.trim(prepared) |
| 1508 | return prepared |
| 1509 | } |
| 1510 | |
| 1511 | /** |
| 1512 | * A statement still being parsed cannot be closed yet: its `Parse` may not |
| 1513 | * have reached the socket. Let the cache exceed its bound temporarily, then |
| 1514 | * discard abandoned entries and close excess ready statements on access. |
| 1515 | */ |
| 1516 | private trim(protectedStatement?: Prepared): void { |
| 1517 | while (this.statements.size > this.max) { |
| 1518 | let evicted: Prepared | undefined |
| 1519 | for (const prepared of this.statements.values()) { |
| 1520 | if (prepared !== protectedStatement && (prepared.ready || !prepared.parsing)) { |
| 1521 | evicted = prepared |
| 1522 | break |
| 1523 | } |
| 1524 | } |
| 1525 | if (evicted === undefined) return |
| 1526 | this.statements.delete(evicted.key) |
| 1527 | if (evicted.ready) this.close(evicted.name) |
| 1528 | } |
| 1529 | } |
| 1530 | |
| 1531 | /** |
| 1532 | * Drops a statement the backend no longer holds, or whose plan went stale. |
| 1533 | * |
| 1534 | * The name is closed either way. A plan that went stale is still held under |
nothing calls this directly
no test coverage detected