Skip to content

feat: auto-create database directory if missing#510

Merged
steveiliop56 merged 1 commit into
tinyauthapp:mainfrom
modrin:feature/auto-create-database-directory
Dec 11, 2025
Merged

feat: auto-create database directory if missing#510
steveiliop56 merged 1 commit into
tinyauthapp:mainfrom
modrin:feature/auto-create-database-directory

Conversation

@modrin
Copy link
Copy Markdown
Contributor

@modrin modrin commented Dec 10, 2025

Problem

When DATABASE_PATH is not set or points to a non-existent directory, TinyAuth v4 fails to start with a confusing error message ("out of memory (14)"). This is problematic in Docker deployments where users expect the application to work out of the box.

Solution

Auto-create the database directory if it doesn't exist and provide a sensible default (/data/tinyauth.db) when DATABASE_PATH is empty. This works seamlessly with any Docker volume configuration.

Changes

  • Auto-create database directory using os.MkdirAll (handles multi-level paths)
  • Default to /data/tinyauth.db when DATABASE_PATH is empty
  • Remove validate:"required" to allow flexibility

Behavior

  • No volume: Directory created in container (ephemeral with anonymous volumes)
  • Volume mounted: Directory created in volume (persistent)
  • Custom path: Directory auto-created at specified path
  • Backward compatible: Existing configs continue to work

Testing

✅ Code compiles successfully (tested with Docker build)
✅ Follows existing code patterns
✅ Backward compatible
✅ Handles multi-level directory paths
✅ No linter errors

Related

Related to PR #506 which improves error messages when database cannot be opened. This PR fixes the root cause by auto-creating the directory, preventing the error from occurring in the first place.

Summary by CodeRabbit

Release Notes

  • Improvements
    • Database directory will now be automatically created during initialization if it doesn't exist.
    • Database path is now optional with a sensible default location.
    • Updated help documentation to reflect automatic directory creation behavior.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Dec 10, 2025

Walkthrough

The changes implement automatic directory creation for database initialization while making the database-path configuration optional. The database path now defaults to "/data/tinyauth.db" if not specified, and the directory is created automatically during service initialization.

Changes

Cohort / File(s) Summary
Configuration & Validation
cmd/root.go, internal/config/config.go
Updated help text for database-path flag to indicate automatic directory creation; removed the validate:"required" constraint from the DatabasePath struct field, making it optional
Database Initialization
internal/service/database_service.go
Added imports (fmt, os, filepath); enhanced Init() to set a default database path of "/data/tinyauth.db" if empty, create the directory via os.MkdirAll before opening the database, and handle directory creation errors

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

  • internal/service/database_service.go: Verify that os.MkdirAll is called with appropriate permissions and that error handling for directory creation is consistent with the rest of the codebase.
  • internal/config/config.go: Confirm that removing the validate:"required" constraint aligns with the new default-path behavior and doesn't introduce unintended validation gaps elsewhere.

Poem

🐰 A path without a home now finds one,
Directories spring forth before the sun,
No required fields to fuss and fight,
Just defaults and creation, snug and tight!
hops contentedly

Pre-merge checks and finishing touches

❌ 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%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title directly and accurately describes the main change: auto-creating the database directory when it's missing, which is the core objective and primary change across all modified files.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.

Copy link
Copy Markdown
Contributor

@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: 0

🧹 Nitpick comments (1)
internal/service/database_service.go (1)

33-44: Init correctly defaults and prepares the DB path; consider DRY’ing the default and tightening perms

The new dbPath handling and MkdirAll call solve the original startup failure when the directory doesn’t exist and give a sensible fallback when the path is empty. This looks functionally solid.

Two non-blocking suggestions:

  • Avoid duplicating the default path string: /data/tinyauth.db now lives here and in cmd/root.go. Consider centralizing this in a shared constant (e.g., in a config/common package) so future changes don’t drift.
  • Consider stricter directory permissions: since the DB holds auth data, 0700 is usually sufficient and a bit safer than 0755 in multi-user environments:
-	dir := filepath.Dir(dbPath)
-	if err := os.MkdirAll(dir, 0755); err != nil {
+	dir := filepath.Dir(dbPath)
+	if err := os.MkdirAll(dir, 0700); err != nil {
 		return fmt.Errorf("failed to create database directory %s: %w", dir, err)
 	}
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5f2ec02 and e9307c5.

📒 Files selected for processing (3)
  • cmd/root.go (1 hunks)
  • internal/config/config.go (1 hunks)
  • internal/service/database_service.go (2 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-08-27T11:02:49.689Z
Learnt from: steveiliop56
Repo: steveiliop56/tinyauth PR: 326
File: internal/service/database_service.go:7-11
Timestamp: 2025-08-27T11:02:49.689Z
Learning: In internal/service/database_service.go, using glebarez/sqlite (modernc) for GORM with sqlite3 (mattn) driver for golang-migrate is a valid pattern that works correctly, despite appearing to be a driver mismatch. The golang-migrate sqlite driver causes panics when used with modernc.org/sqlite backend, so the mixed approach should be maintained.

Applied to files:

  • internal/service/database_service.go
🧬 Code graph analysis (1)
internal/service/database_service.go (1)
internal/config/config.go (1)
  • Config (17-46)
🔇 Additional comments (2)
internal/config/config.go (1)

40-40: Making DatabasePath non-required aligns with new defaulting behavior

Removing the validate:"required" constraint is consistent with providing a default (/data/tinyauth.db) and having DatabaseService.Init handle an empty path, so config without an explicit database-path will now start successfully instead of failing validation.

cmd/root.go (1)

69-69: Database flag default and description match the new behavior

Using /data/tinyauth.db as the flag default and documenting that the directory will be created if missing is consistent with the new initialization logic and should make Docker usage less surprising.

@steveiliop56 steveiliop56 merged commit 3961589 into tinyauthapp:main Dec 11, 2025
2 checks passed
@codecov
Copy link
Copy Markdown

codecov Bot commented Dec 11, 2025

Codecov Report

❌ Patch coverage is 0% with 8 lines in your changes missing coverage. Please review.
✅ Project coverage is 23.56%. Comparing base (5f2ec02) to head (e9307c5).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
internal/service/database_service.go 0.00% 7 Missing ⚠️
cmd/root.go 0.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #510      +/-   ##
==========================================
- Coverage   23.62%   23.56%   -0.07%     
==========================================
  Files          36       36              
  Lines        2239     2245       +6     
==========================================
  Hits          529      529              
- Misses       1673     1679       +6     
  Partials       37       37              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

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.

2 participants