> ## Documentation Index
> Fetch the complete documentation index at: https://private-7c7dfe99-fix-nav-issues.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

> リモートの PostgreSQL サーバーに格納されているデータに対して、`SELECT` および `INSERT` クエリを実行できます。

# postgresql

リモートの PostgreSQL サーバーに格納されているデータに対して、`SELECT` および `INSERT` クエリを実行できます。

<div id="syntax">
  ## 構文
</div>

```sql theme={null}
postgresql({host:port, database, table, user, password[, schema, [, on_conflict]] | named_collection[, option=value [,..]]})
```

<div id="arguments">
  ## 引数
</div>

| 引数            | 説明                                          |
| ------------- | ------------------------------------------- |
| `host:port`   | PostgreSQL サーバーのアドレス。                       |
| `database`    | リモートデータベースの名前。                              |
| `table`       | リモートテーブルの名前。                                |
| `user`        | PostgreSQL ユーザー。                            |
| `password`    | ユーザーのパスワード。                                 |
| `schema`      | デフォルト以外のテーブルスキーマ。省略可能です。                    |
| `on_conflict` | 競合解決の戦略。例: `ON CONFLICT DO NOTHING`。省略可能です。 |

引数は [named collections](/ja/concepts/features/configuration/server-config/named-collections) を使用して渡すこともできます。この場合、`host` と `port` は別々に指定する必要があります。この方法は本番環境に推奨されます。

<div id="returned_value">
  ## 戻り値
</div>

元の PostgreSQL テーブルと同じカラムを持つテーブルオブジェクト。

<Note>
  テーブル関数 `postgresql(...)` を、カラム名リスト付きのテーブル名と区別するには、`INSERT` クエリでキーワード `FUNCTION` または `TABLE FUNCTION` を使用する必要があります。以下の例を参照してください。
</Note>

<div id="implementation-details">
  ## 実装の詳細
</div>

PostgreSQL 側の `SELECT` クエリは、読み取り専用の PostgreSQL トランザクション内で `COPY (SELECT ...) TO STDOUT` として実行され、各 `SELECT` クエリの後にコミットされます。

`=`, `!=`, `>`, `>=`, `<`, `<=`, `IN` などの単純な `WHERE` 句は、PostgreSQL サーバー上で実行されます。

すべての JOIN、集計、ソート、`IN [ array ]` 条件、および `LIMIT` サンプリング制約は、PostgreSQL へのクエリが完了した後にのみ ClickHouse で実行されます。

PostgreSQL 側の `INSERT` クエリは、各 `INSERT` ステートメントの後に自動コミットされる PostgreSQL トランザクション内で、`COPY "table_name" (field1, field2, ... fieldN) FROM STDIN` として実行されます。

PostgreSQL の Array 型は ClickHouse の配列に変換されます。

<Note>
  PostgreSQL では、Integer\[] のような配列データ型のカラムに、行ごとに次元数の異なる配列を含めることができますが、ClickHouse ではすべての行で同じ次元数の多次元配列しか許可されないため、注意してください。
</Note>

複数のレプリカをサポートしており、`|` で列挙する必要があります。例:

```sql theme={null}
SELECT name FROM postgresql(`postgres{1|2|3}:5432`, 'postgres_database', 'postgres_table', 'user', 'password');
```

または

```sql theme={null}
SELECT name FROM postgresql(`postgres1:5431|postgres2:5432`, 'postgres_database', 'postgres_table', 'user', 'password');
```

PostgreSQL の Dictionary ソースで、レプリカの優先度をサポートしています。map 内の数値が大きいほど優先度は低くなります。最も高い優先度は `0` です。

<div id="examples">
  ## 例
</div>

PostgreSQL のテーブル：

```text theme={null}
postgres=# CREATE TABLE "public"."test" (
"int_id" SERIAL,
"int_nullable" INT NULL DEFAULT NULL,
"float" FLOAT NOT NULL,
"str" VARCHAR(100) NOT NULL DEFAULT '',
"float_nullable" FLOAT NULL DEFAULT NULL,
PRIMARY KEY (int_id));

CREATE TABLE

postgres=# INSERT INTO test (int_id, str, "float") VALUES (1,'test',2);
INSERT 0 1

postgresql> SELECT * FROM test;
  int_id | int_nullable | float | str  | float_nullable
 --------+--------------+-------+------+----------------
       1 |              |     2 | test |
(1 row)
```

通常の引数を使用してClickHouseからデータを選択する:

```sql theme={null}
SELECT * FROM postgresql('localhost:5432', 'test', 'test', 'postgresql_user', 'password') WHERE str IN ('test');
```

または、[named collections](/ja/concepts/features/configuration/server-config/named-collections)を使用する方法もあります：

```sql theme={null}
CREATE NAMED COLLECTION mypg AS
        host = 'localhost',
        port = 5432,
        database = 'test',
        user = 'postgresql_user',
        password = 'password';
SELECT * FROM postgresql(mypg, table='test') WHERE str IN ('test');
```

```text theme={null}
┌─int_id─┬─int_nullable─┬─float─┬─str──┬─float_nullable─┐
│      1 │         ᴺᵁᴸᴸ │     2 │ test │           ᴺᵁᴸᴸ │
└────────┴──────────────┴───────┴──────┴────────────────┘
```

データの挿入:

```sql theme={null}
INSERT INTO TABLE FUNCTION postgresql('localhost:5432', 'test', 'test', 'postgrsql_user', 'password') (int_id, float) VALUES (2, 3);
SELECT * FROM postgresql('localhost:5432', 'test', 'test', 'postgresql_user', 'password');
```

```text theme={null}
┌─int_id─┬─int_nullable─┬─float─┬─str──┬─float_nullable─┐
│      1 │         ᴺᵁᴸᴸ │     2 │ test │           ᴺᵁᴸᴸ │
│      2 │         ᴺᵁᴸᴸ │     3 │      │           ᴺᵁᴸᴸ │
└────────┴──────────────┴───────┴──────┴────────────────┘
```

非デフォルトのスキーマを使用する:

```text theme={null}
postgres=# CREATE SCHEMA "nice.schema";

postgres=# CREATE TABLE "nice.schema"."nice.table" (a integer);

postgres=# INSERT INTO "nice.schema"."nice.table" SELECT i FROM generate_series(0, 99) as t(i)
```

```sql theme={null}
CREATE TABLE pg_table_schema_with_dots (a UInt32)
        ENGINE PostgreSQL('localhost:5432', 'clickhouse', 'nice.table', 'postgrsql_user', 'password', 'nice.schema');
```

<div id="related">
  ## 関連
</div>

* [PostgreSQL テーブルエンジン](/ja/reference/engines/table-engines/integrations/postgresql)
* [PostgreSQL を Dictionary ソースとして使用する](/ja/reference/statements/create/dictionary/sources/postgresql)

<div id="replicating-or-migrating-postgres-data-with-with-peerdb">
  ### PeerDB を使用した Postgres データのレプリケーションまたは移行
</div>

> テーブル関数に加えて、ClickHouse の [PeerDB](https://docs.peerdb.io/introduction) を使って、Postgres から ClickHouse への継続的なデータパイプラインを構築することもできます。PeerDB は、CDC (変更データキャプチャ) を使用して Postgres から ClickHouse にデータをレプリケートするために専用設計されたツールです。
