Skip to content

refactor: lazy-init shared db for DATABASE_URL (#224)#234

Merged
coji merged 3 commits intomainfrom
refactor/lazy-shared-db-init-224
Mar 23, 2026
Merged

refactor: lazy-init shared db for DATABASE_URL (#224)#234
coji merged 3 commits intomainfrom
refactor/lazy-shared-db-init-224

Conversation

@coji
Copy link
Owner

@coji coji commented Mar 23, 2026

Summary

Why

db.server.ts was evaluating DATABASE_URL at load time. Any test file that statically imported a module pulling in db.server had to use dynamic import ordering. Lazy init removes that constraint.

Notes

  • tenant-db.server.ts already read DATABASE_URL only inside getTenantDbPath(); no code change there.

Closes #224

Made with Cursor

Summary by CodeRabbit

リリースノート

  • パフォーマンス改善

    • データベースの初期化を遅延ロード方式に変更し、アプリケーション起動時の負荷を軽減しました。
  • 内部改善

    • テストファイルのモジュール読み込みを最適化し、コードの保守性を向上させました。

- Open SQLite on first db/dialect access via Proxy (no env read at import)
- Replace test dynamic imports of tenant-db with static imports
- tenant-db already resolved paths lazily in getTenantDbPath

Made-with: Cursor
@coderabbitai
Copy link

coderabbitai bot commented Mar 23, 2026

Warning

Rate limit exceeded

@coji has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 11 minutes and 55 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: cc4a4929-116c-403f-b741-224a95bdeccd

📥 Commits

Reviewing files that changed from the base of the PR and between 291f8d4 and 3ca535b.

📒 Files selected for processing (12)
  • app/libs/timezone.server.test.ts
  • app/routes/$orgSlug/settings/github-users._index/mutations.server.test.ts
  • app/routes/$orgSlug/settings/repositories._index/mutations.server.test.ts
  • app/routes/$orgSlug/settings/repositories/$repository/settings/+functions/mutations.server.test.ts
  • app/routes/$orgSlug/settings/teams._index/mutations.server.test.ts
  • app/routes/$orgSlug/workload/$login/+functions/queries.server.test.ts
  • app/services/db.server.ts
  • app/services/tenant-db.server.test.ts
  • app/services/tenant-db.server.ts
  • app/types/organization.ts
  • batch/db/mutations.test.ts
  • batch/github/store.test.ts
📝 Walkthrough

Walkthrough

複数のテストファイルで動的インポート(await import(...))から静的ES モジュールインポートに切り替え、app/services/db.server.tsではデータベース接続の初期化を早期から遅延初期化に変更。これにより環境変数スタブ後の import 順序への依存性を排除し、テストコード内のボイラープレートを削減。

Changes

Cohort / File(s) Summary
テストファイルの静的インポート化
app/libs/timezone.server.test.ts, app/routes/$orgSlug/settings/github-users._index/mutations.server.test.ts, app/routes/$orgSlug/settings/repositories._index/mutations.server.test.ts, app/routes/$orgSlug/settings/repositories/$repository/settings/+functions/mutations.server.test.ts, app/routes/$orgSlug/settings/teams._index/mutations.server.test.ts, app/routes/$orgSlug/workload/$login/+functions/queries.server.test.ts, app/services/tenant-db.server.test.ts, batch/db/mutations.test.ts, batch/github/store.test.ts
動的 await import(...) を標準的な ES モジュール import に統一。OrganizationId 型と関数インポートをモジュール上部に移動し、テスト実行前の環境変数スタブに依存する import 順序要件を排除。
DB サーバーの遅延初期化
app/services/db.server.ts
SQLite databasedialectdb の初期化を eager から lazy(シングルトンパターン)に変更。getSharedDbState() を介した初回アクセス時の初期化、DATABASE_URL 検証の遅延、および Proxy を用いた透過的なアクセスを実装。

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • PR #141: 同じ OrganizationId 型のインポート/使用方法を修正し、動的インポートから静的インポートへの切り替えを行っているため、コードレベルで関連している。
  • PR #205: app/services/db.server.ts の DB/dialect 初期化方法を変更しており、SQLite 設定・初期化処理に関連している。
  • PR #116: OrganizationId 型と imports/usages を更新している点で関連。本 PR はテストの静的インポート化、検出対象 PR は branded OrganizationId の導入と伝播を行っている。

Poem

🐰✨ インポート、今はまっすぐに
動的の迷路もさようなら
遅延初期化で素早く目覚め
テストコードは軽やかに踊る
環境変数の心配も無く 🌱

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed タイトルは主要な変更を明確に説明しており、遅延初期化とDATA­BASE_URLに関する変更を適切に要約しています。
Linked Issues check ✅ Passed db.server.tsの遅延初期化実装とテストファイルの動的インポート削除により、issue #224の要件がすべて満たされています
Out of Scope Changes check ✅ Passed すべての変更がissue #224の範囲内であり、遅延初期化とテスト修正に限定されています。

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch refactor/lazy-shared-db-init-224

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coji
Copy link
Owner Author

coji commented Mar 23, 2026

CodeRabbit(import hoist)への回答

静的 importvi.stubEnv より先に評価される点はそのとおりですが、この PR では 共有 DB(db.server.ts)を遅延初期化しています。DATABASE_URL / SQLite オープンは db または dialect への 初回プロパティアクセスまで行われません。

また tenant-db.server.ts はもともと getTenantDbPath() 呼び出し時まで DATABASE_URL を読みません。テスト対象の mutations.server / queries.server はモジュールトップで env を読まず、実際の DB アクセスはスタブ適用後の実行時に走ります。

そのため、以前の await import(...) で順序を確保していたパターンは 不要になっており、静的 import のままで意図どおりです。

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@app/services/db.server.ts`:
- Around line 69-72: The closeDb() function is closing the same SQLite handle
twice because Kysely's SqliteDriver.destroy() already closes
sharedDbState.database; remove the extra sharedDbState.database.close() call so
destroy() is the sole resource cleanup. Apply the same fix to closeTenantDb()
and closeAllTenantDbs(): stop calling the underlying database.close() after
awaiting the Kysely destroy() and let destroy() handle closing the
better-sqlite3 handle.

In `@app/services/tenant-db.server.test.ts`:
- Around line 7-12: The import lines in this test use a relative path; replace
them with the project alias prefix by changing the module import to the
app-alias (e.g. import { closeAllTenantDbs, closeTenantDb, deleteTenantDb,
getTenantDb } from '~/services/tenant-db.server') so all references to
closeAllTenantDbs, closeTenantDb, deleteTenantDb and getTenantDb come from the
aliased path and conform to the guideline.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: b25ebe59-9a01-48d7-917c-765da21f5ed1

📥 Commits

Reviewing files that changed from the base of the PR and between 02cdff3 and 291f8d4.

📒 Files selected for processing (10)
  • app/libs/timezone.server.test.ts
  • app/routes/$orgSlug/settings/github-users._index/mutations.server.test.ts
  • app/routes/$orgSlug/settings/repositories._index/mutations.server.test.ts
  • app/routes/$orgSlug/settings/repositories/$repository/settings/+functions/mutations.server.test.ts
  • app/routes/$orgSlug/settings/teams._index/mutations.server.test.ts
  • app/routes/$orgSlug/workload/$login/+functions/queries.server.test.ts
  • app/services/db.server.ts
  • app/services/tenant-db.server.test.ts
  • batch/db/mutations.test.ts
  • batch/github/store.test.ts

coji added 2 commits March 23, 2026 11:11
- SqliteDriver.destroy() already calls better-sqlite3 close()
- Use ~/app import in tenant-db.server.test per project convention

Made-with: Cursor
- Add test-only toOrgId helper next to OrganizationId brand
- Deduplicate local toOrgId shims in integration tests

Made-with: Cursor
@coji coji merged commit a05ffa2 into main Mar 23, 2026
6 checks passed
@coji coji deleted the refactor/lazy-shared-db-init-224 branch March 23, 2026 02:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

refactor: tenant-db.server の DATABASE_URL 読み込みを遅延初期化に変更

1 participant