Skip to content

Normalize stored timestamps to UTC and tighten date-filter UX#23

Merged
JulienTant merged 2 commits into
mainfrom
date-filter-followups
May 19, 2026
Merged

Normalize stored timestamps to UTC and tighten date-filter UX#23
JulienTant merged 2 commits into
mainfrom
date-filter-followups

Conversation

@JulienTant
Copy link
Copy Markdown
Owner

@JulienTant JulienTant commented May 19, 2026

Summary

Follow-ups to #21:

  • Timezone correctness: published_date, discovered_date, and last_scanned are now stored as UTC at write time, so the lexicographic string comparison used by --since / --before is correct for feeds that supply non-UTC offsets.
  • Migration 000003 rewrites existing rows via strftime('%Y-%m-%dT%H:%M:%fZ', …) so prior data is normalized in place.
  • --since / --before parse errors now flow through printError / markError, matching the rest of the articles command.
  • Reject --since > --before with a friendly message instead of silently returning an empty list.
  • --before semantics remain exclusive, as documented.

Test plan

  • golangci-lint run passes
  • gotestsum -- ./... passes (132 tests)
  • New tests:
    • TestAddArticleStoresPublishedDateInUTC / TestUpdateBlogLastScannedStoresInUTC — JST input is persisted with a Z suffix.
    • TestDateFilterRespectsTimezoneEquivalence — a JST 2024-01-15 02:00 article (UTC 2024-01-14 17:00) is correctly excluded by --since 2024-01-15.
    • TestMigrationNormalizesLegacyTimestampsToUTC — legacy +09:00 rows inserted raw are rewritten to UTC by the migration SQL.
    • TestParseDateFilter / TestParseDateRange — empty inputs, valid/invalid formats, only-one-side, equal bounds, and the since > before rejection.

Summary by CodeRabbit

  • New Features

    • Added date range filtering for articles with --since and --before flags supporting YYYY-MM-DD format
    • Enhanced date input validation with clear error messaging
  • Bug Fixes

    • Fixed timezone inconsistencies by normalizing all stored timestamps to UTC, ensuring reliable date filtering across different timezones

Review Change Stack

- Store published_date, discovered_date, last_scanned as UTC at write time
  so lexicographic comparison in --since/--before works across feeds with
  non-UTC offsets.
- Add migration 000003 to rewrite existing rows via strftime to UTC.
- Route --since/--before parse errors through printError/markError.
- Reject --since > --before with a friendly message.
- Cover new behavior with storage + CLI tests, including a legacy-row
  migration test.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 19, 2026

Warning

Rate limit exceeded

@JulienTant has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 41 minutes and 1 second before requesting another review.

You’ve run out of usage credits. Purchase more in the billing tab.

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

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: b2c3db19-4e69-4eea-a676-201082552e3a

📥 Commits

Reviewing files that changed from the base of the PR and between 6a90b4a and a362cc2.

📒 Files selected for processing (3)
  • internal/storage/database.go
  • internal/storage/database_test.go
  • internal/storage/migrations/000003_normalize_dates_utc.up.sql
📝 Walkthrough

Walkthrough

This PR adds UTC timestamp normalization to the CLI and database layers. A new CLI helper validates and orders --since/--before date filters. Database methods normalize stored and queried timestamps to UTC. A migration converts legacy timestamps to UTC RFC3339 format.

Changes

UTC Timestamp Normalization

Layer / File(s) Summary
CLI Date Range Parsing
internal/cli/commands.go, internal/cli/commands_test.go
Introduces parseDateRange helper that validates --since/--before dates, enforces ordering (sincebefore), and integrates with the articles command. Tests cover empty/valid/invalid inputs and ordering constraints.
Database UTC Storage and Filtering
internal/storage/database.go, internal/storage/database_test.go
UpdateBlogLastScanned, ListArticles, and formatTimePtr all convert timestamps to UTC before storage or querying. Tests verify UTC representation on write, timezone-aware filtering behavior, and full read-write cycle correctness.
Database Migration: Normalize Legacy Timestamps
internal/storage/migrations/000003_normalize_dates_utc.up.sql, internal/storage/migrations/000003_normalize_dates_utc.down.sql, internal/storage/database_test.go
Migration rewrites published_date, discovered_date, and last_scanned to UTC RFC3339 format. Down migration is a no-op. Integration test verifies in-place conversion and API readability of normalized data.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • JulienTant/blogwatcher-cli#21: Introduces the --since/--before flags and initial ListArticles date filtering; this PR extends that work with a dedicated range-validation helper and UTC-normalization across both CLI parsing and database storage layers.

Poem

🐰 Timestamps once danced in timezones galore,
But UTC midnight settles the score!
Z marks the spot where all moments align,
Legacy data now normalized fine.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 7.69% 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
Title check ✅ Passed The title clearly and concisely summarizes the two main objectives: normalizing timestamps to UTC and improving date filter validation.
Description check ✅ Passed The description covers all required template sections with detailed explanations and a comprehensive test plan showing verification was completed.
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch date-filter-followups

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

@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

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@internal/storage/database_test.go`:
- Around line 527-528: Replace the raw SQL string usages in the tests with
squirrel query builders: instead of calling db.conn.QueryRowContext(ctx, "SELECT
published_date FROM articles WHERE url = ?", url).Scan(&stored) (and the similar
raw queries around the other ranges), build the query using
squirrel.Select("published_date").From("articles").Where(squirrel.Eq{"url":
url}).RunWith(db.conn).QueryRowContext(ctx) (or use ToSql/QueryRowContext
pattern consistent with your test helpers), then Scan(&stored); apply the same
transformation for the other occurrences (the selects/inserts in lines 549-550
and 590-622) so all queries use squirrel builders rather than raw SQL strings,
keeping db.conn, ctx and Scan usage intact.

In `@internal/storage/migrations/000003_normalize_dates_utc.up.sql`:
- Around line 8-18: The UPDATEs that normalize timestamps (on
articles.published_date, articles.discovered_date and blogs.last_scanned) should
be hardened so strftime() failures don't silently set values to NULL; change
each SET to preserve the original value when strftime(...) yields NULL (e.g.,
wrap with COALESCE(strftime(...), <original_column>)) so unparseable legacy
timestamps are retained for investigation rather than overwritten.
- Around line 9-17: The migration currently normalizes timestamps with
strftime('%Y-%m-%dT%H:%M:%fZ') which produces fractional-second shapes that can
differ from Go's time.RFC3339Nano and break lexicographic comparisons; change
the three UPDATEs to a consistent shape by removing fractional seconds (use
strftime('%Y-%m-%dT%H:%M:%SZ')) for published_date, discovered_date and
last_scanned so all stored strings are identical-length RFC3339 UTC timestamps,
avoiding mixed forms like ...00Z vs ...00.000Z.
🪄 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: defaults

Review profile: CHILL

Plan: Pro

Run ID: a9b9778c-e8be-44b7-aaa3-24f55f170c5f

📥 Commits

Reviewing files that changed from the base of the PR and between 01fed02 and 6a90b4a.

📒 Files selected for processing (6)
  • internal/cli/commands.go
  • internal/cli/commands_test.go
  • internal/storage/database.go
  • internal/storage/database_test.go
  • internal/storage/migrations/000003_normalize_dates_utc.down.sql
  • internal/storage/migrations/000003_normalize_dates_utc.up.sql

Comment thread internal/storage/database_test.go Outdated
Comment thread internal/storage/migrations/000003_normalize_dates_utc.up.sql
Comment thread internal/storage/migrations/000003_normalize_dates_utc.up.sql Outdated
- Migration: wrap strftime() in COALESCE so unparseable legacy timestamps
  are preserved instead of silently nulled, and drop fractional seconds
  for a uniform fixed-width RFC3339 shape.
- App writes: store timestamps via a second-precision UTC layout so the
  lexicographic comparison in ListArticles is stable across all rows.
  Parsing still uses RFC3339Nano for legacy/fractional values.
- Tests: replace raw SQL in storage tests with squirrel, replay the actual
  migration file rather than inline SQL, and cover the COALESCE
  preservation behavior.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@JulienTant JulienTant merged commit 34886d8 into main May 19, 2026
2 checks passed
@JulienTant JulienTant deleted the date-filter-followups branch May 19, 2026 18:17
@JulienTant JulienTant mentioned this pull request May 19, 2026
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.

1 participant