Skip to content

DB seederを追加 - #2979

Open
ramdos0207 wants to merge 4 commits into
masterfrom
db-seed
Open

DB seederを追加#2979
ramdos0207 wants to merge 4 commits into
masterfrom
db-seed

Conversation

@ramdos0207

@ramdos0207 ramdos0207 commented Apr 4, 2026

Copy link
Copy Markdown
Contributor

本番と同じぐらいの重さにするためのseederを追加

Summary by CodeRabbit

  • New Features
    • Added a seed command for populating the database with synthetic test data.
    • Seeding creates sample users, hierarchical channels, messages, stamps, and reactions.
    • Existing system data is handled safely during seeding.
    • Added a Makefile target for running the seed operation through Docker Compose.
    • The operation reports setup or data-generation errors when seeding cannot complete.

@coderabbitai

coderabbitai Bot commented Apr 4, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: ee38dc6c-cfa9-4a93-a419-24e2a4d6fad6

📥 Commits

Reviewing files that changed from the base of the PR and between 54e7675 and 0825809.

📒 Files selected for processing (1)
  • cmd/seed.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • cmd/seed.go

📝 Walkthrough

Walkthrough

This pull request adds a database seeding feature. It provides Make and Docker Compose execution, registers a Cobra seed command, and generates synthetic users, channels, messages, stamps, and reactions.

Changes

Database seed command

Layer / File(s) Summary
Seed entry point and initialization
Makefile, cmd/root.go, cmd/seed.go
Adds the seed Make target, registers the Cobra command, initializes services, and creates system roles, the traq administrator, and #general.
Users, channels, and messages
cmd/seed.go
Creates 1,000 users, deactivates 300 users, generates hierarchical public channels, batch-inserts messages, and updates latest non-deleted channel messages.
Stamps and reactions
cmd/seed.go
Generates PNG stamps, persists ten stamps per seeded user, and batch-inserts randomized message-stamp reactions.

Estimated code review effort: 4 (Complex) | ~45 minutes

Merge Risk: ⚪ Minimal · up to 08258

No actionable merge-blocking risk remains; the change is merge-ready after normal checks and review.

Sequence Diagram(s)

sequenceDiagram
  participant Makefile
  participant rootCommand
  participant seedCommand
  participant Database
  participant FileManager
  Makefile->>rootCommand: invoke backend seed
  rootCommand->>seedCommand: execute seed command
  seedCommand->>Database: create users, channels, and messages
  seedCommand->>FileManager: create PNG stamp files
  seedCommand->>Database: persist stamps and reactions
Loading
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.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 The title clearly and concisely describes the main change: adding a database seeder.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch db-seed

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

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

Inline comments:
In `@cmd/seed.go`:
- Around line 191-203: The seed command currently hard-codes creation of an
admin user "traq"/"traq" using file.GenerateIconFile and repo.CreateUser
(CreateUserArgs with role.Admin); change this so the admin user is only created
in non-production/dev environments and the password is not embedded: add a check
for the runtime environment (e.g., config.Environment or an
IsDevelopment/isLocal guard) and skip creating the default admin unless that
check passes OR an explicit admin password is provided via a CLI flag (e.g.,
--admin-password) or env var (e.g., ADMIN_PASSWORD); read the password from that
flag/env var and pass it into repo.CreateUser instead of the hard-coded "traq"
value, and ensure role.Admin is only assigned under the gated condition.
- Around line 406-416: The backfill can return multiple rows per channel when
several messages share MAX(created_at); change the INSERT SELECT so each channel
yields exactly one row by choosing a deterministic tie-breaker (e.g., the
largest message id among rows with the max created_at). Replace the SELECT block
with a grouped query that joins the max created_at per channel and then GROUPs
BY m.channel_id selecting MAX(m.id) AS message_id and MAX(m.created_at) AS
date_time (so each channel contributes a single (channel_id, message_id,
date_time) tuple), then keep the ON DUPLICATE KEY UPDATE as-is; refer to the
channel_latest_messages table and the messages table/columns used in this diff
and note the primary key on channel_id defined in model/messages.go for locating
where to apply the change.
- Around line 154-156: Replace the detached context creation in the RunE of the
seed command with the Cobra-provided context (use cmd.Context()) and ensure that
all GORM operations use db.WithContext(ctx) rather than raw db, and that any
helper functions invoked from RunE that perform I/O accept and propagate this
ctx; specifically update the RunE closure to obtain ctx := cmd.Context(), change
direct db.Exec/raw writes and batch inserts to db.WithContext(ctx).Exec /
db.WithContext(ctx).Create (or equivalent), and if functions called from this
block (including any wrappers around batch inserts) don't accept context, add
context.Context as the first parameter and pass ctx through. Ensure
getCLILoggers() usage remains unchanged but that logger-using calls also take
ctx where applicable.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 4fbe8e0e-74f6-482a-ba15-ca0ceb03f408

📥 Commits

Reviewing files that changed from the base of the PR and between d6d3981 and da9b8d0.

📒 Files selected for processing (3)
  • Makefile
  • cmd/root.go
  • cmd/seed.go

Comment thread cmd/seed.go Outdated
Comment thread cmd/seed.go
Comment on lines +191 to +203
// 管理者ユーザー traq/traq の作成
adminIconID, err := file.GenerateIconFile(ctx, fm, "traq")
if err != nil {
return fmt.Errorf("failed to generate admin icon: %w", err)
}
if u, err := repo.CreateUser(ctx, repository.CreateUserArgs{
Name: "traq",
Password: "traq",
Role: role.Admin,
IconFileID: adminIconID,
}); err != nil {
logger.Warn("failed to create traq admin user (may already exist)", zap.Error(err))
} else {

@coderabbitai coderabbitai Bot Apr 4, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

Don't hard-code a known admin login in a general-purpose seed command.

This creates traq / traq with role.Admin against whatever database the active config points at. If seed is ever run outside an isolated local DB, it introduces a predictable privileged credential. Please gate this to dev-only environments and require the password from an explicit flag or env var instead of embedding it.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@cmd/seed.go` around lines 191 - 203, The seed command currently hard-codes
creation of an admin user "traq"/"traq" using file.GenerateIconFile and
repo.CreateUser (CreateUserArgs with role.Admin); change this so the admin user
is only created in non-production/dev environments and the password is not
embedded: add a check for the runtime environment (e.g., config.Environment or
an IsDevelopment/isLocal guard) and skip creating the default admin unless that
check passes OR an explicit admin password is provided via a CLI flag (e.g.,
--admin-password) or env var (e.g., ADMIN_PASSWORD); read the password from that
flag/env var and pass it into repo.CreateUser instead of the hard-coded "traq"
value, and ensure role.Admin is only assigned under the gated condition.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

まぁそうだが、初回起動前にmake seedした場合にしか起こらない問題で、そして初回起動時にtraqユーザーが作成されるのは既存の問題なので、このPRではそのままにする

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@ramdos0207 承知しました。この PR では変更しないという判断を尊重します。

make seed を初回起動前に実行した場合の traq 管理者作成は、既存の初回起動時の挙動と同じ問題として扱う、という前提ですね。必要であれば、この既存挙動を対象にしたフォローアップ Issue を作成できます。

🐇 ˘︵˘


✏️ Learnings added
Learnt from: ramdos0207
Repo: traPtitech/traQ PR: 2979
File: cmd/seed.go:191-203
Timestamp: 2026-08-15T14:35:32.414Z
Learning: In the traQ repository, running `make seed` before the first startup can create the default `traq` administrator. This is equivalent to existing first-startup behavior, where the `traq` user is also created. Remediation of the predictable default administrator credential is intentionally out of scope for pull request `#2979` and should be handled as a separate existing-behavior concern.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

You are interacting with an AI system.

Comment thread cmd/seed.go Outdated
@ramdos0207 ramdos0207 moved this from Inbox to Todo in traQ Server May 26, 2026
@ramdos0207 ramdos0207 moved this from Todo to In review in traQ Server May 26, 2026
@YuHima03
YuHima03 self-requested a review July 4, 2026 07:15
@YuHima03
YuHima03 removed their request for review August 10, 2026 11:38
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: In review

Development

Successfully merging this pull request may close these issues.

1 participant