Menghubungkan psycopg3 ke database dialek PostgreSQL

Halaman ini menjelaskan cara menghubungkan driver psycopg3 PostgreSQL ke database dialek PostgreSQL di Spanner. psycopg3 adalah driver Python untuk PostgreSQL.

  1. Pastikan PGAdapter berjalan di mesin yang sama dengan aplikasi yang terhubung menggunakan driver psycopg3 PostgreSQL.

    export GOOGLE_APPLICATION_CREDENTIALS=/CREDENTIALS_FILE_PATH/credentials.json
    docker pull gcr.io/cloud-spanner-pg-adapter/pgadapter
    docker run \
      -d -p 5432:5432 \
      -v ${GOOGLE_APPLICATION_CREDENTIALS}:${GOOGLE_APPLICATION_CREDENTIALS}:ro \
      -e GOOGLE_APPLICATION_CREDENTIALS \
      gcr.io/cloud-spanner-pg-adapter/pgadapter \
      -p PROJECT_NAME -i INSTANCE_NAME \
      -x
    

    Untuk mengetahui informasi selengkapnya, lihat Mulai PGAdapter.

  2. Hubungkan ke PGAdapter menggunakan TCP.

    import psycopg
    
    with psycopg.connect("host=APPLICATION_HOST port=PORT dbname=DATABASE_NAME sslmode=disable") as conn:
      conn.autocommit = True
      with conn.cursor() as cur:
        cur.execute("select 'Hello world!' as hello")
        print("Greeting from Cloud Spanner PostgreSQL:", cur.fetchone()[0])
    

    Ganti kode berikut:

    • APPLICATION_HOST: nama host atau alamat IP mesin tempat PGAdapter berjalan. Jika berjalan secara lokal, gunakan localhost.
    • PORT: nomor port tempat PGAdapter berjalan. Ubah ini di string koneksi jika PGAdapter berjalan di port kustom. Jika tidak, gunakan port default, 5432.

Soket domain Unix

Bagian ini menjelaskan cara menggunakan soket domain Unix untuk terhubung ke database dialek PostgreSQL. Gunakan soket domain Unix untuk latensi serendah mungkin.

Untuk menggunakan soket domain Unix, PGAdapter harus berjalan di host yang sama dengan aplikasi klien.

Pastikan driver JDBC PostgreSQL dimuat.

import psycopg

with psycopg.connect("host=/tmp
                      port=PORT
                      dbname=DATABASE_NAME") as conn:
conn.autocommit = True
with conn.cursor() as cur:
  cur.execute("select 'Hello world!' as hello")
  print("Greetings from Cloud Spanner PostgreSQL:", cur.fetchone()[0])

Ganti kode berikut:

  • /tmp: direktori soket domain default untuk PGAdapter. Ini dapat diubah menggunakan argumen command line -dir.
  • PORT: nomor port tempat PGAdapter berjalan. Ubah ini di string koneksi jika PGAdapter berjalan di port kustom. Jika tidak, gunakan port default, 5432.

Langkah berikutnya

  • Pelajari PGAdapter lebih lanjut.
  • Untuk mengetahui informasi selengkapnya tentang opsi koneksi driver psycopg3 PostgreSQL, lihat Opsi Koneksi psycopg3 di repositori GitHub PGAdapter.