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?

More than 5 years have passed since last update.

サクッとJSON形式のschema情報(bigquery用)を抽出するクエリ

Last updated at Posted at 2020-07-10

既存の他DBのスキーム情報からサクッとJSON形式のレイアウト情報を抽出するクエリです。

用途

bigqueryへのテーブル新規登録時のJson形式レイアウトをテーブルから取得したい時などに利用


SELECT  
  '[' || ARRAY_JOIN(
            ARRAY_AGG('{"name":"' || column_name || '", "type":"' || data_type || '", "mode": "' || is_nullable || '"}') 
            , ','
            ) 
  || ']'
FROM  
  (
  SELECT  
    column_name
    , CASE WHEN data_type = 'varchar' 
              THEN 'string' 
          WHEN data_type = 'double'
              THEN 'float'
          WHEN data_type = 'bigint'
              THEN 'integer'
              ELSE data_type 
      END AS data_type
    , CASE WHEN is_nullable = 'YES' 
              THEN 'nullable' 
              ELSE 'required' 
      END AS is_nullable
  FROM  
    information_schema.columns 
  WHERE 
    -- 以下にDB名とテーブル名を入れてクエリ実行すればJSON形式のレイアウトを取得可能
    table_schema || '.' || table_name = 'DB.table'
  )
  

bigquery触りたての頃は、既存のDB(mysqlとか)からデータ持ってくのに、Excelとかスプレッドシートをうまく使ってjsonレイアウト作ってたのですが、このクエリのおかげでかなり工数削減できるようになりました。
PRESTOで作ってあるので、ほかのDBでは試してないのですが、少し直せばいけると思われます。

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?