> ## Documentation Index
> Fetch the complete documentation index at: https://clickhouse.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

> Templateフォーマットのドキュメント

# Template

| 入力 | 出力 | エイリアス |
| -- | -- | ----- |
| ✔  | ✔  |       |

<div id="description">
  ## 説明
</div>

他の標準フォーマットでは足りない、より細かなカスタマイズが必要な場合は、
`Template` フォーマットを使うと、値のプレースホルダーを含む独自の フォーマット文字列 と、
データのエスケープ規則を指定できます。

使用する設定は次のとおりです。

| Setting                                                                                                  | Description                                                            |
| -------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- |
| [`format_template_row`](#format_template_row)                                                            | 行の フォーマット文字列 を含むファイルへの path を指定します。                                    |
| [`format_template_resultset`](#format_template_resultset)                                                | 行の フォーマット文字列 を含むファイルへの path を指定します。                                    |
| [`format_template_rows_between_delimiter`](#format_template_rows_between_delimiter)                      | 行間の区切り文字を指定します。これは最後の行を除く各行の後に出力される (または入力として期待される) ものです (デフォルトは `\n`) |
| `format_template_row_format`                                                                             | 行の フォーマット文字列 を[インラインで](#inline_specification)指定します。                    |
| `format_template_resultset_format`                                                                       | 結果セットの フォーマット文字列 を[インラインで](#inline_specification)指定します。                |
| Some settings of other formats (e.g.`output_format_json_quote_64bit_integers` when using `JSON` escaping |                                                                        |

<div id="settings-and-escaping-rules">
  ## 設定とエスケープルール
</div>

<div id="format_template_row">
  ### format\_template\_row
</div>

設定 `format_template_row` は、次の構文で行の フォーマット文字列 を含むファイルへのパスを指定します。

```text theme={null}
delimiter_1${column_1:serializeAs_1}delimiter_2${column_2:serializeAs_2} ... delimiter_N
```

各構文要素の意味は次のとおりです。

| Part of syntax  | Description                                      |
| --------------- | ------------------------------------------------ |
| `delimiter_i`   | 値の間の区切り文字 (`$` 記号は `$$` としてエスケープ可能)              |
| `column_i`      | 選択または挿入する値に対応するカラムの名前または索引 (空の場合、そのカラムはスキップされます) |
| `serializeAs_i` | カラムの値に適用するエスケープ規則。                               |

サポートされているエスケープ規則は次のとおりです。

| Escaping Rule        | Description          |
| -------------------- | -------------------- |
| `CSV`, `JSON`, `XML` | 同名のフォーマットと同様         |
| `Escaped`            | `TSV` と同様            |
| `Quoted`             | `Values` と同様         |
| `Raw`                | エスケープなし。`TSVRaw` と同様 |
| `None`               | エスケープ規則なし - 下記の注記を参照 |

<Note>
  エスケープ規則を省略した場合は、`None` が使用されます。`XML` は出力にのみ適しています。
</Note>

例を見てみましょう。次のフォーマット文字列が与えられているとします。

```text theme={null}
Search phrase: ${s:Quoted}, count: ${c:Escaped}, ad price: $$${p:JSON};
```

以下の値は、`SELECT` を使用する場合は出力され、`INPUT` を使用する場合は入力として期待されます。
それぞれ、カラム `Search phrase:`, `, count:`, `, ad price: $` の間、および `;` の区切り文字で区切られます。

* `s` (エスケープルールは `Quoted`)
* `c` (エスケープルールは `Escaped`)
* `p` (エスケープルールは `JSON`)

例えば:

* `INSERT` する場合、以下の行は期待されるテンプレートに一致しており、値 `bathroom interior design`, `2166`, `$3` がカラム `Search phrase`, `count`, `ad price` に読み込まれます。
* `SELECT` する場合、値 `bathroom interior design`, `2166`, `$3` がすでにテーブルのカラム `Search phrase`, `count`, `ad price` に格納されているとすると、以下の行が出力されます。

```yaml theme={null}
Search phrase: 'bathroom interior design', count: 2166, ad price: $3;
```

<div id="format_template_rows_between_delimiter">
  ### format\_template\_rows\_between\_delimiter
</div>

設定 `format_template_rows_between_delimiter` は、行間の区切り文字を指定します。これは、最後の行を除く各行の後に出力される (または入力時に期待される) 文字列です (デフォルトは `\n`) 。

<div id="format_template_resultset">
  ### format\_template\_resultset
</div>

設定 `format_template_resultset` は、結果セット用のフォーマット文字列を含むファイルのパスを指定します。

結果セット用のフォーマット文字列は、行用のフォーマット文字列と同じ構文です。
プレフィックスや接尾辞、追加情報の出力方法を指定でき、カラム名の代わりに次のプレースホルダーを含めます。

* `data` は、`format_template_row` フォーマットのデータを含む行で、`format_template_rows_between_delimiter` で区切られます。このプレースホルダーは、フォーマット文字列内で最初のプレースホルダーでなければなりません。
* `totals` は、`format_template_row` フォーマットの合計値を含む行です (WITH TOTALS を使用する場合) 。
* `min` は、`format_template_row` フォーマットの最小値を含む行です (extremes が 1 に設定されている場合) 。
* `max` は、`format_template_row` フォーマットの最大値を含む行です (extremes が 1 に設定されている場合) 。
* `rows` は、出力される行の総数です。
* `rows_before_limit` は、LIMIT がなかった場合に存在していた行数の最小値です。これは、クエリに LIMIT が含まれている場合にのみ出力されます。クエリに GROUP BY が含まれる場合、rows\_before\_limit\_at\_least は、LIMIT がなかった場合に存在していた行数の正確な値です。
* `time` は、リクエストの実行時間 (秒) です。
* `rows_read` は、読み込まれた行数です。
* `bytes_read` は、読み込まれたバイト数 (非圧縮) です。

プレースホルダー `data`、`totals`、`min`、`max` にはエスケープ規則を指定してはなりません (または `None` を明示的に指定する必要があります) 。それ以外のプレースホルダーには、任意のエスケープ規則を指定できます。

<Note>
  `format_template_resultset` 設定が空文字列の場合、デフォルト値として `${data}` が使用されます。
</Note>

INSERT クエリのフォーマットでは、プレフィックスまたは接尾辞がある場合、一部のカラムまたはフィールドを省略できます (例を参照) 。

<div id="inline_specification">
  ### インライン指定
</div>

多くの場合、Templateフォーマットのフォーマット設定
(`format_template_row`、`format_template_resultset` で設定) を、クラスター内のすべてのノードのディレクトリにデプロイするのは困難であり、不可能なこともあります。
さらに、フォーマットが非常に単純であれば、ファイルに置く必要がない場合もあります。

このような場合は、`format_template_row_format` (`format_template_row` 用) および `format_template_resultset_format` (`format_template_resultset` 用) を使用して、テンプレート文字列を、それを含むファイルへのパスとしてではなく、クエリ内で直接設定できます。

<Note>
  フォーマット文字列およびエスケープシーケンスのルールは、次の場合と同じです。

  * `format_template_row_format` を使用する場合の [`format_template_row`](#format_template_row)。
  * `format_template_resultset_format` を使用する場合の [`format_template_resultset`](#format_template_resultset)。
</Note>

<div id="example-usage">
  ## 使用例
</div>

`Template`フォーマットの使用例を2つ見ていきます。まずはデータの選択、次にデータの挿入です。

<div id="selecting-data">
  ### データの取得
</div>

```sql title="Query" theme={null}
SELECT SearchPhrase, count() AS c FROM test.hits GROUP BY SearchPhrase ORDER BY c DESC LIMIT 5 FORMAT Template SETTINGS
format_template_resultset = '/some/path/resultset.format', format_template_row = '/some/path/row.format', format_template_rows_between_delimiter = '\n    '
```

```text title="/some/path/resultset.format" theme={null}
<!DOCTYPE HTML>
<html> <head> <title>Search phrases</title> </head>
 <body>
  <table border="1"> <caption>Search phrases</caption>
    <tr> <th>Search phrase</th> <th>Count</th> </tr>
    ${data}
  </table>
  <table border="1"> <caption>Max</caption>
    ${max}
  </table>
  <b>Processed ${rows_read:XML} rows in ${time:XML} sec</b>
 </body>
</html>
```

```text title="/some/path/row.format" theme={null}
<tr> <td>${0:XML}</td> <td>${1:XML}</td> </tr>
```

```html title="Response" theme={null}
<!DOCTYPE HTML>
<html> <head> <title>Search phrases</title> </head>
 <body>
  <table border="1"> <caption>Search phrases</caption>
    <tr> <th>Search phrase</th> <th>Count</th> </tr>
    <tr> <td></td> <td>8267016</td> </tr>
    <tr> <td>bathroom interior design</td> <td>2166</td> </tr>
    <tr> <td>clickhouse</td> <td>1655</td> </tr>
    <tr> <td>spring 2014 fashion</td> <td>1549</td> </tr>
    <tr> <td>freeform photos</td> <td>1480</td> </tr>
  </table>
  <table border="1"> <caption>Max</caption>
    <tr> <td></td> <td>8873898</td> </tr>
  </table>
  <b>Processed 3095973 rows in 0.1569913 sec</b>
 </body>
</html>
```

<div id="inserting-data">
  ### データの挿入
</div>

```text theme={null}
Some header
Page views: 5, User id: 4324182021466249494, Useless field: hello, Duration: 146, Sign: -1
Page views: 6, User id: 4324182021466249494, Useless field: world, Duration: 185, Sign: 1
Total rows: 2
```

```sql theme={null}
INSERT INTO UserActivity SETTINGS
format_template_resultset = '/some/path/resultset.format', format_template_row = '/some/path/row.format'
FORMAT Template
```

```text title="/some/path/resultset.format" theme={null}
Some header\n${data}\nTotal rows: ${:CSV}\n
```

```text title="/some/path/row.format" theme={null}
Page views: ${PageViews:CSV}, User id: ${UserID:CSV}, Useless field: ${:CSV}, Duration: ${Duration:CSV}, Sign: ${Sign:CSV}
```

プレースホルダー内の`PageViews`、`UserID`、`Duration`、`Sign`は、テーブル内のカラム名です。行内の`Useless field`の後ろにある値と、接尾辞内の`\nTotal rows:`の後ろにある値は無視されます。
入力データ内のすべての区切り文字は、指定されたフォーマット文字列内の区切り文字と厳密に一致している必要があります。

<div id="inline_specification">
  ### インライン指定
</div>

Markdown テーブルを手作業でフォーマットするのは面倒ではありませんか？この例では、`Template` フォーマットとインライン指定の設定を使って、シンプルなタスク、つまり `system.formats` テーブルからいくつかの ClickHouse フォーマット名を `SELECT` し、それらを Markdown テーブルとして整形する方法を見ていきます。これは、`Template` フォーマットと設定 `format_template_row_format` および `format_template_resultset_format` を使えば簡単に実現できます。

前の例では、結果セットと行のフォーマット文字列を別々のファイルに指定し、それらのファイルのパスをそれぞれ設定 `format_template_resultset` と `format_template_row` で指定していました。ここでは、テンプレートが単純で、Markdown テーブルを作るための `|` と `-` が少しあるだけなので、インラインで指定します。結果セットのテンプレート文字列は、設定 `format_template_resultset_format` を使って指定します。テーブルヘッダーを作るため、`${data}` の前に `|ClickHouse Formats|\n|---|\n` を追加しています。行のテンプレート文字列 ``|`{0:XML}`|`` は、設定 `format_template_row_format` で指定します。`Template` フォーマットは、指定したフォーマットで行をプレースホルダー `${data}` に挿入します。この例ではカラムは 1 つだけですが、さらに追加したい場合は、行テンプレート文字列に `{1:XML}`、`{2:XML}` などを追加すれば対応できます。その際は必要に応じて適切なエスケープルールを選択してください。この例では、エスケープルール `XML` を使用しています。

```sql title="Query" theme={null}
WITH formats AS
(
 SELECT * FROM system.formats
 ORDER BY rand()
 LIMIT 5
)
SELECT * FROM formats
FORMAT Template
SETTINGS
 format_template_row_format='|`${0:XML}`|',
 format_template_resultset_format='|ClickHouse Formats|\n|---|\n${data}\n'
```

ご覧のとおり、あの Markdown テーブルを作るために大量の `|` や `-` を手作業で追加する手間が省けました。

```response title="Response" theme={null}
|ClickHouse Formats|
|---|
|`BSONEachRow`|
|`CustomSeparatedWithNames`|
|`Prometheus`|
|`DWARF`|
|`Avro`|
```
