Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
trowski committed Sep 14, 2016
0 parents commit caf829a
Show file tree
Hide file tree
Showing 46 changed files with 2,717 additions and 0 deletions.
6 changes: 6 additions & 0 deletions .gitattributes
@@ -0,0 +1,6 @@
example export-ignore
test export-ignore
.gitattributes export-ignore
.gitignore export-ignore
.travis.yml export-ignore
phpunit.xml.dist export-ignore
4 changes: 4 additions & 0 deletions .gitignore
@@ -0,0 +1,4 @@
build
composer.lock
phpunit.xml
vendor
39 changes: 39 additions & 0 deletions .travis.yml
@@ -0,0 +1,39 @@
sudo: false

language: php

php:
- 7.0
- 7.1
- nightly

matrix:
allow_failures:
- php: 7.1
- php: nightly
fast_finish: true

services:
- postgresql

install:
- git clone https://github.com/m6w6/ext-pq;
pushd ext-pq;
phpize;
./configure;
make;
make install;
popd;
echo "extension=pq.so" >> "$(php -r 'echo php_ini_loaded_file();')";
- composer self-update
- composer install --no-interaction --prefer-source

before_script:
- psql -c 'CREATE DATABASE test;' -U postgres

script:
- vendor/bin/phpunit --coverage-text --coverage-clover build/logs/clover.xml

after_script:
- composer require satooshi/php-coveralls dev-master
- vendor/bin/coveralls -v --exclude-no-stmt
21 changes: 21 additions & 0 deletions LICENSE
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2016 amphp

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
61 changes: 61 additions & 0 deletions README.md
@@ -0,0 +1,61 @@
# PostgreSQL Client for Amp

This library is a component for [Amp](https://github.com/amphp/amp) that provides an asynchronous client for PostgreSQL.

[![Build Status](https://img.shields.io/travis/amphp/postgres/master.svg?style=flat-square)](https://travis-ci.org/amphp/postgres)
[![Coverage Status](https://img.shields.io/coveralls/amphp/postgres/master.svg?style=flat-square)](https://coveralls.io/r/amphp/postgres)
[![Semantic Version](https://img.shields.io/github/release/amphp/postgres.svg?style=flat-square)](http://semver.org)
[![MIT License](https://img.shields.io/packagist/l/amphp/postgres.svg?style=flat-square)](LICENSE)
[![@amphp on Twitter](https://img.shields.io/badge/twitter-%40asyncphp-5189c7.svg?style=flat-square)](https://twitter.com/asyncphp)

##### Requirements

- PHP 7

##### Installation

The recommended way to install is with the [Composer](http://getcomposer.org/) package manager. (See the [Composer installation guide](https://getcomposer.org/doc/00-intro.md) for information on installing and using Composer.)

Run the following command to use this library in your project:

```bash
composer require amphp/postgres
```

You can also manually edit `composer.json` to add this library as a project requirement.

```js
// composer.json
{
"require": {
"amphp/postgres": "^0.1"
}
}
```

#### Example

```php
#!/usr/bin/env php
<?php

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

use Amp\Postgres;

Amp\execute(function () {
/** @var \Amp\Postgres\Connection $connection */
$connection = yield Postgres\connect('host=localhost user=postgres dbname=test');

/** @var \Amp\Postgres\Statement $statement */
$statement = yield $connection->prepare('SELECT * FROM test WHERE id=$1');

/** @var \Amp\Postgres\TupleResult $result */
$result = yield $statement->execute(1337);

while (yield $result->next()) {
$row = $result->getCurrent();
// $row is an array (map) of column values. e.g.: $row['column_name']
}
});
```
43 changes: 43 additions & 0 deletions composer.json
@@ -0,0 +1,43 @@
{
"name": "amphp/postgres",
"description": "Asynchronous PostgreSQL client for Amp.",
"keywords": [
"database",
"db",
"postgresql",
"postgre",
"pgsql",
"asynchronous",
"async"
],
"homepage": "http://amphp.org",
"license": "MIT",
"authors": [
{
"name": "Aaron Piotrowski",
"email": "aaron@trowski.com"
}
],
"require": {
"amphp/amp": "dev-master as 2.0",
"async-interop/event-loop-implementation": "^0.3"
},
"require-dev": {
"amphp/loop": "dev-master",
"phpunit/phpunit": "^5.0"
},
"minimum-stability": "dev",
"autoload": {
"psr-4": {
"Amp\\Postgres\\": "lib"
},
"files": [
"lib/functions.php"
]
},
"autoload-dev": {
"psr-4": {
"Amp\\Postgres\\Test\\": "test"
}
}
}
22 changes: 22 additions & 0 deletions example/test.php
@@ -0,0 +1,22 @@
#!/usr/bin/env php
<?php

require dirname(__DIR__) . '/vendor/autoload.php';

use Amp\Postgres;

Amp\execute(function () {
/** @var \Amp\Postgres\Connection $connection */
$connection = yield Postgres\connect('host=localhost user=postgres');

/** @var \Amp\Postgres\Statement $statement */
$statement = yield $connection->prepare('SHOW ALL');

/** @var \Amp\Postgres\TupleResult $result */
$result = yield $statement->execute();

while (yield $result->next()) {
$row = $result->getCurrent();
\printf("%-35s = %s (%s)\n", $row['name'], $row['setting'], $row['description']);
}
});
113 changes: 113 additions & 0 deletions lib/AbstractConnection.php
@@ -0,0 +1,113 @@
<?php declare(strict_types = 1);

namespace Amp\Postgres;

use Amp\{ CallableMaker, Coroutine, Deferred, function pipe };
use Interop\Async\Awaitable;

abstract class AbstractConnection implements Connection {
use CallableMaker;

/** @var \Amp\Postgres\PqConnection */
private $executor;

/** @var \Amp\Deferred|null */
private $busy;

/** @var callable */
private $release;

/**
* @param string $connectionString
* @param int $timeout Timeout until the connection attempt fails.
*
* @return \Interop\Async\Awaitable<\Amp\Postgres\Connection>
*/
abstract public static function connect(string $connectionString, int $timeout = null): Awaitable;

/**
* @param $executor;
*/
public function __construct(Executor $executor) {
$this->executor = $executor;
$this->release = $this->callableFromInstanceMethod("release");
}

/**
* @param callable $method Method to execute.
* @param mixed ...$args Arguments to pass to function.
*
* @return \Generator
*
* @resolve resource
*
* @throws \Amp\Postgres\FailureException
*/
private function send(callable $method, ...$args): \Generator {
while ($this->busy !== null) {
yield $this->busy->getAwaitable();
}

return $method(...$args);
}

private function release() {
$busy = $this->busy;
$this->busy = null;
$busy->resolve();
}

/**
* {@inheritdoc}
*/
public function query(string $sql): Awaitable {
return new Coroutine($this->send([$this->executor, "query"], $sql));
}

/**
* {@inheritdoc}
*/
public function execute(string $sql, ...$params): Awaitable {
return new Coroutine($this->send([$this->executor, "execute"], $sql, ...$params));
}

/**
* {@inheritdoc}
*/
public function prepare(string $sql): Awaitable {
return new Coroutine($this->send([$this->executor, "prepare"], $sql, $sql));
}

/**
* {@inheritdoc}
*/
public function transaction(int $isolation = Transaction::COMMITTED): Awaitable {
switch ($isolation) {
case Transaction::UNCOMMITTED:
$awaitable = $this->query("BEGIN TRANSACTION ISOLATION LEVEL READ UNCOMMITTED");
break;

case Transaction::COMMITTED:
$awaitable = $this->query("BEGIN TRANSACTION ISOLATION LEVEL READ COMMITTED");
break;

case Transaction::REPEATABLE:
$awaitable = $this->query("BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ");
break;

case Transaction::SERIALIZABLE:
$awaitable = $this->query("BEGIN TRANSACTION ISOLATION LEVEL SERIALIZABLE");
break;

default:
throw new \Error("Invalid transaction type");
}

return pipe($awaitable, function (CommandResult $result) use ($isolation) {
$this->busy = new Deferred;
$transaction = new Transaction($this->executor, $isolation);
$transaction->onComplete($this->release);
return $transaction;
});
}
}

0 comments on commit caf829a

Please sign in to comment.