Skip to content

Commit

Permalink
Add PostgresArray
Browse files Browse the repository at this point in the history
  • Loading branch information
trowski committed Jan 7, 2025
1 parent 0d1d0b3 commit abcfc45
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 2 deletions.
17 changes: 15 additions & 2 deletions src/Internal/functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Amp\Postgres\Internal;

use Amp\Postgres\PostgresArray;
use Amp\Postgres\PostgresByteA;
use Amp\Postgres\PostgresExecutor;

Expand Down Expand Up @@ -105,8 +106,9 @@ function encodeParam(PostgresExecutor $executor, mixed $value): string|int|float
return match (\gettype($value)) {
"NULL", "integer", "double", "string" => $value,
"boolean" => $value ? 't' : 'f',
"array" => '{' . \implode(',', \array_map(fn ($i) => encodeArrayItem($executor, $i), $value)) . '}',
"array" => encodeArray($executor, $value, ','),
"object" => match (true) {
$value instanceof PostgresArray => $value->encode($executor),
$value instanceof PostgresByteA => $executor->escapeByteA($value->getData()),
$value instanceof \BackedEnum => $value->value,
$value instanceof \Stringable => (string) $value,
Expand All @@ -122,6 +124,14 @@ function encodeParam(PostgresExecutor $executor, mixed $value): string|int|float
};
}

/**
* @internal
*/
function encodeArray(PostgresExecutor $executor, array $array, string $delimiter): string
{
return '{' . \implode($delimiter, \array_map(fn ($i) => encodeArrayItem($executor, $i), $array)) . '}';
}

/**
* @internal
*
Expand All @@ -133,7 +143,10 @@ function encodeArrayItem(PostgresExecutor $executor, mixed $value): mixed
"NULL" => "NULL",
"string" => '"' . \str_replace(['\\', '"'], ['\\\\', '\\"'], $value) . '"',
"array", "boolean", "integer", "double" => encodeParam($executor, $value),
"object" => encodeArrayItem($executor, encodeParam($executor, $value)),
"object" => match (true) {
$value instanceof PostgresArray => encodeParam($executor, $value),
default => encodeArrayItem($executor, encodeParam($executor, $value)),
},
default => throw new \TypeError(\sprintf(
"Invalid value type '%s' in array",
\get_debug_type($value),
Expand Down
21 changes: 21 additions & 0 deletions src/PostgresArray.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php declare(strict_types=1);

namespace Amp\Postgres;

final class PostgresArray
{
public function __construct(
private readonly array $data,
private readonly string $delimiter = ',',
) {
}

/**
* Encodes the array for use in a query. Note that the value returned must still be quoted using
* {@see PostgresExecutor::quoteLiteral()} if inserting directly into a query string.
*/
public function encode(PostgresExecutor $executor): string
{
return Internal\encodeArray($executor, $this->data, $this->delimiter);
}
}

0 comments on commit abcfc45

Please sign in to comment.