Skip to content

Remove documents table #618

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 36 commits into from
May 3, 2025
Merged

Remove documents table #618

merged 36 commits into from
May 3, 2025

Conversation

tankerkiller125
Copy link
Contributor

@tankerkiller125 tankerkiller125 commented Apr 6, 2025

What type of PR is this?

  • cleanup

What this PR does / why we need it:

This PR removes the documents table after merging the important bits into the attachments table. This significantly simplifies the overall design of the database and also makes it simpler for further work with attachements.

Which issue(s) this PR fixes:

Part of #265

Summary by CodeRabbit

  • New Features

    • Attachments now include direct fields for title and path, making document details immediately accessible.
    • Added support for marking an attachment as "primary" when uploading via the API and user interface.
  • Improvements

    • Simplified data model: document management is now fully integrated into attachments, eliminating the separate document entity.
    • Attachment creation, renaming, and deletion are streamlined and more intuitive.
    • API, OpenAPI/Swagger docs, and frontend updated to reflect new attachment structure (title, path, primary).
  • Migrations

    • Database migrations merge document data into attachments and remove the documents table.
  • Bug Fixes

    • Improved file handling to prevent naming conflicts and ensure safe file storage for attachments.
  • Chores

    • Removed obsolete code, tests, and dependencies related to the old document entity. Updated linting and CI configuration.

@tankerkiller125 tankerkiller125 requested a review from Copilot April 6, 2025 01:57
Copy link
Contributor

coderabbitai bot commented Apr 6, 2025

Warning

Rate limit exceeded

@tankerkiller125 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 17 minutes and 30 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.

📥 Commits

Reviewing files that changed from the base of the PR and between 8fc87dd and b05385c.

📒 Files selected for processing (2)
  • frontend/components/Item/AttachmentsList.vue (2 hunks)
  • frontend/lib/api/types/data-contracts.ts (3 hunks)

Walkthrough

This change removes the entire Document entity and all related logic, schema, migrations, and API references from the codebase. All document-related repositories, schema definitions, queries, mutations, and tests are deleted. The Attachment entity is expanded with new title and path fields, now storing document data directly within attachments. All attachment management, file storage, and API endpoints are updated to use these new fields, eliminating the need for a separate Document object. The database schema and migrations are updated to merge document data into attachments and drop the documents table. The API contracts, frontend types, and UI are refactored to reflect the new structure, removing nested document objects and exposing title and path directly on attachments.

Changes

Files/Paths Change Summary
backend/internal/data/ent/document.go, .../document_create.go, .../document_delete.go, ... Deleted all Document entity files: Removed Document struct, schema, queries, mutations, and related methods.
backend/internal/data/ent/attachment.go, .../attachment/attachment.go, .../attachment/where.go Attachment refactor: Added title and path fields; removed document edge and related logic; added predicates for new fields.
backend/internal/data/ent/schema/attachment.go Added title and path fields; removed document edge.
backend/internal/data/ent/schema/document.go, .../group.go, .../group/group.go, .../group/where.go Removed document edge from Group schema and related code.
backend/internal/data/ent/client.go, .../tx.go, .../ent.go, .../runtime.go, .../mutation.go Removed Document client, validation, runtime, and mutation logic.
backend/internal/data/ent/migrate/schema.go Schema/migration: Dropped documents table, added title and path to attachments, updated foreign keys.
backend/internal/data/migrations/sqlite3/20250405050521_merge_docs_and_attachments.sql, ... Migration: Merged document data into attachments, dropped documents table.
backend/internal/data/repo/repo_documents.go, .../repo_documents_test.go Deleted document repository and its tests.
backend/internal/data/repo/repos_all.go Removed Docs field from repository aggregator.
backend/internal/data/repo/repo_item_attachments.go, ..._test.go Refactored attachment repo: direct file handling, new title/path fields, removed document logic, updated tests.
backend/internal/core/services/service_items_attachments.go, ..._test.go Updated services and tests to use new attachment fields, removed document logic.
backend/app/api/handlers/v1/v1_ctrl_items_attachments.go API: Added primary parameter, removed document logic, updated handler.
backend/app/api/static/docs/docs.go, .../swagger.json, .../swagger.yaml, .../openapi-2.0.json, ... API docs: Removed DocumentOut, updated ItemAttachment to have title/path, added primary parameter.
frontend/lib/api/types/data-contracts.ts, .../Item/AttachmentsList.vue, .../item/[id]/index/edit.vue Frontend: Removed DocumentOut, updated ItemAttachment to have title/path, updated UI to use new fields.
backend/go.mod Added blake3 for file hashing, cpuid as indirect dependency.
backend/pkgs/pathlib/pathlib.go, .../pathlib_test.go Removed safe path utility and its tests (no longer needed).
.github/workflows/partial-backend.yaml, backend/.golangci.yml Updated CI and lint config.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Frontend
    participant API
    participant ItemService
    participant AttachmentRepo
    participant FileSystem

    User->>Frontend: Upload attachment (title, file, primary)
    Frontend->>API: POST /items/{id}/attachments (title, file, primary)
    API->>ItemService: AttachmentAdd(itemID, title, type, primary, file)
    ItemService->>AttachmentRepo: Create(itemID, {title, content}, type, primary)
    AttachmentRepo->>FileSystem: Save file (hashed path)
    FileSystem-->>AttachmentRepo: Success/Failure
    AttachmentRepo-->>ItemService: Attachment entity (with title, path)
    ItemService-->>API: ItemOut (attachments with title, path)
    API-->>Frontend: Response (attachments with title, path)
    Frontend-->>User: Show attachment (title, download link)
Loading

Possibly related PRs

  • sysadminsmedia/homebox#287: Refactors attachment repository logic to ensure only one primary attachment per item, which is closely related to the current PR's changes to attachment primary status and repository structure.

Suggested reviewers

  • tonyaellie

Poem

Attachments now stand tall and free,
No more documents—just clarity!
With titles and paths, their story's told,
In code and schema, brave and bold.
The tables merge, the files align,
Simpler flows by grand design.
🎉 Cheers to code that's light and neat—
Attachments now are self-complete!


Security Recommendations:

  • Ensure that file uploads are validated for allowed types and size to prevent malicious file uploads.
  • Sanitize and validate all user-provided fields (title, path) to avoid injection attacks.
  • When deleting attachments, confirm that file system operations cannot be exploited for path traversal or unauthorized file deletion.
  • Review access controls to ensure users can only manipulate attachments for items they own or are authorized to manage.
  • When using blake3 hashes for file paths, ensure no sensitive information is leaked via filenames or directories.
✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@Copilot Copilot AI left a comment

Choose a reason for hiding this comment

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

Copilot reviewed 36 out of 36 changed files in this pull request and generated no comments.

Comments suppressed due to low confidence (3)

backend/internal/data/ent/group.go:51

  • Ensure that the new loadedTypes array size of 6 correctly reflects the removal of the "documents" edge and that all index references in GroupEdges accessor methods have been updated to prevent off-by-one errors.
loadedTypes [6]bool

backend/internal/data/ent/attachment_query.go:376

  • Verify that the updated loadedTypes array for attachments (now size 1) correctly accounts for the removal of the document edge and that related eager-loading logic is properly adjusted.
loadedTypes = [1]bool{

backend/internal/data/ent/client.go:42

  • Confirm that removal of the Document client initialization does not leave any downstream dependencies unresolved and update any affected modules accordingly.
c.Document = NewDocumentClient(c.config)

@tankerkiller125 tankerkiller125 marked this pull request as draft April 6, 2025 01:58
coderabbitai[bot]

This comment was marked as outdated.

coderabbitai[bot]

This comment was marked as outdated.

Copy link

cloudflare-workers-and-pages bot commented Apr 6, 2025

Deploying homebox-docs with  Cloudflare Pages  Cloudflare Pages

Latest commit: 6847fdd
Status: ✅  Deploy successful!
Preview URL: https://ca6030db.homebox-docs.pages.dev
Branch Preview URL: https://mk-merge-attachments-and-doc.homebox-docs.pages.dev

View logs

coderabbitai[bot]

This comment was marked as outdated.

coderabbitai[bot]

This comment was marked as outdated.

coderabbitai[bot]

This comment was marked as outdated.

coderabbitai[bot]

This comment was marked as outdated.

coderabbitai[bot]

This comment was marked as outdated.

@tankerkiller125 tankerkiller125 requested a review from Copilot April 6, 2025 17:10
Copy link
Contributor

@Copilot Copilot AI left a comment

Choose a reason for hiding this comment

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

Copilot reviewed 52 out of 55 changed files in this pull request and generated 1 comment.

Files not reviewed (3)
  • backend/app/api/static/docs/swagger.json: Language not supported
  • backend/app/api/static/docs/swagger.yaml: Language not supported
  • backend/go.mod: Language not supported

coderabbitai[bot]

This comment was marked as outdated.

coderabbitai[bot]

This comment was marked as outdated.

coderabbitai[bot]

This comment was marked as outdated.

@tonyaellie
Copy link
Collaborator

Switching the branch for my dev workspace to this and running it results in all of my prev images not loading correctly
image
If i clone from scratch and just add new stuff it works fine

@tankerkiller125
Copy link
Contributor Author

Hmmm, seems that the migration isn't working quite right

@tonyaellie
Copy link
Collaborator

Seems to be working better but seems to loose the attachment title

@coderabbitai coderabbitai bot added the ⬆️ enhancement New feature or request label Apr 19, 2025
@tankerkiller125
Copy link
Contributor Author

This PR is on hold until I can get the migrations stuff sorted. It seems that we're in desperate need of a total migrations system replacement as the ent migration system frankly sucks when it's embedded into an application. Will be creating a different PR for that work.

Copy link
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: 3

🧹 Nitpick comments (1)
backend/app/api/main.go (1)

164-166: Enhanced migration settings improve security and reliability

The addition of these three migration options strengthens the database schema creation process:

  • Explicitly setting the dialect ensures compatibility between different database systems
  • Enabling foreign keys helps maintain data integrity during the migration
  • Using replay mode ensures consistent migration application

These settings will help address the migration issues reported in GitHub Actions. From a security perspective, enabling foreign key constraints is particularly valuable as it prevents orphaned records that could potentially lead to data integrity issues.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a6c65a3 and 7791d43.

⛔ Files ignored due to path filters (1)
  • backend/internal/data/migrations/postgres/atlas.sum is excluded by !**/*.sum
📒 Files selected for processing (2)
  • backend/app/api/main.go (1 hunks)
  • backend/internal/data/migrations/postgres/20250419184104_merge_docs_attachments.sql (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
backend/app/api/main.go (1)
backend/internal/sys/config/conf_database.go (1)
  • Database (12-21)
⏰ Context from checks skipped due to timeout of 90000ms (16)
  • GitHub Check: Frontend Tests / Integration Tests PGSQL 16
  • GitHub Check: Frontend Tests / Integration Tests
  • GitHub Check: End-to-End Playwright Tests / E2E Playwright Testing 3/4
  • GitHub Check: End-to-End Playwright Tests / E2E Playwright Testing 1/4
  • GitHub Check: End-to-End Playwright Tests / E2E Playwright Testing 4/4
  • GitHub Check: End-to-End Playwright Tests / E2E Playwright Testing 2/4
  • GitHub Check: Frontend Tests / Integration Tests PGSQL 17
  • GitHub Check: Frontend Tests / Integration Tests PGSQL 15
  • GitHub Check: build (linux/arm64)
  • GitHub Check: build (linux/arm/v7)
  • GitHub Check: build (linux/amd64)
  • GitHub Check: build (linux/arm64)
  • GitHub Check: build (linux/arm/v7)
  • GitHub Check: build (linux/amd64)
  • GitHub Check: Analyze (go)
  • GitHub Check: Cloudflare Pages
🔇 Additional comments (1)
backend/internal/data/migrations/postgres/20250419184104_merge_docs_attachments.sql (1)

11-12:

✅ Verification successful

Verify all foreign key constraints are handled

The migration drops one constraint, but there might be other foreign keys or indexes related to the documents table.


🏁 Script executed:

#!/bin/bash
# Check for any other constraints or indexes referencing the documents table
echo "Checking for other potential constraints or references to documents table:"
rg -A 3 "CONSTRAINT.*documents|REFERENCES.*documents|INDEX.*documents" --glob "*.sql"

# Look for any code that might still expect the document relationship
echo "Searching for code that might still reference documents:"
rg -A 3 "document_attachments|documents" --type go --type sql

Length of output: 19664


All PostgreSQL foreign keys to “documents” are accounted for and removed

Our search confirmed that the only constraint in Postgres referencing the documents table is
attachments_documents_attachments in the init migration, and it’s dropped in step 3 of your merge migration. No other SQL migrations or Go code rely on a DB-level documents relationship.

• SQL migrations:
– No remaining REFERENCES "documents" or CONSTRAINT … documents in the Postgres folder.
• Application code:
– The hits in repo_item_attachments.go and tests refer to a filesystem directory named “documents,” not the DB table.

Security recommendation:
Wrap the entire migration in a transaction and ensure you have a recent backup—this avoids exposing intermediate states or orphaned data if something goes wrong.

…and-docs

# Conflicts:
#	backend/app/api/main.go
#	backend/app/tools/migrations/main.go
#	backend/go.mod
#	backend/go.sum
#	backend/internal/data/migrations/postgres/atlas.sum
#	backend/internal/data/migrations/sqlite3/atlas.sum
#	backend/internal/data/repo/repo_maintenance.go
@coderabbitai coderabbitai bot added the 📖 documentation Improvements or additions to documentation label May 1, 2025
@tankerkiller125
Copy link
Contributor Author

This one is now ready for some solid testing with the new migration system @katosdev @tonyaellie everything seems to work correctly in my testing including existing documents moving over with the correct path and name data.

@tonyaellie
Copy link
Collaborator

When switching from main to this with images worked perfectly. Copying my data from a docker version of the hay-kot to this branch i had to replace /data/xxx/documents/yyy.png with .data/xxx/documents/yyy.png for the path but i assume that was due to the switch from docker? Otherwise worked fine

@tankerkiller125
Copy link
Contributor Author

@tonyaellie Yeah switching between docker and IDE code will do that, I keep a copy of the hay-kot binary version for this kind of testing.

@tankerkiller125 tankerkiller125 merged commit 606a92b into main May 3, 2025
21 of 25 checks passed
@tankerkiller125 tankerkiller125 deleted the mk/merge-attachments-and-docs branch May 3, 2025 14:16
@tankerkiller125 tankerkiller125 linked an issue Jun 7, 2025 that may be closed by this pull request
3 tasks
@tankerkiller125 tankerkiller125 removed a link to an issue Jun 7, 2025
3 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
📖 documentation Improvements or additions to documentation ⬆️ enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants