镜像站点 · 本页由第三方 GitHub 只读镜像提供,非 GitHub 官方站点,不接受任何登录或凭据输入。前往 github.com
Skip to content

Update batch script tables - #31508

Merged
sgress454 merged 10 commits into
mainfrom
sgress454/31505-update-batch-tables
Aug 5, 2025
Merged

sgress454 merged 10 commits into
mainfrom
sgress454/31505-update-batch-tables

Conversation

@sgress454

@sgress454 sgress454 commented Aug 1, 2025 •

Copy link
Copy Markdown
Contributor

for #31505

Checklist for submitter

  • Input data is properly validated, SELECT * is avoided, SQL injection is prevented (using placeholders for values in statements)

Testing

  • Added/updated automated tests

  • QA'd all new/changed functionality manually
    no changed functionality

Database migrations

  • Checked table schema to confirm autoupdate
  • Checked schema for all modified table for columns that will auto-update timestamps during migration.
  • Confirmed that updating the timestamps is acceptable, and will not cause unwanted side effects.
  • Ensured the correct collation is explicitly set for character columns (COLLATE utf8mb4_unicode_ci).
    collate for both these tables is previously set to utf8mb4_0900_ai_ci, but they don't contain user-settable strings

Summary by CodeRabbit

  • New Features

    • Expanded batch activity tracking with new fields for job ID, status, and activity type.
    • Enhanced database structure to support more flexible batch activity and host result management.
  • Bug Fixes

    • Updated references throughout the application to use the new table names for batch activities and host results, ensuring consistency.
  • Tests

    • Added and updated tests to validate the new batch activity schema and migration behavior.
  • Chores

    • Applied database migration to rename and restructure relevant tables for improved clarity and extensibility.

@sgress454
sgress454 requested a review from a team as a code owner August 1, 2025 14:12
@coderabbitai

coderabbitai Bot commented Aug 1, 2025 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

📝 Walkthrough

Walkthrough

This change renames and restructures two database tables related to batch script executions, updates associated SQL queries and code references, and adds a migration with a corresponding test. The schema now uses the names batch_activities and batch_activity_host_results with updated columns and constraints. Related Go code and tests are updated to reflect these changes.

Changes

Cohort / File(s) Change Summary
Database migration and test
server/datastore/mysql/migrations/tables/20250801083116_UpdateBatchScriptTables.go, server/datastore/mysql/migrations/tables/20250801083116_UpdateBatchScriptTables_test.go
Adds a migration that renames and restructures batch script tables, adds new columns, updates data, and provides a test to verify migration correctness.
Database schema
server/datastore/mysql/schema.sql
Renames and redefines batch_script_executions as batch_activities and batch_script_execution_host_results as batch_activity_host_results, updates columns, constraints, and migration status.
Host filtering logic
server/datastore/mysql/hosts.go
Updates table references in host filtering logic from old batch script tables to the new names.
Script execution logic
server/datastore/mysql/scripts.go
Updates SQL queries and insert statements to use the new table names and column structure.
Script execution tests
server/datastore/mysql/scripts_test.go
Updates test queries to use the new table names for checking host execution errors.

Sequence Diagram(s)

sequenceDiagram
    participant App
    participant DB

    App->>DB: Insert into batch_activities (new batch execution)
    App->>DB: Insert into batch_activity_host_results (host results)
    App->>DB: Query batch_activity_host_results for errors
    App->>DB: Query batch_activities for execution details
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~40 minutes

This review involves checking a non-trivial schema migration, updates to multiple SQL queries and code references, and a migration test. The changes are broad but focused on renaming and restructuring, with minimal logic changes.

✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch sgress454/31505-update-batch-tables

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.
    • Explain this complex logic.
    • 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 explain this code block.
  • 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 explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

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

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 generate unit tests to generate unit tests for 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.

@sgress454

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Aug 1, 2025

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

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

🔭 Outside diff range comments (1)
server/datastore/mysql/hosts.go (1)

1190-1215: Missing parentheses change query meaning

In the “errored” branch the filter is built as:

... AND bsehr.error IS NOT NULL OR hsr.exit_code > 0

Because AND binds tighter than OR, MySQL will read this as
(prev AND bsehr.error IS NOT NULL) OR hsr.exit_code > 0, returning every host whose exit_code>0 even for a different batch. Wrap the OR conditions:

- batchScriptExecutionIDFilter += ` AND bsehr.error IS NOT NULL OR hsr.exit_code > 0`
+ batchScriptExecutionIDFilter += ` AND (bsehr.error IS NOT NULL OR hsr.exit_code > 0)`

Also make sure batch_activity_host_results.batch_execution_id and host_script_results.execution_id are indexed, or the new LEFT JOINs will hurt ListHosts latency on large fleets.

🧹 Nitpick comments (1)
server/datastore/mysql/schema.sql (1)

109-112: nullable columns without defaults may cause surprise

status and activity_type allow NULL. In practice they will likely always be set ('started', 'script', etc.). Consider:

status        varchar(32)  NOT NULL DEFAULT 'started',
activity_type varchar(32)  NOT NULL DEFAULT 'script',

This guarantees data completeness and lets simple queries skip COALESCE.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5abf101 and 33dd92c.

📒 Files selected for processing (6)
  • server/datastore/mysql/hosts.go (2 hunks)
  • server/datastore/mysql/migrations/tables/20250801083116_UpdateBatchScriptTables.go (1 hunks)
  • server/datastore/mysql/migrations/tables/20250801083116_UpdateBatchScriptTables_test.go (1 hunks)
  • server/datastore/mysql/schema.sql (2 hunks)
  • server/datastore/mysql/scripts.go (4 hunks)
  • server/datastore/mysql/scripts_test.go (1 hunks)
🧰 Additional context used
🧠 Learnings (3)
📚 Learning: in ee/server/service/hostidentity/depot/depot.go, the error from result.rowsaffected() is intentiona...
Learnt from: getvictor
PR: fleetdm/fleet#30589
File: ee/server/service/hostidentity/depot/depot.go:115-115
Timestamp: 2025-07-08T16:11:49.555Z
Learning: In ee/server/service/hostidentity/depot/depot.go, the error from result.RowsAffected() is intentionally ignored because the information is only used for logging purposes, not for critical program logic.

Applied to files:

  • server/datastore/mysql/scripts_test.go
  • server/datastore/mysql/scripts.go
  • server/datastore/mysql/hosts.go
📚 Learning: in ee/server/service/hostidentity/depot/depot.go, the scep depot interface methods like put() do not...
Learnt from: getvictor
PR: fleetdm/fleet#30589
File: ee/server/service/hostidentity/depot/depot.go:108-111
Timestamp: 2025-07-08T16:12:48.797Z
Learning: In ee/server/service/hostidentity/depot/depot.go, the SCEP depot interface methods like Put() do not accept context parameters, and the common_mysql.WithRetryTxx callback function type TxFn only receives a transaction parameter, not a context. Therefore, using context.Background() in tx.ExecContext calls within the transaction callback is the correct approach.

Applied to files:

  • server/datastore/mysql/scripts.go
📚 Learning: in the fleet codebase, down migration functions are intentionally left empty/no-op. the team does no...
Learnt from: getvictor
PR: fleetdm/fleet#30589
File: server/datastore/mysql/migrations/tables/20250707095725_HostIdentitySCEPCertificates.go:53-55
Timestamp: 2025-07-08T16:13:39.114Z
Learning: In the Fleet codebase, Down migration functions are intentionally left empty/no-op. The team does not implement rollback functionality for database migrations, so empty Down_* functions in migration files are correct and should not be flagged as issues.

Applied to files:

  • server/datastore/mysql/migrations/tables/20250801083116_UpdateBatchScriptTables.go
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (24)
  • GitHub Check: test-go (vuln, ubuntu-latest, mysql:9.3.0, false)
  • GitHub Check: test-go (vuln, ubuntu-latest, mysql:8.0.36, false)
  • GitHub Check: test-go (service, ubuntu-latest, mysql:9.3.0, false)
  • GitHub Check: test-go (service, ubuntu-latest, mysql:8.0.36, false)
  • GitHub Check: test-go (mysql, ubuntu-latest, mysql:9.3.0, false)
  • GitHub Check: test-go (scripts, ubuntu-latest, mysql:8.0.36, false)
  • GitHub Check: test-go (integration-mdm, ubuntu-latest, mysql:8.0.36, false)
  • GitHub Check: test-go (main, ubuntu-latest, mysql:9.3.0, false)
  • GitHub Check: test-go (integration-core, ubuntu-latest, mysql:8.0.36, false)
  • GitHub Check: test-go (mysql, ubuntu-latest, mysql:8.0.36, false)
  • GitHub Check: test-go (main, ubuntu-latest, mysql:8.0.36, false)
  • GitHub Check: test-go (integration-enterprise, ubuntu-latest, mysql:8.0.36, false)
  • GitHub Check: test-go (fleetctl, ubuntu-latest, mysql:8.0.36, false)
  • GitHub Check: test-go (integration-mdm, ubuntu-latest, mysql:9.3.0, false)
  • GitHub Check: test-go (integration-core, ubuntu-latest, mysql:9.3.0, false)
  • GitHub Check: test-go (integration-enterprise, ubuntu-latest, mysql:9.3.0, false)
  • GitHub Check: test-go (fleetctl, ubuntu-latest, mysql:9.3.0, false)
  • GitHub Check: lint (macos-latest)
  • GitHub Check: lint (windows-latest)
  • GitHub Check: lint (ubuntu-latest)
  • GitHub Check: build-binaries
  • GitHub Check: publish
  • GitHub Check: Analyze (javascript)
  • GitHub Check: Analyze (go)
🔇 Additional comments (16)
server/datastore/mysql/scripts_test.go (4)

844-844: Good documentation update

The comment correctly reflects the new table name after the migration.


848-848: SQL query correctly updated

The table name change from batch_script_execution_host_results to batch_activity_host_results matches the migration and maintains the same query logic.


853-853: Consistent documentation update

The comment properly reflects the new table name, maintaining consistency with the previous update.


856-856: SQL query consistently updated

This second query correctly uses the new table name, maintaining consistency with the earlier change on line 848.

server/datastore/mysql/migrations/tables/20250801083116_UpdateBatchScriptTables.go (5)

8-18: Migration setup looks good

The migration registration and first table rename follow Fleet's standard patterns with proper error handling and descriptive error messages.


20-28: Column additions are well-designed

The new columns use appropriate data types: int unsigned for job_id and varchar(255) for status/activity_type fields. Adding them as nullable initially is a safe migration approach.


30-44: Data updates are safe and logical

The updates properly use WHERE ... IS NULL clauses to avoid overwriting existing data, and the default values ('started' and 'script') are appropriate for existing batch script executions.


46-51: Second table rename is consistent

The rename from batch_script_execution_host_results to batch_activity_host_results aligns with the broader refactoring and maintains consistent error handling.


56-58: Down migration correctly follows Fleet patterns

The empty Down migration function is intentional per Fleet's design - the team doesn't implement rollback functionality for database migrations, so this is the correct approach.

server/datastore/mysql/hosts.go (1)

547-551: Check cleanup list and foreign keys

You added batch_activity_host_results to hostRefs, so deleting a host now wipes its batch-activity rows. Nice. Please double-check the new table has a host_id FK ON DELETE CASCADE (or at least an index) to keep this delete fast and safe.

server/datastore/mysql/scripts.go (4)

868-868: Correct table name update for batch activities.

The table rename from batch_script_executions to batch_activities aligns well with the migration strategy described in the PR objectives. This maintains the same functionality while using the new, more generic table name.


887-887: Proper table name update for host results.

The rename from batch_script_execution_host_results to batch_activity_host_results follows the same pattern as the activities table. This keeps the host-specific execution tracking functionality intact while using the updated schema.


920-920: Correct query table reference update.

The FROM clause properly references the new batch_activity_host_results table name, maintaining the same query logic for gathering execution statistics.


934-934: Proper batch activities table reference.

The query correctly uses the new batch_activities table name while preserving the JOIN logic for retrieving script details in the summary.

server/datastore/mysql/migrations/tables/20250801083116_UpdateBatchScriptTables_test.go (1)

10-39: Well-structured migration test with good coverage.

This test does a nice job of validating the migration by:

  • Setting up the pre-migration state with test data
  • Applying the migration
  • Verifying that new columns (job_id, status, activity_type) have the expected default values

The use of sql.NullString and sql.NullInt64 is appropriate for handling potentially null database values, and the assertions properly validate the migration behavior.

One small suggestion: consider adding a comment explaining why job_id is expected to be null while status and activity_type have default values, as this helps document the migration's intended behavior.

server/datastore/mysql/schema.sql (1)

1427-1434: auto-increment bump looks good

The AUTO_INCREMENT moves to 407 and you insert row id 406. That keeps IDs monotonic, so the next migration lands on 407 automatically. Nice catch.

Comment thread server/datastore/mysql/schema.sql Resolved
Comment thread server/datastore/mysql/schema.sql Resolved
@codecov

codecov Bot commented Aug 1, 2025 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 63.63636% with 20 lines in your changes missing coverage. Please review.
✅ Project coverage is 63.71%. Comparing base (a19c2f7) to head (16664f3).
⚠️ Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
...s/tables/20250805083116_UpdateBatchScriptTables.go 60.00% 14 Missing and 6 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #31508      +/-   ##
==========================================
+ Coverage   63.69%   63.71%   +0.01%     
==========================================
  Files        1961     1962       +1     
  Lines      191141   191191      +50     
  Branches     6216     6216              
==========================================
+ Hits       121755   121818      +63     
+ Misses      59837    59823      -14     
- Partials     9549     9550       +1     
Flag Coverage Δ
backend 65.10% <63.63%> (+0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

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

@sgress454

Copy link
Copy Markdown
Contributor Author

Moving back to draft as we have more fields to add after discussion w/ @dantecatalfamo

@sgress454
sgress454 marked this pull request as draft August 1, 2025 17:16
@sgress454
sgress454 marked this pull request as ready for review August 4, 2025 04:47
return fmt.Errorf("failed to update activity_type in batch_activities: %w", err)
}

// Add an index on the new `status` column

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.

As discussed with @dantecatalfamo, to help optimize the query for batch activity status.

dantecatalfamo
dantecatalfamo previously approved these changes Aug 5, 2025

@dantecatalfamo dantecatalfamo left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

exquisite

@sgress454
sgress454 merged commit 672076f into main Aug 5, 2025
@sgress454
sgress454 deleted the sgress454/31505-update-batch-tables branch August 5, 2025 18:40

This branch was previously deployed

1 inactive deployment
Docker Hub — 16664f37 Deployed Aug 5, 2025 by sgress454
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