Developing with the Prism API

Use a driver for application code. The Prism API defines the messages and transport conventions needed to implement a client. Use bindings compatible with your server’s Prism major version and consult the protocol reference for message fields and availability.

Obtain the bindings

The Prism API 2.5 release provides the Protobuf ZIP, generated Go bindings, and a Java JAR containing the schemas for code generation. The Maven coordinates are org.polypheny:prism:2.5. Prism API 2.5 release · Download the Protobuf ZIP · Download the Java schema JAR

Install the released bindings from PyPI or NuGet or generate bindings from the schemas with protoc. PyPI package polypheny-prism-api 2.5 · NuGet package Polypheny.Prism 2.5.0 · Protobuf compiler

To generate Python bindings yourself, unpack protobuf-files-2.5.zip and run the following in the directory containing org. The compiler and runtime versions in this example support the optional fields in the definitions.

python -m pip install grpcio-tools==1.64.1 protobuf==5.27.2
python -m grpc_tools.protoc -I . --python_out=. org/polypheny/prism/*.proto

Transport and session

  1. Open a TCP connection to the Prism port, or connect to the configured Unix domain socket. Both peers send the transport version prefixed by a single byte giving the length, including the final newline. The transport version strings are plain-v1@polypheny.com for TCP and unix-v1@polypheny.com for Unix sockets. Verify the peer sends the same string.
  2. After the transport handshake, prefix every serialized Protobuf message with its byte length as an eight-byte little-endian integer. Read the full prefix and payload, handling partial socket reads.
  3. Send a Request with a positive ID and a connection_request as the first message. Supply the Prism API version, credentials, and any connection properties. Check ConnectionResponse.is_compatible before sending queries. TCP authentication requires a username and password. With a Unix socket, the server can use the peer’s operating system credentials when the client omits the username.
  4. Match each Response to its request by ID. Read responses until Response.last is true. Handle an error_response as the terminal failure for that request. For query results, Frame.is_last separately tells you when to stop sending FetchRequest messages. Optional SQLSTATE and error code fields
  5. Close statement handles when finished. When auto-commit is disabled, use the commit and rollback requests to manage transactions. End the session with DisconnectRequest and close the socket.

After connecting, check ConnectionResponse.supports_generated_keys before requesting generated keys. If your client enables partial batch results, retain the batch progress response while reading through to the terminal error. Generated keys · Batch progress on failure

Run a query over TCP

This example uses Python 3.9 or later, the Prism 2.5 bindings, and a running Polypheny-DB server with a compatible Prism 2.x interface. The client uses 127.0.0.1:20590, the local pa user, and an empty password by default. Set PRISM_HOST, PRISM_PORT, PRISM_USER, and PRISM_PASSWORD as needed. Install the bindings in a Python virtual environment. Server compatibility

python -m pip install polypheny-prism-api==2.5

Save as prism_query.py and run it with Python. The example fetches two rows one at a time and prints Ada and Lin.

import os
import socket
import struct
from contextlib import contextmanager
from itertools import count

from org.polypheny.prism import protointerface_pb2 as protocol


class PrismRequestError(RuntimeError):
    def __init__(self, error):
        super().__init__(error.message)
        self.sqlstate = None
        self.error_code = None
        if error.HasField("details"):
            details = error.details
            if details.HasField("state"):
                self.sqlstate = details.state
            if details.HasField("error_code"):
                self.error_code = details.error_code


def read_exact(sock, size):
    data = bytearray()
    while len(data) < size:
        chunk = sock.recv(size - len(data))
        if not chunk:
            raise EOFError("Prism closed the connection")
        data.extend(chunk)
    return bytes(data)


def exchange(sock, request):
    payload = request.SerializeToString()
    sock.sendall(struct.pack("<Q", len(payload)) + payload)
    while True:
        (size,) = struct.unpack("<Q", read_exact(sock, 8))
        response = protocol.Response.FromString(read_exact(sock, size))
        if response.id != request.id:
            raise RuntimeError(f"Unexpected response ID {response.id}")
        if response.HasField("error_response"):
            raise PrismRequestError(response.error_response)
        if response.last:
            return response


def execute_direct(sock, request_ids, statement, language="sql", namespace=None, fetch_size=-1):
    request = protocol.Request(id=next(request_ids))
    query = request.execute_unparameterized_statement_request
    query.language_name = language
    query.statement = statement
    query.fetch_size = fetch_size
    if namespace is not None:
        query.namespace_name = namespace
    return exchange(sock, request).statement_response


def close_statement(sock, request_ids, statement_id):
    request = protocol.Request(id=next(request_ids))
    request.close_statement_request.statement_id = statement_id
    exchange(sock, request)


@contextmanager
def open_session():
    address = (os.getenv("PRISM_HOST", "127.0.0.1"), int(os.getenv("PRISM_PORT", "20590")))
    request_ids = count(1)
    with socket.create_connection(address, timeout=10) as sock:
        version = b"plain-v1@polypheny.com\n"
        sock.sendall(bytes([len(version)]) + version)
        (size,) = read_exact(sock, 1)
        if read_exact(sock, size) != version:
            raise RuntimeError("Unexpected Prism transport version")

        request = protocol.Request(id=next(request_ids))
        request.connection_request.major_api_version = 2
        request.connection_request.minor_api_version = 5
        request.connection_request.username = os.getenv("PRISM_USER", "pa")
        request.connection_request.password = os.getenv("PRISM_PASSWORD", "")
        response = exchange(sock, request).connection_response
        server_api = (response.major_api_version, response.minor_api_version)
        if not response.is_compatible:
            raise RuntimeError(f"Incompatible Prism API version {server_api}")

        yield sock, request_ids, server_api

        request = protocol.Request(id=next(request_ids))
        request.disconnect_request.SetInParent()
        exchange(sock, request)


if __name__ == "__main__":
    with open_session() as (sock, request_ids, server_api):
        sql = "SELECT name FROM (VALUES ('Ada'), ('Lin')) AS example(name) ORDER BY name"
        statement = execute_direct(sock, request_ids, sql, fetch_size=1)
        try:
            frame = statement.result.frame
            while True:
                for row in frame.relational_frame.rows:
                    print(row.values[0].string.string)
                if frame.is_last:
                    break
                request = protocol.Request(id=next(request_ids))
                request.fetch_request.statement_id = statement.statement_id
                request.fetch_request.fetch_size = 1
                frame = exchange(sock, request).frame
        finally:
            close_statement(sock, request_ids, statement.statement_id)

The helper consumes intermediate responses and returns the final response on success. On request failure, PrismRequestError exposes the original message and any structured fields the server supplied. With a message-only response, both attributes are None. When an exception exits the session context, it closes the socket. A client that keeps the session open after a direct execution failure should retain the statement ID from the intermediate response and release the handle.

To inspect a document namespace, send an EntitiesRequest on the same authenticated session and read the document variants of its EntitiesResponse. Document collection metadata

Run a prepared Cypher query

Use prepare_named_statement_request to declare a reusable Cypher statement with $parameter value expressions. Send each value as a ProtoValue using the corresponding name without the dollar sign. Select CypherResultFormat = relational to preserve an ordered path as one cell even when the result consists only of graph values. Named parameter rules · Graph frame selection

Save this example as prism_cypher.py beside prism_query.py and run it in the same environment. Use a development server with Prism 2.3 or later, support for named Cypher parameters and unbounded relationship patterns, and an account that can create and drop graph namespaces. The example creates and drops its own namespace. Set namespace to an unused lowercase SQL identifier if prism_routes_demo already exists.

from org.polypheny.prism import protointerface_pb2 as protocol

from prism_query import close_statement, exchange, execute_direct, open_session


def run_command(sock, request_ids, statement, **options):
    response = execute_direct(sock, request_ids, statement, **options)
    close_statement(sock, request_ids, response.statement_id)


namespace = "prism_routes_demo"
with open_session() as (sock, request_ids, server_api):
    if server_api < (2, 3):
        raise RuntimeError("Tabular graph values require Prism 2.3 or later")

    run_command(sock, request_ids, f"CREATE GRAPH NAMESPACE {namespace}")
    try:
        run_command(
            sock,
            request_ids,
            "CREATE (:Place {name: 'Ada'})-[:ROUTE]->"
            "(:Place {name: 'Lin'})-[:ROUTE]->(:Place {name: 'Sam'})",
            language="cypher",
            namespace=namespace,
        )

        request = protocol.Request(id=next(request_ids))
        request.set_client_info_properties_request.properties["CypherResultFormat"] = "relational"
        exchange(sock, request)

        request = protocol.Request(id=next(request_ids))
        prepare = request.prepare_named_statement_request
        prepare.language_name = "cypher"
        prepare.namespace_name = namespace
        prepare.statement = (
            "MATCH p=(:Place {name: $origin})-[:ROUTE*]->(:Place {name: $destination}) "
            "RETURN p AS route"
        )
        signature = exchange(sock, request).prepared_statement_signature

        try:
            request = protocol.Request(id=next(request_ids))
            execute = request.execute_named_statement_request
            execute.statement_id = signature.statement_id
            execute.fetch_size = -1
            execute.parameters.parameters["origin"].string.string = "Ada"
            execute.parameters.parameters["destination"].string.string = "Sam"

            frame = exchange(sock, request).statement_result.frame
            if frame.WhichOneof("result") != "relational_frame":
                raise RuntimeError("Expected a tabular Cypher result")
            for row in frame.relational_frame.rows:
                cell = row.values[0]
                if cell.WhichOneof("value") != "path":
                    raise RuntimeError("Expected a graph path")
                print(" -> ".join(node.properties["name"].string.string for node in cell.path.nodes))
        finally:
            close_statement(sock, request_ids, signature.statement_id)
    finally:
        run_command(sock, request_ids, f"DROP NAMESPACE {namespace}")

The result prints Ada -> Lin -> Sam. The unbounded pattern [:ROUTE*] follows one or more relationships. Under the default format, the graph-only projection streams the path as flat graph elements. Cypher patterns · Result frames

For partial results, keep using the same statement ID until Frame.is_last is true. In auto-commit, finish or close an open Cypher cursor before executing another statement or changing auto-commit. To release only the result and keep a prepared handle, use CloseResultRequest. Cursor and transaction lifetime

© Polypheny GmbH. All Rights Reserved.