OiO.lk Blog python Cannot connect to postgres databes over prisma python client. “prisma.engine.errors.EngineConnectionError: Could not connect to the query engine”
python

Cannot connect to postgres databes over prisma python client. “prisma.engine.errors.EngineConnectionError: Could not connect to the query engine”


I am trying to use prisma python client to connect to postgres which is deploied locally in docker. However it always report error prisma.engine.errors.EngineConnectionError: Could not connect to the query engine. Can anybody help to resolve this issue?

Note: I am using Nextjs as front-end and Python as backend, prisma works fine in nextjs and works fine with prisma==0.13.1 as well on another Linux(CentOS Linux release 8.5.2111) which is lower performance(1G, 1CPU). I am trying to migurate to a powful performance VM(15vCPUs and 16 GB RAM).The connection issue happened on it.

I am using Python3.8.18 which install by source code (configure;make;make install) on CentOS Linux release 8.5.2111

prisma==0.15.0 (doesn’t work on prisma==0.13.1 as well).

prisma verson is 5.17( after run prisma generate)

# prisma --version
Environment variables loaded from .env
prisma                : 5.17.0
@prisma/client        : Not found
Computed binaryTarget : rhel-openssl-1.1.x
Operating System      : linux
Architecture          : x64
Node.js               : v23.0.0
Query Engine (Binary) : query-engine 393aa359c9ad4a4bb28630fb5613f9c281cde053 (at ../.cache/prisma-python/binaries/5.17.0/393aa359c9ad4a4bb28630fb5613f9c281cde053/node_modules/@prisma/engines/query-engine-rhel-openssl-1.1.x)
Schema Engine         : schema-engine-cli 393aa359c9ad4a4bb28630fb5613f9c281cde053 (at ../.cache/prisma-python/binaries/5.17.0/393aa359c9ad4a4bb28630fb5613f9c281cde053/node_modules/@prisma/engines/schema-engine-rhel-openssl-1.1.x)
Schema Wasm           : @prisma/prisma-schema-wasm 5.17.0-31.393aa359c9ad4a4bb28630fb5613f9c281cde053
Default Engines Hash  : 393aa359c9ad4a4bb28630fb5613f9c281cde053
Studio                : 0.502.0

Here is prisma schema file

[root@xxxxx]# cat prisma/schema.prisma 
// database
datasource db {
  provider = "postgres"
  url      = env("DATABASE_URL")
}

// generator
generator client {
  provider             = "prisma-client-py"
  recursive_type_depth = 5
  interface            = "sync"
}

model User {
  id    String @id @unique
  email String @unique
}

Here is .env file in current folder

[root@yt-oecent prisma]# cat .env 
DATABASE_URL=postgres://myuser:mypassword@127.0.0.1:5432/mydatabase?sslmode=disable

Here is postgres docker-compose.yml

[root@xxxxx]# cat docker-compose.yml 
version: '3.8'

services:
  db:
    image: postgres:latest
    container_name: postgres_db
    environment:
      POSTGRES_USER: myuser
      POSTGRES_PASSWORD: mypassword
      POSTGRES_DB: mydatabase
    ports:
      - "5432:5432"
    volumes:
      - db_data:/var/lib/postgresql/data
    restart: always

volumes:
  db_data:

I am sure that the connection string is correct since the result of connecting over psycopg2 successful.

[root@xxxxxxxx]# cat test_pg.py 
import psycopg2
from psycopg2 import OperationalError


def test_connection():
    try:
        # Connection URL with the endpoint passed as a parameter
        connection = psycopg2.connect(
            "postgres://myuser:mypassword@127.0.0.1:5432/mydatabase"
        )

        # If connection is successful
        print("Connection successful!")
        connection.close()

    except OperationalError as e:
        # If connection fails
        print(f"Connection failed! Error: {e}")


if __name__ == "__main__":
    test_connection()
[root@xxxxx ]# python3 test_pg.py 
Connection successful!

However failure with python prisma client:

[root@xxxx]# cat test_prisma.py 
from prisma import Prisma
import logging
from dotenv import load_dotenv
import os
import asyncio

load_dotenv()  # Load environment variables from .env file

DATABASE_URL = os.getenv("DATABASE_URL")

logging.basicConfig(level=logging.DEBUG)

async def run():
    db = Prisma()
    print(DATABASE_URL)
    await db.connect()
    print("Connected to PostgreSQL database successfully!")
    await db.disconnect()



if __name__ == "__main__":
    asyncio.run(run())

Below is the testing result, The third line of output DEBUG:prisma._base_client:datasources: None is suspicious.

[root@yt-oecent prisma]# python3 test_prisma.py 
DEBUG:asyncio:Using selector: EpollSelector
postgres://myuser:mypassword@127.0.0.1:5432/mydatabase?sslmode=disable
DEBUG:prisma._base_client:datasources: None
DEBUG:prisma.engine._query:Connecting to query engine
DEBUG:prisma.engine.utils:Expecting local query engine /root/prisma/prisma-query-engine-rhel-openssl-1.1.x
DEBUG:prisma.engine.utils:Expecting global query engine /root/.cache/prisma-python/binaries/5.17.0/393aa359c9ad4a4bb28630fb5613f9c281cde053/prisma-query-engine-rhel-openssl-1.1.x
DEBUG:prisma.engine.utils:Query engine found from the Prisma CLI generated path: /root/.cache/prisma-python/binaries/5.17.0/393aa359c9ad4a4bb28630fb5613f9c281cde053/node_modules/prisma/query-engine-rhel-openssl-1.1.x
DEBUG:prisma.engine.utils:Using Query Engine binary at /root/.cache/prisma-python/binaries/5.17.0/393aa359c9ad4a4bb28630fb5613f9c281cde053/node_modules/prisma/query-engine-rhel-openssl-1.1.x
DEBUG:prisma.engine.utils:Version check took 0.0122s
DEBUG:prisma.engine.utils:Using query engine version 393aa359c9ad4a4bb28630fb5613f9c281cde053
DEBUG:prisma.engine.utils:Using query engine at /root/.cache/prisma-python/binaries/5.17.0/393aa359c9ad4a4bb28630fb5613f9c281cde053/node_modules/prisma/query-engine-rhel-openssl-1.1.x
DEBUG:prisma.engine.utils:Ensuring query engine took: 0.0258s
DEBUG:prisma.engine._query:Running query engine on port 59631
DEBUG:prisma.engine._query:Starting query engine...
DEBUG:prisma.engine._http:Constructed GET request to http://localhost:59631/status
DEBUG:prisma.engine._http:Request headers: {'Accept': 'application/json'}
DEBUG:prisma.engine._http:Request content: None
DEBUG:httpx:load_ssl_context verify=True cert=None trust_env=True http2=False
DEBUG:httpx:load_verify_locations cafile="/usr/local/lib/python3.8/site-packages/certifi/cacert.pem"
DEBUG:httpcore.connection:connect_tcp.started host="localhost" port=59631 local_address=None timeout=30 socket_options=None

DEBUG:httpcore.connection:connect_tcp.failed exception=ConnectError(ConnectionRefusedError(111, 'Connection refused'))
DEBUG:prisma.engine._query:Could not connect to query engine due to [Errno 111] Connection refused; retrying...
DEBUG:prisma.engine._http:Constructed GET request to http://localhost:59631/status
DEBUG:prisma.engine._http:Request headers: {'Accept': 'application/json'}
DEBUG:prisma.engine._http:Request content: None
DEBUG:httpcore.connection:connect_tcp.started host="localhost" port=59631 local_address=None timeout=30 socket_options=None
DEBUG:httpcore.connection:connect_tcp.failed exception=ConnectError(ConnectionRefusedError(111, 'Connection refused'))
DEBUG:prisma.engine._query:Could not connect to query engine due to [Errno 111] Connection refused; retrying...
DEBUG:prisma.engine._query:Disconnecting query engine...
DEBUG:prisma.engine._query:Disconnected query engine
Traceback (most recent call last):
  File "/usr/local/lib/python3.8/site-packages/httpx/_transports/default.py", line 72, in map_httpcore_exceptions
    yield
  File "/usr/local/lib/python3.8/site-packages/httpx/_transports/default.py", line 236, in handle_request
    resp = self._pool.handle_request(req)
  File "/usr/local/lib/python3.8/site-packages/httpcore/_sync/connection_pool.py", line 216, in handle_request
    raise exc from None
  File "/usr/local/lib/python3.8/site-packages/httpcore/_sync/connection_pool.py", line 196, in handle_request
    response = connection.handle_request(
  File "/usr/local/lib/python3.8/site-packages/httpcore/_sync/connection.py", line 99, in handle_request
    raise exc
  File "/usr/local/lib/python3.8/site-packages/httpcore/_sync/connection.py", line 76, in handle_request
    stream = self._connect(request)
  File "/usr/local/lib/python3.8/site-packages/httpcore/_sync/connection.py", line 122, in _connect
    stream = self._network_backend.connect_tcp(**kwargs)
  File "/usr/local/lib/python3.8/site-packages/httpcore/_backends/sync.py", line 213, in connect_tcp
    sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
  File "/usr/local/lib/python3.8/contextlib.py", line 131, in __exit__
    self.gen.throw(type, value, traceback)
  File "/usr/local/lib/python3.8/site-packages/httpcore/_exceptions.py", line 14, in map_exceptions
    raise to_exc(exc) from exc
httpcore.ConnectError: [Errno 111] Connection refused

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/local/lib/python3.8/site-packages/prisma/engine/_query.py", line 208, in spawn
    data = self.request('GET', '/status')
  File "/usr/local/lib/python3.8/site-packages/prisma/engine/_http.py", line 150, in request
    response = self.session.request(method, url, **kwargs)
  File "/usr/local/lib/python3.8/site-packages/prisma/_sync_http.py", line 25, in request
    return Response(self.session.request(method, url, **kwargs))
  File "/usr/local/lib/python3.8/site-packages/httpx/_client.py", line 837, in request
    return self.send(request, auth=auth, follow_redirects=follow_redirects)
  File "/usr/local/lib/python3.8/site-packages/httpx/_client.py", line 926, in send
    response = self._send_handling_auth(
  File "/usr/local/lib/python3.8/site-packages/httpx/_client.py", line 954, in _send_handling_auth
    response = self._send_handling_redirects(
  File "/usr/local/lib/python3.8/site-packages/httpx/_client.py", line 991, in _send_handling_redirects
    response = self._send_single_request(request)
  File "/usr/local/lib/python3.8/site-packages/httpx/_client.py", line 1027, in _send_single_request
    response = transport.handle_request(request)
  File "/usr/local/lib/python3.8/site-packages/httpx/_transports/default.py", line 236, in handle_request
    resp = self._pool.handle_request(req)
  File "/usr/local/lib/python3.8/contextlib.py", line 131, in __exit__
    self.gen.throw(type, value, traceback)
  File "/usr/local/lib/python3.8/site-packages/httpx/_transports/default.py", line 89, in map_httpcore_exceptions
    raise mapped_exc(message) from exc
httpx.ConnectError: [Errno 111] Connection refused

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "test_prisma.py", line 23, in <module>
    asyncio.run(run())
  File "/usr/local/lib/python3.8/asyncio/runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "/usr/local/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete
    return future.result()
  File "test_prisma.py", line 16, in run
    await db.connect()
  File "/usr/local/lib/python3.8/site-packages/prisma/_base_client.py", line 323, in connect
    self._internal_engine.connect(
  File "/usr/local/lib/python3.8/site-packages/prisma/engine/_query.py", line 190, in connect
    self.spawn(file, timeout=timeout, datasources=datasources)
  File "/usr/local/lib/python3.8/site-packages/prisma/engine/_query.py", line 229, in spawn
    raise errors.EngineConnectionError('Could not connect to the query engine') from last_exc
prisma.engine.errors.EngineConnectionError: Could not connect to the query engine
DEBUG:prisma.engine._query:Disconnecting query engine...
DEBUG:prisma.engine._query:Disconnected query engine
DEBUG:prisma._base_client:unclosed client - stopping engine
DEBUG:prisma.engine._query:Disconnecting query engine...
DEBUG:prisma.engine._query:Disconnected query engine



You need to sign in to view this answers

Exit mobile version