0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Redash の日付パラメータを雑に受け取りたい

Last updated at Posted at 2025-12-02

🧩 実務で困ったこと

Redash クエリで、異なる日付を集計できるように日付をパラメータ化することがよくあります。
通常、FROM, TO の 2つのパラメータを用意し、

DECLARE __from TIMESTAMP DEFAULT TIMESTAMP("{{FROM}} 00:00:00", "Asia/Tokyo");
DECLARE __to TIMESTAMP DEFAULT TIMESTAMP("{{TO}} 00:00:00", "Asia/Tokyo");

のように TIMESTAMP 型に変換する処理を頻繁に書いています。
ただ、Redash の日付入力は Date と Date & Time が混在しがちで、
「日付だけ」「日付+時刻」「秒あり」などフォーマットがバラつくことがあります。

実務でも

「このレポートだけ直近3時間見たい」
「普段は日単位だけど、緊急時だけ時刻指定したい」

といった要望をもらうため、既存のクエリを壊さず、どんなフォーマットでも受け取れる方法 が必要でした。

🧮 最終的に採用した方法

TIMESTAMP の受け取りを Try/catch (exception) で全部受けるような形にします。
ひたすら例外処理でパースを試すことで、

  • DATE
  • DATE and Time
  • DATE and Time (with seconds)

どれでも入力できるようにします。

DECLARE __to TIMESTAMP;
DECLARE __from TIMESTAMP;

-- ===== TO =====
BEGIN
    SET __to = TIMESTAMP("{{TO}} 23:59:59");
EXCEPTION WHEN ERROR THEN
    BEGIN
        SET __to = TIMESTAMP("{{TO}}:59");
    EXCEPTION WHEN ERROR THEN
        SET __to = TIMESTAMP("{{TO}}");
    END;
END;

-- ===== FROM =====
BEGIN
    SET __from = TIMESTAMP("{{FROM}} 00:00:00");
EXCEPTION WHEN ERROR THEN
    BEGIN
        SET __from = TIMESTAMP("{{FROM}}:00");
    EXCEPTION WHEN ERROR THEN
        SET __from = TIMESTAMP("{{FROM}}");
    END;
END;

SELECT
    __from AS from_ts,
    __to   AS to_ts;
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?