### Install pymgclient from Source Distribution Source: https://github.com/memgraph/pymgclient/blob/master/docs/source/introduction.rst Install pymgclient after building the source distribution. Ensure you have the necessary build tools installed. ```bash python3 -m build --sdist pip install dist/*.tar.gz ``` -------------------------------- ### Install pymgclient from Source Distribution Source: https://github.com/memgraph/pymgclient/blob/master/docs/source/introduction.rst Install pymgclient using pip after building the source distribution. This is an alternative to installing prebuilt binaries. ```bash pip install --no-binary pymgclient pymgclient ``` ```bash pip install -e . ``` ```bash python3 -m build --sdist pip install dist/*.tar.gz ``` -------------------------------- ### Install Build Prerequisites on Debian/Ubuntu Source: https://github.com/memgraph/pymgclient/blob/master/docs/source/introduction.rst Install the necessary build prerequisites for pymgclient on Debian/Ubuntu systems using apt. ```bash sudo apt install python3-dev cmake make gcc g++ libssl-dev ``` -------------------------------- ### Install pymgclient Binaries on Windows Source: https://github.com/memgraph/pymgclient/blob/master/docs/source/introduction.rst Install the prebuilt binary packages of pymgclient on Windows using the py launcher or pip. The --user flag installs the package in the user's home directory. ```bash py -3 -m pip install --user pymgclient ``` ```bash pip install --user pymgclient ``` -------------------------------- ### Install pymgclient Binaries on Linux/macOS Source: https://github.com/memgraph/pymgclient/blob/master/docs/source/introduction.rst Install the prebuilt binary packages of pymgclient using pip3. The --user flag installs the package in the user's home directory. ```bash pip3 install --user pymgclient ``` -------------------------------- ### Install Build Prerequisites on CentOS/Fedora Source: https://github.com/memgraph/pymgclient/blob/master/docs/source/introduction.rst Install the necessary build prerequisites for pymgclient on CentOS/Fedora systems using dnf. ```bash sudo dnf install -y python3-devel cmake3 make gcc gcc-c++ openssl-devel ``` -------------------------------- ### Install pymgclient using pip (Editable Mode) Source: https://github.com/memgraph/pymgclient/blob/master/docs/source/introduction.rst Install pymgclient in editable mode, useful for development. This command installs the package directly from the source directory. ```bash pip install -e . ``` -------------------------------- ### Install pymgclient Source: https://context7.com/memgraph/pymgclient/llms.txt Install pymgclient using pip. Pre-built wheels are available for Linux, macOS, and Windows. Building from source with dynamic OpenSSL linkage is also supported. ```bash # Linux / macOS pip3 install --user pymgclient # Windows py -3 -m pip install --user pymgclient # Build from source with dynamic OpenSSL linkage (Linux example) sudo apt install python3-dev cmake make gcc g++ libssl-dev PYMGCLIENT_STATIC_OPENSSL=0 pip install --no-binary pymgclient pymgclient ``` -------------------------------- ### Install pymgclient on Windows using pip Source: https://github.com/memgraph/pymgclient/blob/master/docs/source/introduction.rst Install pymgclient on Windows using pip. The `--no-binary` flag ensures it's built from source, which might be necessary in certain environments. ```bash pip install --user --no-binary pymgclient pymgclient ``` -------------------------------- ### Install pymgclient Dynamically Linking OpenSSL on Windows Source: https://github.com/memgraph/pymgclient/blob/master/docs/source/introduction.rst Install pymgclient on Windows with dynamic linking for OpenSSL. Set the PYMGCLIENT_STATIC_OPENSSL environment variable to 0 before running pip install. ```bash PYMGCLIENT_STATIC_OPENSSL=0 \ pip install --user --no-binary pymgclient pymgclient ``` -------------------------------- ### Install MSYS2 Packages on Windows Source: https://github.com/memgraph/pymgclient/blob/master/docs/source/introduction.rst Install essential development packages using pacman within the MSYS2 environment on Windows. This is a prerequisite for building pymgclient on Windows. ```bash pacman -Su pacman -S --needed base-devel mingw-w64-x86_64-toolchain \ mingw-w64-x86_64-cmake mingw-w64-x86_64-openssl ``` -------------------------------- ### Lazy Connections Example Source: https://github.com/memgraph/pymgclient/blob/master/docs/source/connection.rst Demonstrates how to establish and use a lazy connection, including executing queries and fetching results row by row. It also highlights the limitation of executing multiple queries concurrently without fetching all results. ```APIDOC ## Lazy Connections When a query is executed using :meth:`.execute` on a cursor, the default :mod:`mgclient` behaviour is to wait for all of the results to be available and store them into cursor's internal result list. On one hand, that means that :meth:`.execute` will block until all of the results are ready and all results will be stored in memory at the same time. On the other hand, that also means that result fetching methods will never block. Sometimes, that behaviour is unwanted. Maybe we don't need all results in memory at the same time, because we only want to do row-by-row processing on huge result sets. In that case, we may use a lazy connection. A lazy connection is created by passing ``True`` for ``lazy`` parameter when calling :func:`.connect`. Cursors created using lazy connections will only try to read results from the network socket when :meth:`.fetchone`, :meth:`.fetchmany` or :meth:`.fetchall` is called. Also, they can allocate less memory because they don't have to store the entire result set in memory at once. However, lazy connections have two limitations: 1. They are always in autocommit mode. If necessary, transactions can be explicitly managed by executing ``BEGIN``, ``COMMIT`` or ``ROLLBACK`` queries. 2. At most one query can execute at a given time. Trying to execute multiple queries at once will raise an :exc:`InterfaceError`. Before trying to execute a new query, all results of the previous query must be fetched from its corresponding cursor (for example by calling :meth:`.fetchone` until it returns :obj:`None`, or by calling :meth:`.fetchmany`). Here's an example usage of a lazy connection:: >>> import mgclient >>> conn = mgclient.connect(host="127.0.0.1", port=7687, lazy=True) >>> cursor = conn.cursor() >>> cursor.execute("UNWIND range(1, 3) AS n RETURN n * n") >>> cursor.fetchone() (1, ) >>> cursor.fetchone() (4, ) >>> cursor.fetchone() (9, ) # We still didn't get None from fetchone() >>> cursor.execute("RETURN 100") Traceback (most recent call last): File "", line 1, in mgclient.InterfaceError: cannot call execute during execution of a query >>> cursor.fetchone() None # Now we can execute a new query >>> cursor.execute("RETURN 100") ``` -------------------------------- ### Install pymgclient with Dynamic OpenSSL Linking on Linux/macOS Source: https://github.com/memgraph/pymgclient/blob/master/docs/source/introduction.rst Install pymgclient while dynamically linking to the host machine's OpenSSL library for improved security. This is achieved by setting the PYMGCLIENT_STATIC_OPENSSL environment variable to 0. ```bash PYMGCLIENT_STATIC_OPENSSL=0 \ pip install --no-binary pymgclient pymgclient ``` ```bash PYMGCLIENT_STATIC_OPENSSL=0 \ pip3 install --user --no-binary pymgclient pymgclient ``` -------------------------------- ### Run pymgclient Test Suite Source: https://github.com/memgraph/pymgclient/blob/master/docs/source/introduction.rst Execute the test suite for pymgclient from the source directory using pytest. This verifies the installation and functionality. ```bash python3 -m pytest ``` -------------------------------- ### Verify GCC Installation on Windows Source: https://github.com/memgraph/pymgclient/blob/master/docs/source/introduction.rst Check if the GCC compiler is installed and accessible in your Windows environment after setting up MSYS2. This confirms the toolchain is ready. ```bash gcc --version ``` -------------------------------- ### Lazy Connection: Executing Subsequent Query Source: https://github.com/memgraph/pymgclient/blob/master/docs/source/connection.rst Shows the correct way to execute a new query after ensuring all results from the previous query have been fetched. This example follows a successful fetchone() call that returned None, indicating the previous result set is exhausted. ```python cursor.fetchone() # Now we can execute a new query cursor.execute("RETURN 100") ``` -------------------------------- ### Accessing Relationship Attributes with mgclient.Relationship Source: https://context7.com/memgraph/pymgclient/llms.txt Shows how to access the type, properties, start ID, and end ID of a relationship. This requires an active database connection and a cursor to execute Cypher queries. ```python import mgclient conn = mgclient.connect(host="127.0.0.1", port=7687) cursor = conn.cursor() cursor.execute(""" CREATE (a:City {name: 'London'})-[r:DISTANCE_TO {km: 344}]->(b:City {name: 'Paris'}) RETURN r """) rel = cursor.fetchone()[0] print(rel.type) # DISTANCE_TO print(rel.properties) # {'km': 344} print(rel.start_id) # id of London node print(rel.end_id) # id of Paris node print(str(rel)) # [:DISTANCE_TO {'km': 344}] conn.rollback() conn.close() ``` -------------------------------- ### Basic PyMgclient Module Usage Source: https://github.com/memgraph/pymgclient/blob/master/docs/source/usage.rst Demonstrates the fundamental steps for using the mgclient module, including connecting to the database, creating a cursor, executing a query, fetching results, and committing changes. This follows the DB-API 2.0 standard. ```python import mgclient # Make a connection to the database conn = mgclient.connect(host='127.0.0.1', port=7687) # Create a cursor for query execution cursor = conn.cursor() # Execute a query cursor.execute(""" CREATE (n:Person {name: 'John'})-[e:KNOWS]-> (m:Person {name: 'Steve'}) RETURN n, e, m """) # Fetch one row of query results row = cursor.fetchone() print(row[0]) print(row[1]) print(row[2]) # Make database changes persistent conn.commit() ``` -------------------------------- ### Connect and Query Memgraph Database Source: https://github.com/memgraph/pymgclient/blob/master/README.md Demonstrates how to establish a connection to a Memgraph database, execute a Cypher query, fetch results, and commit changes. Ensure the Memgraph instance is running and accessible at the specified host and port. ```python >>> import mgclient # Make a connection to the database >>> conn = mgclient.connect(host='127.0.0.1', port=7687) # Create a cursor for query execution >>> cursor = conn.cursor() # Execute a query >>> cursor.execute(""" CREATE (n:Person {name: 'John'})-[e:KNOWS]-> (m:Person {name: 'Steve'}) RETURN n, e, m """) # Fetch one row of query results >>> row = cursor.fetchone() >>> print(row[0]) (:Person {'name': 'John'}) >>> print(row[1]) [:KNOWS] >>> print(row[2]) (:Person {'name': 'Steve'}) # Make database changes persistent >>> conn.commit() ``` -------------------------------- ### Create Lazy Connection and Execute Query Source: https://github.com/memgraph/pymgclient/blob/master/docs/source/connection.rst Demonstrates how to establish a lazy connection and execute a query. Lazy connections are created by setting the 'lazy' parameter to True during connection. Cursors from lazy connections fetch results only when fetch methods are called. ```python import mgclient conn = mgclient.connect(host="127.0.0.1", port=7687, lazy=True) cursor = conn.cursor() cursor.execute("UNWIND range(1, 3) AS n RETURN n * n") cursor.fetchone() cursor.fetchone() cursor.fetchone() ``` -------------------------------- ### Traversing a Path with mgclient.Path Source: https://context7.com/memgraph/pymgclient/llms.txt Illustrates how to work with the `mgclient.Path` object, accessing its nodes and relationships, and printing path information. Ensure a connection and cursor are set up. ```python import mgclient conn = mgclient.connect(host="127.0.0.1", port=7687) cursor = conn.cursor() cursor.execute(""" CREATE p = (a:Stop {name: 'A'})-[:NEXT]->(b:Stop {name: 'B'})-[:NEXT]->(c:Stop {name: 'C'}) RETURN p """) path = cursor.fetchone()[0] print(len(path.nodes)) # 3 print(len(path.relationships)) # 2 for node in path.nodes: print(node.properties["name"], end=" ") # A B C print() print(str(path)) # (:Stop {'name': 'A'})-[:NEXT]->(:Stop {'name': 'B'})-[:NEXT]->(:Stop {'name': 'C'}) conn.rollback() conn.close() ``` -------------------------------- ### Execute parameterized openCypher queries with pymgclient Source: https://context7.com/memgraph/pymgclient/llms.txt Execute openCypher statements using parameterized queries for safety against injection. Use $name placeholders and a params dictionary. Fetches and prints a created node. ```python import mgclient conn = mgclient.connect(host="127.0.0.1", port=7687) cursor = conn.cursor() # ✗ Unsafe — never do this # cursor.execute("CREATE (:User {id: '%s'})" % user_id) # ✓ Safe parameterized query cursor.execute( "CREATE (u:User {id: $uid, email: $email, active: $active}) RETURN u", {"uid": "usr-001", "email": "alice@example.com", "active": True}, ) row = cursor.fetchone() node = row[0] print(node) # (:User {'id': 'usr-001', 'email': 'alice@example.com', 'active': True}) print(node.labels) # {'User'} print(node.properties) # {'id': 'usr-001', 'email': 'alice@example.com', 'active': True} conn.commit() conn.close() ``` -------------------------------- ### Using mgclient DB-API 2.0 Constants and Exception Handling Source: https://context7.com/memgraph/pymgclient/llms.txt Demonstrates the usage of DB-API 2.0 module-level constants provided by pymgclient, including API level, thread safety, parameter style, SSL modes, and connection status codes. It also shows how to handle database and interface errors. ```python import mgclient # DB-API 2.0 constants print(mgclient.apilevel) # '2.0' print(mgclient.threadsafety) # 1 (module is thread-safe; connections are not) print(mgclient.paramstyle) # 'cypher' # SSL mode constants print(mgclient.MG_SSLMODE_DISABLE) # 0 print(mgclient.MG_SSLMODE_REQUIRE) # 1 # Connection status constants print(mgclient.CONN_STATUS_READY) # connection idle print(mgclient.CONN_STATUS_IN_TRANSACTION) # inside an implicit transaction print(mgclient.CONN_STATUS_EXECUTING) # lazy connection is streaming print(mgclient.CONN_STATUS_CLOSED) # connection closed by user print(mgclient.CONN_STATUS_BAD) # connection in error state # Exception handling conn = mgclient.connect(host="127.0.0.1", port=7687) cursor = conn.cursor() try: cursor.execute("INVALID CYPHER @@@@") except mgclient.DatabaseError as e: print(f"DatabaseError: {e}") except mgclient.InterfaceError as e: print(f"InterfaceError (driver-level): {e}") finally: conn.close() ``` -------------------------------- ### Connect to Memgraph with pymgclient Source: https://context7.com/memgraph/pymgclient/llms.txt Establish a connection to Memgraph using mgclient.connect(). Supports basic, authenticated, SSL-encrypted, and lazy (streaming) connections. Ensure host or address is provided. ```python import mgclient # Basic insecure connection conn = mgclient.connect(host="127.0.0.1", port=7687) print(conn.status) # mgclient.CONN_STATUS_READY # Authenticated connection conn_auth = mgclient.connect( host="db.example.com", port=7687, username="alice", password="s3cret", ) # SSL connection with TOFU (trust-on-first-use) callback def trust_callback(hostname, ip_address, key_type, fingerprint): print(f"Connecting to {hostname} ({ip_address}), key: {key_type} {fingerprint}") return True # return False to abort the connection conn_ssl = mgclient.connect( host="127.0.0.1", port=7687, sslmode=mgclient.MG_SSLMODE_REQUIRE, sslcert="/path/to/client.crt", sslkey="/path/to/client.key", trust_callback=trust_callback, ) print(conn_ssl.status) # mgclient.CONN_STATUS_READY # Lazy (streaming) connection — always in autocommit mode conn_lazy = mgclient.connect(host="127.0.0.1", port=7687, lazy=True) print(conn_lazy.autocommit) # True ``` -------------------------------- ### mgclient.connect() Source: https://context7.com/memgraph/pymgclient/llms.txt Opens a new database connection to Memgraph. Supports various configurations including authentication, SSL, and lazy (streaming) connections. ```APIDOC ## mgclient.connect() ### Description Creates and returns a new `Connection` object representing a single Bolt session to Memgraph. Exactly one of `host` or `address` must be given. The `lazy=True` flag switches to streaming mode where results are pulled row-by-row rather than buffered all at once. ### Parameters - **host** (str) - Required - The hostname or IP address of the Memgraph instance. - **port** (int) - Required - The port number for the Memgraph instance. - **username** (str) - Optional - The username for authentication. - **password** (str) - Optional - The password for authentication. - **sslmode** (int) - Optional - Specifies the SSL mode (e.g., `mgclient.MG_SSLMODE_REQUIRE`). - **sslcert** (str) - Optional - Path to the client certificate file. - **sslkey** (str) - Optional - Path to the client key file. - **trust_callback** (function) - Optional - A callback function for SSL certificate verification. - **lazy** (bool) - Optional - If True, enables lazy (streaming) result fetching. Defaults to False. ### Request Example ```python import mgclient # Basic insecure connection conn = mgclient.connect(host="127.0.0.1", port=7687) # Authenticated connection conn_auth = mgclient.connect( host="db.example.com", port=7687, username="alice", password="s3cret", ) # SSL connection with TOFU (trust-on-first-use) callback def trust_callback(hostname, ip_address, key_type, fingerprint): print(f"Connecting to {hostname} ({ip_address}), key: {key_type} {fingerprint}") return True conn_ssl = mgclient.connect( host="127.0.0.1", port=7687, sslmode=mgclient.MG_SSLMODE_REQUIRE, sslcert="/path/to/client.crt", sslkey="/path/to/client.key", trust_callback=trust_callback, ) # Lazy (streaming) connection conn_lazy = mgclient.connect(host="127.0.0.1", port=7687, lazy=True) ``` ### Response #### Success Response (Connection Object) - **status** (int) - The connection status (e.g., `mgclient.CONN_STATUS_READY`). - **autocommit** (bool) - Indicates if the connection is in autocommit mode (True for lazy connections). #### Response Example ```python print(conn.status) # mgclient.CONN_STATUS_READY print(conn_lazy.autocommit) # True ``` ``` -------------------------------- ### Passing Parameters to openCypher Queries Source: https://github.com/memgraph/pymgclient/blob/master/docs/source/usage.rst Illustrates the secure method of passing parameters to openCypher queries using placeholder syntax ($name) and a dictionary mapping, instead of string formatting. This prevents security vulnerabilities. ```python server_id = 'srvr-38219012-sw' c.execute("MATCH (s:Server {id: $sid}) SET s.hits = s.htis + 1", {'sid': server_id}) ``` -------------------------------- ### mgclient.connect Source: https://github.com/memgraph/pymgclient/blob/master/docs/source/module.rst Establishes a connection to the Memgraph database. Supports lazy connections. ```APIDOC ## mgclient.connect ### Description Establishes a connection to the Memgraph database. This function adheres to the DB-API 2.0 standard and supports a 'lazy' connection parameter. See :ref:`lazy-connections` section to learn about advantages and limitations of using the ``lazy`` parameter. ``` -------------------------------- ### Create and use a cursor with pymgclient Source: https://context7.com/memgraph/pymgclient/llms.txt Obtain a Cursor object from a Connection to execute queries and fetch results. Multiple cursors share the same transaction. Inspect column metadata and row count. ```python import mgclient conn = mgclient.connect(host="127.0.0.1", port=7687) cursor = conn.cursor() # Execute a query and inspect column metadata cursor.execute("MATCH (n:Person) RETURN n.name AS name, n.age AS age LIMIT 5") print(cursor.description) # [Column(name='name', ...), Column(name='age', ...)] print(cursor.rowcount) # number of rows fetched rows = cursor.fetchall() for row in rows: print(row) # e.g. ('Alice', 30) cursor.close() conn.close() ``` -------------------------------- ### Cursor.execute() Source: https://context7.com/memgraph/pymgclient/llms.txt Executes an openCypher query, supporting parameterized queries for safe execution. ```APIDOC ## Cursor.execute() ### Description Executes a single openCypher statement against the database. An optional `params` dictionary provides named parameter substitution via `$name` placeholders — always prefer parameterized queries over string formatting to prevent injection. ### Parameters - **query** (str) - The openCypher query string to execute. - **params** (dict) - Optional. A dictionary mapping parameter names (without `$`) to their values for substitution. ### Request Example ```python import mgclient conn = mgclient.connect(host="127.0.0.1", port=7687) cursor = conn.cursor() # Safe parameterized query cursor.execute( "CREATE (u:User {id: $uid, email: $email, active: $active}) RETURN u", {"uid": "usr-001", "email": "alice@example.com", "active": True}, ) row = cursor.fetchone() node = row[0] print(node) print(node.labels) print(node.properties) conn.commit() conn.close() ``` ### Response #### Success Response - The result of the query, typically fetched using `fetchone()`, `fetchmany()`, or `fetchall()`. #### Response Example ```python # For the CREATE query example: # node will be a Memgraph Node object print(node) # (:User {'id': 'usr-001', 'email': 'alice@example.com', 'active': True}) print(node.labels) # {'User'} print(node.properties) # {'id': 'usr-001', 'email': 'alice@example.com', 'active': True} ``` ``` -------------------------------- ### Accessing Node Attributes with mgclient.Node Source: https://context7.com/memgraph/pymgclient/llms.txt Demonstrates how to retrieve and print the ID, labels, and properties of a node returned from a query. Ensure a connection to Memgraph is established and a cursor is available. ```python import mgclient conn = mgclient.connect(host="127.0.0.1", port=7687) cursor = conn.cursor() cursor.execute("CREATE (n:Movie:Drama {title: 'Inception', year: 2010}) RETURN n") row = cursor.fetchone() node = row[0] print(node.id) # e.g. 42 print(node.labels) # {'Movie', 'Drama'} print(node.properties) # {'title': 'Inception', 'year': 2010} print(str(node)) # (:Drama:Movie {'title': 'Inception', 'year': 2010}) conn.rollback() conn.close() ``` -------------------------------- ### Connection.cursor() Source: https://context7.com/memgraph/pymgclient/llms.txt Creates a new `Cursor` object associated with the connection, used for executing queries and fetching results. ```APIDOC ## Connection.cursor() ### Description Returns a new `Cursor` object bound to this connection for the full duration of its lifetime. Multiple cursors on the same connection share the same underlying transaction — changes made by one cursor are immediately visible to all others. ### Parameters None ### Request Example ```python import mgclient conn = mgclient.connect(host="127.0.0.1", port=7687) cusor = conn.cursor() # Execute a query and inspect column metadata cursor.execute("MATCH (n:Person) RETURN n.name AS name, n.age AS age LIMIT 5") print(cursor.description) print(cursor.rowcount) rows = cursor.fetchall() for row in rows: print(row) cursor.close() conn.close() ``` ### Response #### Success Response (Cursor Object) - **description** (list) - A list of `Column` objects describing the result set schema. - **rowcount** (int) - The number of rows fetched by the last executed query. #### Response Example ```python # Assuming a query returning 'name' and 'age' print(cursor.description) # [Column(name='name', type_name='STRING', ...), Column(name='age', type_name='INT64', ...)] print(cursor.rowcount) # e.g., 5 ``` ``` -------------------------------- ### Fetch a batch of rows with Cursor.fetchmany() Source: https://context7.com/memgraph/pymgclient/llms.txt Fetches up to `size` rows, defaulting to `cursor.arraysize`. Returns an empty list when no more rows are available. Useful for processing large result sets in chunks. ```python import mgclient conn = mgclient.connect(host="127.0.0.1", port=7687) cursor = conn.cursor() # Seed some data for i in range(10): cursor.execute("CREATE (:Item {n: $n})", {"n": i}) conn.commit() cursor.execute("MATCH (i:Item) RETURN i.n ORDER BY i.n") # Process in batches of 3 cursor.arraysize = 3 while True: batch = cursor.fetchmany() # uses arraysize by default if not batch: break print([row[0] for row in batch]) # [0, 1, 2] # [3, 4, 5] # [6, 7, 8] # [9] conn.close() ``` -------------------------------- ### Module constants and exceptions Source: https://context7.com/memgraph/pymgclient/llms.txt pymgclient exposes DB-API 2.0 module-level constants and a standard exception hierarchy, with all database-level errors currently raising `OperationalError`. ```APIDOC ## Module constants and exceptions pymgclient exposes DB-API 2.0 module-level constants and a standard exception hierarchy rooted at `mgclient.Error`. All database-level errors currently raise `OperationalError`. ```python import mgclient # DB-API 2.0 constants print(mgclient.apilevel) # '2.0' print(mgclient.threadsafety) # 1 (module is thread-safe; connections are not) print(mgclient.paramstyle) # 'cypher' # SSL mode constants print(mgclient.MG_SSLMODE_DISABLE) # 0 print(mgclient.MG_SSLMODE_REQUIRE) # 1 # Connection status constants print(mgclient.CONN_STATUS_READY) # connection idle print(mgclient.CONN_STATUS_IN_TRANSACTION) # inside an implicit transaction print(mgclient.CONN_STATUS_EXECUTING) # lazy connection is streaming print(mgclient.CONN_STATUS_CLOSED) # connection closed by user print(mgclient.CONN_STATUS_BAD) # connection in error state # Exception handling conn = mgclient.connect(host="127.0.0.1", port=7687) cursor = conn.cursor() try: cursor.execute("INVALID CYPHER @@@@") except mgclient.DatabaseError as e: print(f"DatabaseError: {e}") except mgclient.InterfaceError as e: print(f"InterfaceError (driver-level): {e}") finally: conn.close() ``` ``` -------------------------------- ### Set Environment Variable for Dynamic OpenSSL Linking Source: https://github.com/memgraph/pymgclient/blob/master/docs/source/introduction.rst Set the PYMGCLIENT_STATIC_OPENSSL environment variable to 0 to dynamically link against the host machine's OpenSSL library for better security. Some distributions may also require specifying the OpenSSL library path. ```bash export PYMGCLIENT_STATIC_OPENSSL=0 export OPENSSL_ROOT_DIR=/ export OPENSSL_CRYPTO_LIBRARY=/lib64/libcrypto.so ``` -------------------------------- ### Cursor.fetchmany() Source: https://context7.com/memgraph/pymgclient/llms.txt Fetches up to `size` rows (defaults to `cursor.arraysize`, which is 1) as a list of tuples. Returns an empty list when no more rows are available. Useful for processing large result sets in chunks. ```APIDOC ## Cursor.fetchmany() ### Description Fetches up to `size` rows (defaults to `cursor.arraysize`, which is 1) as a list of tuples. Returns an empty list when no more rows are available. Useful for processing large result sets in chunks. ### Usage Example ```python import mgclient conn = mgclient.connect(host="127.0.0.1", port=7687) cusor = conn.cursor() # Seed some data for i in range(10): cursor.execute("CREATE (:Item {n: $n})", {"n": i}) conn.commit() cursor.execute("MATCH (i:Item) RETURN i.n ORDER BY i.n") # Process in batches of 3 cursor.arraysize = 3 while True: batch = cursor.fetchmany() # uses arraysize by default if not batch: break print([row[0] for row in batch]) # [0, 1, 2] # [3, 4, 5] # [6, 7, 8] # [9] conn.close() ``` ``` -------------------------------- ### `mgclient.Path` — Graph path object Source: https://context7.com/memgraph/pymgclient/llms.txt Represents a walk through the graph as an alternating sequence of nodes and relationships. It exposes `nodes` and `relationships`. ```APIDOC ## `mgclient.Path` — Graph path object Represents a walk through the graph as an alternating sequence of nodes and relationships. Exposes `nodes` (list of `Node`) and `relationships` (list of `Relationship`); `nodes` always has exactly one more element than `relationships`. ```python import mgclient conn = mgclient.connect(host="127.0.0.1", port=7687) cursor = conn.cursor() cursor.execute(""" CREATE p = (a:Stop {name: 'A'})-[:NEXT]->(b:Stop {name: 'B'})-[:NEXT]->(c:Stop {name: 'C'}) RETURN p """) path = cursor.fetchone()[0] print(len(path.nodes)) # 3 print(len(path.relationships)) # 2 for node in path.nodes: print(node.properties["name"], end=" ") # A B C print() print(str(path)) # (:Stop {'name': 'A'})-[:NEXT]->(:Stop {'name': 'B'})-[:NEXT]->(:Stop {'name': 'C'}) conn.rollback() conn.close() ``` ``` -------------------------------- ### Fetch a single row with Cursor.fetchone() Source: https://context7.com/memgraph/pymgclient/llms.txt Retrieves the next row from a query result. Returns `None` if no more rows are available. Ensure `execute()` has been called and produced results to avoid `InterfaceError`. ```python import mgclient conn = mgclient.connect(host="127.0.0.1", port=7687) cursor = conn.cursor() cursor.execute(""" CREATE (n:Person {name: 'John'})-[e:KNOWS]->(m:Person {name: 'Steve'}) RETURN n, e, m """) row = cursor.fetchone() john, knows_rel, steve = row[0], row[1], row[2] print(john) # (:Person {'name': 'John'}) print(knows_rel) # [:KNOWS] print(steve) # (:Person {'name': 'Steve'}) # Next call returns None (only one row was produced) assert cursor.fetchone() is None conn.commit() conn.close() ``` -------------------------------- ### Cursor.fetchall() Source: https://context7.com/memgraph/pymgclient/llms.txt Returns all (remaining) rows of the query result as a list of tuples. After the call, subsequent fetch calls will return an empty list or `None`. ```APIDOC ## Cursor.fetchall() ### Description Returns all (remaining) rows of the query result as a list of tuples. After the call, subsequent fetch calls will return an empty list or `None`. ### Usage Example ```python import mgclient conn = mgclient.connect(host="127.0.0.1", port=7687) cusor = conn.cursor() cursor.execute("UNWIND range(1, 5) AS n RETURN n * n AS square") results = cursor.fetchall() print(results) # [(1,), (4,), (9,), (16,), (25,)] # rowcount reflects the total rows returned print(cursor.rowcount) # 5 conn.close() ``` ``` -------------------------------- ### Cursor Class Source: https://github.com/memgraph/pymgclient/blob/master/docs/source/cursor.rst The Cursor class provides methods for interacting with the database, executing queries, and retrieving results. Its members include methods for fetching data and accessing query descriptions. ```APIDOC ## mgclient.Cursor This class represents a database cursor, used to execute queries and fetch results. ### Members This class has the following members: * `:attr:`description`: A list of :class:`Column` instances describing the columns of the result set. (Additional members are documented by the autoclass directive but not explicitly detailed in the provided text.) ``` -------------------------------- ### Cursor.fetchone() Source: https://context7.com/memgraph/pymgclient/llms.txt Fetches the next row of the most recent query result as a tuple. Returns None when all rows are exhausted. Raises InterfaceError if execute() has not been called or did not produce results. ```APIDOC ## Cursor.fetchone() ### Description Returns the next row of the most recent query result as a tuple, or `None` when all rows are exhausted. Raises `InterfaceError` if `execute()` has not been called or did not produce results. ### Usage Example ```python import mgclient conn = mgclient.connect(host="127.0.0.1", port=7687) cusor = conn.cursor() cursor.execute(""" CREATE (n:Person {name: 'John'})-[e:KNOWS]->(m:Person {name: 'Steve'}) RETURN n, e, m """) row = cursor.fetchone() john, knows_rel, steve = row[0], row[1], row[2] print(john) # (:Person {'name': 'John'}) print(knows_rel) # [:KNOWS] print(steve) # (:Person {'name': 'Steve'}) # Next call returns None (only one row was produced) assert cursor.fetchone() is None conn.commit() conn.close() ``` ``` -------------------------------- ### Fetch all remaining rows with Cursor.fetchall() Source: https://context7.com/memgraph/pymgclient/llms.txt Retrieves all remaining rows from a query result as a list of tuples. Subsequent fetch calls will return an empty list or `None`. The `rowcount` attribute reflects the total rows returned. ```python import mgclient conn = mgclient.connect(host="127.0.0.1", port=7687) cursor = conn.cursor() cursor.execute("UNWIND range(1, 5) AS n RETURN n * n AS square") results = cursor.fetchall() print(results) # [(1,), (4,), (9,), (16,), (25,)] # rowcount reflects the total rows returned print(cursor.rowcount) # 5 conn.close() ``` -------------------------------- ### Module Constants Source: https://github.com/memgraph/pymgclient/blob/master/docs/source/module.rst Defines constants required by the DB-API 2.0 specification. ```APIDOC ## Module Constants ### DB-API 2.0 Constants - **mgclient.apilevel**: String constant stating the supported DB API level. For :mod:`mgclient` it is ``2.0``. - **mgclient.threadsafety**: Integer constant stating the level of thread safety the interface supports. For :mod:`mgclient` it is 1, meaning that threads may share the module, but not connections. - **mgclient.paramstyle**: String constant stating the type of parameter marker formatting expected by the interface. For :mod:`mgclient` it is ``cypher``, which is not a valid value by DB-API 2.0 specification. See Passing parameters section for more details. ``` -------------------------------- ### Connection.commit() / Connection.rollback() Source: https://context7.com/memgraph/pymgclient/llms.txt Persists all changes made during the current transaction with `commit()`, or discards them with `rollback()`. Both are no-ops when `autocommit` is `True` or when no transaction is in progress. Closing a connection without committing implicitly rolls back. ```APIDOC ## Connection.commit() / Connection.rollback() ### Description `commit()` persists all changes made during the current transaction; `rollback()` discards them. Both are no-ops when `autocommit` is `True` or when no transaction is in progress. Closing a connection without committing implicitly rolls back. ### Usage Example ```python import mgclient conn = mgclient.connect(host="127.0.0.1", port=7687) cusor = conn.cursor() try: cursor.execute("CREATE (:Account {id: 'A', balance: 100})") cursor.execute("CREATE (:Account {id: 'B', balance: 50})") cursor.execute( "MATCH (a:Account {id: 'A'}), (b:Account {id: 'B'}) " "SET a.balance = a.balance - $amt, b.balance = b.balance + $amt", {"amt": 30}, ) conn.commit() print("Transfer committed") except mgclient.DatabaseError as e: conn.rollback() print(f"Transaction rolled back: {e}") finally: conn.close() ``` ``` -------------------------------- ### Lazy Connection: Handling Query Execution Errors Source: https://github.com/memgraph/pymgclient/blob/master/docs/source/connection.rst Illustrates a limitation of lazy connections: attempting to execute a new query before fetching all results from the previous one raises an InterfaceError. Ensure all results are fetched (e.g., by calling fetchone() until None is returned) before executing another query. ```python # We still didn't get None from fetchone() cursor.execute("RETURN 100") ``` -------------------------------- ### Exceptions Source: https://github.com/memgraph/pymgclient/blob/master/docs/source/module.rst Defines exceptions that adhere to the DB-API 2.0 specification. ```APIDOC ## Exceptions By DB-API 2.0 specification, the module makes all error information available through these exceptions or subclasses thereof: - **mgclient.Warning** - **mgclient.Error** - **mgclient.InterfaceError** - **mgclient.DatabaseError** - **mgclient.DataError** - **mgclient.OperationalError** - **mgclient.IntegrityError** - **mgclient.InternalError** - **mgclient.ProgrammingError** - **mgclient.NotSupportedError** .. NOTE:: In the current state, :exc:`OperationalError` is raised for all errors obtained from the database. This will probably be improved in the future. ``` -------------------------------- ### Stream large result sets with lazy connections Source: https://context7.com/memgraph/pymgclient/llms.txt Lazy connections fetch results on demand, avoiding memory buffering. They are always in autocommit mode and allow only one active query at a time. Ensure results are exhausted before running a new query. ```python import mgclient conn = mgclient.connect(host="127.0.0.1", port=7687, lazy=True) cursor = conn.cursor() cursor.execute("UNWIND range(1, 1000000) AS n RETURN n") # Stream rows one at a time — constant memory usage count = 0 while True: row = cursor.fetchone() if row is None: break count += 1 print(f"Processed {count} rows") # Must exhaust current results before running a new query cursor.execute("RETURN 'done' AS msg") print(cursor.fetchone()) # ('done',) conn.close() ``` -------------------------------- ### Transaction control with Connection.commit() and Connection.rollback() Source: https://context7.com/memgraph/pymgclient/llms.txt Persists changes with `commit()` or discards them with `rollback()`. These are no-ops if `autocommit` is `True` or no transaction is active. Closing a connection without committing implicitly rolls back. ```python import mgclient conn = mgclient.connect(host="127.0.0.1", port=7687) cursor = conn.cursor() try: cursor.execute("CREATE (:Account {id: 'A', balance: 100})") cursor.execute("CREATE (:Account {id: 'B', balance: 50})") cursor.execute( "MATCH (a:Account {id: 'A'}), (b:Account {id: 'B'}) " "SET a.balance = a.balance - $amt, b.balance = b.balance + $amt", {"amt": 30}, ) conn.commit() print("Transfer committed") except mgclient.DatabaseError as e: conn.rollback() print(f"Transaction rolled back: {e}") finally: conn.close() ``` -------------------------------- ### `mgclient.Node` — Graph node object Source: https://context7.com/memgraph/pymgclient/llms.txt Represents a Memgraph node returned from a query. It exposes `id`, `labels`, and `properties`, and supports equality comparison. ```APIDOC ## `mgclient.Node` — Graph node object Represents a Memgraph node returned from a query. Exposes `id` (int), `labels` (frozenset of strings), and `properties` (dict). Supports equality comparison and a human-readable string representation. ```python import mgclient conn = mgclient.connect(host="127.0.0.1", port=7687) cursor = conn.cursor() cursor.execute("CREATE (n:Movie:Drama {title: 'Inception', year: 2010}) RETURN n") row = cursor.fetchone() node = row[0] print(node.id) # e.g. 42 print(node.labels) # {'Movie', 'Drama'} print(node.properties) # {'title': 'Inception', 'year': 2010} print(str(node)) # (:Drama:Movie {'title': 'Inception', 'year': 2010}) conn.rollback() conn.close() ``` ``` -------------------------------- ### Lazy connections Source: https://context7.com/memgraph/pymgclient/llms.txt A lazy connection fetches results on demand from the network socket only when `fetchone()`, `fetchmany()`, or `fetchall()` is called, avoiding buffering the full result set in memory. It is always in autocommit mode and allows only one active query at a time. ```APIDOC ## Lazy connections ### Description A lazy connection fetches results on demand from the network socket only when `fetchone()`, `fetchmany()`, or `fetchall()` is called, avoiding buffering the full result set in memory. It is always in autocommit mode and allows only one active query at a time. ### Usage Example ```python import mgclient conn = mgclient.connect(host="127.0.0.1", port=7687, lazy=True) cusor = conn.cursor() cursor.execute("UNWIND range(1, 1000000) AS n RETURN n") # Stream rows one at a time — constant memory usage count = 0 while True: row = cursor.fetchone() if row is None: break count += 1 print(f"Processed {count} rows") # Must exhaust current results before running a new query cusor.execute("RETURN 'done' AS msg") print(cursor.fetchone()) # ('done',) conn.close() ``` ``` -------------------------------- ### Control autocommit mode with Connection.autocommit Source: https://context7.com/memgraph/pymgclient/llms.txt A read/write boolean property. When `True`, statements commit immediately. Required for DDL statements like `CREATE INDEX`. Lazy connections always have `autocommit=True` and cannot change this property. ```python import mgclient conn = mgclient.connect(host="127.0.0.1", port=7687) # DDL must run outside a transaction conn.autocommit = True cursor = conn.cursor() cursor.execute("CREATE INDEX ON :Person(name)") # Switch back for transactional DML conn.autocommit = False cursor.execute("MATCH (p:Person {name: $n}) SET p.indexed = true", {"n": "Alice"}) conn.commit() conn.close() ``` -------------------------------- ### Connection.autocommit Source: https://context7.com/memgraph/pymgclient/llms.txt A read/write boolean property. When `True`, every executed statement is committed immediately and `commit()` / `rollback()` are no-ops. Required for DDL statements such as `CREATE INDEX`. Lazy connections always have `autocommit=True` and the property cannot be changed. ```APIDOC ## Connection.autocommit ### Description Read/write boolean property. When `True`, every executed statement is committed immediately and `commit()` / `rollback()` are no-ops. Required for DDL statements such as `CREATE INDEX`. Lazy connections always have `autocommit=True` and the property cannot be changed. ### Usage Example ```python import mgclient conn = mgclient.connect(host="127.0.0.1", port=7687) # DDL must run outside a transaction conn.autocommit = True cusor = conn.cursor() cusor.execute("CREATE INDEX ON :Person(name)") # Switch back for transactional DML conn.autocommit = False cusor.execute("MATCH (p:Person {name: $n}) SET p.indexed = true", {"n": "Alice"}) conn.commit() conn.close() ``` ``` -------------------------------- ### `mgclient.Relationship` — Graph relationship object Source: https://context7.com/memgraph/pymgclient/llms.txt Represents a directed, typed edge returned from a query. It exposes `id`, `start_id`, `end_id`, `type`, and `properties`. ```APIDOC ## `mgclient.Relationship` — Graph relationship object Represents a directed, typed edge returned from a query. Exposes `id`, `start_id`, `end_id` (all int), `type` (str), and `properties` (dict). ```python import mgclient conn = mgclient.connect(host="127.0.0.1", port=7687) cursor = conn.cursor() cursor.execute(""" CREATE (a:City {name: 'London'})-[r:DISTANCE_TO {km: 344}]->(b:City {name: 'Paris'}) RETURN r """) rel = cursor.fetchone()[0] print(rel.type) # DISTANCE_TO print(rel.properties) # {'km': 344} print(rel.start_id) # id of London node print(rel.end_id) # id of Paris node print(str(rel)) # [:DISTANCE_TO {'km': 344}] conn.rollback() conn.close() ``` ``` -------------------------------- ### Graph Type Objects Source: https://github.com/memgraph/pymgclient/blob/master/docs/source/module.rst Defines objects for representing graph data structures. ```APIDOC ## Graph Type Objects ### mgclient.Node Represents a node in the graph. - **id**: Identifier of the node. - **labels**: Set of labels associated with the node. - **properties**: Dictionary of properties of the node. ### mgclient.Relationship Represents a relationship in the graph. - **id**: Identifier of the relationship. - **start_id**: Identifier of the starting node of the relationship. - **end_id**: Identifier of the ending node of the relationship. - **type**: Type of the relationship. - **properties**: Dictionary of properties of the relationship. ### mgclient.Path Represents a path in the graph. This object has members that can be accessed directly. ```