Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
1
Help us understand the problem. What is going on with this article?
@tamanobi

BigQueryでクエリロジックのテストを書く

More than 1 year has passed since last update.

BigQueryで虚無からSQLだけでデータを作る と ERROR() を使う

ERROR

これを実行すると結果が合っていた場合は、クエリが実行され、間違っているときはエラーになる。

SQL


#standardSQL
WITH TEST_DATA AS (
-- テストデータ
SELECT * FROM UNNEST(ARRAY<STRUCT<time TIMESTAMP, event STRING, id INT64>>
[
  (TIMESTAMP "2020-02-17 00:00:00+00", 'すごいイベント', NULL)
  , (TIMESTAMP "2020-02-18 01:00:00+00", 'awesome event', 123)
]))
, EXPECTED AS (
-- 期待する結果

SELECT * FROM UNNEST(ARRAY<STRUCT<time TIMESTAMP, event STRING>>
[
  (TIMESTAMP "2020-02-17T00:00:00", 'すごいイベント')
])
)
, ACTUAL AS (
-- ここがクエリ
SELECT time, event FROM
  TEST_DATA
WHERE time < TIMESTAMP_ADD(TIMESTAMP "2020-02-18T12:00:00", INTERVAL -1 DAY)
)

-- diffを出す
, diff AS (
SELECT *, "actual - expected" AS description FROM (SELECT *, ROW_NUMBER() OVER() AS n FROM ACTUAL EXCEPT DISTINCT SELECT *, ROW_NUMBER() OVER() AS n FROM EXPECTED) UNION ALL
SELECT *, "expected - actual" AS description FROM (SELECT *, ROW_NUMBER() OVER() AS n FROM EXPECTED EXCEPT DISTINCT SELECT *, ROW_NUMBER() OVER() AS n FROM ACTUAL)
)

-- diffがなければOK
SELECT IF(NOT EXISTS(SELECT * FROM diff), "OK", ERROR("クエリが間違っています"))

クライアントから呼び出せばいい???

うーん、もっといい方法はないだろうか……。何らかのプログラミング言語のBigQueryクライアントから呼び出して言語標準の辞書ベースで比較するの一番ラクだろうか。

1
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
tamanobi
Vim/Python/C++/Common Lisp/PHP/JavaScript/データ分析/機械学習/画像解析/NEM
admin-guild
「Webサービスの運営に必要なあらゆる知見」を共有できる場として作られた、運営者のためのコミュニティです。

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
1
Help us understand the problem. What is going on with this article?