Skip to content

Commit b471ee2

Browse files
committed
transaction code
new db credentials
1 parent 0ca519a commit b471ee2

14 files changed

+244
-62
lines changed

composer.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,8 @@
66
"guzzlehttp/guzzle": "^7.9",
77
"psr/http-client": "^1.0",
88
"ext-json": "*",
9-
"php": "^8.1"
9+
"php": "^8.1",
10+
"ext-curl": "*"
1011
},
1112
"require-dev": {
1213
"phpunit/phpunit": "^11.0"

composer.lock

Lines changed: 8 additions & 8 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/Results/ResultSet.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,4 +26,6 @@ public function count(): int
2626
{
2727
return count($this->rows);
2828
}
29+
30+
2931
}

src/Transaction.php

Lines changed: 69 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,22 +2,88 @@
22

33
namespace Neo4j\QueryAPI;
44

5+
use GuzzleHttp\Client;
56
use Neo4j\QueryAPI\Results\ResultSet;
67

78
class Transaction
89
{
10+
private Client $client;
11+
private string $baseUrl;
12+
private array $headers;
13+
private ?string $transactionId = null;
14+
15+
public function __construct(string $baseUrl, string $username, string $password)
16+
{
17+
$this->client = new Client();
18+
$this->baseUrl = $baseUrl;
19+
$auth = base64_encode("$username:$password");
20+
$this->headers = [
21+
'Authorization' => 'Basic ' . $auth,
22+
'Content-Type' => 'application/json',
23+
'Accept' => 'application/json',
24+
];
25+
}
26+
27+
public function begin(): void
28+
{
29+
$response = $this->client->post($this->baseUrl .'/db/neo4j'. '/tx', [
30+
'headers' => $this->headers,
31+
'body' => json_encode([]),
32+
]);
33+
34+
$responseData = json_decode($response->getBody(), true);
35+
$this->transactionId = $responseData['commit'] ?? null;
36+
}
37+
938
public function run(string $statement, array $params = []): ResultSet
1039
{
40+
if (!$this->transactionId) {
41+
$this->begin();
42+
}
43+
44+
$payload = json_encode([
45+
'statements' => [
46+
[
47+
'statement' => $statement,
48+
'parameters' => $params,
49+
],
50+
],
51+
]);
52+
53+
$response = $this->client->post($this->baseUrl .'/db/neo4j'.'/tx/' . $this->transactionId, [
54+
'headers' => $this->headers,
55+
'body' => $payload,
56+
]);
57+
58+
$responseData = json_decode($response->getBody(), true);
1159

60+
return new ResultSet($responseData['results'] ?? []);
1261
}
1362

14-
public function commit(string $statement = null, array $parameters = []): null|ResultSet
63+
public function commit(): ?ResultSet
1564
{
65+
if (!$this->transactionId) {
66+
throw new \Exception("No active transaction to commit.");
67+
}
1668

69+
$response = $this->client->post($this->transactionId, [
70+
'headers' => $this->headers,
71+
'body' => json_encode([]),
72+
]);
73+
74+
$responseData = json_decode($response->getBody(), true);
75+
$this->transactionId = null;
76+
77+
return new ResultSet($responseData['results'] ?? []);
1778
}
1879

1980
public function rollback(): void
2081
{
21-
82+
if ($this->transactionId) {
83+
$this->client->delete($this->baseUrl . '/tx/' . $this->transactionId, [
84+
'headers' => $this->headers,
85+
]);
86+
$this->transactionId = null;
87+
}
2288
}
23-
}
89+
}

src/query-api-test.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
11
<?php
22

3-
use Neo4j\QueryAPI\Neo4jQueryAPI;
3+
use Neo4j\QueryAPI\Transaction;
44
use GuzzleHttp\Exception\RequestException;
55

66
require __DIR__ . '/../vendor/autoload.php';
77

88

99
// Login to the Neo4j instance
10-
$api = Neo4jQueryAPI::login(
10+
$api = Transaction::login(
1111
'https://bb79fe35.databases.neo4j.io',
1212
'neo4j',
1313
'OXDRMgdWFKMcBRCBrIwXnKkwLgDlmFxipnywT6t_AK0'

src/run_neo4j_query.php

Lines changed: 74 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,82 @@
11
<?php
2-
/*
3-
require 'vendor/autoload.php';
42

5-
use Laudis\Neo4j\ClientBuilder;
6-
use Laudis\Neo4j\Authentication\Authenticate;
7-
8-
$address = 'neo4j+s://bb79fe35.databases.neo4j.io';
3+
$neo4j_url = 'https://f2455ee6.databases.neo4j.io';
94
$username = 'neo4j';
10-
$password = 'OXDRMgdWFKMcBRCBrIwXnKkwLgDlmFxipnywT6t_AK0';
5+
$password = 'h5YLhuoSnPD6yMy8OwmFPXs6WkL8uX25zxHCKhiF_hY';
6+
7+
function runNeo4jTransaction($query): void
8+
{
9+
global $neo4j_url, $username, $password;
10+
11+
$ch = curl_init();
12+
13+
echo "Authorization Header: " . base64_encode("$username:$password") . "\n";
14+
15+
curl_setopt($ch, CURLOPT_URL, $neo4j_url . '/db/neo4j/transaction/commit');
16+
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
17+
curl_setopt($ch, CURLOPT_POST, true);
18+
curl_setopt($ch, CURLOPT_HTTPHEADER, [
19+
'Content-Type: application/json',
20+
'Authorization: Basic ' . base64_encode("$username:$password")
21+
]);
22+
23+
$payload = json_encode([
24+
"statements" => []
25+
]);
26+
27+
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
28+
29+
$response = curl_exec($ch);
30+
if(curl_errno($ch)) {
31+
echo 'Error starting transaction: ' . curl_error($ch);
32+
return;
33+
}
34+
35+
echo "Transaction Start Response: ";
36+
print_r($response);
37+
38+
$http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
39+
if ($http_status === 403) {
40+
echo "403 Forbidden: Check credentials and permissions.\n";
41+
}
42+
43+
$transaction_data = json_decode($response, true);
44+
45+
if (!isset($transaction_data['results'])) {
46+
echo "Transaction creation failed or missing results. Response: ";
47+
print_r($transaction_data);
48+
return;
49+
}
50+
51+
$query_data = [
52+
"statements" => [
53+
[
54+
"statement" => $query
55+
]
56+
]
57+
];
58+
59+
curl_setopt($ch, CURLOPT_URL, $neo4j_url . '/db/neo4j/query/v2/tx');
60+
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($query_data));
61+
62+
$response = curl_exec($ch);
63+
if(curl_errno($ch)) {
64+
echo 'Error running query: ' . curl_error($ch);
65+
return;
66+
}
1167

68+
$commit_data = json_decode($response, true);
69+
if (isset($commit_data['errors']) && count($commit_data['errors']) > 0) {
70+
echo "Query error: " . $commit_data['errors'][0]['message'];
71+
return;
72+
}
1273

13-
// Create a Neo4j client using the Laudis PHP driver with authentication
14-
$client = ClientBuilder::create()
15-
->withDriver(
16-
'bolt',
17-
$address,
18-
Authenticate::basic($username, $password) // Proper authentication object
19-
)
20-
->build();
74+
echo "Transaction successful. Data returned: ";
75+
print_r($commit_data);
2176

22-
// Define the Cypher query
23-
$cypherQuery = 'MATCH (n:Person) RETURN n LIMIT 10';
77+
curl_close($ch);
78+
}
2479

25-
// Run the query and fetch results
26-
$results = $client->run($cypherQuery);
80+
$query = 'MATCH (n) RETURN n LIMIT 5';
2781

28-
// Print the results
29-
echo "<pre>"; // Optional: formats the output nicely for readability
30-
print_r($results->toArray());
31-
echo "</pre>";
32-
*/
82+
runNeo4jTransaction($query);

src/run_query.php

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,14 +8,14 @@
88
try {
99
// Login to the Neo4j instance
1010
$api = Neo4jQueryAPI::login(
11-
'https://bb79fe35.databases.neo4j.io', // Replace with your Neo4j instance URL
11+
'https://f2455ee6.databases.neo4j.io', // Replace with your Neo4j instance URL
1212
'neo4j', // Replace with your Neo4j username
13-
'OXDRMgdWFKMcBRCBrIwXnKkwLgDlmFxipnywT6t_AK0' // Replace with your Neo4j password
13+
'h5YLhuoSnPD6yMy8OwmFPXs6WkL8uX25zxHCKhiF_hY' // Replace with your Neo4j password
1414

1515
);
1616

1717
// Define a Cypher query
18-
$query = "MATCH (n:Person) RETURN n ";
18+
$query = "MATCH (n:Person) RETURN n LIMIT 10";
1919

2020
// Fetch results in plain JSON format
2121
$plainResults = $api->run($query, [], 'neo4j', false);
@@ -38,4 +38,3 @@
3838
} catch (Exception $e) {
3939
echo "General Error: " . $e->getMessage();
4040
}
41-

src/run_transaction.php

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
<?php
2+
3+
require __DIR__ . '/../vendor/autoload.php';
4+
use Neo4j\QueryAPI\Transaction;
5+
6+
try {
7+
// Initialize the Transaction object with your Neo4j database credentials
8+
$neo4j = new Transaction('https://f2455ee6.databases.neo4j.io', 'neo4j', 'h5YLhuoSnPD6yMy8OwmFPXs6WkL8uX25zxHCKhiF_hY');
9+
10+
// Begin a transaction
11+
$neo4j->beginTransaction();
12+
13+
// Run Cypher queries within the transaction
14+
$neo4j->runQuery('CREATE (a:Person {name: $name})', ['name' => 'Alice']);
15+
$neo4j->runQuery('CREATE (b:Person {name: $name})', ['name' => 'Bob']);
16+
$neo4j->runQuery(
17+
'MATCH (a:Person {name: $name1}), (b:Person {name: $name2}) CREATE (a)-[:FRIEND]->(b)',
18+
['name1' => 'Alice', 'name2' => 'Bob']
19+
);
20+
21+
// Commit the transaction
22+
$neo4j->commitTransaction();
23+
echo "Transaction committed successfully.\n";
24+
25+
} catch (Exception $e) {
26+
// Handle error and rollback transaction if necessary
27+
if (isset($neo4j)) {
28+
try {
29+
$neo4j->rollbackTransaction();
30+
echo "Transaction rolled back successfully.\n";
31+
} catch (Exception $rollbackException) {
32+
echo "Failed to rollback transaction: " . $rollbackException->getMessage();
33+
}
34+
}
35+
echo "Transaction failed: " . $e->getMessage() . "\n";
36+
}

src/runtransaction.php

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
<?php
2+
3+
require __DIR__ . '/../vendor/autoload.php';
4+
5+
use Neo4j\QueryAPI\Transaction;
6+
7+
$baseUrl = 'https://6f72daa1.databases.neo4j.io';
8+
$username = 'neo4j';
9+
$password = '9lWmptqBgxBOz8NVcTJjgs3cHPyYmsy63ui6Spmw1d0';
10+
11+
try {
12+
$transaction = new Transaction($baseUrl, $username, $password);
13+
14+
$query = 'CREATE (n:Person {name: $name, age: $age}) RETURN n';
15+
$parameters = [
16+
'name' => 'Alice',
17+
'age' => 30,
18+
];
19+
20+
$resultSet = $transaction->run($query, $parameters);
21+
22+
echo "Query executed successfully. Results:\n";
23+
foreach ($resultSet as $row) {
24+
print_r($row);
25+
}
26+
27+
$transaction->commit();
28+
echo "Transaction committed successfully.\n";
29+
30+
} catch (Exception $e) {
31+
echo "An error occurred: " . $e->getMessage() . "\n";
32+
}

test.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@
2727

2828
$client = new Client();
2929

30-
$response = $client->post('http://localhost:7474/db/neo4j/query/v2/tx', [
30+
$response = $client->post('https://6f72daa1.databases.neo4j.io/db/neo4j/query/v2/tx', [
3131
'headers' => $headers,
3232
'body' => $payload,
3333
]);

0 commit comments

Comments
 (0)