Database
Operations scoped to a specific ArangoDB database.
Instances are obtained through ArangoClient::database() and share
the parent client's HTTP transport. The database name is fixed at
construction time and is automatically applied as a /_db/{name} URL
prefix on every request() sent through this object.
Example:
$db = $client->database( 'mydb' ) ;
if ( !$db->exists() )
{
$db->create() ;
}
$collections = $db->request( 'GET' , '/_api/collection' )->body ;
Tags
Table of Contents
Constants
- COLLECTIONS_FIELD : string = 'collections'
- Field carrying the collections-scope object on `POST /_api/transaction/begin`.
- EXCLUDE_SYSTEM_PARAM : string = 'excludeSystem'
- Query parameter used by `GET /_api/collection` to skip system collections.
- TRANSACTION_BEGIN_SUFFIX : string = '/begin'
- Sub-route used to start a streaming transaction (`POST /_api/transaction/begin`).
- TRANSACTION_ID_FIELD : string = 'id'
- Field carrying the transaction id on `/_api/transaction/*` responses.
- TRANSACTION_RESULT_FIELD : string = 'result'
- Wrapping field of the lifecycle payload on every `/_api/transaction/*` response.
Properties
- $client : ArangoClient
- $name : string
Methods
- __construct() : mixed
- analyzer() : Analyzer
- Returns an {@see Analyzer} instance bound to the given name in this database.
- analyzers() : array<int, Analyzer>
- Returns a list of {@see Analyzer} handles for every analyzer currently registered on this database.
- beginTransaction() : Transaction
- Starts a streaming transaction on the server and returns a {@see Transaction} handle bound to its server-assigned id.
- collection() : Collection
- Returns a {@see Collection} instance bound to the given name in this database.
- collections() : array<int, Collection>
- Lists the collections living in this database.
- create() : void
- Creates this database on the server.
- createAnalyzer() : Analyzer
- Creates an ArangoSearch analyzer on this database and returns a fresh {@see Analyzer} handle bound to it.
- createGraph() : Graph
- Creates a named graph on this database and returns a fresh {@see Graph} handle bound to it.
- createView() : View
- Creates an ArangoSearch view on this database and returns a fresh {@see View} handle bound to it.
- drop() : void
- Drops this database from the server.
- edgeCollection() : EdgeCollection
- Returns an {@see EdgeCollection} instance bound to the given name in this database.
- exists() : bool
- Returns true when this database currently exists on the server.
- explain() : array<string, mixed>
- Asks the server for the execution plan the optimizer would use for the given AQL query, without running it.
- getName() : string
- Returns the database name this instance is bound to.
- graph() : Graph
- Returns a {@see Graph} instance bound to the given name in this database.
- graphs() : array<int, Graph>
- Returns a list of {@see Graph} handles for every graph currently registered on this database.
- listAnalyzers() : array<int, array<string, mixed>>
- Lists the raw server-side descriptions of every analyzer currently registered on this database.
- listGraphs() : array<int, array<string, mixed>>
- Lists the raw server-side descriptions of every graph currently registered on this database.
- listTransactions() : array<int, array<string, mixed>>
- Lists the streaming transactions currently active on this database.
- listViews() : array<int, array<string, mixed>>
- Lists the raw server-side descriptions of every view currently registered on this database.
- parse() : array<string, mixed>
- Parses an AQL query and returns its AST + the list of collections it references, without executing it.
- query() : Cursor
- Executes an AQL query against this database and returns a {@see Cursor} for iterating over the results.
- request() : HttpResponse
- Sends a request scoped to this database. The URL is automatically prefixed with `/_db/{name}`.
- transaction() : Transaction
- Wraps an existing server-side transaction id into a fresh {@see Transaction} handle bound to this database.
- view() : View
- Returns a {@see View} instance bound to the given name in this database.
- views() : array<int, View>
- Returns a list of {@see View} handles for every view currently registered on this database.
- withTransaction() : mixed
- High-level streaming-transaction helper: starts a transaction with the given collections scope, runs `$callback` inside {@see Transaction::step()}, and commits on success or aborts on failure.
- extractTransactionId() : string
- Extracts the transaction id from a `/_api/transaction/*` response body, unwrapping the outer `result` envelope when present.
Constants
COLLECTIONS_FIELD
Field carrying the collections-scope object on `POST /_api/transaction/begin`.
private
string
COLLECTIONS_FIELD
= 'collections'
EXCLUDE_SYSTEM_PARAM
Query parameter used by `GET /_api/collection` to skip system collections.
private
string
EXCLUDE_SYSTEM_PARAM
= 'excludeSystem'
TRANSACTION_BEGIN_SUFFIX
Sub-route used to start a streaming transaction (`POST /_api/transaction/begin`).
private
string
TRANSACTION_BEGIN_SUFFIX
= '/begin'
TRANSACTION_ID_FIELD
Field carrying the transaction id on `/_api/transaction/*` responses.
private
string
TRANSACTION_ID_FIELD
= 'id'
TRANSACTION_RESULT_FIELD
Wrapping field of the lifecycle payload on every `/_api/transaction/*` response.
private
string
TRANSACTION_RESULT_FIELD
= 'result'
Properties
$client
public
ArangoClient
$client
$name
public
string
$name
Methods
__construct()
public
__construct(ArangoClient $client, string $name) : mixed
Parameters
- $client : ArangoClient
-
Parent client (used for the shared transport and for server-level admin operations).
- $name : string
-
Name of the target database on the server.
analyzer()
Returns an {@see Analyzer} instance bound to the given name in this database.
public
analyzer(string $name) : Analyzer
No HTTP call is made — the handle is purely client-side. Use createAnalyzer() to actually create the analyzer on the server, or Analyzer::create() on the returned instance.
Parameters
- $name : string
-
Analyzer name.
Return values
Analyzeranalyzers()
Returns a list of {@see Analyzer} handles for every analyzer currently registered on this database.
public
analyzers() : array<int, Analyzer>
Hits GET /_api/analyzer, then wraps each entry's name into
a fresh Analyzer instance. For the raw descriptions
(with type, features, properties), use
listAnalyzers().
Server-side built-in analyzers (identity, text_en,
text_de, …) are included in the listing — filter them out
on the caller side when iterating over user-defined
analyzers only.
Tags
Return values
array<int, Analyzer>beginTransaction()
Starts a streaming transaction on the server and returns a {@see Transaction} handle bound to its server-assigned id.
public
beginTransaction([array<int, string> $write = [] ][, array<int, string> $read = [] ][, array<int, string> $exclusive = [] ][, array<string, mixed> $options = [] ]) : Transaction
$write, $read and $exclusive list the collections the
transaction will touch. Each can be a flat array of collection
names (['users', 'audits']) — at least one of the three must
be non-empty (otherwise the server rejects with
transaction must contain at least one collection).
$options is a free-form array forwarded as-is to the server.
Recognised keys are waitForSync, allowImplicit, lockTimeout,
maxTransactionSize, skipFastLockRound, allowDirtyRead.
Example:
$trx = $db->beginTransaction
(
write : [ 'users' , 'audits' ] ,
read : [ 'audits' ] ,
options : [ 'lockTimeout' => 30 , 'waitForSync' => true ] ,
) ;
try
{
$trx->step( static fn() => $db->collection( 'users' )->insert( [ ... ] ) ) ;
$trx->commit() ;
}
catch ( \Throwable $e )
{
try { $trx->abort() ; } catch ( ArangoException ) }
throw $e ;
}
Parameters
- $write : array<int, string> = []
-
Collections written by the transaction (default: empty).
- $read : array<int, string> = []
-
Collections read by the transaction (default: empty).
- $exclusive : array<int, string> = []
-
Collections held exclusively for the transaction (default: empty).
- $options : array<string, mixed> = []
-
Server-side options (
waitForSync,lockTimeout,maxTransactionSize,skipFastLockRound,allowImplicit,allowDirtyRead).
Tags
Return values
Transactioncollection()
Returns a {@see Collection} instance bound to the given name in this database.
public
collection(string $name) : Collection
The collection is created lazily on the client side — no HTTP call is made by this method. The returned instance shares this database's HTTP transport, so every operation on the collection benefits from the same connection pool, retry policy and host-ring failover.
Parameters
- $name : string
-
Name of the target collection.
Return values
Collectioncollections()
Lists the collections living in this database.
public
collections([bool $includeSystem = false ]) : array<int, Collection>
System collections (names starting with _) are excluded by
default — pass $includeSystem = true to receive them too. The
server's metadata entries are turned into bare Collection
instances (sharing the same transport as this database), so the
caller can call CRUD methods directly on each item.
Parameters
- $includeSystem : bool = false
-
Whether to include system collections in the result.
Tags
Return values
array<int, Collection>create()
Creates this database on the server.
public
create() : void
Delegates to ArangoClient::createDatabase(); the underlying call is a server-global route, not scoped to $name.
Tags
createAnalyzer()
Creates an ArangoSearch analyzer on this database and returns a fresh {@see Analyzer} handle bound to it.
public
createAnalyzer(string $name, AnalyzerOptions $options[, array<int, string> $features = [] ]) : Analyzer
Shortcut over $db->analyzer($name)->create($options, $features)
that hits the server right away. See Analyzer::create()
for the accepted options and features.
Parameters
- $name : string
-
Analyzer name.
- $options : AnalyzerOptions
-
Type-specific options (IdentityAnalyzer, TextAnalyzer, NormAnalyzer, StemAnalyzer).
- $features : array<int, string> = []
-
Optional list of analyzer features (entries of AnalyzerFeature).
Tags
Return values
AnalyzercreateGraph()
Creates a named graph on this database and returns a fresh {@see Graph} handle bound to it.
public
createGraph(string $name[, array<int, EdgeDefinition> $edgeDefinitions = [] ][, array<string, mixed> $options = [] ]) : Graph
Shortcut over $db->graph($name)->create($edgeDefinitions, $options)
that hits the server right away. See Graph::create() for
the recognised options.
Parameters
- $name : string
-
Graph name.
- $edgeDefinitions : array<int, EdgeDefinition> = []
-
Edge definitions to register on creation (may be empty for a vertex-only graph).
- $options : array<string, mixed> = []
-
Extra creation options forwarded verbatim to the server.
Tags
Return values
GraphcreateView()
Creates an ArangoSearch view on this database and returns a fresh {@see View} handle bound to it.
public
createView(string $name[, array<string, ArangoSearchLink|array<string, mixed>> $links = [] ][, array<string, mixed> $options = [] ]) : View
Shortcut over $db->view($name)->create($links, $options)
that hits the server right away. Only the arangosearch
view type is exposed in V1.
Parameters
- $name : string
-
View name.
- $links : array<string, ArangoSearchLink|array<string, mixed>> = []
-
Per-collection link map (each value is an ArangoSearchLink VO or its array shape).
- $options : array<string, mixed> = []
-
Extra arangosearch options forwarded verbatim (cleanupIntervalStep, consolidationIntervalMsec, primarySort, …).
Tags
Return values
Viewdrop()
Drops this database from the server.
public
drop() : void
Delegates to ArangoClient::dropDatabase(); the underlying call is a server-global route, not scoped to $name.
Tags
edgeCollection()
Returns an {@see EdgeCollection} instance bound to the given name in this database.
public
edgeCollection(string $name) : EdgeCollection
Identical to collection() on the client side (no HTTP call
is made by this method) — the returned instance simply exposes
the edge-specific helpers (inEdges / outEdges / edges) and
defaults its create() to CollectionType::EDGE.
The underlying transport, retry policy and host-ring failover
are shared with this database.
Parameters
- $name : string
-
Name of the target edge collection.
Return values
EdgeCollectionexists()
Returns true when this database currently exists on the server.
public
exists() : bool
Internally calls ArangoClient::listDatabases() and checks whether $name is included in the result.
Tags
Return values
boolexplain()
Asks the server for the execution plan the optimizer would use for the given AQL query, without running it.
public
explain(AqlQuery|string $query[, array<string, mixed> $bindVars = [] ][, array<string, mixed> $options = [] ]) : array<string, mixed>
Wraps POST /_api/explain. The returned array follows the wire
shape verbatim — plan (single-plan response) or plans
({ allPlans: true }) plus warnings, cacheable, and
stats. Decoding stays raw because the plan tree is deep and
volatile (optimizer rules evolve between server versions), so
a typed value object would be a fragile bet.
Typical use cases:
- confirm an index is actually used (look for
IndexNodein the plan), - inspect the join order the optimizer chose,
- compare alternative plans with
[ 'allPlans' => true ].
Parameters
- $query : AqlQuery|string
-
Either a built AqlQuery or a raw AQL string.
- $bindVars : array<string, mixed> = []
-
Bind values for the raw string form. MUST be empty when
$queryis an AqlQuery. - $options : array<string, mixed> = []
-
Server-side explain options (
allPlans,maxNumberOfPlans,optimizer.rules, …).
Tags
Return values
array<string, mixed> —Raw server response.
getName()
Returns the database name this instance is bound to.
public
getName() : string
Return values
stringgraph()
Returns a {@see Graph} instance bound to the given name in this database.
public
graph(string $name) : Graph
No HTTP call is made — the handle is purely client-side. Use createGraph() to actually create the graph on the server, or Graph::create() on the returned instance.
Parameters
- $name : string
-
Graph name.
Return values
Graphgraphs()
Returns a list of {@see Graph} handles for every graph currently registered on this database.
public
graphs() : array<int, Graph>
Hits GET /_api/gharial, then wraps each entry's name into a
fresh Graph instance. For the raw descriptions (with
edge definitions, orphan collections, etc.), use
listGraphs().
Tags
Return values
array<int, Graph>listAnalyzers()
Lists the raw server-side descriptions of every analyzer currently registered on this database.
public
listAnalyzers() : array<int, array<string, mixed>>
Wraps GET /_api/analyzer. Returns the payload verbatim —
each entry carries at least name / type / features /
properties.
Server-side built-in analyzers (identity, text_en,
text_de, …) are included in the listing — filter them out
on the caller side when iterating over user-defined
analyzers only.
Tags
Return values
array<int, array<string, mixed>>listGraphs()
Lists the raw server-side descriptions of every graph currently registered on this database.
public
listGraphs() : array<int, array<string, mixed>>
Wraps GET /_api/gharial. Returns the payload verbatim — each
entry carries at least _key / _id / name /
edgeDefinitions / orphanCollections.
Tags
Return values
array<int, array<string, mixed>>listTransactions()
Lists the streaming transactions currently active on this database.
public
listTransactions() : array<int, array<string, mixed>>
Wraps GET /_api/transaction. Returns the server-side payload
verbatim — each entry exposes at least id and state (one
of TransactionStatus,
keyed state here rather than status on this list endpoint).
Useful for admin tooling and for diagnosing orphan transactions that survived a client crash.
Tags
Return values
array<int, array<string, mixed>>listViews()
Lists the raw server-side descriptions of every view currently registered on this database.
public
listViews() : array<int, array<string, mixed>>
Wraps GET /_api/view. Returns the payload verbatim — each
entry carries at least name / type / id /
globallyUniqueId.
Tags
Return values
array<int, array<string, mixed>>parse()
Parses an AQL query and returns its AST + the list of collections it references, without executing it.
public
parse(AqlQuery|string $query) : array<string, mixed>
Wraps POST /_api/query. The naming mirrors arangojs
(db.parse()). Useful as a lightweight validation step: a
malformed query is rejected here with the same errorNum the
server would emit at execution time, but without going through
the cursor / batch machinery.
Bind values are intentionally ignored by the endpoint — only
the query string itself is parsed. Pass an AqlQuery if it is
what you already hold; only its ->query part is sent over
the wire.
Parameters
- $query : AqlQuery|string
-
Either a built AqlQuery or a raw AQL string. Only the query string is forwarded.
Tags
Return values
array<string, mixed> —Raw server response (parsed, collections, bindVars, ast, …).
query()
Executes an AQL query against this database and returns a {@see Cursor} for iterating over the results.
public
query(AqlQuery|string $query[, array<string, mixed> $bindVars = [] ][, array<string, mixed> $options = [] ]) : Cursor
The first argument can be either:
- a fully-built AqlQuery (typically produced by aql() or by a query builder),
- a raw query string, in which case
$bindVarscarries the bind values.
$options is a free-form array forwarded as-is to the server's
POST /_api/cursor endpoint. Common keys are count, batchSize,
fullCount, ttl, memoryLimit, cache, options.profile, …
(see https://docs.arangodb.com/stable/aql/how-to-invoke-aql/#cursor-api).
Example:
use function oihana\arango\clients\aql\helpers\aql ;
$cursor = $db->query
(
aql( 'FOR u IN users FILTER u.active == ? RETURN u' , true ) ,
options : [ 'count' => true ] ,
) ;
foreach ( $cursor as $user ) { ... }
echo count( $cursor ) ;
Parameters
- $query : AqlQuery|string
-
Either a built AqlQuery or a raw AQL string.
- $bindVars : array<string, mixed> = []
-
Bind values for the raw string form. MUST be empty when
$queryis an AqlQuery. - $options : array<string, mixed> = []
-
Server-side cursor options (count, batchSize, fullCount, …).
Tags
Return values
Cursorrequest()
Sends a request scoped to this database. The URL is automatically prefixed with `/_db/{name}`.
public
request(string $method, string $path[, array<string, mixed>|string|null $body = null ][, array<string, mixed> $query = [] ][, array<string, string> $headers = [] ][, string|null $transactionId = null ]) : HttpResponse
Parameters
- $method : string
-
HTTP verb.
- $path : string
-
API path beginning with
/. - $body : array<string, mixed>|string|null = null
-
Request body. When an array is passed it is JSON-encoded; when a string is passed it is sent verbatim as the raw HTTP body (used for
/_api/importJSON Lines payloads — caller must then supply the matchingContent-Typeheader). - $query : array<string, mixed> = []
-
Query string parameters.
- $headers : array<string, string> = []
-
Extra headers (merged with the per-request defaults).
- $transactionId : string|null = null
-
Optional streaming transaction id; when non-null, the transport stamps
x-arango-trx-id: {id}on the outbound request so the server attaches the operation to the running transaction.
Tags
Return values
HttpResponsetransaction()
Wraps an existing server-side transaction id into a fresh {@see Transaction} handle bound to this database.
public
transaction(string $id) : Transaction
No HTTP call is made — the handle is purely client-side. Use this when a transaction id has been obtained out-of-band (for example through listTransactions() or shared by another process) and the caller wants to commit, abort or inspect it.
Parameters
- $id : string
-
Server-side transaction id.
Return values
Transactionview()
Returns a {@see View} instance bound to the given name in this database.
public
view(string $name) : View
No HTTP call is made — the handle is purely client-side. Use createView() to actually create the view on the server, or View::create() on the returned instance.
Parameters
- $name : string
-
View name.
Return values
Viewviews()
Returns a list of {@see View} handles for every view currently registered on this database.
public
views() : array<int, View>
Hits GET /_api/view, then wraps each entry's name into a
fresh View instance. For the raw descriptions (with
type, id, globallyUniqueId), use listViews().
Tags
Return values
array<int, View>withTransaction()
High-level streaming-transaction helper: starts a transaction with the given collections scope, runs `$callback` inside {@see Transaction::step()}, and commits on success or aborts on failure.
public
withTransaction(callable(Transaction): mixed $callback[, array<int, string> $write = [] ][, array<int, string> $read = [] ][, array<int, string> $exclusive = [] ][, array<string, mixed> $options = [] ]) : mixed
The callback receives the Transaction handle as its
single argument, so it can inspect id / status() if needed.
Every plain CRUD call inside the callback automatically carries
the x-arango-trx-id header (because the callback runs inside
step()), so the caller almost never needs to use the handle
directly — it's there for the edge cases.
Lifecycle guarantees:
- On a clean return from
$callback, the transaction iscommit()-ed and the return value is propagated up. - On a
\Throwableraised from$callback,abort()is called best-effort (any exception fromabort()is silently swallowed — the server may have already terminated the transaction) and the original exception is re-thrown. - Do NOT call
commit()orabort()from inside$callback— the helper owns the lifecycle. Doing so will surface as a1657/1658error when the helper tries to terminate the transaction itself.
Example:
$newKey = $db->withTransaction
(
callback : static function ( Transaction $trx ) use ( $db , $payload )
{
$user = $db->collection( 'users' )->insert( $payload , [ 'returnNew' => true ] ) ;
$db->collection( 'audits' )->insert
(
[ 'event' => 'user.created' , 'userKey' => $user->getKey() ] ,
) ;
return $user->getKey() ;
} ,
write : [ 'users' , 'audits' ] ,
) ;
Parameters
- $callback : callable(Transaction): mixed
-
User-provided block.
- $write : array<int, string> = []
-
Collections written by the transaction.
- $read : array<int, string> = []
-
Collections read by the transaction.
- $exclusive : array<int, string> = []
-
Collections held exclusively for the transaction.
- $options : array<string, mixed> = []
-
Server-side options (see beginTransaction()).
Tags
Return values
mixed —The value returned by $callback.
extractTransactionId()
Extracts the transaction id from a `/_api/transaction/*` response body, unwrapping the outer `result` envelope when present.
private
extractTransactionId(mixed $body) : string
Parameters
- $body : mixed
-
Decoded response body.
Return values
string —The transaction id, or an empty string when the field is absent.