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

Open
wants to merge 31 commits into
base: main
Choose a base branch
from
Open

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 have direct title and path fields, simplifying access and management.
    • A primary flag can be set when adding an attachment to indicate if it is the primary attachment.
    • Item summaries now include a soldTime property for sale details.
  • Improvements

    • Attachment APIs and UI now display and edit titles directly, no longer through a nested document object.
    • File storage and metadata for attachments are managed more efficiently and transparently.
  • Removals

    • The separate "Document" entity and all related API endpoints, database tables, and UI references have been removed.
    • Documentation and API schemas no longer reference or return nested document objects within attachments.
  • Bug Fixes

    • Improved handling of attachment file naming and storage to avoid conflicts and ensure consistency.
  • Documentation

    • API documentation updated to reflect the new attachment structure and the addition of the primary and soldTime fields.

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

coderabbitai bot commented Apr 6, 2025

Walkthrough

This change removes the entire concept of "Document" entities from the codebase, merging their fields (such as title and path) directly into the Attachment entity. All schema definitions, database migrations, API contracts, repository methods, and service logic related to documents are deleted or refactored. Attachments now store their own title and path fields, and all references to documents—across backend, frontend, and API documentation—are replaced with direct attachment properties. The migration scripts update the database accordingly, while tests, repository logic, and service methods are adapted to the new model.

Changes

File(s) / Path(s) Change Summary
backend/internal/data/ent/attachment.go, .../attachment/attachment.go, .../attachment/where.go, .../attachment_create.go, .../attachment_query.go, .../attachment_update.go Refactored the Attachment entity: added title and path fields, removed the document edge and all document-related methods, predicates, and ordering. Updated create/update/query logic to handle new fields and removed document references.
backend/internal/data/ent/document.go, .../document/document.go, .../document/where.go, .../document_create.go, .../document_delete.go, .../document_query.go, .../document_update.go, .../schema/document.go Deleted all files and code related to the Document entity, including schema, queries, mutations, and validation.
backend/internal/data/ent/client.go, .../ent/tx.go, .../ent/ent.go, .../ent/mutation.go, .../ent/predicate/predicate.go, .../ent/runtime.go Removed Document client, transaction, column validation, predicate, and mutation logic. Updated runtime initialization to exclude document schema.
backend/internal/data/ent/group.go, .../group/group.go, .../group/where.go, .../group_create.go, .../group_query.go, .../group_update.go, .../schema/group.go Removed all references to documents from the Group entity: deleted edges, methods, and query logic for documents.
backend/internal/data/ent/schema/attachment.go Added title and path fields to Attachment schema; removed document edge.
backend/internal/data/ent/migrate/schema.go Updated migration schema: removed documents table and document_attachments column; added title and path fields to attachments. Updated foreign key references.
backend/internal/data/migrations/sqlite3/20250405050521_merge_docs_and_attachments.sql, .../postgres/20250419184104_merge_docs_attachments.sql Migration scripts to merge document data into attachments, add new columns, copy data, drop document-related columns and tables.
backend/internal/data/repo/repo_documents.go, .../repo_documents_test.go Deleted the DocumentRepository and its tests.
backend/internal/data/repo/repos_all.go, .../repo/repo_item_attachments.go, .../repo/repo_item_attachments_test.go, .../repo/repo_items.go Refactored repositories: removed Docs field, updated attachment repo to manage file storage and metadata directly, added rename, updated create/delete logic, removed document references from tests and mapping.
backend/internal/core/services/service_items_attachments.go, .../service_items_attachments_test.go Refactored attachment service logic to operate directly on attachments, removed document-related logic and parameters, updated tests accordingly.
backend/app/api/handlers/v1/v1_ctrl_items_attachments.go Updated handler to support new primary parameter and pass it to the attachment service; removed document references.
backend/app/api/static/docs/docs.go, .../swagger.json, .../swagger.yaml Removed DocumentOut definition from OpenAPI; updated ItemAttachment to include path, title, and primary directly; updated endpoints and item summary definitions.
docs/en/api/openapi-2.0.json, .../openapi-2.0.yaml Updated API schema: removed DocumentOut, updated ItemAttachment and ItemSummary, added primary parameter for attachment creation.
frontend/lib/api/types/data-contracts.ts, .../api/test/user/items.test.ts, .../Item/AttachmentsList.vue, .../item/[id]/index/edit.vue Updated frontend types, tests, and components: removed DocumentOut, made attachment title and path direct properties, updated all usages accordingly.
backend/pkgs/pathlib/pathlib.go, .../pathlib_test.go Deleted pathlib utility and its tests (safe path generation and conflict detection).
backend/go.mod Added new dependencies: blake3 for hashing, cpuid for CPU feature detection.
backend/.golangci.yml Migrated golangci-lint config to version 2 syntax, updated enabled linters and exclusions.
.github/workflows/partial-backend.yaml Updated GitHub Actions workflow to use golangci-lint-action v7.
backend/app/tools/migrations/main.go Simplified switch statement for database URL assignment.
backend/internal/data/repo/repo_maintenance.go Refactored maintenance status filtering to use switch statement; added "both" status.
backend/internal/data/repo/repo_users_test.go Updated test assertion to use assert.Len.
backend/app/api/main.go Added migration options for SQL dialect, foreign keys, and replay mode.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant API
    participant Service
    participant Repo
    participant DB
    participant Filesystem

    Client->>API: POST /items/{id}/attachments (file, title, primary)
    API->>Service: AttachmentAdd(ctx, itemID, filename, type, primary, file)
    Service->>Repo: Create(ctx, itemID, {Title, Content}, type, primary)
    Repo->>Filesystem: Save file (hashed path)
    Filesystem-->>Repo: Success/Failure
    Repo->>DB: Insert Attachment (with title, path, etc.)
    DB-->>Repo: Attachment entity
    Repo-->>Service: Attachment entity
    Service-->>API: ItemOut (with attachments: [{title, path, ...}])
    API-->>Client: Response (attachment info)
Loading

Possibly related PRs

  • sysadminsmedia/homebox#579: Removes document-related code and merges document fields into attachments, superseding previous PRs that modified attachment/document relationships.

Poem

Once lived a Document, proud and tall,
Now Attachment stands, embracing all.
Title and path, no longer apart,
Merged in the code with a refactor's art.
The schema is leaner, the API clean,
Attachments now rule where Documents had been!

🗃️✨

Security tip:

  • Ensure that file paths and titles are properly sanitized to prevent path traversal or injection vulnerabilities.
  • Validate and restrict file uploads to accepted types and sizes.
  • Review access controls to ensure only authorized users can create, rename, or delete attachments.
  • Regularly audit file storage for orphaned or unreferenced files.
  • Keep dependencies up to date and monitor for security advisories related to new packages (e.g., blake3).

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 golangci-lint (1.64.8)

Error: you are using a configuration file for golangci-lint v2 with golangci-lint v1: please use golangci-lint v2
Failed executing command with error: you are using a configuration file for golangci-lint v2 with golangci-lint v1: please use golangci-lint v2

✨ 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.

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: 7791d43
Status: ✅  Deploy successful!
Preview URL: https://2455caa7.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.

coderabbitai[bot]

This comment was marked as outdated.

coderabbitai[bot]

This comment was marked as outdated.

@tankerkiller125 tankerkiller125 marked this pull request as ready for review April 19, 2025 15:47
@tankerkiller125
Copy link
Contributor Author

I don't understand why the SQLite integration test fails but all the others are fine. And it's only in Github Actions, the test runs fine locally when I run it.

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.

Pull Request Overview

This PR removes all document-related entities and logic, merging document data into attachments and thus simplifying the overall database design and related service logic.

  • Removed document table, entity, and client, along with its associated query and mutation functions.
  • Updated attachment creation, update, queries, and API endpoints to include new title, path, and primary flag for improved metadata handling.
  • Adjusted tests, migrations, and build configurations to reflect the new attachment-based design.

Reviewed Changes

Copilot reviewed 59 out of 62 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
backend/internal/data/ent/document/where.go Deleted obsolete document filtering functions.
backend/internal/data/ent/document/document.go Removed document entity definitions and constants.
backend/internal/data/ent/document.go Removed document entity and related helper methods.
backend/internal/data/ent/client.go Removed document client references and updated hook setup.
backend/internal/data/ent/attachment_update.go Added handling for title and path fields in attachment updates; removed document-related code.
backend/internal/data/ent/attachment_query.go Removed document edge queries and related eager-loading logic.
backend/internal/data/ent/attachment_create.go Updated attachment creation to set title, path and perform validation accordingly.
backend/internal/data/ent/attachment/where.go Introduced new predicates for title and path fields.
backend/internal/data/ent/attachment/attachment.go Added title and path fields to the Attachment entity; removed document edge references.
backend/internal/core/services/service_items_attachments_test.go Updated tests to reference attachment path instead of document path.
backend/internal/core/services/service_items_attachments.go Updated service methods to use the new attachment design and primary flag.
backend/app/tools/migrations/main.go Refactored the database driver switch-case block.
backend/app/api/static/docs/docs.go Updated API documentation to remove references to documents.
backend/app/api/handlers/v1/v1_ctrl_items_attachments.go Updated HTTP handlers to handle the new primary flag and attachment field changes.
backend/.golangci.yml & .github/workflows/partial-backend.yaml Updated linting and workflow versions to support current project standards.
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

@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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
⬆️ enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants