This guide builds a small Go application that reserves inventory in Polypheny. It updates the available quantity and creates an order in one transaction. If the order cannot be saved, the quantity stays unchanged.
Prerequisites
- Go 1.23 or newer.
- A running Polypheny instance with a Prism 2.2 interface.
- Permission to create tables and write to the default relational namespace,
public.
Create the tables
Run these SQL statements in the Polypheny UI using the public namespace. Set up the tables once before running the application.
CREATE TABLE shop_stock (
sku VARCHAR(20) PRIMARY KEY,
available INTEGER NOT NULL
);
CREATE TABLE shop_orders (
id INTEGER PRIMARY KEY,
sku VARCHAR(20) NOT NULL,
quantity INTEGER NOT NULL
);
INSERT INTO shop_stock (sku, available) VALUES ('desk-lamp', 5);
Set up the Go module
Create the application directory and install the Polypheny Go driver.
mkdir polypheny-app
cd polypheny-app
go mod init example.com/polypheny-app
go get github.com/polypheny/Polypheny-Go-Driver@v0.2.0
Reserve stock and record the order
Save the following program as main.go. The blank import registers the polypheny driver with Go’s database/sql package. The application shares one *sql.DB connection pool between the write transaction and the verification query.
package main
import (
"context"
"database/sql"
"fmt"
"log"
"os"
"strconv"
"time"
_ "github.com/polypheny/Polypheny-Go-Driver"
)
func reserveStock(ctx context.Context, db *sql.DB, orderID int, sku string, quantity int) error {
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
result, err := tx.ExecContext(ctx,
"UPDATE shop_stock SET available = available - ? WHERE sku = ? AND available >= ?",
quantity, sku, quantity,
)
if err != nil {
return fmt.Errorf("reserve stock: %w", err)
}
updated, err := result.RowsAffected()
if err != nil {
return err
}
if updated != 1 {
return fmt.Errorf("not enough stock for %s", sku)
}
_, err = tx.ExecContext(ctx,
"INSERT INTO shop_orders (id, sku, quantity) VALUES (?, ?, ?)",
orderID, sku, quantity,
)
if err != nil {
return fmt.Errorf("create order: %w", err)
}
return tx.Commit()
}
func run() error {
if len(os.Args) != 3 {
return fmt.Errorf("usage: go run . <order-id> <quantity>")
}
orderID, err := strconv.Atoi(os.Args[1])
if err != nil || orderID <= 0 {
return fmt.Errorf("order ID must be a positive integer")
}
quantity, err := strconv.Atoi(os.Args[2])
if err != nil || quantity <= 0 {
return fmt.Errorf("quantity must be a positive integer")
}
dsn := os.Getenv("POLYPHENY_DSN")
if dsn == "" {
return fmt.Errorf("POLYPHENY_DSN must be set")
}
db, err := sql.Open("polypheny", dsn)
if err != nil {
return err
}
defer db.Close()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := db.PingContext(ctx); err != nil {
return fmt.Errorf("connect to Polypheny: %w", err)
}
const sku = "desk-lamp"
if err := reserveStock(ctx, db, orderID, sku, quantity); err != nil {
return err
}
var available int
err = db.QueryRowContext(ctx, "SELECT available FROM shop_stock WHERE sku = ?", sku).Scan(&available)
if err != nil {
return fmt.Errorf("read inventory: %w", err)
}
fmt.Printf("Order %d reserved %d units. %d units remain.\n", orderID, quantity, available)
return nil
}
func main() {
if err := run(); err != nil {
log.Fatal(err)
}
}
The condition available >= ? lets the update reserve stock only when enough units are available. The ? placeholders bind Go values as SQL parameters. Both writes go through tx, so either both commit or the deferred rollback discards the reservation.
Run and verify
The connection string format is host:port,username:password. Use the Prism TCP port, which defaults to 20590. This command assumes a local instance with the pa user and an empty password.
POLYPHENY_DSN='localhost:20590,pa:' go run . 101 2
The program prints Order 101 reserved 2 units. 3 units remain. Check the saved state from the SQL workspace.
SELECT sku, available FROM shop_stock WHERE sku = 'desk-lamp';
SELECT id, sku, quantity FROM shop_orders WHERE id IN (101, 102);
Try reserving four more units. The application reports that there is not enough stock. Run the verification queries again to confirm that three units remain and order 102 was never created.
POLYPHENY_DSN='localhost:20590,pa:' go run . 102 4
For connection options, MQL, Cypher and entity metadata, see the Polypheny Go Driver reference.
Query a graph with Cypher
This example requires a Polypheny instance with the Prism 2.3 graph implementation and Go driver v0.2.0. Use an account that can create and drop graph namespaces. The program creates go_graph_docs_demo and drops it on exit. If that name is in use, choose an unused lowercase SQL identifier for the namespace constant.
Create a separate module for the graph application.
mkdir polypheny-graph-app
cd polypheny-graph-app
go mod init example.com/polypheny-graph-app
go get github.com/polypheny/Polypheny-Go-Driver@v0.2.0
Save this program as main.go. SQL creates the graph namespace. Inside one reserved connection’s Raw callback, Cypher inserts three people and their relationships in an explicit transaction. The catalog requests discover the graph, and the subsequent queries show scalar columns, mixed graph and scalar columns, an ordered path and a flat graph result.
package main
import (
"context"
"database/sql"
"database/sql/driver"
"fmt"
"log"
"os"
"strings"
"time"
polypheny "github.com/polypheny/Polypheny-Go-Driver"
"github.com/polypheny/Polypheny-Go-Driver/prism"
"google.golang.org/protobuf/encoding/protojson"
)
const namespace = "go_graph_docs_demo"
func nodeName(node *prism.ProtoNode) string {
return node.GetProperties()["name"].GetString_().GetString_()
}
func showValue(value *prism.ProtoValue) string {
switch cell := value.GetValue().(type) {
case *prism.ProtoValue_Node:
return "Node " + nodeName(cell.Node)
case *prism.ProtoValue_Edge:
return fmt.Sprintf("Edge %v (%s)", cell.Edge.GetLabels(), cell.Edge.GetDirection())
case *prism.ProtoValue_Path:
names := make([]string, len(cell.Path.GetNodes()))
for i, node := range cell.Path.GetNodes() {
names[i] = nodeName(node)
}
return "Path " + strings.Join(names, " -> ")
case *prism.ProtoValue_Graph:
return fmt.Sprintf("Graph with %d nodes and %d edges", len(cell.Graph.GetNodes()), len(cell.Graph.GetEdges()))
default:
return protojson.Format(value)
}
}
func showResult(result *prism.StatementResult) error {
frame := result.GetFrame()
if frame == nil {
fmt.Printf("Update count: %d\n", result.GetScalar())
return nil
}
switch data := frame.GetResult().(type) {
case *prism.Frame_RelationalFrame:
for _, column := range data.RelationalFrame.GetColumnMeta() {
fmt.Printf("Column %d: %s (%s)\n", column.GetColumnIndex(), column.GetColumnLabel(), column.GetTypeMeta().GetProtoValueType())
}
for _, row := range data.RelationalFrame.GetRows() {
for i, value := range row.GetValues() {
fmt.Printf(" Cell %d: %s\n", i, showValue(value))
}
}
case *prism.Frame_GraphFrame:
for _, element := range data.GraphFrame.GetElement() {
switch item := element.GetElement().(type) {
case *prism.GraphElement_Node:
fmt.Println("Flat node:", nodeName(item.Node))
case *prism.GraphElement_Edge:
fmt.Println("Flat edge:", item.Edge.GetLabels())
default:
return fmt.Errorf("unexpected graph element %T", item)
}
}
default:
return fmt.Errorf("unexpected result frame %T", data)
}
return nil
}
func populateGraph(ctx context.Context, conn *polypheny.PolyphenyConn) error {
tx, err := conn.BeginTx(ctx, driver.TxOptions{})
if err != nil {
return err
}
defer tx.Rollback()
result, err := conn.ExecuteCypherContext(ctx, namespace,
"CREATE (:Person {name: 'Ada'})-[:KNOWS]->"+
"(:Person {name: 'Lin'})-[:KNOWS]->(:Person {name: 'Sam'})")
if err != nil {
return err
}
if err := showResult(result); err != nil {
return err
}
return tx.Commit()
}
func run() error {
dsn := os.Getenv("POLYPHENY_DSN")
if dsn == "" {
return fmt.Errorf("POLYPHENY_DSN must be set")
}
db, err := sql.Open("polypheny", dsn)
if err != nil {
return err
}
defer db.Close()
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if _, err := db.ExecContext(ctx, "CREATE GRAPH NAMESPACE "+namespace); err != nil {
return err
}
defer func() {
cleanup, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if _, err := db.ExecContext(cleanup, "DROP NAMESPACE "+namespace); err != nil {
log.Printf("drop example namespace: %v", err)
}
}()
connection, err := db.Conn(ctx)
if err != nil {
return err
}
defer connection.Close()
return connection.Raw(func(raw any) error {
conn, ok := raw.(*polypheny.PolyphenyConn)
if !ok {
return fmt.Errorf("unexpected driver connection %T", raw)
}
pattern, model := namespace, "GRAPH"
namespaces, err := conn.SearchNamespaces(ctx, &pattern, &model)
if err != nil {
return err
}
for _, item := range namespaces.GetNamespaces() {
fmt.Println("Namespace:", item.GetNamespaceName(), item.GetNamespaceType())
}
if err := populateGraph(ctx, conn); err != nil {
return err
}
entities, err := conn.SearchEntities(ctx, namespace, nil)
if err != nil {
return err
}
for _, entity := range entities.GetEntities() {
if entity.GetGraph() != nil {
fmt.Println("Graph entity marker")
}
}
for _, query := range []string{
"MATCH (n:Person) RETURN n.name AS name ORDER BY n.name",
"MATCH (n:Person) RETURN n, n.name ORDER BY n.name",
"MATCH (:Person)-[r:KNOWS]->(:Person) RETURN r, 'Edge' AS label",
"MATCH p=(:Person {name: 'Ada'})-[:KNOWS*1..3]->(:Person {name: 'Sam'}) RETURN p, 'Path' AS label",
"MATCH (n:Person) RETURN n",
} {
fmt.Println("Query:", query)
result, err := conn.ExecuteCypherContext(ctx, namespace, query)
if err != nil {
return err
}
if err := showResult(result); err != nil {
return err
}
}
return nil
})
}
func main() {
if err := run(); err != nil {
log.Fatal(err)
}
}
Run the application with the Prism TCP connection string.
POLYPHENY_DSN='localhost:20590,pa:' go run .
The namespace listing includes go_graph_docs_demo with model GRAPH. The entity request returns a graph marker. The scalar query reads the three names, the mixed query preserves each node beside its name, the edge query reports two KNOWS edges, and the path query prints Path Ada -> Lin -> Sam. The final query emits three flat node elements. The program prints the create statement’s result as supplied by the server. A write can return a scalar count or a tabular ROWCOUNT frame.
ExecuteCypherContext fetches the complete result and closes the statement before returning, including when the server divides a query into multiple pages. Tabular results retain column metadata. The sample uses protojson.Format to show scalar values with their Prism encoding. Use the generated value getters when converting cells to application types.
The transaction in populateGraph commits only after the create operation succeeds. Its deferred rollback runs if an error interrupts the operation. Keep transaction operations inside the same Raw callback and complete the transaction before returning the connection to the pool. For the result types, property maps, direction semantics and current graph metadata fields, see the Go graph reference.