Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Sign up for free
Menu
Search
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Pricing
Search
Sign in
Sign up for free
Introduction to Database Connection Management ...
Search
Sponsored
·
Your Podcast. Everywhere. Effortlessly.
Share. Educate. Inspire. Entertain. You do you. We'll handle the rest.
→
sugar-cat
May 11, 2024
520
1
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
Introduction to Database Connection Management Patterns in TypeScript.pdf
sugar-cat
May 11, 2024
More Decks by sugar-cat
See All by sugar-cat
HonoとOpenTelemetryで実現するオブザーバービリティ構築
sugarcat7
0
630
ErrorTrackingとOrchestrion
sugarcat7
0
460
DiscordとCloudflare
sugarcat7
2
1.4k
Cloudflare Workflowsを使いたい倒したい
sugarcat7
8
2.8k
tslogで実現するセキュアなメタデータ管理とロギング
sugarcat7
4
1.7k
最近個人開発が熱い ~モニタリング強化編v0.1.0~
sugarcat7
3
540
Honoで実現するバックエンド開発のイマ
sugarcat7
23
6.6k
GoとWASI~超入門~
sugarcat7
2
340
最近個人開発が熱い ~多言語対応編~
sugarcat7
2
520
Featured
See All Featured
SEO Brein meetup: CTRL+C is not how to scale international SEO
lindahogenes
2
3k
ピンチをチャンスに:未来をつくるプロダクトロードマップ #pmconf2020
aki_iinuma
128
56k
Agile that works and the tools we love
rasmusluckow
331
22k
[SF Ruby Conf 2025] Rails X
palkan
3
1.5k
Odyssey Design
rkendrick25
PRO
2
920
RailsConf 2023
tenderlove
30
1.6k
Leading Effective Engineering Teams in the AI Era
addyosmani
9
2.8k
Unsuck your backbone
ammeep
672
58k
Impact Scores and Hybrid Strategies: The future of link building
tamaranovitovic
0
480
Self-Hosted WebAssembly Runtime for Runtime-Neutral Checkpoint/Restore in Edge–Cloud Continuum
chikuwait
0
920
Building Applications with DynamoDB
mza
96
7.3k
I Don’t Have Time: Getting Over the Fear to Launch Your Podcast
jcasabona
35
2.9k
Transcript
Introduction to Database Connection Management Patterns in TypeScript 2024/5/11 TSKaigi
@sugar235711
2 sugar(sugar-cat) 所属: Cyber Agent/AIShift バックエンドエンジニア パフォーマンスチューニングとかセキュリティの話が好きです 自己紹介
3 Agenda 1. usingについて 2. DatabaseのConnection管理について 2.1. クエリビルダーとPool 2.2. Poolを扱う際の注意点
2.3. 実装方法(try-finally) 2.4. 実装方法(using) 3. まとめ
4 TypeScript 5.2で追加されたExplicit Resource Management(明示的リソース 管理)機能 • usingというキーワードとともに宣言された変数は、スコープの終わりに Symbol.disposeメソッドが自動的に呼び出される 1.
usingについて https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-2.html#using-declarations-and-explicit-resource-management
5 TypeScript 5.2で追加されたExplicit Resource Management(明示的リソース 管理)機能 • usingというキーワードとともに宣言された変数は、スコープの終わりに Symbol.disposeメソッドが自動的に呼び出される 1.
usingについて https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-2.html#using-declarations-and-explicit-resource-management ①Disposableを実装
6 TypeScript 5.2で追加されたExplicit Resource Management(明示的リソース 管理)機能 • usingというキーワードとともに宣言された変数は、スコープの終わりに Symbol.disposeメソッドが自動的に呼び出される 1.
usingについて https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-2.html#using-declarations-and-explicit-resource-management ①Disposableを実装 ②usingで変数をBinding
7 TypeScript 5.2で追加されたExplicit Resource Management(明示的リソース 管理)機能 • usingというキーワードとともに宣言された変数は、スコープの終わりに Symbol.disposeメソッドが自動的に呼び出される 1.
usingについて https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-2.html#using-declarations-and-explicit-resource-management ①Disposableを実装 ②usingで変数をBinding ③スコープを抜ける際にSymbol.disposeの処理が 実行される ※Processのkillでは実行されない
8 TypeScript 5.2で追加されたExplicit Resource Management(明示的リソース 管理)機能 • usingというキーワードとともに宣言された変数は、スコープの終わりに Symbol.disposeメソッドが自動的に呼び出される 1.
usingについて https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-2.html#using-declarations-and-explicit-resource-management ①Disposableを実装 ②usingで変数をBinding ③スコープを抜ける際にSymbol.disposeの処理が 実行される ※Processのkillでは実行されない ➔ try-finally blockの代替 ・宣言的なリソース解放 ・統一的なリソース解放のためのIFの提供
9 非同期処理に対応したSymbol.asyncDispose、Disposableインターフェースを 実装せずともCleanupが行えるDisposableStackもある 1. usingについて https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-2.html#using-declarations-and-explicit-resource-management
10 非同期処理に対応したSymbol.asyncDispose、Disposableインターフェースを 実装せずともCleanupが行えるDisposableStackもある 1. usingについて 各ランタイム上でのusing互換のAPIが実装されている ※DisposableStackはそのまま使えない(今のところ) Node.js: v20.4.0 https://nodejs.org/en/blog/release/v20.4.0#support-to-the-explicit-resource-manage
ment-proposal Deno: v1.38 https://deno.com/blog/v1.38#using-with-deno-apis Bun: v1.0.23 https://bun.sh/blog/bun-v1.0.23#resource-management-is-now-supported Workers https://developers.cloudflare.com/workers/runtime-apis/rpc/lifecycle/#how-to-use-the -using-declaration-in-your-worker ※V8 エンジン側でネイティブサポートされてないので、 Wranglerのプレリリース 版を使用する https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-2.html#using-declarations-and-explicit-resource-management
11 昨今TypeScriptを使ったバックエンド開発のライブラリ選定は2パターン • オールインワン系 ◦ DBMSに依存しないAPI/Migration機構/Pooling (e.g. Prisma) • 組み合わせ
• クエリビルダーとしての機能がメインなORM(軽量) (e.g. Drizzle, Kysely, sqlc) • DBMSごとコネクションプールを管理するDriver (e.g. node-postgres) 2.1. クエリビルダーとコネクションプール 2. DatabaseのConnection管理について
12 昨今TypeScriptを使ったバックエンド開発のライブラリ選定は2パターン • オールインワン系 ◦ DBMSに依存しないAPI/Migration機構/Pooling (e.g. Prisma) • 組み合わせ
• クエリビルダーとしての機能がメインなORM(軽量) (e.g. Drizzle, Kysely, sqlc) • DBMSごとコネクションプールを管理するDriver (e.g. node-postgres) 2.1. クエリビルダーとコネクションプール 2. DatabaseのConnection管理について
13 基本的にはDB(Schema)ごとにPoolは1つ(シングルトンで扱う) 1Pool内でトランザクションごとにコネクションを発行/解放して使い回す 2.2. コネクションプールを扱う際の注意点 2. DatabaseのConnection管理について
14 高階関数で実行したいクエリを渡して、try-finallyでコネクションとロールバックの 制御をする 2.3. 実装方法(try-finally) 2. DatabaseのConnection管理について
15 コネクションはfinallyで補足しリリースする ➔ クエリの成功・失敗にかかわらずコネクションをリリースできる 2.3. 実装方法(try-finally) 2. DatabaseのConnection管理について
16 コネクションはfinallyで補足しリリースする ➔ クエリの成功・失敗にかかわらずコネクションをリリースできる 2.3. 実装方法(try-finally) 2. DatabaseのConnection管理について [問題点] conn.release()でエラーが起きた場合、
新たにエラーがthrowされ、クエリ実行時のエ ラーが上書きされてしまう
17 Drizzle ORMのpg-coreでは内部のPoolの管理にtry-finallyが使用されている 2.3. 実装方法(try-finally) ※余談 2. DatabaseのConnection管理について https://github.com/drizzle-team/drizzle-orm/blob/a78eefe08e127922565486143e0150a718b27e8a/drizzle-orm/src/node-postgres/session.ts#L145
18 処理の流れが見づらい場合はResult型を定義し、一連の処理を扱うとネストが減 り見通しが良い 2.3. 実装方法(Resultを用いた実例) ※余談 2. DatabaseのConnection管理について
19 finally部分の処理をDisposableStackのdefer内に移動 2.4. 実装方法(using: finallyをDisposableStackに置き換え) 2. DatabaseのConnection管理について Txのスコープを外れる際にコネクションが解放される
20 finally部分の処理をDisposableStackのdefer内に移動 2.4. 実装方法(using: TransactionのfinallyをDisposableStackに置き換え) 2. DatabaseのConnection管理について Txのスコープを外れる際にコネクションが解放される クエリ実行時かつcleaup内のreleaseでエラーになっ た場合、エラーは上書きされずSuppressedErrorとし
てthrowされる
21 finally部分の処理をDisposableStackのdefer内に移動 2.4. 実装方法(using: TransactionのfinallyをDisposableStackに置き換え) 2. DatabaseのConnection管理について Txのスコープを外れる際にコネクションが解放される クエリ実行時かつcleaup内のreleaseでエラーになっ た場合、エラーは上書きされずSuppressedErrorとし
てthrowされる SuppressedErrorの各プロパティに2種類の エラーが捕捉される:最後のthrowと直近のthrow) error: conn.release()の解放エラー suppressed: op.getError()のエラー →Txの可読性・エラートレースを改善可能 ※Pool側にDisposableの実装を行っても同等の挙動を実現できます
22 • 高階関数でクエリを実行するとTransactionの流れが追いやすい • usingとを使用することでコネクションの解放処理の可読性を向上できるよう になる • Suppressed Errorによって複数エラーの識別が可能になる Special
Thanks🎉 @brn227 @KK_sep_TT @__yoshi_dev 3. まとめ