Skip to content

Commit

Permalink
Refactor codes
Browse files Browse the repository at this point in the history
  • Loading branch information
richan-fongdasen committed Apr 18, 2024
1 parent a2da98c commit c98c431
Show file tree
Hide file tree
Showing 29 changed files with 1,317 additions and 339 deletions.
2 changes: 1 addition & 1 deletion phpstan-baseline.neon
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
parameters:
treatPhpDocTypesAsCertain: false
ignoreErrors:
- '#Variable method call on RichanFongdasen\\Turso\\TursoHttpClient.#'
- '#Variable method call on RichanFongdasen\\Turso\\TursoClient.#'
17 changes: 17 additions & 0 deletions src/Contracts/TursoQuery.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php

declare(strict_types=1);

namespace RichanFongdasen\Turso\Contracts;

use Illuminate\Contracts\Support\Arrayable;
use Stringable;

interface TursoQuery extends Arrayable, Stringable
{
public function getIndex(): int;

public function getType(): string;

public function setIndex(int $index): self;
}
2 changes: 2 additions & 0 deletions src/Database/TursoConnection.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ class TursoConnection extends Connection
public function __construct(TursoPDO $pdo, string $database = ':memory:', string $tablePrefix = '', array $config = [])
{
parent::__construct($pdo, $database, $tablePrefix, $config);

$this->schemaGrammar = $this->getDefaultSchemaGrammar();
}

/**
Expand Down
61 changes: 15 additions & 46 deletions src/Database/TursoPDOStatement.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
use PDOException;
use PDOStatement;
use RichanFongdasen\Turso\Facades\Turso;
use RichanFongdasen\Turso\Http\QueryResponse;

/**
* Turso PDO Statement.
Expand All @@ -24,14 +25,13 @@ class TursoPDOStatement extends PDOStatement

protected array $bindings = [];

protected ?Collection $responses = null;
protected ?QueryResponse $response = null;

public function __construct(
protected TursoPDO $pdo,
protected string $query,
protected array $options = [],
) {
$this->responses = new Collection();
}

public function setFetchMode(int $mode, mixed ...$args): bool
Expand Down Expand Up @@ -88,16 +88,14 @@ public function execute(?array $params = null): bool
$this->bindValue($key, $value, $type);
});

$rawResponse = Turso::query($this->query, array_values($this->bindings));
$this->responses = $this->formatResponse($rawResponse);

$lastId = (int) data_get($rawResponse, 'result.last_insert_rowid', 0);
$this->response = Turso::query($this->query, array_values($this->bindings));

$lastId = (int) $this->response->getLastInsertId();
if ($lastId > 0) {
$this->pdo->setLastInsertId(value: $lastId);
}

$this->affectedRows = (int) data_get($rawResponse, 'result.affected_row_count', 0);
$this->affectedRows = $this->response->getAffectedRows();

return true;
}
Expand All @@ -108,7 +106,7 @@ public function fetch(int $mode = PDO::FETCH_DEFAULT, int $cursorOrientation = P
$mode = $this->fetchMode;
}

$response = $this->responses?->shift();
$response = $this->response?->getRows()->shift();

if ($response === null) {
return false;
Expand All @@ -129,61 +127,32 @@ public function fetch(int $mode = PDO::FETCH_DEFAULT, int $cursorOrientation = P

public function fetchAll(int $mode = PDO::FETCH_DEFAULT, ...$args): array
{
if (! ($this->responses instanceof Collection)) {
if (! ($this->response instanceof QueryResponse)) {
return [];
}

if ($mode === PDO::FETCH_DEFAULT) {
$mode = $this->fetchMode;
}

$allRows = $this->response->getRows();

$response = match ($mode) {
PDO::FETCH_BOTH => $this->responses->map(function (Collection $row) {
PDO::FETCH_BOTH => $allRows->map(function (Collection $row) {
return array_merge($row->toArray(), $row->values()->toArray());
})->toArray(),
PDO::FETCH_ASSOC, PDO::FETCH_NAMED => $this->responses->toArray(),
PDO::FETCH_NUM => $this->responses->map(function (Collection $row) {
PDO::FETCH_ASSOC, PDO::FETCH_NAMED => $allRows->toArray(),
PDO::FETCH_NUM => $allRows->map(function (Collection $row) {
return $row->values()->toArray();
})->toArray(),
PDO::FETCH_OBJ => $this->responses->map(function (Collection $row) {
PDO::FETCH_OBJ => $allRows->map(function (Collection $row) {
return (object) $row->toArray();
})->toArray(),

default => throw new PDOException('Unsupported fetch mode.'),
};

$this->responses = new Collection();

return $response;
}

protected function formatResponse(array $originalResponse): Collection
{
$response = new Collection();
$columns = collect((array) data_get($originalResponse, 'result.cols', []))
->keyBy('name')
->keys()
->all();

$rows = collect((array) data_get($originalResponse, 'result.rows', []))
->each(function (array $item) use (&$response, $columns) {
$row = new Collection();

collect($item)
->each(function (array $column, int $index) use (&$row, $columns) {
$value = match ($column['type']) {
'blob' => base64_decode((string) $column['value'], true),
'integer' => (int) $column['value'],
'float' => (float) $column['value'],
'null' => null,
default => (string) $column['value'],
};

$row->put(data_get($columns, $index), $value);
});

$response->push($row);
});
// $this->responses = new Collection();

return $response;
}
Expand All @@ -201,6 +170,6 @@ public function nextRowset(): bool

public function rowCount(): int
{
return $this->responses?->count() ?? 0;
return $this->response?->getRows()->count() ?? 0;
}
}
4 changes: 2 additions & 2 deletions src/Facades/Turso.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@
use RichanFongdasen\Turso\TursoManager;

/**
* @see \RichanFongdasen\Turso\TursoHttpClient
* @see \RichanFongdasen\Turso\TursoClient
*
* @mixin \RichanFongdasen\Turso\TursoManager
* @mixin \RichanFongdasen\Turso\TursoHttpClient
* @mixin \RichanFongdasen\Turso\TursoClient
*/
class Turso extends Facade
{
Expand Down
135 changes: 135 additions & 0 deletions src/Http/QueryResponse.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
<?php

declare(strict_types=1);

namespace RichanFongdasen\Turso\Http;

use Illuminate\Support\Collection;
use RichanFongdasen\Turso\Contracts\TursoQuery;
use RichanFongdasen\Turso\Exceptions\TursoQueryException;
use RichanFongdasen\Turso\Queries\ExecuteQuery;

class QueryResponse
{
protected int $affectedRows = 0;

protected Collection $columns;

protected ?string $lastInsertId = null;

protected TursoQuery $query;

protected array $rawResponse;

protected int $replicationIndex = 0;

protected string $responseType = '';

protected Collection $rows;

public function __construct(TursoQuery $query, array $response = [])
{
$this->query = $query;
$this->rawResponse = $response;
$this->responseType = data_get($response, 'type', 'error');

$this->affectedRows = (int) data_get($response, 'response.result.affected_row_count', 0);
$this->lastInsertId = data_get($response, 'response.result.last_insert_rowid');
$this->replicationIndex = (int) data_get($response, 'response.result.replication_index');

$this->columns = $this->extractColumns($response);
$this->rows = $this->extractRows($response);

$this->checkIfResponseHasError();
}

protected function checkIfResponseHasError(): void
{
if ($this->responseType !== 'error') {
return;
}

$errorCode = (string) data_get($this->rawResponse, 'error.code', 'UNKNOWN_ERROR');
$errorMessage = (string) data_get($this->rawResponse, 'error.message', 'Error: An unknown error has occurred');

$statement = ($this->query instanceof ExecuteQuery)
? $this->query->getStatement()
: $this->query->getType();

throw new TursoQueryException($errorCode, $errorMessage, $statement);
}

protected function extractColumns(array $response): Collection
{
return collect((array) data_get($response, 'response.result.cols', []))
->keyBy('name')
->keys();
}

protected function extractRows(array $response): Collection
{
$rows = new Collection();

collect((array) data_get($response, 'response.result.rows', []))
->each(function (array $item) use (&$rows) {
$row = new Collection();

collect($item)
->each(function (array $column, int $index) use (&$row) {
$value = match ($column['type']) {
'blob' => base64_decode((string) $column['value'], true),
'integer' => (int) $column['value'],
'float' => (float) $column['value'],
'null' => null,
default => (string) $column['value'],
};

$row->put($this->columns->get($index), $value);
});

$rows->push($row);
});

return $rows;
}

public function getAffectedRows(): int
{
return $this->affectedRows;
}

public function getColumns(): Collection
{
return $this->columns;
}

public function getLastInsertId(): ?string
{
return $this->lastInsertId;
}

public function getQuery(): TursoQuery
{
return $this->query;
}

public function getRawResponse(): array
{
return $this->rawResponse;
}

public function getReplicationIndex(): int
{
return $this->replicationIndex;
}

public function getResponseType(): string
{
return $this->responseType;
}

public function getRows(): Collection
{
return $this->rows;
}
}
Loading

0 comments on commit c98c431

Please sign in to comment.