Skip to content

Commit 2ce3de6

Browse files
committed
Commit
1 parent 1c33ab9 commit 2ce3de6

File tree

7 files changed

+293
-1
lines changed

7 files changed

+293
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
1-
# database
1+
# Webman database
2+
This is Webman's database library, which includes database client and connection pool.

composer.json

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
{
2+
"name": "webman/database",
3+
"type": "library",
4+
"license": "MIT",
5+
"description": "Webman database",
6+
"require": {
7+
"workerman/webman-framework": "^2.0.0"
8+
},
9+
"autoload": {
10+
"psr-4": {
11+
"Webman\\Database\\": "src"
12+
}
13+
},
14+
"minimum-stability": "dev",
15+
"prefer-stable": true
16+
}

src/DatabaseManager.php

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
<?php
2+
3+
namespace Webman\Database;
4+
5+
use Illuminate\Database\DatabaseManager as BaseDatabaseManager;
6+
use Throwable;
7+
use Webman\Context;
8+
use Webman\Coroutine\Pool;
9+
10+
class DatabaseManager extends BaseDatabaseManager
11+
{
12+
13+
/**
14+
* @var Pool[]
15+
*/
16+
protected static array $pools = [];
17+
18+
/**
19+
* Get connection
20+
*
21+
* @param $name
22+
* @return mixed
23+
* @throws Throwable
24+
*/
25+
public function connection($name = null)
26+
{
27+
$name = $name ?: $this->getDefaultConnection();
28+
[$database, $type] = $this->parseConnectionName($name);
29+
30+
$key = "database.connections.$name";
31+
$connection = Context::get($key);
32+
if (!$connection) {
33+
if (!isset(static::$pools[$name])) {
34+
$poolConfig = $this->app['config']['database.connections'][$name]['pool'] ?? [];
35+
$pool = new Pool($poolConfig['max_connections'] ?? 6, $poolConfig);
36+
$pool->setConnectionCreator(function () use ($database, $type) {
37+
return $this->configure($this->makeConnection($database), $type);
38+
});
39+
$pool->setConnectionCloser(function ($connection) {
40+
$connection->disconnect();
41+
});
42+
$pool->setHeartbeatChecker(function ($connection) {
43+
return $connection->select('select 1');
44+
});
45+
static::$pools[$name] = $pool;
46+
}
47+
try {
48+
$connection = static::$pools[$name]->get();
49+
Context::set($key, $connection);
50+
} finally {
51+
Context::onDestroy(function () use ($connection, $name) {
52+
try {
53+
static::$pools[$name]->put($connection);
54+
} catch (Throwable) {
55+
// ignore
56+
}
57+
});
58+
}
59+
}
60+
return $connection;
61+
}
62+
63+
}

src/Initializer.php

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
<?php
2+
/**
3+
* This file is part of webman.
4+
*
5+
* Licensed under The MIT License
6+
* For full copyright and license information, please see the MIT-LICENSE.txt
7+
* Redistributions of files must retain the above copyright notice.
8+
*
9+
* @author walkor<[email protected]>
10+
* @copyright walkor<[email protected]>
11+
* @link http://www.workerman.net/
12+
* @license http://www.opensource.org/licenses/mit-license.php MIT License
13+
*/
14+
15+
namespace Webman\Database;
16+
17+
use Illuminate\Container\Container as IlluminateContainer;
18+
use Webman\Database\Manager as Capsule;
19+
use Illuminate\Events\Dispatcher;
20+
use Illuminate\Pagination\Paginator;
21+
use Illuminate\Pagination\CursorPaginator;
22+
use Illuminate\Pagination\Cursor;
23+
use Jenssegers\Mongodb\Connection as JenssegersMongodbConnection;
24+
use MongoDB\Laravel\Connection as LaravelMongodbConnection;
25+
use support\Container;
26+
27+
class Initializer
28+
{
29+
30+
/**
31+
* @param $config
32+
* @return void
33+
*/
34+
public static function init($config): void
35+
{;
36+
$connections = $config['connections'] ?? [];
37+
if (!$connections) {
38+
return;
39+
}
40+
41+
$capsule = new Capsule(IlluminateContainer::getInstance());
42+
43+
$capsule->getDatabaseManager()->extend('mongodb', function ($config, $name) {
44+
$config['name'] = $name;
45+
return class_exists(LaravelMongodbConnection::class) ? new LaravelMongodbConnection($config) : new JenssegersMongodbConnection($config);
46+
});
47+
48+
$default = $config['default'] ?? false;
49+
if ($default) {
50+
$defaultConfig = $connections[$default] ?? false;
51+
if ($defaultConfig) {
52+
$capsule->addConnection($defaultConfig, $default);
53+
$capsule->getDatabaseManager()->setDefaultConnection($default);
54+
unset($connections[$default]);
55+
}
56+
}
57+
58+
foreach ($connections as $name => $config) {
59+
$capsule->addConnection($config, $name);
60+
}
61+
62+
if (class_exists(Dispatcher::class) && !$capsule->getEventDispatcher()) {
63+
$capsule->setEventDispatcher(Container::make(Dispatcher::class, [IlluminateContainer::getInstance()]));
64+
}
65+
66+
$capsule->setAsGlobal();
67+
68+
$capsule->bootEloquent();
69+
70+
// Paginator
71+
if (class_exists(Paginator::class)) {
72+
if (method_exists(Paginator::class, 'queryStringResolver')) {
73+
Paginator::queryStringResolver(function () {
74+
$request = request();
75+
return $request?->queryString();
76+
});
77+
}
78+
Paginator::currentPathResolver(function () {
79+
$request = request();
80+
return $request ? $request->path(): '/';
81+
});
82+
Paginator::currentPageResolver(function ($pageName = 'page') {
83+
$request = request();
84+
if (!$request) {
85+
return 1;
86+
}
87+
$page = (int)($request->input($pageName, 1));
88+
return $page > 0 ? $page : 1;
89+
});
90+
if (class_exists(CursorPaginator::class)) {
91+
CursorPaginator::currentCursorResolver(function ($cursorName = 'cursor') {
92+
return Cursor::fromEncoded(request()->input($cursorName));
93+
});
94+
}
95+
}
96+
}
97+
98+
}

src/Manager.php

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
<?php
2+
3+
namespace Webman\Database;
4+
5+
use Illuminate\Database\Connection;
6+
use Illuminate\Database\Connectors\ConnectionFactory;
7+
8+
class Manager extends \Illuminate\Database\Capsule\Manager
9+
{
10+
/**
11+
* Build the database manager instance.
12+
*
13+
* @return void
14+
*/
15+
protected function setupManager()
16+
{
17+
$factory = new ConnectionFactory($this->container);
18+
$this->manager = new DatabaseManager($this->container, $factory);
19+
Connection::resolverFor('mysql', function ($connection, $database, $prefix, $config) {
20+
return new MySqlConnection($connection, $database, $prefix, $config);
21+
});
22+
}
23+
}

src/MysqlConnection.php

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
<?php
2+
3+
namespace Webman\Database;
4+
5+
use Illuminate\Database\MySqlConnection as BaseMySqlConnection;
6+
7+
class MysqlConnection extends BaseMySqlConnection
8+
{
9+
/**
10+
* Disconnect。
11+
*
12+
* @return void
13+
*/
14+
public function disconnect()
15+
{
16+
parent::disconnect();
17+
// Set $this->queryGrammar to null to avoid memory leaks.
18+
$this->queryGrammar = null;
19+
}
20+
21+
/**
22+
* Reconnect.
23+
*
24+
* @return void
25+
*/
26+
public function reconnect()
27+
{
28+
$result = parent::reconnect();
29+
if (!$this->queryGrammar) {
30+
$this->useDefaultQueryGrammar();
31+
}
32+
return $result;
33+
}
34+
35+
public function __destruct()
36+
{
37+
echo "__destruct\n";
38+
}
39+
}

src/support/Db.php

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
<?php
2+
/**
3+
* This file is part of webman.
4+
*
5+
* Licensed under The MIT License
6+
* For full copyright and license information, please see the MIT-LICENSE.txt
7+
* Redistributions of files must retain the above copyright notice.
8+
*
9+
* @author walkor<[email protected]>
10+
* @copyright walkor<[email protected]>
11+
* @link http://www.workerman.net/
12+
* @license http://www.opensource.org/licenses/mit-license.php MIT License
13+
*/
14+
15+
namespace support;
16+
17+
use Closure;
18+
use Illuminate\Database\Capsule\Manager;
19+
use Illuminate\Database\Connection;
20+
21+
/**
22+
* Class Db
23+
* @package support
24+
* @method static array select(string $query, $bindings = [], $useReadPdo = true)
25+
* @method static int insert(string $query, $bindings = [])
26+
* @method static int update(string $query, $bindings = [])
27+
* @method static int delete(string $query, $bindings = [])
28+
* @method static bool statement(string $query, $bindings = [])
29+
* @method static mixed transaction(Closure $callback, $attempts = 1)
30+
* @method static void beginTransaction()
31+
* @method static void rollBack($toLevel = null)
32+
* @method static void commit()
33+
*/
34+
class Db extends Manager
35+
{
36+
/**
37+
* @return Manager
38+
*/
39+
public static function getInstance(): Manager
40+
{
41+
return static::$instance;
42+
}
43+
44+
/**
45+
* @return Connection[]
46+
*/
47+
public static function getConnections(): array
48+
{
49+
return static::$instance->getDatabaseManager()->getConnections();
50+
}
51+
52+
}

0 commit comments

Comments
 (0)