1
This commit is contained in:
@@ -1,115 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace db;
|
||||
|
||||
use database\seeders\SeedManager;
|
||||
use think\console\Command;
|
||||
use think\console\Input;
|
||||
use think\console\input\Argument;
|
||||
use think\console\Output;
|
||||
use think\console\input\Option;
|
||||
use think\facade\Db;
|
||||
|
||||
class DatabaseManage extends Command
|
||||
{
|
||||
protected function configure()
|
||||
{
|
||||
$this->setName('db:manage')
|
||||
->addArgument('action', \think\console\input\Argument::OPTIONAL, 'The action to perform: backup or init or seed')
|
||||
->setDescription('Manage the database: backup or initialize');
|
||||
}
|
||||
|
||||
protected function execute(Input $input, Output $Output)
|
||||
{
|
||||
$strAction = $input->getArgument('action');
|
||||
|
||||
if ($strAction === 'backup') {
|
||||
$this->backupDatabase($Output);
|
||||
} elseif ($strAction === 'init') {
|
||||
$this->initializeDatabase($Output);
|
||||
} elseif ($strAction === 'seed') {
|
||||
$this->seed($Output);
|
||||
} else {
|
||||
$Output->writeln("Invalid action. Use 'backup' or 'init'. or 'seed'");
|
||||
}
|
||||
}
|
||||
|
||||
private function seed(Output $Output)
|
||||
{
|
||||
$SeedManager = new SeedManager;
|
||||
$Output->writeln("开始数据播种" . PHP_EOL);
|
||||
$SeedManager->handle();
|
||||
$Output->writeln("数据播种结束");
|
||||
}
|
||||
|
||||
private function backupDatabase(Output $Output)
|
||||
{
|
||||
$arrConfig = config('database.connections.mysql');
|
||||
$strDb = $arrConfig['database'];
|
||||
$strUserName = $arrConfig['username'];
|
||||
$strPwd = $arrConfig['password'];
|
||||
$strHost = $arrConfig['hostname'];
|
||||
$strBackupFile = app()->getRootPath() . 'database/schema/mysql-schema.dump';
|
||||
|
||||
$strTempFile = tempnam(sys_get_temp_dir(), 'mysql-schema-') . '.dump';
|
||||
|
||||
$strCmd = "mysqldump -h{$strHost} -u{$strUserName} -p{$strPwd} --no-data {$strDb} > {$strTempFile}";
|
||||
|
||||
system($strCmd, $intResultCode);
|
||||
|
||||
if ($intResultCode === 0) {
|
||||
if (file_exists($strBackupFile)) {
|
||||
unlink($strBackupFile);
|
||||
}
|
||||
|
||||
if (rename($strTempFile, $strBackupFile)) {
|
||||
$Output->writeln("Database backup successful: {$strBackupFile}");
|
||||
} else {
|
||||
$Output->writeln("Failed to move backup file to destination.");
|
||||
}
|
||||
} else {
|
||||
$Output->writeln("Database backup failed.");
|
||||
unlink($strTempFile);
|
||||
}
|
||||
}
|
||||
|
||||
private function initializeDatabase(Output $Output)
|
||||
{
|
||||
$arrConfig = config('database.connections.mysql');
|
||||
$strDb = $arrConfig['database'];
|
||||
$strUserName = $arrConfig['username'];
|
||||
$strPwd = $arrConfig['password'];
|
||||
$strHost = $arrConfig['hostname'];
|
||||
$strPort = $arrConfig['hostport'];
|
||||
$strBackupFile = app()->getRootPath() . 'database/schema/mysql-schema.dump';
|
||||
|
||||
$checkTableQuery = "SHOW TABLES LIKE 'migrations'";
|
||||
$boolMigrateExists = Db::query($checkTableQuery);
|
||||
|
||||
if (!empty($boolMigrateExists)) {
|
||||
$Output->writeln("数据库已存在,跳过初始化导入");
|
||||
return;
|
||||
}
|
||||
|
||||
$strTempFile = tempnam(sys_get_temp_dir(), 'mysql-schema-') . '.dump';
|
||||
|
||||
if (!copy($strBackupFile, $strTempFile)) {
|
||||
$Output->writeln("创建临时导入文件失败.");
|
||||
return;
|
||||
}
|
||||
|
||||
$strCmd = "mysql -h{$strHost} -P{$strPort} -u{$strUserName} -p{$strPwd} {$strDb} < {$strTempFile}";
|
||||
|
||||
system($strCmd, $intResultCode);
|
||||
|
||||
if ($intResultCode === 0) {
|
||||
$Output->writeln("成功导入初始化文件");
|
||||
} else {
|
||||
$Output->writeln("初始化文件导入失败");
|
||||
}
|
||||
|
||||
unlink($strTempFile);
|
||||
}
|
||||
}
|
||||
@@ -1,191 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace db\mongo;
|
||||
|
||||
use MongoDB\Client;
|
||||
use MongoDB\Exception\Exception as MongoDBException;
|
||||
use MongoDB\BSON\UTCDateTime;
|
||||
|
||||
class MongoBase
|
||||
{
|
||||
private $client;
|
||||
|
||||
/**
|
||||
* Undocumented variable
|
||||
*
|
||||
* @var \MongoDB\Database
|
||||
*/
|
||||
private $db;
|
||||
|
||||
private static $instance;
|
||||
|
||||
public static function getInstance(): self
|
||||
{
|
||||
|
||||
// return [
|
||||
// 'uri' => 'mongodb://username:password@your_ip:27017',
|
||||
// 'database' => 'your_database',
|
||||
// ];
|
||||
|
||||
if (!self::$instance) {
|
||||
self::$instance = new self();
|
||||
}
|
||||
return self::$instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造函数,初始化 MongoDB 连接
|
||||
* @param string $uri MongoDB 连接字符串
|
||||
* @param string $dbName 数据库名称
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
try {
|
||||
$arrConfig = config('mongodb');
|
||||
$strUri = sprintf('mongodb://%s:%s@%s:%s', $arrConfig['username'], $arrConfig['password'], $arrConfig['hostname'], $arrConfig['hostport']);
|
||||
|
||||
$this->client = new Client($strUri);
|
||||
$this->db = $this->client->selectDatabase($arrConfig['database']);
|
||||
} catch (MongoDBException $e) {
|
||||
throw new \Exception("MongoDB connection failed: " . $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取下一个自增序列值
|
||||
* @param string $sequenceName 序列名称
|
||||
* @return int 自增 ID
|
||||
*/
|
||||
public function getNextSequence(string $sequenceName): int
|
||||
{
|
||||
try {
|
||||
$counters = $this->db->selectCollection('counters');
|
||||
$result = $counters->findOneAndUpdate(
|
||||
['_id' => $sequenceName],
|
||||
['$inc' => ['sequence_value' => 1]],
|
||||
[
|
||||
'upsert' => true,
|
||||
'returnDocument' => \MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER
|
||||
]
|
||||
);
|
||||
return $result->sequence_value ?? 1;
|
||||
} catch (MongoDBException $e) {
|
||||
throw new \Exception("Failed to generate sequence: " . $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 插入单条数据
|
||||
* @param string $collection 集合名称
|
||||
* @param array $data 数据数组
|
||||
* @return mixed 插入的 ID
|
||||
*/
|
||||
public function insertOne(string $collection, array $data)
|
||||
{
|
||||
try {
|
||||
$coll = $this->db->selectCollection($collection);
|
||||
$data['created_at'] = new UTCDateTime(); // 自动添加创建时间
|
||||
$result = $coll->insertOne($data);
|
||||
return $result->getInsertedId();
|
||||
} catch (MongoDBException $e) {
|
||||
throw new \Exception("Insert failed: " . $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public function getDb(): \MongoDB\Database
|
||||
{
|
||||
return $this->db;
|
||||
}
|
||||
|
||||
/**
|
||||
* 插入多条数据
|
||||
* @param string $collection 集合名称
|
||||
* @param array $data 多条数据数组
|
||||
* @return array 插入的 ID 列表
|
||||
*/
|
||||
public function insertMany(string $collection, array $data)
|
||||
{
|
||||
try {
|
||||
$coll = $this->db->selectCollection($collection);
|
||||
foreach ($data as &$item) {
|
||||
$item['created_at'] = new UTCDateTime();
|
||||
}
|
||||
$result = $coll->insertMany($data);
|
||||
return $result->getInsertedIds();
|
||||
} catch (MongoDBException $e) {
|
||||
throw new \Exception("Insert many failed: " . $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询单条数据
|
||||
* @param string $collection 集合名称
|
||||
* @param array $filter 查询条件
|
||||
* @param array $options 查询选项
|
||||
* @return ?object 查询结果
|
||||
*/
|
||||
public function findOne(string $collection, array $filter = [], array $options = []): ?object
|
||||
{
|
||||
try {
|
||||
$coll = $this->db->selectCollection($collection);
|
||||
return $coll->findOne($filter, $options);
|
||||
} catch (MongoDBException $e) {
|
||||
throw new \Exception("Find one failed: " . $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询多条数据
|
||||
* @param string $collection 集合名称
|
||||
* @param array $filter 查询条件
|
||||
* @param array $options 查询选项
|
||||
* @return array 查询结果
|
||||
*/
|
||||
public function findMany(string $collection, array $filter = [], array $options = []): array
|
||||
{
|
||||
try {
|
||||
$coll = $this->db->selectCollection($collection);
|
||||
$cursor = $coll->find($filter, $options);
|
||||
return iterator_to_array($cursor);
|
||||
} catch (MongoDBException $e) {
|
||||
throw new \Exception("Find many failed: " . $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新单条数据
|
||||
* @param string $collection 集合名称
|
||||
* @param array $filter 查询条件
|
||||
* @param array $update 更新内容
|
||||
* @param array $options 更新选项
|
||||
* @return int 受影响的文档数
|
||||
*/
|
||||
public function updateOne(string $collection, array $filter, array $update, array $options = []): int
|
||||
{
|
||||
try {
|
||||
$coll = $this->db->selectCollection($collection);
|
||||
$update['$set']['updated_at'] = new UTCDateTime(); // 自动添加更新时间
|
||||
$result = $coll->updateOne($filter, $update, $options);
|
||||
return $result->getModifiedCount();
|
||||
} catch (MongoDBException $e) {
|
||||
throw new \Exception("Update one failed: " . $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除数据
|
||||
* @param string $collection 集合名称
|
||||
* @param array $filter 查询条件
|
||||
* @return int 删除的文档数
|
||||
*/
|
||||
public function delete(string $collection, array $filter): int
|
||||
{
|
||||
try {
|
||||
$coll = $this->db->selectCollection($collection);
|
||||
$result = $coll->deleteMany($filter);
|
||||
return $result->getDeletedCount();
|
||||
} catch (MongoDBException $e) {
|
||||
throw new \Exception("Delete failed: " . $e->getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user