Compare commits
621 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| ea34371652 | |||
| 92f0c1a973 | |||
| 11ad7217c2 | |||
| b647716f1c | |||
| d8b2d1ca2c | |||
| a439c616b4 | |||
| d036e440cd | |||
| 88fb563c99 | |||
| 1066aa03e8 | |||
| 609e5d4749 | |||
| ea8060b047 | |||
| 29b3accadb | |||
| 22a04814dc | |||
| bb875bd672 | |||
| c2a5d7c5e3 | |||
| 797d44f816 | |||
| 2d067b9d6a | |||
| 666dce01bc | |||
| 8174848de6 | |||
| d2acc197da | |||
| c0ff5be651 | |||
| b77e4be3e8 | |||
| dc34638a31 | |||
| b94f654ad0 | |||
| 9b249e538b | |||
| 4bcd4a8a44 | |||
| 8c3cc60cc3 | |||
| 2ea6d3705d | |||
| 1ede0aa3bd | |||
| 3d37e11497 | |||
| 7f98be6b1c | |||
| abb561f185 | |||
| 6b96e54ab0 | |||
| c9255a6c2b | |||
| 7d06791d67 | |||
| e248bbbea0 | |||
| 694028f983 | |||
| 4fbbbe0cfe | |||
| 0833e87362 | |||
| 8cd195f4ee | |||
| b690228ea2 | |||
| 0e20ab2167 | |||
| 8685e039a4 | |||
| d28af2fa09 | |||
| 89592ff638 | |||
| b490e85a34 | |||
| 2d1d780618 | |||
| 3e73149716 | |||
| a1d42a0831 | |||
| 1092273257 | |||
| f614795f95 | |||
| 79b7bb432f | |||
| 9a670f626e | |||
| 109cc2ac27 | |||
| 3ab08c9ca7 | |||
| c84d9f8328 | |||
| 658445927a | |||
| a73b5c0e2a | |||
| 3179e95a82 | |||
| 85eaeba8ba | |||
| 16fe127019 | |||
| 013be605f4 | |||
| 64087d6258 | |||
| 9c433855d5 | |||
| fd71d23802 | |||
| 2eb63c6bd4 | |||
| e2c0f62532 | |||
| 510a13e3da | |||
| 1b1eec5f78 | |||
| 0b782de1f1 | |||
| 641187e240 | |||
| 501ace9e36 | |||
| c352c46a0f | |||
| fec858ffbd | |||
| c119186ad4 | |||
| 66d5d46add | |||
| d42e30ecbe | |||
| f8a1e700a7 | |||
| 53dbf7a9b2 | |||
| a1238613f9 | |||
| dcf4e0a614 | |||
| b0e627c4fb | |||
| 67c7dd8421 | |||
| d097b66187 | |||
| 82f38732ef | |||
| e1e5af2173 | |||
| 4b304e52a2 | |||
| 77419f2d10 | |||
| 2fb2111526 | |||
| 0c2134a361 | |||
| d942db93d8 | |||
| 0dd7b7e0e7 | |||
| 34ad1f58fe | |||
| f9a9652726 | |||
| ba59b9431e | |||
| fc73dbf98d | |||
| d4b9dd6758 | |||
| b5b5db4d2c | |||
| 735801f756 | |||
| fd8ac37742 | |||
| 4cac66b1d1 | |||
| bc43a32b10 | |||
| f61c678d54 | |||
| beb541f01b | |||
| bae4e54dd5 | |||
| f477b181de | |||
| 5b3b16e4f6 | |||
| 28451d6e02 | |||
| a0871d9cbd | |||
| 313092dd75 | |||
| 6be1180962 | |||
| 370c50f1fe | |||
| ba68102405 | |||
| 2ee482241d | |||
| 0bff75446d | |||
| a3fa4521fc | |||
| 1d37abf5d5 | |||
| a2ceb7310e | |||
| 2b902f3624 | |||
| c036cea809 | |||
| 91edb08238 | |||
| 5158b709bd | |||
| 9c8c8c6bb3 | |||
| cc723a7630 | |||
| 138549f54d | |||
| 99ff8b1ed5 | |||
| 2feff52291 | |||
| e08e811580 | |||
| 6f979394a3 | |||
| 9eb7a11b6c | |||
| e6b7b5ee57 | |||
| 666de7ce40 | |||
| d377deab8e | |||
| 703300182b | |||
| 5caed72909 | |||
| 250cdda33e | |||
| 69b5ef6437 | |||
| d37f43c4ac | |||
| 5b0e69f190 | |||
| b81be565ae | |||
| c30a58a4c5 | |||
| 812505f914 | |||
| 45968536c5 | |||
| d0375388b4 | |||
| c3eced973a | |||
| 6cb5899fe1 | |||
| 853f23bb3d | |||
| 1976822784 | |||
| 17a5dcb2bb | |||
| 58cbfce778 | |||
| c86d6791c9 | |||
| 636c96b73c | |||
| 7f885aca09 | |||
| 8a25e4b7be | |||
| 6dab6eba8c | |||
| b1ac46f14f | |||
| 36e768e3e6 | |||
| 327f40faea | |||
| d3dacf96df | |||
| 76d75806e5 | |||
| 677bda01a0 | |||
| 2c63caaaf8 | |||
| 0bb294edc5 | |||
| e06c04a5bb | |||
| 8b35064395 | |||
| 8f69385eaa | |||
| a85fc58630 | |||
| 2e01419960 | |||
| 543995f5cd | |||
| 4b55ee837e | |||
| 2493b4e15d | |||
| d9ffa9dae2 | |||
| 37c9bcc4d2 | |||
| 0d3a37084e | |||
| 6283d6cd49 | |||
| 1fb13aa3a3 | |||
| 0ea9339816 | |||
| 1318c9e5b3 | |||
| 05f90fe4a4 | |||
| c30c830169 | |||
| bbd4d7b353 | |||
| c718e852dd | |||
| 77648f3878 | |||
| 7015e39fa6 | |||
| ccacfcbc02 | |||
| 37abaa8035 | |||
| c208d023e7 | |||
| add36ab75c | |||
| 321c256100 | |||
| f6cd6756ce | |||
| ce7539ab62 | |||
| 3ba95cc3dd | |||
| 745a5820ba | |||
| 373a1b0fed | |||
| 720c5498f1 | |||
| 9a680d56a7 | |||
| 1d2bca40a2 | |||
| 4c49a09047 | |||
| e597224e86 | |||
| 2a83160792 | |||
| b3759bfa53 | |||
| 9f51ff4659 | |||
| a264b2b8a3 | |||
| be09229577 | |||
| 25296ee714 | |||
| 6678011261 | |||
| 17b194f50c | |||
| b77e6a7618 | |||
| aa14ff3376 | |||
| e5c5ce822c | |||
| 68035a95e4 | |||
| 5f5b90ac49 | |||
| ed749d7a34 | |||
| bec9cd1a3f | |||
| 55bb55f955 | |||
| 5b3b3b7a6b | |||
| e1c893c4e1 | |||
| 0267b9ca11 | |||
| a95f2af9ed | |||
| 4a51a8a336 | |||
| 0a567634d6 | |||
| 08e9211e0e | |||
| d42d284f62 | |||
| 63ddc36958 | |||
| 3d0fd3d5d0 | |||
| 4c27cae802 | |||
| dc73de9abd | |||
| d96f1c27a5 | |||
| bc36df50f8 | |||
| 2c893a52d5 | |||
| e575254139 | |||
| 00a2125efc | |||
| 45d0712cb2 | |||
| 8eb4f5869f | |||
| 29aae506c1 | |||
| 9ab0aa1fe7 | |||
| 4abc1a621b | |||
| 4c6dbc9b3c | |||
| d4219b902a | |||
| 83138dbcb4 | |||
| 9d7605b8e4 | |||
| 203eda17ad | |||
| 1c07e59357 | |||
| a4a5025e95 | |||
| 3da1c718d9 | |||
| 51039961c1 | |||
| a403421bfe | |||
| 5d161fd1e7 | |||
| 65bbc6888a | |||
| c8159194bf | |||
| 49742a08ad | |||
| efa6cf5421 | |||
| ac443a49b1 | |||
| c57e606e55 | |||
| 4f6952bdc5 | |||
| ae5e86c7e2 | |||
| 027ac6f25b | |||
| 6ff252fe2a | |||
| e747a988ff | |||
| b6629987ab | |||
| 8529a8eb0d | |||
| 5e4beed63c | |||
| def1e1e9c1 | |||
| 3a577aaf03 | |||
| 7d8ed087f5 | |||
| 84568c504a | |||
| 1793fa3667 | |||
| bb9112d3b5 | |||
| 688f188d7c | |||
| 711750dba3 | |||
| eedfbb900e | |||
| d65d7b0d87 | |||
| 08f664e136 | |||
| d2029e94a0 | |||
| af966999d0 | |||
| ed0035a707 | |||
| ebbc3368bd | |||
| 7472217482 | |||
| e2c6c2ae46 | |||
| 2486bfd4d1 | |||
| 1b65f84962 | |||
| 5057135590 | |||
| ec1c68be39 | |||
| e47e3f8514 | |||
| 8c6f9676b5 | |||
| 409f75eff6 | |||
| 2e258c7e08 | |||
| 64d3f31138 | |||
| 0bf69d576d | |||
| d22955233c | |||
| f6d4b0fbca | |||
| 3cd2e8d889 | |||
| 5600ede420 | |||
| 6aac4ac878 | |||
| 522d9233ca | |||
| b8906ef54f | |||
| fadd7501ee | |||
| 9ab58b43f9 | |||
| ea780bda4a | |||
| a489d465a7 | |||
| c64e05a81e | |||
| 3b7dd9c709 | |||
| 5b3e2bb569 | |||
| ecfe15c3ac | |||
| b069bc425b | |||
| a7d8ee83ee | |||
| f8f22c39c4 | |||
| fdf696624c | |||
| e002e4b4d0 | |||
| ee8b5fba20 | |||
| 94ebb18b7e | |||
| aaa3fba8ba | |||
| c77b2ef3eb | |||
| 37009c3f59 | |||
| f7f855d279 | |||
| ad43d02673 | |||
| 521fe64b62 | |||
| 0a6fbed5d0 | |||
| 44d350cfea | |||
| 2170ea7d29 | |||
| 33fa378018 | |||
| 478106c6f7 | |||
| 12d3d05001 | |||
| ebf6862834 | |||
| 2153481f69 | |||
| b2807ffe6f | |||
| b4041de60b | |||
| 5c24528957 | |||
| 7833abe644 | |||
| 7a782322b5 | |||
| 5d41c7219f | |||
| 6d122c4ae1 | |||
| 66ecf2585a | |||
| 84f7346d49 | |||
| d3772c0134 | |||
| ff751db14c | |||
| 7fc9a5a908 | |||
| 6fe699413d | |||
| 84d1701ff7 | |||
| 5a96ca96cc | |||
| 4e978cf919 | |||
| b9dae95149 | |||
| fe1711325b | |||
| 3d8c01a42c | |||
| 4843abfdfa | |||
| 919ed98422 | |||
| a8924c270b | |||
| 582583cd32 | |||
| dd65dfbd17 | |||
| ffc8cd7a33 | |||
| 9bb8582aee | |||
| ca516ee766 | |||
| 03c908e4da | |||
| b75204e53e | |||
| b5a7dfa98e | |||
| 81c2b0e114 | |||
| f6c87aadaf | |||
| 225af0038d | |||
| f52609844c | |||
| 6a673152c1 | |||
| 3ecc781002 | |||
| 732b922a4c | |||
| c86eb1a83d | |||
| bc3c286416 | |||
| 5c6663c002 | |||
| dd0eb233bb | |||
| 1370891b93 | |||
| a25634f07a | |||
| 5064e5d683 | |||
| e55eb19768 | |||
| faed634616 | |||
| 1d7ffcda89 | |||
| 92ab70d59d | |||
| 4e109ffdf8 | |||
| 7eb80d607b | |||
| 6d646ea2a3 | |||
| 3c240efa7a | |||
| 59cf5e7d64 | |||
| aafb0dd5e0 | |||
| d9fd802312 | |||
| cd9327f5c2 | |||
| f1faeb038f | |||
| f3a863f55c | |||
| 0a323b5f62 | |||
| 735c077f46 | |||
| 0f28608180 | |||
| 67fdee8fd9 | |||
| f554b4c81e | |||
| 685a0d72b2 | |||
| 69648e3373 | |||
| 555ef93965 | |||
| 4fd91f5f4f | |||
| 0450226d36 | |||
| eac2800561 | |||
| 6493bf91bf | |||
| 1dfe32bf3c | |||
| cd94d2dc57 | |||
| 2aec2afc59 | |||
| 509eabe78e | |||
| c805173600 | |||
| 9b1489f576 | |||
| e2f94c9202 | |||
| 98fff7302e | |||
| afec8be942 | |||
| 0f911db7ee | |||
| f17b163f83 | |||
| 79db796ba3 | |||
| c165f5f205 | |||
| 656753cf60 | |||
| 783703eb0f | |||
| 104ddcc34a | |||
| ff27c0de65 | |||
| 32ab38d5cd | |||
| 24d8959aaf | |||
| 5c9f92f955 | |||
| bfa39c3669 | |||
| af3e6d580e | |||
| 677bb7ad42 | |||
| 8d1c0d056f | |||
| ed24164680 | |||
| 59e25c1648 | |||
| 97d8f8fac5 | |||
| 17e51b7898 | |||
| dba7d6085a | |||
| add511ed2a | |||
| dfbfa701e5 | |||
| 73561a8983 | |||
| 603e0a41fc | |||
| 728b253c0b | |||
| 5cc86e0f0c | |||
| 3c73bc89ba | |||
| 564877c579 | |||
| 007c40a0eb | |||
| f86d155059 | |||
| 767288886f | |||
| 78200ebffd | |||
| 707e13609f | |||
| d53b001ef7 | |||
| 77f63a85ed | |||
| 76154631e5 | |||
| 62f3747701 | |||
| f87a3c386f | |||
| 7554f6b161 | |||
| 322168ff68 | |||
| 02eddb98a2 | |||
| fc828df683 | |||
| 1bc5e49b42 | |||
| 4a654821a1 | |||
| dbf33b6d7d | |||
| 202852a95d | |||
| 72cfba6a5d | |||
| 145970316f | |||
| 58c3b38c73 | |||
| 4dc55fd772 | |||
| 41bce52883 | |||
| 17c8d45349 | |||
| 91cc3c0613 | |||
| ca011c4557 | |||
| 9d81bc6479 | |||
| c7ad5123e2 | |||
| e3169b1348 | |||
| 8f20d59ff8 | |||
| 1c287da18d | |||
| 2845c6c1ac | |||
| e41d03ea27 | |||
| 9fa91a05ef | |||
| f14b198e25 | |||
| 49cd130c81 | |||
| e33776314b | |||
| 64fd34a23c | |||
| bad445aeb6 | |||
| db97de7e40 | |||
| 531b54edb2 | |||
| 56fdf310c8 | |||
| c946eed53f | |||
| bc728071c7 | |||
| 4316e88677 | |||
| 7509597582 | |||
| 86798409fd | |||
| bd3eb54a05 | |||
| 8f6a639317 | |||
| 8796e60285 | |||
| be3ceb8ccc | |||
| e0fc63d78c | |||
| 0d4a690e28 | |||
| 20eff5c29a | |||
| c72c5d4e0d | |||
| e98c67e0c3 | |||
| a6c59331af | |||
| 1314ccc421 | |||
| 39777985f7 | |||
| 744acdc826 | |||
| cf79882a8f | |||
| e4bf6f22be | |||
| 6c721e957b | |||
| e224d2e46b | |||
| ad140bbc00 | |||
| 1f2475b09a | |||
| 41ae0c6118 | |||
| 7d5aec2716 | |||
| d9b9b78128 | |||
| 9a93687c53 | |||
| 5d395bd6f4 | |||
| 92c6b48cb2 | |||
| 2f9e0a9196 | |||
| 62591edf44 | |||
| eb36a30b26 | |||
| a5dde8a140 | |||
| ba6d854035 | |||
| 9ce43895b1 | |||
| b8542f6a70 | |||
| c829192e9c | |||
| 56a20d0f90 | |||
| 01d58b4896 | |||
| 6046f112f9 | |||
| 5670dca21a | |||
| 63d58218e4 | |||
| 2ace780fcb | |||
| 7ea0bee73f | |||
| 6e7955f1d9 | |||
| cb377b4e69 | |||
| d4cf6da9fe | |||
| 2057f2ef53 | |||
| be3106394f | |||
| cbcad9e7c3 | |||
| cdec00038c | |||
| 963c495a4d | |||
| 9d23efaed8 | |||
| 918374f1b2 | |||
| 1c7e0814b8 | |||
| ae135e3538 | |||
| 9fe4c7fd50 | |||
| ceb8e10d1c | |||
| 036a722753 | |||
| 500f4904f9 | |||
| 9e94626ca5 | |||
| d4998d4ffc | |||
| 42b2715cf5 | |||
| df4165ce52 | |||
| 34ae502806 | |||
| de52786503 | |||
| 0900304c17 | |||
| 521bb2ee7f | |||
| d6dce71c6c | |||
| a78760cc3e | |||
| 1e27d52857 | |||
| 1c24908d23 | |||
| 1d809efda8 | |||
| 6febf0c20f | |||
| eff6ae0e95 | |||
| dd6424b4ba | |||
| 093d316605 | |||
| 80620e181b | |||
| 1079cab985 | |||
| a8a2a1fbeb | |||
| 6b3953311a | |||
| 4aff922c83 | |||
| 453481abdb | |||
| 69dbc1e7f3 | |||
| 55f665e10b | |||
| f54f6fbde3 | |||
| 1ace36b6f6 | |||
| 49d8f03cd0 | |||
| f5fd9401dd | |||
| 71c95a824c | |||
| 5e0e76fa57 | |||
| 89b4e57726 | |||
| 29c6478169 | |||
| ecb63ff136 | |||
| 17316250a9 | |||
| 50b6d79756 | |||
| 9626e061b8 | |||
| 3d12b2ea6a | |||
| ad02cbba65 | |||
| 0278a4aac2 | |||
| 0bd7139232 | |||
| 389ad887e6 | |||
| 576f97a53d | |||
| 42bea9d93a | |||
| 0163758d8e | |||
| 450569fce7 | |||
| 83a29b770a | |||
| 2ebdcbd06b | |||
| 5bac6a843d | |||
| 5aa5d3ea13 | |||
| b10ffd832a | |||
| d42fc588b4 | |||
| d5b58a1fc7 | |||
| cada515dc7 | |||
| 5d73bb2c33 | |||
| 164065493e | |||
| 7cf28a3aaa | |||
| 63a1322025 | |||
| e89062a2d7 | |||
| bc0fa6b8d5 | |||
| ffadbdab83 | |||
| 267358263a | |||
| 209621f222 | |||
| 6e75fa462b | |||
| 57f9e3254d | |||
| 22194bbdbc | |||
| 5b22955966 | |||
| ac0c08f909 | |||
| c1e480cd43 | |||
| 61741f926f | |||
| f3d878e21c | |||
| 4ca0a61344 | |||
| 6d699df26e | |||
| 22e094804a | |||
| f8a07c30ae | |||
| c735776e58 | |||
| c5b4f4795b | |||
| 661206b94b | |||
| 61f589058e | |||
| 6d83f647f4 | |||
| 870595b810 | |||
| 970f22804d | |||
| dad6a63ee2 | |||
| 47ed967e46 | |||
| 227aad2910 | |||
| 5d77face53 |
+116
-227
@@ -9,332 +9,221 @@ declare(strict_types=1);
|
||||
|
||||
namespace Database;
|
||||
|
||||
use Closure;
|
||||
use Database\Traits\QueryTrait;
|
||||
use Exception;
|
||||
use JetBrains\PhpStorm\ArrayShape;
|
||||
use Kiri\Abstracts\Component;
|
||||
use Kiri\Di\Context;
|
||||
use Swoole\Coroutine;
|
||||
|
||||
/**
|
||||
* Class ActiveQuery
|
||||
* @package Database
|
||||
*/
|
||||
class ActiveQuery extends Component implements ISqlBuilder
|
||||
class ActiveQuery extends QueryTrait implements ISqlBuilder
|
||||
{
|
||||
|
||||
use QueryTrait;
|
||||
|
||||
/** @var array */
|
||||
public array $with = [];
|
||||
|
||||
/** @var bool */
|
||||
public bool $asArray = FALSE;
|
||||
protected mixed $_mock = null;
|
||||
|
||||
/** @var bool */
|
||||
public bool $useCache = FALSE;
|
||||
|
||||
/**
|
||||
* @var Connection|null
|
||||
* @param bool $asArray
|
||||
* @return static
|
||||
*/
|
||||
public ?Connection $db = NULL;
|
||||
public function asArray(bool $asArray = true): static
|
||||
{
|
||||
$this->asArray = $asArray;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @var array
|
||||
* 参数绑定
|
||||
* @param array $methods
|
||||
* @return $this
|
||||
*/
|
||||
public array $attributes = [];
|
||||
public function with(array $methods): static
|
||||
{
|
||||
$this->modelClass->setWith($methods);
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Comply constructor.
|
||||
* @param $model
|
||||
* @param array $config
|
||||
* @return ModelInterface|array|null|bool
|
||||
* @throws
|
||||
*/
|
||||
public function __construct($model, array $config = [])
|
||||
public function first(): ModelInterface|null|array|bool
|
||||
{
|
||||
$this->modelClass = $model;
|
||||
|
||||
$this->builder = SqlBuilder::builder($this);
|
||||
parent::__construct($config);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 清除不完整数据
|
||||
*/
|
||||
public function clear()
|
||||
{
|
||||
$this->db = NULL;
|
||||
$this->useCache = FALSE;
|
||||
$this->with = [];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $key
|
||||
* @param $value
|
||||
* @return $this
|
||||
*/
|
||||
public function addParam($key, $value): static
|
||||
{
|
||||
$this->attributes[$key] = $value;
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param int $size
|
||||
* @param int $page
|
||||
* @return array
|
||||
* @throws Exception
|
||||
*/
|
||||
#[ArrayShape(['code' => "int", 'message' => "string", 'size' => "mixed", 'page' => "mixed", 'count' => "int", 'next' => "mixed", 'prev' => "mixed", 'param' => "array"])]
|
||||
public function pagination(int $size = 20, int $page = 1): array
|
||||
{
|
||||
$page = max(1, $page);
|
||||
$size = max(1, $size);
|
||||
|
||||
$offset = ($page - 1) * $size;
|
||||
|
||||
$count = $this->count();
|
||||
$lists = $this->limit($offset, $size)->get()->toArray();
|
||||
return [
|
||||
'code' => 0,
|
||||
'message' => 'ok',
|
||||
'size' => $size,
|
||||
'page' => $page,
|
||||
'count' => $count,
|
||||
'next' => max($page + 1, 1),
|
||||
'prev' => max($page - 1, 1),
|
||||
'param' => $lists,
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param array $values
|
||||
* @return $this
|
||||
*/
|
||||
public function addParams(array $values): static
|
||||
{
|
||||
foreach ($values as $key => $val) {
|
||||
$this->addParam($key, $val);
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $name
|
||||
* @return $this
|
||||
*/
|
||||
public function with($name): static
|
||||
{
|
||||
if (empty($name)) {
|
||||
return $this;
|
||||
}
|
||||
if (is_string($name)) {
|
||||
$name = explode(',', $name);
|
||||
}
|
||||
foreach ($name as $val) {
|
||||
array_push($this->with, $val);
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $sql
|
||||
* @param array $params
|
||||
* @return mixed
|
||||
* @throws Exception
|
||||
*/
|
||||
public function execute($sql, array $params = []): Command
|
||||
{
|
||||
return $this->modelClass->getConnection()->createCommand($sql, $params);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return ModelInterface|null
|
||||
* @throws Exception
|
||||
*/
|
||||
public function first(): ModelInterface|null
|
||||
{
|
||||
$data = $this->execute($this->builder->one())->one();
|
||||
if (empty($data)) {
|
||||
return NULL;
|
||||
}
|
||||
$data = $this->buildCommand($this->builder->one())->one();
|
||||
if (is_array($data)) {
|
||||
return $this->populate($data);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
* @throws Exception
|
||||
* @return bool|Collection
|
||||
*/
|
||||
public function toSql(): string
|
||||
public function get(): bool|Collection
|
||||
{
|
||||
return $this->builder->get();
|
||||
$data = $this->buildCommand($this->builder->all())->all();
|
||||
if (is_array($data)) {
|
||||
return new Collection($this, $this->modelClass, $data);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return array|Collection
|
||||
* @throws
|
||||
*/
|
||||
public function get(): Collection|array
|
||||
public function flush(): bool
|
||||
{
|
||||
return $this->all();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @throws Exception
|
||||
*/
|
||||
public function flush(): array|bool|int|string|null
|
||||
{
|
||||
return $this->execute($this->builder->truncate())->exec();
|
||||
return (bool)$this->buildCommand($this->builder->truncate())->exec();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param int $size
|
||||
* @param callable $callback
|
||||
* @return Pagination
|
||||
* @throws Exception
|
||||
* @param Closure $closure
|
||||
* @return void
|
||||
*/
|
||||
public function page(int $size, callable $callback): Pagination
|
||||
public function chunk(int $size, Closure $closure): void
|
||||
{
|
||||
$pagination = new Pagination($this);
|
||||
$pagination->setOffset(0);
|
||||
$pagination->setLimit($size);
|
||||
$pagination->setCallback($callback);
|
||||
return $pagination;
|
||||
if ($this->offset === -1) $this->offset = 0;
|
||||
$data = $this->offset($this->offset)->limit($size)->get();
|
||||
if (!$data || $data->isEmpty()) {
|
||||
return;
|
||||
}
|
||||
if (Context::inCoroutine()) {
|
||||
Coroutine::create(fn() => $closure($data));
|
||||
} else {
|
||||
call_user_func($closure, $data);
|
||||
}
|
||||
$this->offset += $size;
|
||||
$this->chunk($size, $closure);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $field
|
||||
* @param string $setKey
|
||||
* @param string|null $setKey
|
||||
*
|
||||
* @return array|null
|
||||
* @throws Exception
|
||||
*/
|
||||
public function column(string $field, string $setKey = ''): ?array
|
||||
public function column(string $field, ?string $setKey = null): ?array
|
||||
{
|
||||
return $this->all()->column($field, $setKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array|Collection
|
||||
* @throws
|
||||
*/
|
||||
public function all(): Collection|array
|
||||
{
|
||||
$data = $this->execute($this->builder->all())->all();
|
||||
if (!empty($this->with)) {
|
||||
$this->getWith($this->modelClass);
|
||||
}
|
||||
$collect = new Collection($this, $data, $this->modelClass);
|
||||
if ($this->asArray) {
|
||||
return $collect->toArray();
|
||||
}
|
||||
return $collect;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $data
|
||||
* @return ModelInterface
|
||||
* @throws Exception
|
||||
*/
|
||||
public function populate($data): ModelInterface
|
||||
{
|
||||
return $this->getWith($this->modelClass::populate($data));
|
||||
return $this->get()->column($field, $setKey);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param ModelInterface $model
|
||||
* @return ModelInterface
|
||||
* @param mixed $value
|
||||
* @return $this
|
||||
*/
|
||||
public function getWith(ModelInterface $model): ModelInterface
|
||||
public function withMock(mixed $value): static
|
||||
{
|
||||
if (empty($this->with) || !is_array($this->with)) {
|
||||
return $model;
|
||||
}
|
||||
return $model->setWith($this->with);
|
||||
$this->_mock = $value;
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return int
|
||||
* @throws Exception
|
||||
* @return mixed
|
||||
*/
|
||||
public function count(): int
|
||||
public function mock(): mixed
|
||||
{
|
||||
$data = $this->execute($this->builder->count())->one();
|
||||
if ($data && is_array($data)) {
|
||||
return (int)array_shift($data);
|
||||
}
|
||||
return 0;
|
||||
return $this->_mock;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param array $data
|
||||
* @return array|Command|bool|int|string
|
||||
* @throws Exception
|
||||
* @return ModelInterface|array
|
||||
* @throws
|
||||
*/
|
||||
public function batchUpdate(array $data): Command|array|bool|int|string
|
||||
public function populate(array $data): ModelInterface|array
|
||||
{
|
||||
$model = $this->modelClass->populates($data);
|
||||
|
||||
return $this->asArray ? $model->toArray() : $model;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return int
|
||||
* @throws
|
||||
*/
|
||||
public function count(): int
|
||||
{
|
||||
return $this->buildCommand($this->builder->count())->rowCount();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param array $data
|
||||
* @return bool
|
||||
* @throws
|
||||
*/
|
||||
public function update(array $data): bool
|
||||
{
|
||||
if (count($data) < 1) {
|
||||
return true;
|
||||
}
|
||||
$generate = $this->builder->update($data);
|
||||
if (is_bool($generate)) {
|
||||
if (!is_bool($generate)) {
|
||||
return (bool)$this->buildCommand($generate)->exec();
|
||||
} else {
|
||||
return $generate;
|
||||
}
|
||||
return $this->execute(...$generate)->exec();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $data
|
||||
* @return bool
|
||||
* @throws Exception
|
||||
*/
|
||||
public function batchInsert(array $data): bool
|
||||
public function insert(array $data): bool
|
||||
{
|
||||
[$sql, $params] = $this->builder->insert($data, TRUE);
|
||||
$sql = $this->builder->insert($data, isset($data[0]));
|
||||
|
||||
|
||||
return $this->execute($sql, $params)->exec();
|
||||
return (bool)$this->buildCommand($sql)->exec();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $filed
|
||||
* @param string $filed
|
||||
*
|
||||
* @return null
|
||||
* @throws Exception
|
||||
* @return mixed
|
||||
* @throws
|
||||
*/
|
||||
public function value($filed)
|
||||
public function value(string $filed): mixed
|
||||
{
|
||||
return $this->first()[$filed] ?? NULL;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
* @throws Exception
|
||||
* @throws
|
||||
*/
|
||||
public function exists(): bool
|
||||
{
|
||||
return !empty($this->execute($this->builder->one())->fetchColumn());
|
||||
return $this->buildCommand($this->builder->one())->rowCount() > 0;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param bool $getSql
|
||||
* @return int|bool|string|null
|
||||
* @throws Exception
|
||||
* @param string $sql
|
||||
* @param array $params
|
||||
* @return int|bool
|
||||
*/
|
||||
public function delete(bool $getSql = FALSE): int|bool|string|null
|
||||
public function execute(string $sql, array $params = []): int|bool
|
||||
{
|
||||
$sql = $this->builder->delete();
|
||||
if ($getSql === FALSE) {
|
||||
return $this->execute($sql)->delete();
|
||||
return $this->buildCommand($sql, $params)->exec();
|
||||
}
|
||||
return $sql;
|
||||
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
public function delete(): bool
|
||||
{
|
||||
return $this->buildCommand($this->builder->delete())->delete();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
|
||||
namespace Database\Affair;
|
||||
|
||||
use Exception;
|
||||
|
||||
class Commit
|
||||
{
|
||||
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace Database\Annotation;
|
||||
|
||||
|
||||
use Attribute;
|
||||
use Database\Base\Getter;
|
||||
use Exception;
|
||||
|
||||
|
||||
/**
|
||||
* Class Get
|
||||
* @package Annotation\Model
|
||||
*/
|
||||
#[Attribute(Attribute::TARGET_METHOD)] class Get extends \Annotation\Attribute
|
||||
{
|
||||
|
||||
|
||||
/**
|
||||
* Get constructor.
|
||||
* @param string $name
|
||||
*/
|
||||
public function __construct(public string $name)
|
||||
{
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param static $params
|
||||
* @param mixed $class
|
||||
* @param mixed|null $method
|
||||
* @return bool
|
||||
* @throws \Kiri\Exception\NotFindClassException
|
||||
* @throws \ReflectionException
|
||||
*/
|
||||
public function execute(mixed $class, mixed $method = null): bool
|
||||
{
|
||||
di(Getter::class)->addGetter($this->name, $class, $method);
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace Database\Annotation;
|
||||
|
||||
|
||||
use Kiri\Annotation\Attribute;
|
||||
use Database\Base\Relate;
|
||||
use Exception;
|
||||
|
||||
|
||||
/**
|
||||
* Class Relation
|
||||
* @package Annotation\Model
|
||||
*/
|
||||
#[\Attribute(\Attribute::TARGET_METHOD)] class Relation extends Attribute
|
||||
{
|
||||
|
||||
|
||||
/**
|
||||
* Relation constructor.
|
||||
* @param string $name
|
||||
*/
|
||||
public function __construct(public string $name)
|
||||
{
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param mixed $class
|
||||
* @param mixed|null $method
|
||||
* @return bool
|
||||
* @throws Exception
|
||||
*/
|
||||
public function execute(mixed $class, mixed $method = null): bool
|
||||
{
|
||||
di(Relate::class)->addRelate($this->name, $class, $method);
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace Database\Annotation;
|
||||
|
||||
|
||||
use Kiri\Annotation\Attribute;
|
||||
use Database\Base\Setter;
|
||||
use Exception;
|
||||
|
||||
#[\Attribute(\Attribute::TARGET_METHOD)] class Set extends Attribute
|
||||
{
|
||||
|
||||
|
||||
/**
|
||||
* Set constructor.
|
||||
* @param string $name
|
||||
*/
|
||||
public function __construct(public string $name)
|
||||
{
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param static $params
|
||||
* @param mixed $class
|
||||
* @param mixed|null $method
|
||||
* @return bool
|
||||
* @throws \Kiri\Exception\NotFindClassException
|
||||
* @throws \ReflectionException
|
||||
*/
|
||||
public function execute(mixed $class, mixed $method = null): bool
|
||||
{
|
||||
di(Setter::class)->addSetter($this->name, $class, $method);
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,288 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database;
|
||||
|
||||
use Co\Channel;
|
||||
use Exception;
|
||||
use Swoole\Coroutine;
|
||||
use Symfony\Component\Console\Command\Command;
|
||||
use Symfony\Component\Console\Input\InputArgument;
|
||||
use Symfony\Component\Console\Input\InputInterface;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
class BackupCommand extends Command
|
||||
{
|
||||
|
||||
public string $command = 'db:backup';
|
||||
|
||||
|
||||
public string $description = 'php kiri.php db:backup --database users --table u_user --data 1 /Users/admin/snowflake-bi/test.sql';
|
||||
|
||||
|
||||
|
||||
public array $percentStatus = [];
|
||||
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
protected function configure()
|
||||
{
|
||||
$this->setName('db:backup')
|
||||
->addOption('data', 'd', InputArgument::OPTIONAL)
|
||||
->addArgument('path', InputArgument::REQUIRED, "save to path", null)
|
||||
->addOption('table', 't', InputArgument::OPTIONAL)
|
||||
->addOption('database', 'db', InputArgument::OPTIONAL)
|
||||
->setDescription('php kiri.php db:backup --database users --table u_user --data 1 /Users/admin/snowflake-bi/test.sql');
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param InputInterface $input
|
||||
* @param OutputInterface $output
|
||||
* @return int
|
||||
* @throws Exception
|
||||
*/
|
||||
public function execute(InputInterface $input, OutputInterface $output): int
|
||||
{
|
||||
try {
|
||||
/** @var Connection $data */
|
||||
$data = \Kiri::getDi()->get(DatabasesProviders::class)->get($input->getOption('database'));
|
||||
|
||||
$table = $input->getOption('table');
|
||||
if ($table !== null) {
|
||||
$table = explode(',', $table);
|
||||
} else {
|
||||
$tmp = $data->createCommand('show tables from `' . $data->database . '`')->all();
|
||||
$table = [];
|
||||
foreach ($tmp as $value) {
|
||||
$table[] = current($value);
|
||||
}
|
||||
}
|
||||
|
||||
$path = $input->getArgument('path');
|
||||
if (!str_starts_with($path, '/')) {
|
||||
$path = APP_PATH . $path;
|
||||
}
|
||||
|
||||
$isData = $input->getOption('data');
|
||||
if (!is_dir($path)) {
|
||||
mkdir($path);
|
||||
}
|
||||
|
||||
$waite = new Coroutine\WaitGroup();
|
||||
foreach ($table as $value) {
|
||||
$tableInfo = $data->createCommand('show create table `' . $data->database . '`.`' . $value . '`')->one();
|
||||
|
||||
$tmp = rtrim($path, '/') . '/' . current($tableInfo) . '.sql';
|
||||
if (!file_exists($tmp)) {
|
||||
touch($tmp);
|
||||
}
|
||||
|
||||
file_put_contents($tmp, '');
|
||||
|
||||
$tableCreator = next($tableInfo);
|
||||
if (preg_match('/AUTO_INCREMENT=\d+\s/', $tableCreator)) {
|
||||
$tableCreator = preg_replace('/AUTO_INCREMENT=\d+\s/', 'AUTO_INCREMENT=1 ', $tableCreator);
|
||||
}
|
||||
|
||||
file_put_contents($tmp, $tableCreator . ';' . PHP_EOL . PHP_EOL, FILE_APPEND);
|
||||
|
||||
if ($isData == 1) {
|
||||
$waite->add(1);
|
||||
Coroutine::create(function () use ($waite, $input, $value, $tmp) {
|
||||
defer(function () use ($waite) {
|
||||
$waite->done();
|
||||
});
|
||||
$this->writeData($input->getOption('database'), $value, $tmp);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
$waite->wait();
|
||||
|
||||
$output->write('dump data success');
|
||||
} catch (\Throwable $throwable) {
|
||||
$output->writeln(throwable($throwable));
|
||||
} finally {
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public bool $isEnd = false;
|
||||
|
||||
|
||||
/**
|
||||
* @param string $dbname
|
||||
* @param string $tableName
|
||||
* @param string $path
|
||||
* @return void
|
||||
* @throws Exception
|
||||
*/
|
||||
public function writeData(string $dbname, string $tableName, string $path): void
|
||||
{
|
||||
$offset = 0;
|
||||
$size = 1000;
|
||||
|
||||
$channel = new Channel(200);
|
||||
for ($i = 0; $i < 200; $i++) {
|
||||
Coroutine::create(function () use ($channel, $path, $dbname, $tableName) {
|
||||
while ($channel->errCode != SWOOLE_CHANNEL_CLOSED) {
|
||||
if (($data = $channel->pop()) === false) {
|
||||
break;
|
||||
}
|
||||
if (($value = json_decode($data, true)) === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$value = $this->toSql($dbname, $tableName, $value);
|
||||
|
||||
file_put_contents($path, $value . PHP_EOL, FILE_APPEND);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
$id = Coroutine::create(function () use ($channel) {
|
||||
$data = Coroutine::waitSignal(SIGTERM | SIGINT);
|
||||
if ($data) {
|
||||
$this->isEnd = true;
|
||||
}
|
||||
});
|
||||
|
||||
/** @var Connection $database */
|
||||
$database = \Kiri::getDi()->get(DatabasesProviders::class)->get($dbname);
|
||||
|
||||
$total = $database->createCommand("SELECT COUNT(*) as total FROM " . $tableName)->one()['total'];
|
||||
|
||||
$startTime = time();
|
||||
|
||||
$wait = new Coroutine\WaitGroup();
|
||||
while ($this->isEnd === false && $offset < $total) {
|
||||
$wait->add(1);
|
||||
Coroutine::create(function () use ($wait, $offset, $size, $total, $dbname, $tableName, $channel) {
|
||||
defer(function () use ($wait) {
|
||||
$wait->done();
|
||||
});
|
||||
/** @var Connection $database */
|
||||
$database = \Kiri::getDi()->get(DatabasesProviders::class)->get($dbname);
|
||||
|
||||
$data = $database->createCommand("SELECT * FROM $tableName LIMIT $offset,$size")->all();
|
||||
if (is_bool($data) || count($data) < 1) {
|
||||
return;
|
||||
}
|
||||
$channel->push(json_encode($data));
|
||||
|
||||
$this->percentStatus[$dbname . $tableName] = intval(round(($offset + $size) / $total, 2) * 100);
|
||||
|
||||
$this->outputProgress(true);
|
||||
});
|
||||
$offset += $size;
|
||||
}
|
||||
|
||||
$wait->wait();
|
||||
|
||||
echo 'use time ' . (time() - $startTime) . 's' . PHP_EOL;
|
||||
|
||||
$channel->close();
|
||||
|
||||
Coroutine::cancel($id);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $dbname
|
||||
* @param string $value
|
||||
* @param array $data
|
||||
* @return string
|
||||
*/
|
||||
public function toSql(string $dbname, string $value, array $data): string
|
||||
{
|
||||
$strings = ['INSERT INTO ' . $dbname . '.' . $value, '(' . implode(',', array_keys($data[0])) . ') VALUES'];
|
||||
foreach ($data as $datum) {
|
||||
$keys = array_values($datum);
|
||||
$encode = [];
|
||||
foreach ($keys as $val) {
|
||||
if (is_string($val)) {
|
||||
$encode[] = '\'' . addcslashes($val, "\\'") . '\'';
|
||||
} else {
|
||||
$encode[] = $val === '' ? '\'\'' : $val;
|
||||
}
|
||||
}
|
||||
$strings[] = '(' . implode(',', $encode) . '),';
|
||||
}
|
||||
return rtrim(implode('', $strings), ',') . ';';
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $key
|
||||
* @param $percent
|
||||
* @return string
|
||||
* 组合成进度条
|
||||
*/
|
||||
public function buildLine($key, $percent): string
|
||||
{
|
||||
$repeatTimes = 100;
|
||||
if ($percent > 100) $percent = 100;
|
||||
if ($percent > 0) {
|
||||
$hasColor = str_repeat('■', $percent);
|
||||
} else {
|
||||
$hasColor = '';
|
||||
}
|
||||
if ($repeatTimes - $percent > 0) {
|
||||
$noColor = str_repeat(' ', $repeatTimes - $percent);
|
||||
} else {
|
||||
$noColor = '';
|
||||
}
|
||||
if ($percent !== 100) {
|
||||
$percentString = sprintf("[ %s %-6s]", $key, $percent . '%');
|
||||
} else {
|
||||
$percentString = sprintf("[ %s %-5s]", $key, 'OK');;
|
||||
}
|
||||
return $percentString . "[{$hasColor}{$noColor}]" . "\r";
|
||||
}
|
||||
|
||||
/**
|
||||
* @param bool $clear
|
||||
* @return void
|
||||
* 输出进度条
|
||||
*/
|
||||
public function outputProgress(bool $clear = false): void
|
||||
{
|
||||
if ($clear) {
|
||||
$number = count($this->percentStatus);
|
||||
for ($i = 0; $i < $number; $i++) {
|
||||
system("tput cuu1");
|
||||
system("tput el");
|
||||
}
|
||||
}
|
||||
foreach ($this->percentStatus as $key => $value) {
|
||||
echo $this->buildLine($key, $value) . "\n";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $k
|
||||
* @param $value
|
||||
* @return void
|
||||
* 更新进度条值
|
||||
*/
|
||||
public function updateProgressValue($k, $value): void
|
||||
{
|
||||
$this->percentStatus[$k] = $value;
|
||||
if ($this->percentStatus[$k] >= 1000) {
|
||||
$this->percentStatus[$k] = 1000;
|
||||
$this->outputProgress(true);
|
||||
return;
|
||||
}
|
||||
$this->outputProgress(true);
|
||||
usleep(50000);
|
||||
}
|
||||
|
||||
}
|
||||
+30
-25
@@ -13,8 +13,6 @@ namespace Database\Base;
|
||||
use ArrayIterator;
|
||||
use Database\ActiveQuery;
|
||||
use Database\ModelInterface;
|
||||
use Kiri\ToArray;
|
||||
use Exception;
|
||||
use JetBrains\PhpStorm\Pure;
|
||||
use Kiri\Abstracts\Component;
|
||||
use ReturnTypeWillChange;
|
||||
@@ -24,40 +22,36 @@ use Traversable;
|
||||
* Class AbstractCollection
|
||||
* @package Database\Base
|
||||
*/
|
||||
abstract class AbstractCollection extends Component implements \IteratorAggregate, \ArrayAccess, ToArray
|
||||
abstract class AbstractCollection extends Component implements \IteratorAggregate, \ArrayAccess, \Arrayable
|
||||
{
|
||||
|
||||
/**
|
||||
* @var ModelInterface[]
|
||||
*/
|
||||
protected array $_item = [];
|
||||
|
||||
protected ModelInterface|string|null $model;
|
||||
|
||||
protected ActiveQuery $query;
|
||||
private array $_item;
|
||||
|
||||
|
||||
public function clean()
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
public function getItems(): array
|
||||
{
|
||||
unset($this->query, $this->model, $this->_item);
|
||||
// TODO: Change the autogenerated stub
|
||||
return $this->_item;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Collection constructor.
|
||||
*
|
||||
* @param $query
|
||||
* @param ActiveQuery $query
|
||||
* @param array $array
|
||||
* @param ModelInterface|null $model
|
||||
* @throws Exception
|
||||
*/
|
||||
public function __construct($query, array $array = [], ModelInterface $model = null)
|
||||
public function __construct(public ActiveQuery $query, public ?ModelInterface $model = null, array $array = [])
|
||||
{
|
||||
$this->_item = $array;
|
||||
$this->query = $query;
|
||||
$this->model = $model;
|
||||
|
||||
parent::__construct([]);
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
|
||||
@@ -73,7 +67,7 @@ abstract class AbstractCollection extends Component implements \IteratorAggregat
|
||||
/**
|
||||
* @param $item
|
||||
*/
|
||||
public function setItems($item)
|
||||
public function setItems($item): void
|
||||
{
|
||||
$this->_item = $item;
|
||||
}
|
||||
@@ -82,7 +76,7 @@ abstract class AbstractCollection extends Component implements \IteratorAggregat
|
||||
/**
|
||||
* @param $model
|
||||
*/
|
||||
public function setModel($model)
|
||||
public function setModel($model): void
|
||||
{
|
||||
$this->model = $model;
|
||||
}
|
||||
@@ -90,14 +84,14 @@ abstract class AbstractCollection extends Component implements \IteratorAggregat
|
||||
/**
|
||||
* @param $item
|
||||
*/
|
||||
public function addItem($item)
|
||||
public function addItem($item): void
|
||||
{
|
||||
$this->_item[] = $item;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Traversable|CollectionIterator|ArrayIterator
|
||||
* @throws Exception
|
||||
* @throws
|
||||
*/
|
||||
public function getIterator(): Traversable|CollectionIterator|ArrayIterator
|
||||
{
|
||||
@@ -107,7 +101,7 @@ abstract class AbstractCollection extends Component implements \IteratorAggregat
|
||||
|
||||
/**
|
||||
* @return mixed
|
||||
* @throws Exception
|
||||
* @throws
|
||||
*/
|
||||
public function getModel(): ModelInterface
|
||||
{
|
||||
@@ -115,6 +109,15 @@ abstract class AbstractCollection extends Component implements \IteratorAggregat
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return ActiveQuery
|
||||
*/
|
||||
public function makeNewQuery(): ActiveQuery
|
||||
{
|
||||
return $this->model::query();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param mixed $offset
|
||||
* @return bool
|
||||
@@ -127,7 +130,7 @@ abstract class AbstractCollection extends Component implements \IteratorAggregat
|
||||
/**
|
||||
* @param mixed $offset
|
||||
* @return ModelInterface|null
|
||||
* @throws Exception
|
||||
* @throws
|
||||
*/
|
||||
public function offsetGet(mixed $offset): ?ModelInterface
|
||||
{
|
||||
@@ -144,7 +147,8 @@ abstract class AbstractCollection extends Component implements \IteratorAggregat
|
||||
* @param mixed $offset
|
||||
* @param mixed $value
|
||||
*/
|
||||
#[ReturnTypeWillChange] public function offsetSet(mixed $offset, mixed $value)
|
||||
#[ReturnTypeWillChange]
|
||||
public function offsetSet(mixed $offset, mixed $value): void
|
||||
{
|
||||
$this->_item[$offset] = $value;
|
||||
}
|
||||
@@ -153,7 +157,8 @@ abstract class AbstractCollection extends Component implements \IteratorAggregat
|
||||
/**
|
||||
* @param mixed $offset
|
||||
*/
|
||||
#[ReturnTypeWillChange] public function offsetUnset(mixed $offset)
|
||||
#[ReturnTypeWillChange]
|
||||
public function offsetUnset(mixed $offset): void
|
||||
{
|
||||
if ($this->offsetExists($offset)) {
|
||||
unset($this->_item[$offset]);
|
||||
|
||||
@@ -0,0 +1,269 @@
|
||||
<?php
|
||||
|
||||
namespace Database\Base;
|
||||
|
||||
use Closure;
|
||||
use Database\Collection;
|
||||
use Database\Traits\QueryTrait;
|
||||
|
||||
interface ActiveQueryInterface
|
||||
{
|
||||
|
||||
|
||||
/**
|
||||
* @param string $column
|
||||
* @param callable $callable
|
||||
* @return QueryTrait
|
||||
*/
|
||||
public function when(string $column, callable $callable): QueryTrait;
|
||||
|
||||
|
||||
/**
|
||||
* @param string $whereRaw
|
||||
* @return QueryTrait
|
||||
*/
|
||||
public function whereRaw(string $whereRaw): QueryTrait;
|
||||
|
||||
|
||||
/**
|
||||
* @param string $column
|
||||
* @param string $value
|
||||
* @return QueryTrait
|
||||
*/
|
||||
public function whereLocate(string $column, string $value): QueryTrait;
|
||||
|
||||
|
||||
/**
|
||||
* @param string $column
|
||||
* @return QueryTrait
|
||||
*/
|
||||
public function whereNull(string $column): QueryTrait;
|
||||
|
||||
|
||||
/**
|
||||
* @param string $column
|
||||
* @return QueryTrait
|
||||
*/
|
||||
public function whereEmpty(string $column): QueryTrait;
|
||||
|
||||
/**
|
||||
* @param string $column
|
||||
* @return QueryTrait
|
||||
*/
|
||||
public function whereNotEmpty(string $column): QueryTrait;
|
||||
|
||||
/**
|
||||
* @param string $column
|
||||
* @return QueryTrait
|
||||
*/
|
||||
public function whereNotNull(string $column): QueryTrait;
|
||||
|
||||
|
||||
/**
|
||||
* @param string $alias
|
||||
*
|
||||
* @return QueryTrait select * from tableName as t1
|
||||
*
|
||||
* select * from tableName as t1
|
||||
*/
|
||||
public function alias(string $alias = 't1'): QueryTrait;
|
||||
|
||||
/**
|
||||
* @param string|Closure $tableName
|
||||
*
|
||||
* @return QueryTrait
|
||||
*/
|
||||
public function from(string|Closure $tableName): QueryTrait;
|
||||
|
||||
/**
|
||||
* @param string $tableName
|
||||
* @param string $alias
|
||||
* @param array $onCondition
|
||||
* @param array $param
|
||||
* @return QueryTrait
|
||||
*/
|
||||
public function leftJoin(string $tableName, string $alias, array $onCondition, array $param = []): QueryTrait;
|
||||
|
||||
/**
|
||||
* @param string $tableName
|
||||
* @param string $alias
|
||||
* @param array $onCondition
|
||||
* @param array $param
|
||||
* @return QueryTrait
|
||||
*/
|
||||
public function rightJoin(string $tableName, string $alias, array $onCondition, array $param = []): QueryTrait;
|
||||
|
||||
/**
|
||||
* @param string $tableName
|
||||
* @param string $alias
|
||||
* @param array $onCondition
|
||||
* @param array $param
|
||||
* @return QueryTrait
|
||||
*/
|
||||
public function innerJoin(string $tableName, string $alias, array $onCondition, array $param = []): QueryTrait;
|
||||
|
||||
/**
|
||||
* @param string $field
|
||||
*
|
||||
* @return QueryTrait
|
||||
*/
|
||||
public function sum(string $field): QueryTrait;
|
||||
|
||||
/**
|
||||
* @param string $field
|
||||
* @return QueryTrait
|
||||
*/
|
||||
public function max(string $field): QueryTrait;
|
||||
|
||||
/**
|
||||
* @param string $lngField
|
||||
* @param string $latField
|
||||
* @param int|float $lng1
|
||||
* @param int|float $lat1
|
||||
*
|
||||
* @return QueryTrait
|
||||
*/
|
||||
public function distance(string $lngField, string $latField, int|float $lng1, int|float $lat1): QueryTrait;
|
||||
|
||||
/**
|
||||
* @param string|array $column
|
||||
* @param string $sort
|
||||
*
|
||||
* @return QueryTrait [
|
||||
*
|
||||
* [
|
||||
* 'addTime',
|
||||
* 'descTime desc'
|
||||
* ]
|
||||
*/
|
||||
public function orderBy(string|array $column, string $sort = 'DESC'): QueryTrait;
|
||||
|
||||
/**
|
||||
* @param array $column
|
||||
*
|
||||
* @return QueryTrait
|
||||
*/
|
||||
public function select(array $column = ['*']): QueryTrait;
|
||||
|
||||
/**
|
||||
* @return QueryTrait
|
||||
*/
|
||||
public function rand(): QueryTrait;
|
||||
|
||||
/**
|
||||
* @param array|Closure|string $conditionArray
|
||||
* @param string $opera
|
||||
* @param null $value
|
||||
* @return QueryTrait
|
||||
*/
|
||||
public function whereOr(array|Closure|string $conditionArray = [], string $opera = '=', $value = null): QueryTrait;
|
||||
|
||||
|
||||
/**
|
||||
* @param string $column
|
||||
* @param string $value
|
||||
* @return QueryTrait
|
||||
*/
|
||||
public function whereLike(string $column, string $value): QueryTrait;
|
||||
|
||||
/**
|
||||
* @param string $column
|
||||
* @param string $value
|
||||
* @return QueryTrait
|
||||
*/
|
||||
public function whereLeftLike(string $column, string $value): QueryTrait;
|
||||
|
||||
/**
|
||||
* @param string $column
|
||||
* @param string $value
|
||||
* @return QueryTrait
|
||||
*/
|
||||
public function whereRightLike(string $column, string $value): QueryTrait;
|
||||
|
||||
|
||||
/**
|
||||
* @param string $column
|
||||
* @param string $value
|
||||
* @return QueryTrait
|
||||
*/
|
||||
public function whereNotLike(string $column, string $value): QueryTrait;
|
||||
|
||||
|
||||
/**
|
||||
* @param string $columns
|
||||
* @param array|Closure $value
|
||||
* @return QueryTrait
|
||||
*/
|
||||
public function whereIn(string $columns, array|Closure $value): QueryTrait;
|
||||
|
||||
|
||||
/**
|
||||
* @param string $columns
|
||||
* @param array $value
|
||||
* @return QueryTrait
|
||||
*/
|
||||
public function whereNotIn(string $columns, array $value): QueryTrait;
|
||||
|
||||
/**
|
||||
* @param string $column
|
||||
* @param int|float $start
|
||||
* @param int|float $end
|
||||
* @return QueryTrait
|
||||
*/
|
||||
public function whereBetween(string $column, int|float $start, int|float $end): QueryTrait;
|
||||
|
||||
/**
|
||||
* @param string $column
|
||||
* @param int|float $start
|
||||
* @param int|float $end
|
||||
* @return QueryTrait
|
||||
*/
|
||||
public function whereNotBetween(string $column, int|float $start, int|float $end): QueryTrait;
|
||||
|
||||
/**
|
||||
* @param array $column
|
||||
* @return QueryTrait
|
||||
*/
|
||||
public function where(array $column): QueryTrait;
|
||||
|
||||
|
||||
/**
|
||||
* @param string $column
|
||||
* @param string $opera
|
||||
* @param mixed $value
|
||||
* @return QueryTrait
|
||||
*/
|
||||
public function whereMath(string $column, string $opera, mixed $value): QueryTrait;
|
||||
|
||||
|
||||
/**
|
||||
* @param Closure $closure
|
||||
* @return QueryTrait
|
||||
*/
|
||||
public function whereClosure(Closure $closure): QueryTrait;
|
||||
|
||||
|
||||
/**
|
||||
* @param string $name
|
||||
* @param string|null $having
|
||||
*
|
||||
* @return QueryTrait
|
||||
*/
|
||||
public function groupBy(string $name, string $having = NULL): QueryTrait;
|
||||
|
||||
/**
|
||||
* @param int $limit
|
||||
*
|
||||
* @return QueryTrait
|
||||
*/
|
||||
public function limit(int $limit = 20): QueryTrait;
|
||||
|
||||
|
||||
/**
|
||||
* @param int $offset
|
||||
* @return QueryTrait
|
||||
*/
|
||||
public function offset(int $offset): QueryTrait;
|
||||
|
||||
|
||||
}
|
||||
@@ -5,9 +5,7 @@ declare(strict_types=1);
|
||||
namespace Database\Base;
|
||||
|
||||
|
||||
use Database\ActiveQuery;
|
||||
use Database\ModelInterface;
|
||||
use Exception;
|
||||
|
||||
|
||||
/**
|
||||
@@ -17,8 +15,11 @@ use Exception;
|
||||
class CollectionIterator extends \ArrayIterator
|
||||
{
|
||||
|
||||
private ModelInterface|string $model;
|
||||
|
||||
/**
|
||||
* @var ModelInterface|string
|
||||
*/
|
||||
private ModelInterface|string $model;
|
||||
|
||||
|
||||
/**
|
||||
@@ -26,7 +27,7 @@ class CollectionIterator extends \ArrayIterator
|
||||
* @param $model
|
||||
* @param array $array
|
||||
* @param int $flags
|
||||
* @throws Exception
|
||||
* @throws
|
||||
*/
|
||||
public function __construct($model, array $array = [], int $flags = 0)
|
||||
{
|
||||
@@ -38,7 +39,7 @@ class CollectionIterator extends \ArrayIterator
|
||||
/**
|
||||
* @param $current
|
||||
* @return ModelInterface
|
||||
* @throws Exception
|
||||
* @throws
|
||||
*/
|
||||
protected function newModel($current): ModelInterface
|
||||
{
|
||||
@@ -47,7 +48,7 @@ class CollectionIterator extends \ArrayIterator
|
||||
|
||||
|
||||
/**
|
||||
* @throws Exception
|
||||
* @throws
|
||||
*/
|
||||
public function current(): ModelInterface
|
||||
{
|
||||
|
||||
@@ -1,71 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
namespace Database\Base;
|
||||
|
||||
|
||||
use Database\Condition\BetweenCondition;
|
||||
use Database\Condition\InCondition;
|
||||
use Database\Condition\LikeCondition;
|
||||
use Database\Condition\LLikeCondition;
|
||||
use Database\Condition\MathematicsCondition;
|
||||
use Database\Condition\NotBetweenCondition;
|
||||
use Database\Condition\NotInCondition;
|
||||
use Database\Condition\NotLikeCondition;
|
||||
use Database\Condition\RLikeCondition;
|
||||
|
||||
/**
|
||||
* Class ConditionClassMap
|
||||
* @package Database\Base
|
||||
*/
|
||||
class ConditionClassMap
|
||||
{
|
||||
|
||||
public static array $conditionMap = [
|
||||
'IN' => [
|
||||
'class' => InCondition::class
|
||||
],
|
||||
'NOT IN' => [
|
||||
'class' => NotInCondition::class
|
||||
],
|
||||
'LIKE' => [
|
||||
'class' => LikeCondition::class
|
||||
],
|
||||
'NOT LIKE' => [
|
||||
'class' => NotLikeCondition::class
|
||||
],
|
||||
'LLike' => [
|
||||
'class' => LLikeCondition::class
|
||||
],
|
||||
'RLike' => [
|
||||
'class' => RLikeCondition::class
|
||||
],
|
||||
'EQ' => [
|
||||
'class' => MathematicsCondition::class,
|
||||
'type' => 'EQ'
|
||||
],
|
||||
'NEQ' => [
|
||||
'class' => MathematicsCondition::class,
|
||||
'type' => 'NEQ'
|
||||
],
|
||||
'GT' => [
|
||||
'class' => MathematicsCondition::class,
|
||||
'type' => 'GT'
|
||||
],
|
||||
'EGT' => [
|
||||
'class' => MathematicsCondition::class,
|
||||
'type' => 'EGT'
|
||||
],
|
||||
'LT' => [
|
||||
'class' => MathematicsCondition::class,
|
||||
'type' => 'LT'
|
||||
],
|
||||
'ELT' => [
|
||||
'class' => MathematicsCondition::class,
|
||||
'type' => 'ELT'
|
||||
],
|
||||
'BETWEEN' => BetweenCondition::class,
|
||||
'NOT BETWEEN' => NotBetweenCondition::class,
|
||||
];
|
||||
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Database\Base;
|
||||
|
||||
class Getter
|
||||
{
|
||||
|
||||
private array $_classMapping = [];
|
||||
|
||||
|
||||
/**
|
||||
* @param $name
|
||||
* @param $class
|
||||
* @param $method
|
||||
*/
|
||||
public function addGetter($name, $class, $method)
|
||||
{
|
||||
$this->_classMapping[$class][$name] = $method;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $class
|
||||
* @param null $name
|
||||
* @return array|string|null
|
||||
*/
|
||||
public function getGetter($class, $name = null): null|array|string
|
||||
{
|
||||
if (!empty($name)) {
|
||||
return $this->_classMapping[$class][$name] ?? null;
|
||||
}
|
||||
return $this->_classMapping[$class] ?? [];
|
||||
}
|
||||
|
||||
}
|
||||
+311
-568
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
namespace Database\Base;
|
||||
|
||||
class PDO extends \PDO
|
||||
{
|
||||
|
||||
|
||||
/**
|
||||
* @param string $database
|
||||
* @param string $host
|
||||
* @param string $username
|
||||
* @param string $password
|
||||
* @param array $options
|
||||
*/
|
||||
public function __construct(
|
||||
readonly public string $database,
|
||||
readonly public string $host,
|
||||
readonly public string $username,
|
||||
readonly public string $password,
|
||||
readonly public array $options,
|
||||
)
|
||||
{
|
||||
parent::__construct('mysql:dbname=' . $this->database . ';host=' . $this->host, $this->username, $this->password, $this->options);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Database\Base;
|
||||
|
||||
class Relate
|
||||
{
|
||||
|
||||
private array $_classMapping = [];
|
||||
|
||||
|
||||
/**
|
||||
* @param $name
|
||||
* @param $class
|
||||
* @param $method
|
||||
*/
|
||||
public function addRelate($name, $class, $method)
|
||||
{
|
||||
$this->_classMapping[$class][$name] = $method;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $class
|
||||
* @param $name
|
||||
* @return null|array|string
|
||||
*/
|
||||
public function getRelate($class, $name = null): null|array|string
|
||||
{
|
||||
if (!empty($name)) {
|
||||
return $this->_classMapping[$class][$name] ?? null;
|
||||
}
|
||||
return $this->_classMapping[$class] ?? [];
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Database\Base;
|
||||
|
||||
class Setter
|
||||
{
|
||||
|
||||
private array $_classMapping = [];
|
||||
|
||||
|
||||
/**
|
||||
* @param $name
|
||||
* @param $class
|
||||
* @param $method
|
||||
*/
|
||||
public function addSetter($name, $class, $method)
|
||||
{
|
||||
$this->_classMapping[$class][$name] = $method;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $class
|
||||
* @param $name
|
||||
* @return null|array|string
|
||||
*/
|
||||
public function getSetter($class, $name): null|array|string
|
||||
{
|
||||
return $this->_classMapping[$class][$name] ?? null;
|
||||
}
|
||||
|
||||
}
|
||||
+46
-55
@@ -21,33 +21,29 @@ use JetBrains\PhpStorm\Pure;
|
||||
class Collection extends AbstractCollection
|
||||
{
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
public function getItems(): array
|
||||
{
|
||||
// TODO: Change the autogenerated stub
|
||||
return $this->_item;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $field
|
||||
* @param string $field
|
||||
*
|
||||
* @return array|null
|
||||
* @throws Exception
|
||||
*/
|
||||
public function values($field): ?array
|
||||
public function values(string $field): ?array
|
||||
{
|
||||
if (empty($field) || !is_string($field)) {
|
||||
return NULL;
|
||||
return array_values($this->column($field));
|
||||
}
|
||||
$_tmp = [];
|
||||
$data = $this->toArray();
|
||||
foreach ($data as $val) {
|
||||
/** @var ModelInterface $val */
|
||||
$_tmp[] = $val[$field];
|
||||
|
||||
|
||||
/**
|
||||
* @param array $attributes
|
||||
* @return bool
|
||||
* @throws
|
||||
*/
|
||||
public function update(array $attributes): bool
|
||||
{
|
||||
if ($this->isEmpty()) {
|
||||
return $this->getLogger()->failure('No data by update', 'mysql');
|
||||
}
|
||||
return $_tmp;
|
||||
return $this->batch()->update($attributes);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -61,18 +57,9 @@ class Collection extends AbstractCollection
|
||||
foreach ($column as $key => $value) {
|
||||
$column[$key] = $array[$value];
|
||||
}
|
||||
|
||||
return $column;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return $this
|
||||
*/
|
||||
public function orderRand(): static
|
||||
{
|
||||
shuffle($this->_item);
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $start
|
||||
@@ -82,13 +69,13 @@ class Collection extends AbstractCollection
|
||||
*/
|
||||
#[Pure] public function slice(int $start = 0, int $length = 20): array
|
||||
{
|
||||
if (empty($this->_item) || !is_array($this->_item)) {
|
||||
if (empty($this->getItems())) {
|
||||
return [];
|
||||
}
|
||||
if (count($this->_item) < $length) {
|
||||
return $this->_item;
|
||||
if (\count($this->getItems()) < $length) {
|
||||
return $this->getItems();
|
||||
} else {
|
||||
return array_slice($this->_item, $start, $length);
|
||||
return array_slice($this->getItems(), $start, $length);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -130,7 +117,7 @@ class Collection extends AbstractCollection
|
||||
*/
|
||||
#[Pure] public function current(): ModelInterface|array
|
||||
{
|
||||
return current($this->_item);
|
||||
return current($this->getItems());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -138,7 +125,7 @@ class Collection extends AbstractCollection
|
||||
*/
|
||||
#[Pure] public function size(): int
|
||||
{
|
||||
return (int)count($this->_item);
|
||||
return count($this->getItems());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -150,31 +137,36 @@ class Collection extends AbstractCollection
|
||||
$array = [];
|
||||
/** @var Model $value */
|
||||
foreach ($this as $value) {
|
||||
if (!is_object($value)) {
|
||||
continue;
|
||||
$array[] = $value->toArray();
|
||||
}
|
||||
$array[] = $value->setWith($this->query->with)->toArray();
|
||||
}
|
||||
$this->_item = [];
|
||||
return $array;
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws Exception
|
||||
* @throws
|
||||
* 批量删除
|
||||
*/
|
||||
public function delete(): bool
|
||||
{
|
||||
$model = $this->getModel();
|
||||
if (!$model->hasPrimary()) return false;
|
||||
$ids = [];
|
||||
foreach ($this as $item) {
|
||||
$id = $item->getPrimaryValue();
|
||||
if (!empty($id)) {
|
||||
$ids[] = $id;
|
||||
if ($this->isEmpty()) {
|
||||
return $this->getLogger()->failure('No data by delete', 'mysql');
|
||||
}
|
||||
if (!$model->hasPrimary()) {
|
||||
throw new Exception('Must set primary key. if you want to delete data');
|
||||
}
|
||||
return $model::query()->whereIn($model->getPrimary(), $ids)->delete();
|
||||
return $this->batch()->delete();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return ActiveQuery
|
||||
* @throws Exception
|
||||
*/
|
||||
private function batch(): ActiveQuery
|
||||
{
|
||||
return $this->makeNewQuery()->whereIn($this->getModel()->getPrimary(),
|
||||
$this->column($this->getModel()->getPrimary()));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -194,17 +186,16 @@ class Collection extends AbstractCollection
|
||||
}
|
||||
$_filters[] = $value;
|
||||
}
|
||||
return new Collection($this->query, $_filters, $this->model);
|
||||
return new Collection($this->query, $this->model, $_filters);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $value
|
||||
* @param $condition
|
||||
* @param array|ModelInterface $value
|
||||
* @param array $condition
|
||||
* @return bool
|
||||
* @throws Exception
|
||||
*/
|
||||
private function filterCheck($value, $condition): bool
|
||||
private function filterCheck(array|ModelInterface $value, array $condition): bool
|
||||
{
|
||||
$_value = $value;
|
||||
if ($_value instanceof ModelInterface) {
|
||||
@@ -219,11 +210,11 @@ class Collection extends AbstractCollection
|
||||
|
||||
|
||||
/**
|
||||
* @param $key
|
||||
* @param $value
|
||||
* @param string $key
|
||||
* @param mixed $value
|
||||
* @return mixed
|
||||
*/
|
||||
public function exists($key, $value): mixed
|
||||
public function exists(string $key, mixed $value): mixed
|
||||
{
|
||||
foreach ($this as $item) {
|
||||
if ($item->$key === $value) {
|
||||
|
||||
+170
-105
@@ -12,8 +12,9 @@ namespace Database;
|
||||
|
||||
use Exception;
|
||||
use Kiri\Abstracts\Component;
|
||||
use Kiri\Core\Json;
|
||||
use PDOStatement;
|
||||
use Kiri\Di\Container;
|
||||
use PDO;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Class Command
|
||||
@@ -21,152 +22,227 @@ use PDOStatement;
|
||||
*/
|
||||
class Command extends Component
|
||||
{
|
||||
const ROW_COUNT = 'ROW_COUNT';
|
||||
const FETCH = 'FETCH';
|
||||
const FETCH_ALL = 'FETCH_ALL';
|
||||
const EXECUTE = 'EXECUTE';
|
||||
const FETCH_COLUMN = 'FETCH_COLUMN';
|
||||
|
||||
/** @var Connection */
|
||||
public Connection $db;
|
||||
|
||||
/** @var ?string */
|
||||
public Connection $connection;
|
||||
public ?string $sql = '';
|
||||
|
||||
/** @var array */
|
||||
public array $params = [];
|
||||
|
||||
/** @var string */
|
||||
public string $dbname = '';
|
||||
|
||||
|
||||
/**
|
||||
* @return array|bool|int|string|PDOStatement|null
|
||||
* @throws Exception
|
||||
* @param array $params
|
||||
* @throws
|
||||
*/
|
||||
public function incrOrDecr(): array|bool|int|string|PDOStatement|null
|
||||
public function __construct(array $params = [])
|
||||
{
|
||||
return $this->execute(static::EXECUTE);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return int|bool|array|string|null
|
||||
* @throws Exception
|
||||
*/
|
||||
public function save(): int|bool|array|string|null
|
||||
{
|
||||
return $this->execute(static::EXECUTE);
|
||||
parent::__construct();
|
||||
Container::configure($this, $params);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return int|bool|array|string|null
|
||||
* @throws Exception
|
||||
* @return bool
|
||||
* @throws
|
||||
*/
|
||||
public function all(): int|bool|array|string|null
|
||||
public function incrOrDecr(): bool
|
||||
{
|
||||
return $this->execute(static::FETCH_ALL);
|
||||
return (bool)$this->_prepare();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array|bool|int|string|null
|
||||
* @throws Exception
|
||||
* @return bool
|
||||
* @throws
|
||||
*/
|
||||
public function one(): null|array|bool|int|string
|
||||
public function save(): bool
|
||||
{
|
||||
return $this->execute(static::FETCH);
|
||||
return (bool)$this->_prepare();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return bool|array
|
||||
* @throws
|
||||
*/
|
||||
public function all(): bool|array
|
||||
{
|
||||
return $this->search('fetchAll');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return int|bool|array|string|null
|
||||
* @throws Exception
|
||||
* @return array|bool|null
|
||||
* @throws
|
||||
*/
|
||||
public function fetchColumn(): int|bool|array|string|null
|
||||
public function one(): array|null|bool
|
||||
{
|
||||
return $this->execute(static::FETCH_COLUMN);
|
||||
return $this->search('fetch');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return int|bool|array|string|null
|
||||
* @throws Exception
|
||||
* @return mixed
|
||||
* @throws
|
||||
*/
|
||||
public function rowCount(): int|bool|array|string|null
|
||||
public function fetchColumn(): mixed
|
||||
{
|
||||
return $this->execute(static::ROW_COUNT);
|
||||
return $this->search('fetchColumn');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return int|bool|array|string|null
|
||||
* @throws Exception
|
||||
* @return mixed
|
||||
* @throws
|
||||
*/
|
||||
public function flush(): int|bool|array|string|null
|
||||
{
|
||||
return $this->execute(static::EXECUTE);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $type
|
||||
* @return int|bool|array|string|null
|
||||
* @throws Exception
|
||||
*/
|
||||
private function execute(string $type): int|bool|array|string|null
|
||||
public function rowCount(): mixed
|
||||
{
|
||||
$client = $this->connection->getConnection();
|
||||
try {
|
||||
$time = microtime(true);
|
||||
if ($type === static::EXECUTE) {
|
||||
$result = $this->db->getConnect($this->sql)->execute($this->sql,$this->params);
|
||||
} else {
|
||||
$result = $this->search($type);
|
||||
$client->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);
|
||||
if (($prepare = $client->query($this->sql)) === false) {
|
||||
throw new Exception('(' . $prepare->errorInfo()[0] . ')' . $client->errorInfo()[2]);
|
||||
}
|
||||
if (microtime(true) - $time >= 0.02) {
|
||||
$this->warning('Mysql:' . Json::encode([$this->sql, $this->params]) . (microtime(true) - $time));
|
||||
}
|
||||
} catch (\Throwable $exception) {
|
||||
$result = $this->addError($this->sql . '. error: ' . $exception->getMessage(), 'mysql');
|
||||
|
||||
$prepare->execute($this->params);
|
||||
|
||||
$count = $prepare->rowCount();
|
||||
$prepare->closeCursor();
|
||||
|
||||
$this->connection->println($this->sql, $this->params);
|
||||
|
||||
return $count;
|
||||
} catch (Throwable $throwable) {
|
||||
if ($this->isRefresh($throwable)) return $this->rowCount();
|
||||
|
||||
$errorMsg = $throwable->getMessage() . PHP_EOL . ' Sql: ' . $this->sql . '.' . json_encode($this->params);
|
||||
$this->getLogger()->failure($errorMsg . PHP_EOL, 'mysql');
|
||||
return 0;
|
||||
} finally {
|
||||
$this->db->release();
|
||||
$this->connection->release($client);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
* @throws Exception
|
||||
*/
|
||||
public function exists(): bool
|
||||
{
|
||||
$total = $this->search('rowCount');
|
||||
if ($total === false) {
|
||||
throw new Exception('Query data is has error.');
|
||||
}
|
||||
return $total > 0;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $method
|
||||
* @return mixed
|
||||
* @throws
|
||||
*/
|
||||
protected function search(string $method): mixed
|
||||
{
|
||||
$client = $this->connection->getConnection();
|
||||
try {
|
||||
if (($prepare = $client->prepare($this->sql)) === false) {
|
||||
throw new Exception('(' . $prepare->errorInfo()[0] . ')' . $client->errorInfo()[2]);
|
||||
}
|
||||
|
||||
$prepare->execute($this->params);
|
||||
|
||||
$result = $method == 'rowCount' ? $prepare->rowCount() : $prepare->{$method}(PDO::FETCH_ASSOC);
|
||||
$prepare->closeCursor();
|
||||
|
||||
$this->connection->println($this->sql, $this->params);
|
||||
|
||||
return $result;
|
||||
} catch (Throwable $throwable) {
|
||||
if ($this->isRefresh($throwable)) return $this->search($method);
|
||||
|
||||
$errorMsg = $throwable->getMessage() . PHP_EOL . ' Sql: ' . $this->sql . '.' . json_encode($this->params);
|
||||
|
||||
return $this->getLogger()->failure($errorMsg . PHP_EOL, 'mysql');
|
||||
} finally {
|
||||
$this->connection->release($client);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $type
|
||||
* @return array|int|bool|null
|
||||
* @throws Exception
|
||||
* @return bool
|
||||
* @throws
|
||||
*/
|
||||
private function search(string $type): array|int|bool|null
|
||||
public function flush(): bool
|
||||
{
|
||||
$pdo = $this->db->getConnect($this->sql);
|
||||
if ($type === static::FETCH_COLUMN) {
|
||||
$data = $pdo->fetchColumn($this->sql, $this->params);
|
||||
} else if ($type === static::ROW_COUNT) {
|
||||
$data = $pdo->count($this->sql, $this->params);
|
||||
} else if ($type === static::FETCH_ALL) {
|
||||
$data = $pdo->fetchAll($this->sql, $this->params);
|
||||
} else {
|
||||
$data = $pdo->fetch($this->sql, $this->params);
|
||||
}
|
||||
return $data;
|
||||
return (bool)$this->_prepare();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return int|bool|array|string|null
|
||||
* @throws Exception
|
||||
* @return int|bool
|
||||
* @throws
|
||||
*/
|
||||
public function delete(): int|bool|array|string|null
|
||||
private function _prepare(): int|bool
|
||||
{
|
||||
return $this->execute(static::EXECUTE);
|
||||
$client = $this->connection->getConnection();
|
||||
try {
|
||||
$this->connection->println($this->sql, $this->params);
|
||||
if (($prepare = $client->prepare($this->sql)) === false) {
|
||||
throw new Exception('(' . $prepare->errorInfo()[0] . ')' . $prepare->errorInfo()[2]);
|
||||
}
|
||||
if ($prepare->execute($this->params) === false) {
|
||||
throw new Exception('(' . $prepare->errorInfo()[0] . ')' . $prepare->errorInfo()[2]);
|
||||
}
|
||||
$prepare->closeCursor();
|
||||
|
||||
$result = $client->lastInsertId();
|
||||
|
||||
$this->connection->println($this->sql, $this->params);
|
||||
|
||||
return $result == 0 ? $prepare->rowCount() : (int)$result;
|
||||
} catch (Throwable $throwable) {
|
||||
if ($this->isRefresh($throwable)) return $this->_prepare();
|
||||
|
||||
$errorMsg = $throwable->getMessage() . PHP_EOL . ' Sql: ' . $this->sql . '.' . json_encode($this->params);
|
||||
|
||||
return $this->getLogger()->failure($errorMsg . PHP_EOL, 'mysql');
|
||||
} finally {
|
||||
$this->connection->release($client);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return int|bool|array|string|null
|
||||
* @throws Exception
|
||||
* @param Throwable $throwable
|
||||
* @return bool
|
||||
*/
|
||||
public function exec(): int|bool|array|string|null
|
||||
protected function isRefresh(Throwable $throwable): bool
|
||||
{
|
||||
return $this->execute(static::EXECUTE);
|
||||
if (str_contains($throwable->getMessage(), 'MySQL server has gone away')) {
|
||||
return true;
|
||||
}
|
||||
if (str_contains($throwable->getMessage(), 'Send of 14 bytes failed with errno=32 Broken pipe')) {
|
||||
return true;
|
||||
}
|
||||
if (str_contains($throwable->getMessage(), 'Lost connection to MySQL server during query')) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
* @throws
|
||||
*/
|
||||
public function delete(): bool
|
||||
{
|
||||
return (bool)$this->_prepare();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return int|bool
|
||||
*/
|
||||
public function exec(): int|bool
|
||||
{
|
||||
return $this->_prepare();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -175,21 +251,10 @@ class Command extends Component
|
||||
*/
|
||||
public function bindValues(array $data = []): static
|
||||
{
|
||||
if (!empty($data)) {
|
||||
if (count($data) > 0) {
|
||||
$this->params = array_merge($this->params, $data);
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $sql
|
||||
* @return $this
|
||||
* @throws Exception
|
||||
*/
|
||||
public function setSql($sql): static
|
||||
{
|
||||
$this->sql = $sql;
|
||||
return $this;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -16,12 +16,7 @@ abstract class Condition extends Component
|
||||
|
||||
protected string $column = '';
|
||||
protected string $opera = '=';
|
||||
|
||||
/** @var array|mixed */
|
||||
protected $value;
|
||||
|
||||
const INT_TYPE = ['bit', 'bool', 'tinyint', 'smallint', 'mediumint', 'int', 'bigint', 'float', 'double', 'decimal', 'timestamp'];
|
||||
|
||||
protected mixed $value;
|
||||
protected array $attributes = [];
|
||||
|
||||
abstract public function builder();
|
||||
|
||||
@@ -18,7 +18,7 @@ class DefaultCondition extends Condition
|
||||
*/
|
||||
#[Pure] public function builder(): string
|
||||
{
|
||||
return sprintf('%s %s %s', $this->column, $this->opera, addslashes($this->value));
|
||||
return $this->column . ' ' . $this->opera . ' ' . addslashes($this->value);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -12,17 +12,16 @@ class HashCondition extends Condition
|
||||
|
||||
/**
|
||||
* @return string
|
||||
* @throws
|
||||
*/
|
||||
public function builder(): string
|
||||
{
|
||||
$array = [];
|
||||
if (empty($this->value)) {
|
||||
return '';
|
||||
if (count($this->value) < 1) {
|
||||
throw new \Exception('Builder data by a empty array.');
|
||||
}
|
||||
foreach ($this->value as $key => $value) {
|
||||
if (is_null($value)) continue;
|
||||
|
||||
$array[] = sprintf("%s = '%s'", $key, addslashes($value));
|
||||
$array[] = $key . '=' . addslashes($value);
|
||||
}
|
||||
return implode(' AND ', $array);
|
||||
}
|
||||
|
||||
@@ -3,8 +3,6 @@ declare(strict_types=1);
|
||||
|
||||
namespace Database\Condition;
|
||||
|
||||
use Database\ActiveQuery;
|
||||
use Exception;
|
||||
use JetBrains\PhpStorm\Pure;
|
||||
|
||||
/**
|
||||
@@ -17,14 +15,14 @@ class InCondition extends Condition
|
||||
|
||||
/**
|
||||
* @return string
|
||||
* @throws Exception
|
||||
* @throws
|
||||
*/
|
||||
#[Pure] public function builder(): string
|
||||
{
|
||||
if (is_array($this->value)) {
|
||||
return sprintf('%s IN (%s)', $this->column, implode(',', $this->value));
|
||||
return $this->column . ' IN (' . implode(',', $this->value) . ')';
|
||||
} else {
|
||||
return sprintf('%s IN (%s)', $this->column, $this->value);
|
||||
return $this->column . ' IN (' . $this->value . ')';
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -12,9 +12,13 @@ class JsonCondition extends Condition
|
||||
{
|
||||
|
||||
|
||||
public function builder()
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
public function builder(): bool
|
||||
{
|
||||
// TODO: Implement builder() method.
|
||||
return \json_validate($this->value);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -3,8 +3,6 @@ declare(strict_types=1);
|
||||
|
||||
namespace Database\Condition;
|
||||
|
||||
use Kiri\Core\Str;
|
||||
|
||||
/**
|
||||
* Class LLikeCondition
|
||||
* @package Database\Condition
|
||||
|
||||
@@ -3,8 +3,6 @@ declare(strict_types=1);
|
||||
|
||||
namespace Database\Condition;
|
||||
|
||||
use Kiri\Core\Str;
|
||||
|
||||
/**
|
||||
* Class LikeCondition
|
||||
* @package Database\Condition
|
||||
|
||||
@@ -15,11 +15,12 @@ class NotInCondition extends Condition
|
||||
|
||||
/**
|
||||
* @return string|null
|
||||
* @throws
|
||||
*/
|
||||
#[Pure] public function builder(): ?string
|
||||
{
|
||||
if (!is_array($this->value)) {
|
||||
return null;
|
||||
throw new \Exception('Builder data by a empty string. need array');
|
||||
}
|
||||
$value = '\'' . implode('\',\'', $this->value) . '\'';
|
||||
return '`' . $this->column . '` not in(' . $value . ')';
|
||||
|
||||
@@ -3,8 +3,6 @@ declare(strict_types=1);
|
||||
|
||||
namespace Database\Condition;
|
||||
|
||||
use Kiri\Core\Str;
|
||||
|
||||
/**
|
||||
* Class NotLikeCondition
|
||||
* @package Database\Condition
|
||||
|
||||
@@ -21,7 +21,7 @@ class OrCondition extends Condition
|
||||
*/
|
||||
#[Pure] public function builder(): string
|
||||
{
|
||||
return sprintf('(%s) OR %s', implode(' AND ', $this->oldParams), addslashes($this->value));
|
||||
return '(' . implode(' AND ', $this->oldParams) . ') OR ' . addslashes($this->value);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -3,8 +3,6 @@ declare(strict_types=1);
|
||||
|
||||
namespace Database\Condition;
|
||||
|
||||
use Kiri\Core\Str;
|
||||
|
||||
/**
|
||||
* Class RLikeCondition
|
||||
* @package Database\Condition
|
||||
|
||||
+247
-214
@@ -14,18 +14,21 @@ namespace Database;
|
||||
use Database\Affair\BeginTransaction;
|
||||
use Database\Affair\Commit;
|
||||
use Database\Affair\Rollback;
|
||||
use Database\Mysql\PDO;
|
||||
use Database\Mysql\Schema;
|
||||
use Exception;
|
||||
use Kiri;
|
||||
use Kiri\Server\Events\OnWorkerExit;
|
||||
use Kiri\Abstracts\Component;
|
||||
use Kiri\Abstracts\Config;
|
||||
use Kiri\Di\Context;
|
||||
use Kiri\Pool\Pool;
|
||||
use Kiri\Events\EventProvider;
|
||||
use Kiri\Exception\NotFindClassException;
|
||||
use Kiri\Kiri;
|
||||
use Kiri\Annotation\Inject;
|
||||
use ReflectionException;
|
||||
use Server\Events\OnWorkerExit;
|
||||
use Server\Events\OnWorkerStop;
|
||||
use Kiri\Error\StdoutLogger;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Kiri\Server\Events\OnWorkerStart;
|
||||
use Kiri\Server\Events\OnTaskerStart;
|
||||
use Kiri\Server\Events\OnAfterRequest;
|
||||
use Kiri\Di\Inject\Container;
|
||||
use Swoole\Timer;
|
||||
use Database\Base\PDO;
|
||||
|
||||
/**
|
||||
* Class Connection
|
||||
@@ -40,294 +43,324 @@ class Connection extends Component
|
||||
public string $username = '';
|
||||
public string $charset = 'utf-8';
|
||||
public string $tablePrefix = '';
|
||||
|
||||
public string $database = '';
|
||||
|
||||
public int $connect_timeout = 30;
|
||||
|
||||
public int $read_timeout = 10;
|
||||
|
||||
public array $pool;
|
||||
|
||||
/**
|
||||
* @var bool
|
||||
* enable database cache
|
||||
*/
|
||||
public int $timeout = 30;
|
||||
public int $waite_time = 3;
|
||||
public int $tick_time = 60;
|
||||
public int $idle_count = 3;
|
||||
public int $idle_time = 60;
|
||||
public array $pool = ['max' => 10, 'min' => 1];
|
||||
private int $storey = 0;
|
||||
protected int $timerId = -1;
|
||||
public bool $enableCache = false;
|
||||
|
||||
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
public string $cacheDriver = 'redis';
|
||||
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
public array $slaveConfig = [];
|
||||
public array $attributes = [];
|
||||
|
||||
|
||||
private ?Schema $_schema = null;
|
||||
public array $slave = [];
|
||||
protected ?\Closure $_println = null;
|
||||
|
||||
|
||||
/**
|
||||
* execute by __construct
|
||||
* @throws Exception
|
||||
* @var StdoutLogger
|
||||
*/
|
||||
public function init()
|
||||
#[Container(LoggerInterface::class)]
|
||||
public StdoutLogger $logger;
|
||||
|
||||
/**
|
||||
* @param Pool $connections
|
||||
*/
|
||||
public function __construct(public Pool $connections)
|
||||
{
|
||||
$this->eventProvider->on(OnWorkerStop::class, [$this, 'clear_connection'], 0);
|
||||
$this->eventProvider->on(OnWorkerExit::class, [$this, 'clear_connection'], 0);
|
||||
$this->eventProvider->on(BeginTransaction::class, [$this, 'beginTransaction'], 0);
|
||||
$this->eventProvider->on(Rollback::class, [$this, 'rollback'], 0);
|
||||
$this->eventProvider->on(Commit::class, [$this, 'commit'], 0);
|
||||
parent::__construct();
|
||||
|
||||
$this->_println = \config('databases.logger', null);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param null $sql
|
||||
* @return PDO
|
||||
* @throws Exception
|
||||
* @param string $sql
|
||||
* @param array $params
|
||||
* @return void
|
||||
*/
|
||||
public function getConnect($sql = NULL): PDO
|
||||
public function println(string $sql, array $params = []): void
|
||||
{
|
||||
return $this->getPdo($sql);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @throws Exception
|
||||
*/
|
||||
public function fill()
|
||||
{
|
||||
$connections = $this->connections();
|
||||
$pool = Config::get('databases.pool.max', 10);
|
||||
|
||||
$connections->initConnections('Mysql:' . $this->cds, true, $pool);
|
||||
if (!empty($this->slaveConfig) && $this->cds != $this->slaveConfig['cds']) {
|
||||
$connections->initConnections('Mysql:' . $this->slaveConfig['cds'], false, $pool);
|
||||
if (is_callable($this->_println)) {
|
||||
call_user_func($this->_println, $sql, $params);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $sql
|
||||
* @return PDO
|
||||
* @throws Exception
|
||||
* @return void
|
||||
* @throws
|
||||
*/
|
||||
private function getPdo($sql): PDO
|
||||
public function init(): void
|
||||
{
|
||||
if ($this->isWrite($sql)) {
|
||||
return $this->masterInstance();
|
||||
} else {
|
||||
return $this->slaveInstance();
|
||||
$eventProvider = Kiri::getDi()->get(EventProvider::class);
|
||||
$eventProvider->on(BeginTransaction::class, [$this, 'beginTransaction'], 0);
|
||||
$eventProvider->on(Rollback::class, [$this, 'rollback'], 0);
|
||||
$eventProvider->on(Commit::class, [$this, 'commit'], 0);
|
||||
$eventProvider->on(OnAfterRequest::class, [$this, 'clear']);
|
||||
$eventProvider->on(OnWorkerExit::class, [$this, 'disconnect']);
|
||||
$eventProvider->on(OnWorkerStart::class, [$this, 'tick']);
|
||||
$eventProvider->on(OnTaskerStart::class, [$this, 'tick']);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return void
|
||||
*/
|
||||
public function tick(): void
|
||||
{
|
||||
$this->timerId = Timer::tick($this->tick_time, fn() => $this->checkClientHealth($this->pool()));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param Pool $pool
|
||||
* @return void
|
||||
* @throws
|
||||
*/
|
||||
protected function checkClientHealth(Pool $pool): void
|
||||
{
|
||||
$pool->flush($this->cds, $this->pool['min'] ?? 1);
|
||||
$length = $pool->size($this->cds);
|
||||
for ($i = 0; $i < $length; $i++) {
|
||||
try {
|
||||
if (($client = $this->validator($pool)) === false) {
|
||||
break;
|
||||
}
|
||||
$pool->push($this->cds, $client);
|
||||
} catch (\Throwable $exception) {
|
||||
if (!str_contains($exception->getMessage(), 'Client timeout.')) {
|
||||
$this->logger->error(throwable($exception), [$this->cds]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return mixed
|
||||
* @throws ReflectionException
|
||||
* @throws NotFindClassException
|
||||
* @throws Exception
|
||||
*/
|
||||
public function getSchema(): Schema
|
||||
{
|
||||
if ($this->_schema === null) {
|
||||
$this->_schema = Kiri::createObject([
|
||||
'class' => Schema::class,
|
||||
'db' => $this
|
||||
]);
|
||||
}
|
||||
return $this->_schema;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $sql
|
||||
* @return bool
|
||||
* @param Pool $pool
|
||||
* @return PDO|bool
|
||||
* @throws
|
||||
*/
|
||||
public function isWrite($sql): bool
|
||||
protected function validator(Pool $pool): PDO|bool
|
||||
{
|
||||
if (empty($sql)) return false;
|
||||
if (str_starts_with(strtolower($sql), 'select')) {
|
||||
/** @var $client PDO */
|
||||
if (($client = $pool->get($this->cds)) === false) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
if ($client->query('select 1') === false) {
|
||||
throw new Exception($client->errorInfo()[1]);
|
||||
}
|
||||
return $client;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return mixed
|
||||
* @throws Exception
|
||||
*/
|
||||
public function getCacheDriver(): mixed
|
||||
{
|
||||
if (!$this->enableCache) {
|
||||
return null;
|
||||
}
|
||||
return Kiri::app()->get($this->cacheDriver);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return PDO
|
||||
* @throws Exception
|
||||
* @throws
|
||||
*/
|
||||
public function masterInstance(): PDO
|
||||
public function getConnection(): PDO
|
||||
{
|
||||
return $this->connections()->get([
|
||||
'cds' => $this->cds,
|
||||
'username' => $this->username,
|
||||
'password' => $this->password,
|
||||
'attributes' => $this->attributes,
|
||||
'connect_timeout' => $this->connect_timeout,
|
||||
'read_timeout' => $this->read_timeout,
|
||||
'dbname' => $this->database,
|
||||
'pool' => $this->pool
|
||||
], true);
|
||||
if (!$this->inTransaction()) {
|
||||
return $this->getNormalClientHealth();
|
||||
} else {
|
||||
return $this->getTransactionClient();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return PDO
|
||||
* @throws Exception
|
||||
* @throws
|
||||
*/
|
||||
public function slaveInstance(): PDO
|
||||
protected function getNormalClientHealth(): PDO
|
||||
{
|
||||
if (empty($this->slaveConfig) || Db::transactionsActive()) {
|
||||
return $this->masterInstance();
|
||||
$data = $this->pool()->get($this->cds, $this->waite_time);
|
||||
if ($data === false) {
|
||||
throw new Exception('Client Waite timeout.');
|
||||
}
|
||||
if ($this->slaveConfig['cds'] == $this->cds) {
|
||||
return $this->masterInstance();
|
||||
}
|
||||
return $this->connections()->get($this->slaveConfig, false);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return \Kiri\Pool\Connection
|
||||
* @throws Exception
|
||||
*/
|
||||
private function connections(): \Kiri\Pool\Connection
|
||||
{
|
||||
return Kiri::getDi()->get(\Kiri\Pool\Connection::class);
|
||||
return $data;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return $this
|
||||
* @throws Exception
|
||||
* @throws
|
||||
*/
|
||||
public function beginTransaction(): static
|
||||
{
|
||||
$this->connections()->beginTransaction($this->cds);
|
||||
if ($this->storey < 0) {
|
||||
$this->storey = 0;
|
||||
}
|
||||
$this->storey++;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return $this|bool
|
||||
* @throws Exception
|
||||
*/
|
||||
public function inTransaction(): bool|static
|
||||
{
|
||||
return $this->connections()->inTransaction($this->cds);
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws Exception
|
||||
* @return PDO
|
||||
* @throws
|
||||
*/
|
||||
public function getTransactionClient(): PDO
|
||||
{
|
||||
$pdo = Context::get($this->cds);
|
||||
if ($pdo === null) {
|
||||
/** @var PDO $pdo */
|
||||
$pdo = Context::set($this->cds, $this->getNormalClientHealth());
|
||||
}
|
||||
if ($this->storey > 0 && !$pdo->inTransaction()) {
|
||||
$pdo->beginTransaction();
|
||||
}
|
||||
return $pdo;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
* @throws
|
||||
*/
|
||||
public function inTransaction(): bool
|
||||
{
|
||||
return $this->storey > 0;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @throws
|
||||
* 事务回滚
|
||||
*/
|
||||
public function rollback()
|
||||
public function rollback(): void
|
||||
{
|
||||
$this->connections()->rollback($this->cds);
|
||||
$this->release();
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws Exception
|
||||
* 事务提交
|
||||
*/
|
||||
public function commit()
|
||||
{
|
||||
$this->connections()->commit($this->cds);
|
||||
$this->release();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $sql
|
||||
* @return PDO
|
||||
* @throws Exception
|
||||
*/
|
||||
public function refresh($sql): PDO
|
||||
{
|
||||
if ($this->isWrite($sql)) {
|
||||
$instance = $this->masterInstance();
|
||||
} else {
|
||||
$instance = $this->slaveInstance();
|
||||
}
|
||||
return $instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param null $sql
|
||||
* @param array $attributes
|
||||
* @return Command
|
||||
* @throws Exception
|
||||
*/
|
||||
public function createCommand($sql = null, array $attributes = []): Command
|
||||
{
|
||||
$command = new Command(['db' => $this, 'sql' => $sql]);
|
||||
return $command->bindValues($attributes);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
*
|
||||
* 回收链接
|
||||
* @throws
|
||||
*/
|
||||
public function release()
|
||||
{
|
||||
if (!Kiri::isWorker() && !Kiri::isProcess()) {
|
||||
$this->clear_connection();
|
||||
$this->storey--;
|
||||
if ($this->storey == 0) {
|
||||
if (!Context::exists($this->cds)) {
|
||||
return;
|
||||
}
|
||||
$connections = $this->connections();
|
||||
$connections->release($this->cds, true);
|
||||
$connections->release($this->slaveConfig['cds'], false);
|
||||
$pdo = $this->getTransactionClient();
|
||||
if ($pdo->inTransaction()) {
|
||||
$pdo->rollback();
|
||||
}
|
||||
$this->release($pdo);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws
|
||||
* 事务提交
|
||||
*/
|
||||
public function commit(): void
|
||||
{
|
||||
$this->storey--;
|
||||
if ($this->storey == 0) {
|
||||
if (!Context::exists($this->cds)) {
|
||||
return;
|
||||
}
|
||||
$pdo = $this->getTransactionClient();
|
||||
if ($pdo->inTransaction()) {
|
||||
$pdo->commit();
|
||||
}
|
||||
$this->release($pdo);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @throws Exception
|
||||
* @return void
|
||||
* @throws
|
||||
*/
|
||||
public function recovery()
|
||||
public function clear(): void
|
||||
{
|
||||
$connections = $this->connections();
|
||||
|
||||
$connections->release($this->cds, true);
|
||||
$connections->release($this->slaveConfig['cds'], false);
|
||||
/** @var PDO $pdo */
|
||||
$pdo = Context::get($this->cds);
|
||||
if ($pdo === null) {
|
||||
return;
|
||||
}
|
||||
if ($this->inTransaction()) {
|
||||
$pdo->rollback();
|
||||
}
|
||||
$this->release($pdo);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $sql
|
||||
* @param array $attributes
|
||||
* @return Command
|
||||
* @throws
|
||||
*/
|
||||
public function createCommand(string $sql, array $attributes = []): Command
|
||||
{
|
||||
return (new Command(['connection' => $this, 'sql' => $sql]))->bindValues($attributes);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 回收链接
|
||||
* @throws
|
||||
*/
|
||||
public function release(PDO $pdo): void
|
||||
{
|
||||
if (!$this->inTransaction()) {
|
||||
$this->pool()->push($this->cds, $pdo);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
*
|
||||
* 回收链接
|
||||
* @throws
|
||||
*/
|
||||
public function clear_connection()
|
||||
public function clear_connection(): void
|
||||
{
|
||||
$connections = $this->connections();
|
||||
|
||||
$connections->connection_clear($this->cds, true);
|
||||
$connections->connection_clear($this->slaveConfig['cds'], false);
|
||||
$this->pool()->flush($this->cds, 0);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @throws Exception
|
||||
* @throws
|
||||
*/
|
||||
public function disconnect()
|
||||
public function disconnect(): void
|
||||
{
|
||||
$connections = $this->connections();
|
||||
$connections->disconnect($this->cds, true);
|
||||
$connections->disconnect($this->slaveConfig['cds'], false);
|
||||
if ($this->timerId > -1) {
|
||||
Timer::clear($this->timerId);
|
||||
}
|
||||
$this->pool()->close($this->cds);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return PDO
|
||||
*/
|
||||
public function newConnect(): PDO
|
||||
{
|
||||
$pdo = new PDO($this->database, $this->cds, $this->username, $this->password, [
|
||||
\PDO::ATTR_CASE => \PDO::CASE_NATURAL,
|
||||
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
|
||||
\PDO::ATTR_ORACLE_NULLS => \PDO::NULL_NATURAL,
|
||||
\PDO::ATTR_STRINGIFY_FETCHES => false,
|
||||
\PDO::ATTR_EMULATE_PREPARES => true,
|
||||
\PDO::ATTR_TIMEOUT => $this->timeout,
|
||||
\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES ' . $this->charset
|
||||
]);
|
||||
foreach ($this->attributes as $key => $attribute) {
|
||||
$pdo->setAttribute($key, $attribute);
|
||||
}
|
||||
return $pdo;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return Pool
|
||||
*/
|
||||
protected function pool(): Pool
|
||||
{
|
||||
if (!$this->connections->hasChannel($this->cds)) {
|
||||
$this->connections->created($this->cds, $this->pool['max'] ?? 1, [$this, 'newConnect']);
|
||||
}
|
||||
return $this->connections;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+34
-34
@@ -5,12 +5,8 @@ namespace Database;
|
||||
|
||||
|
||||
use Exception;
|
||||
use Kiri\Abstracts\Config;
|
||||
use Kiri;
|
||||
use Kiri\Abstracts\Providers;
|
||||
use Kiri\Application;
|
||||
use Kiri\Exception\ConfigException;
|
||||
use Kiri\Kiri;
|
||||
use Server\Events\OnWorkerStart;
|
||||
|
||||
/**
|
||||
* Class DatabasesProviders
|
||||
@@ -21,69 +17,73 @@ class DatabasesProviders extends Providers
|
||||
|
||||
|
||||
/**
|
||||
* @param Application $application
|
||||
* @throws Exception
|
||||
* @var array
|
||||
*/
|
||||
public function onImport(Application $application)
|
||||
protected array $connections = [];
|
||||
|
||||
|
||||
/**
|
||||
* @return void
|
||||
* @throws
|
||||
*/
|
||||
public function onImport(): void
|
||||
{
|
||||
$this->eventProvider->on(OnWorkerStart::class, [$this, 'createPool']);
|
||||
$main = Kiri::getDi()->get(Kiri\Application::class);
|
||||
$main->command(BackupCommand::class, ImplodeCommand::class);
|
||||
$databases = \config('databases.connections', []);
|
||||
if (count($databases) < 1) {
|
||||
return;
|
||||
}
|
||||
foreach ($databases as $key => $database) {
|
||||
$this->set($key, $this->_settings($database));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $name
|
||||
* @param string $name
|
||||
* @return Connection
|
||||
* @throws Exception
|
||||
*/
|
||||
public function get($name): Connection
|
||||
public function get(string $name): Connection
|
||||
{
|
||||
return Kiri::app()->get($name);
|
||||
return $this->connections[$name];
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @throws ConfigException
|
||||
* @param string $key
|
||||
* @param array $connection
|
||||
* @return void
|
||||
* @throws Exception
|
||||
*/
|
||||
public function createPool(OnWorkerStart $onWorkerStart)
|
||||
protected function set(string $key, array $connection): void
|
||||
{
|
||||
$databases = Config::get('databases.connections', []);
|
||||
if (empty($databases)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$app = Kiri::app();
|
||||
foreach ($databases as $key => $database) {
|
||||
$database = $this->_settings($database);
|
||||
|
||||
$connection = Kiri::getDi()->create(Connection::class, $database);
|
||||
$connection->fill();
|
||||
|
||||
$app->set($key, $connection);
|
||||
}
|
||||
$this->connections[$key] = Kiri::createObject($connection);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $database
|
||||
* @param array $database
|
||||
* @return array
|
||||
*/
|
||||
private function _settings($database): array
|
||||
private function _settings(array $database): array
|
||||
{
|
||||
$clientPool = $database['pool'] ?? ['min' => 1, 'max' => 5, 'tick' => 60];
|
||||
return [
|
||||
'id' => $database['id'],
|
||||
'cds' => $database['cds'],
|
||||
'class' => Connection::class,
|
||||
'username' => $database['username'],
|
||||
'password' => $database['password'],
|
||||
'tablePrefix' => $database['tablePrefix'],
|
||||
'database' => $database['database'],
|
||||
'connect_timeout' => $database['connect_timeout'] ?? 30,
|
||||
'read_timeout' => $database['read_timeout'] ?? 10,
|
||||
'timeout' => $database['timeout'] ?? 10,
|
||||
'tick_time' => $database['tick_time'] ?? 60,
|
||||
'waite_time' => $database['waite_time'] ?? 3,
|
||||
'pool' => $clientPool,
|
||||
'attributes' => $database['attributes'] ?? [],
|
||||
'charset' => $database['charset'] ?? 'utf8mb4',
|
||||
'slaveConfig' => $database['slaveConfig']
|
||||
'charset' => $database['charset'] ?? 'utf8mb4'
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -9,80 +9,85 @@ declare(strict_types=1);
|
||||
|
||||
namespace Database;
|
||||
|
||||
use Closure;
|
||||
use Database\Affair\BeginTransaction;
|
||||
use Database\Affair\Commit;
|
||||
use Database\Affair\Rollback;
|
||||
use Database\Traits\QueryTrait;
|
||||
use Exception;
|
||||
use Kiri\Abstracts\Config;
|
||||
use Kiri\Events\EventDispatch;
|
||||
use Kiri\Exception\ConfigException;
|
||||
use Kiri;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Class Db
|
||||
* @package Database
|
||||
*/
|
||||
class Db implements ISqlBuilder
|
||||
class Db extends QueryTrait implements ISqlBuilder
|
||||
{
|
||||
use QueryTrait;
|
||||
|
||||
|
||||
private static bool $_inTransaction = false;
|
||||
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
* @var Connection|null
|
||||
*/
|
||||
public static function transactionsActive(): bool
|
||||
{
|
||||
return static::$_inTransaction === true;
|
||||
}
|
||||
private ?Connection $connection = null;
|
||||
|
||||
|
||||
/**
|
||||
* @throws Exception
|
||||
* @param string|Connection $dbname
|
||||
* @return Db
|
||||
* @throws
|
||||
*/
|
||||
public static function beginTransaction()
|
||||
public static function connect(string|Connection $dbname): Db
|
||||
{
|
||||
if (!static::transactionsActive()) {
|
||||
di(EventDispatch::class)->dispatch(new BeginTransaction());
|
||||
$db = new Db();
|
||||
if (is_string($dbname)) {
|
||||
$db->connection = Kiri::getDi()->get(DatabasesProviders::class)->get($dbname);
|
||||
} else {
|
||||
$db->connection = $dbname;
|
||||
}
|
||||
static::$_inTransaction = true;
|
||||
return $db;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @throws Exception
|
||||
* @return void
|
||||
* @throws
|
||||
*/
|
||||
public static function commit()
|
||||
public static function beginTransaction(): void
|
||||
{
|
||||
if (static::transactionsActive()) {
|
||||
di(EventDispatch::class)->dispatch(new Commit());
|
||||
}
|
||||
static::$_inTransaction = false;
|
||||
fire(new BeginTransaction());
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @throws Exception
|
||||
* @return void
|
||||
* @throws
|
||||
*/
|
||||
public static function rollback()
|
||||
public static function commit(): void
|
||||
{
|
||||
if (static::transactionsActive()) {
|
||||
di(EventDispatch::class)->dispatch(new Rollback());
|
||||
}
|
||||
static::$_inTransaction = false;
|
||||
fire(new Commit());
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $table
|
||||
*
|
||||
* @return void
|
||||
* @throws
|
||||
*/
|
||||
public static function rollback(): void
|
||||
{
|
||||
fire(new Rollback());
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $table
|
||||
* @param string $database
|
||||
* @return static
|
||||
*/
|
||||
public static function table($table): Db|static
|
||||
public static function table(string $table, string $database = 'db'): Db|static
|
||||
{
|
||||
$connection = new Db();
|
||||
$connection->from($table);
|
||||
return $connection;
|
||||
return self::connect($database)->from($table);
|
||||
}
|
||||
|
||||
|
||||
@@ -101,264 +106,105 @@ class Db implements ISqlBuilder
|
||||
|
||||
|
||||
/**
|
||||
* @param string $column
|
||||
* @return string
|
||||
* @return int
|
||||
*/
|
||||
public static function increment(string $column): string
|
||||
public function count(): int
|
||||
{
|
||||
return '+ ' . $column;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $column
|
||||
* @return string
|
||||
*/
|
||||
public static function decrement(string $column): string
|
||||
{
|
||||
return '- ' . $column;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param Connection|null $connection
|
||||
* @return mixed
|
||||
* @throws Exception
|
||||
*/
|
||||
public function get(Connection $connection = NULL): mixed
|
||||
{
|
||||
$connection = static::getDefaultConnection($connection);
|
||||
|
||||
return $connection->createCommand(SqlBuilder::builder($this)->one())
|
||||
->all();
|
||||
return $this->connection->createCommand(SqlBuilder::builder($this)->count())->rowCount();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $column
|
||||
* @return string
|
||||
* @return bool
|
||||
*/
|
||||
public static function raw($column): string
|
||||
public function exists(): bool
|
||||
{
|
||||
return '`' . $column . '`';
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Connection|null $connection
|
||||
* @return mixed
|
||||
* @throws Exception
|
||||
*/
|
||||
public function find(Connection $connection = NULL): mixed
|
||||
{
|
||||
$connection = static::getDefaultConnection($connection);
|
||||
|
||||
return $connection->createCommand(SqlBuilder::builder($this)->all())
|
||||
->one();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Connection|NULL $connection
|
||||
* @return bool|int
|
||||
* @throws Exception
|
||||
*/
|
||||
public function count(Connection $connection = NULL): bool|int
|
||||
{
|
||||
$connection = static::getDefaultConnection($connection);
|
||||
|
||||
return $connection->createCommand(SqlBuilder::builder($this)->count())
|
||||
->exec();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Connection|NULL $connection
|
||||
* @return bool|int
|
||||
* @throws Exception
|
||||
*/
|
||||
public function exists(Connection $connection = NULL): bool|int
|
||||
{
|
||||
$connection = static::getDefaultConnection($connection);
|
||||
|
||||
return $connection->createCommand(SqlBuilder::builder($this)->one())
|
||||
->fetchColumn();
|
||||
return $this->connection->createCommand(SqlBuilder::builder($this)->one())->rowCount() > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $sql
|
||||
* @param array $attributes
|
||||
* @param Connection|null $connection
|
||||
* @return array|bool|int|string|null
|
||||
* @throws Exception
|
||||
* @throws
|
||||
*/
|
||||
public static function findAllBySql(string $sql, array $attributes = [], Connection $connection = NULL): int|bool|array|string|null
|
||||
public function fetchAll(string $sql, array $attributes = []): int|bool|array|string|null
|
||||
{
|
||||
$connection = static::getDefaultConnection($connection);
|
||||
|
||||
return $connection->createCommand($sql, $attributes)->all();
|
||||
return $this->connection->createCommand($sql, $attributes)->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $sql
|
||||
* @param array $attributes
|
||||
* @param Connection|NULL $connection
|
||||
* @return string|array|bool|int|null
|
||||
* @throws Exception
|
||||
*/
|
||||
public static function findBySql(string $sql, array $attributes = [], Connection $connection = NULL): string|array|bool|int|null
|
||||
{
|
||||
$connection = static::getDefaultConnection($connection);
|
||||
|
||||
return $connection->createCommand($sql, $attributes)->one();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $field
|
||||
* @return array|null
|
||||
* @throws Exception
|
||||
*/
|
||||
public function values(string $field): ?array
|
||||
public function fetch(string $sql, array $attributes = []): ?array
|
||||
{
|
||||
$data = $this->get();
|
||||
if (empty($data) || empty($field)) {
|
||||
return NULL;
|
||||
}
|
||||
$first = current($data);
|
||||
if (!isset($first[$field])) {
|
||||
return NULL;
|
||||
}
|
||||
return array_column($data, $field);
|
||||
return $this->connection->createCommand($sql, $attributes)->one();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $field
|
||||
* @return mixed
|
||||
* @throws Exception
|
||||
* @return bool
|
||||
*/
|
||||
public function value($field): mixed
|
||||
public function delete(): bool
|
||||
{
|
||||
$data = $this->find();
|
||||
if (!empty($field) && isset($data[$field])) {
|
||||
return $data[$field];
|
||||
}
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Connection|null $connection
|
||||
* @return bool|int
|
||||
* @throws ConfigException
|
||||
* @throws Exception
|
||||
*/
|
||||
public function delete(?Connection $connection = null): bool|int
|
||||
{
|
||||
$connection = static::getDefaultConnection($connection);
|
||||
|
||||
return $connection->createCommand($connection->getBuild()->builder($this))->delete();
|
||||
return $this->connection->createCommand(SqlBuilder::builder($this)->delete())->delete();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $table
|
||||
* @param null $connection
|
||||
* @return bool|int
|
||||
* @throws ConfigException
|
||||
* @throws Exception
|
||||
* @return array|bool|null
|
||||
* @throws
|
||||
*/
|
||||
public static function drop(string $table, $connection = null): bool|int
|
||||
public static function show(string $table): array|bool|null
|
||||
{
|
||||
$connection = static::getDefaultConnection($connection);
|
||||
|
||||
$sprint = sprintf('DROP TABLE `%s`.`%s`', $connection->database, $table);
|
||||
return $connection->createCommand($sprint)->delete();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $table
|
||||
* @param null $connection
|
||||
* @return bool|int
|
||||
* @throws Exception
|
||||
*/
|
||||
public static function truncate(string $table, $connection = null): bool|int
|
||||
{
|
||||
$connection = static::getDefaultConnection($connection);
|
||||
|
||||
$sprint = sprintf('TRUNCATE `%s`.`%s`', $connection->database, $table);
|
||||
return $connection->createCommand($sprint)->exec();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $table
|
||||
* @param Connection|NULL $connection
|
||||
* @return mixed
|
||||
* @throws ConfigException
|
||||
* @throws Exception
|
||||
*/
|
||||
public static function showCreateSql(string $table, Connection $connection = NULL): mixed
|
||||
{
|
||||
$connection = static::getDefaultConnection($connection);
|
||||
|
||||
$sprint = sprintf('SHOW CREATE TABLE `%s`.`%s`', $connection->database, $table);
|
||||
return $connection->createCommand($sprint)->one();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $table
|
||||
* @param Connection|NULL $connection
|
||||
* @return bool|int|null
|
||||
* @throws ConfigException
|
||||
* @throws Exception
|
||||
*/
|
||||
public static function desc(string $table, Connection $connection = NULL): bool|int|null
|
||||
{
|
||||
$connection = static::getDefaultConnection($connection);
|
||||
|
||||
$sprint = sprintf('SHOW FULL FIELDS FROM `%s`.`%s`', $connection->database, $table);
|
||||
return $connection->createCommand($sprint)->all();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $table
|
||||
* @param Connection|NULL $connection
|
||||
* @return mixed
|
||||
* @throws Exception
|
||||
*/
|
||||
public static function show(string $table, Connection $connection = NULL): mixed
|
||||
{
|
||||
if (empty($table)) {
|
||||
if ($table == '') {
|
||||
return null;
|
||||
}
|
||||
$connection = static::getDefaultConnection($connection);
|
||||
$connection = static::getDefaultConnection();
|
||||
|
||||
$table = [' const TABLE = \'select * from %s where REFERENCED_TABLE_NAME=%s\';'];
|
||||
return $connection->createCommand((new Query())
|
||||
->select('*')
|
||||
->from('INFORMATION_SCHEMA.KEY_COLUMN_USAGE')
|
||||
->where(['REFERENCED_TABLE_NAME' => $table])
|
||||
->getSql())->one();
|
||||
->build())->one();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $table
|
||||
* @param Connection|null $connection
|
||||
* @param string $database
|
||||
* @return array|null
|
||||
* @throws
|
||||
*/
|
||||
public static function desc(string $table, ?Connection $connection = null, string $database = 'db'): ?array
|
||||
{
|
||||
$sql = SqlBuilder::builder(new Query())->columns($table);
|
||||
|
||||
$connection = self::getDefaultConnection($connection, $database);
|
||||
|
||||
return $connection->createCommand($sql)->all();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param null|Connection $connection
|
||||
* @param null $name
|
||||
* @param string $database
|
||||
* @return mixed
|
||||
* @throws ConfigException
|
||||
* @throws Exception
|
||||
* @throws
|
||||
*/
|
||||
public static function getDefaultConnection(?Connection $connection, $name = null): Connection
|
||||
public static function getDefaultConnection(?Connection $connection = null, string $database = 'db'): Connection
|
||||
{
|
||||
if ($connection instanceof Connection) {
|
||||
return $connection;
|
||||
}
|
||||
$databases = Config::get('databases.connections', []);
|
||||
$databases = \config('databases.connections', []);
|
||||
$providers = Kiri::getDi()->get(DatabasesProviders::class);
|
||||
if (empty($databases) || !is_array($databases)) {
|
||||
throw new Exception('Please configure the database link.');
|
||||
}
|
||||
if (!empty($name)) {
|
||||
if (!isset($databases[$name])) {
|
||||
throw new Exception('Please configure the database link.');
|
||||
}
|
||||
return $databases[$name];
|
||||
}
|
||||
return current($databases);
|
||||
return $providers->get($databases[$database]);
|
||||
}
|
||||
|
||||
|
||||
|
||||
+5
-17
@@ -3,8 +3,9 @@ declare(strict_types=1);
|
||||
|
||||
namespace Database;
|
||||
|
||||
use Exception;
|
||||
use Database\Traits\HasBase;
|
||||
use Exception;
|
||||
use Kiri;
|
||||
|
||||
/**
|
||||
* Class HasCount
|
||||
@@ -13,27 +14,14 @@ use Database\Traits\HasBase;
|
||||
class HasCount extends HasBase
|
||||
{
|
||||
|
||||
/**
|
||||
* @param $name
|
||||
* @param $arguments
|
||||
* @return ActiveQuery
|
||||
* @throws Exception
|
||||
*/
|
||||
public function __call($name, $arguments): mixed
|
||||
{
|
||||
if (method_exists($this, $name)) {
|
||||
return call_user_func([$this, $name], ...$arguments);
|
||||
}
|
||||
return $this->_relation->getQuery($this->model::className())->$name(...$arguments);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array|null|ModelInterface
|
||||
* @throws Exception
|
||||
* @throws
|
||||
*/
|
||||
public function get(): array|ModelInterface|null
|
||||
{
|
||||
return $this->_relation->count($this->model::className(), $this->value);
|
||||
$relation = Kiri::getDi()->get(Relation::class);
|
||||
return $relation->get($this->name);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+8
-18
@@ -6,10 +6,12 @@
|
||||
* Time: 13:58
|
||||
*/
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database;
|
||||
|
||||
use Exception;
|
||||
use Database\Traits\HasBase;
|
||||
use Exception;
|
||||
use Kiri;
|
||||
|
||||
/**
|
||||
* Class HasMany
|
||||
@@ -21,24 +23,12 @@ class HasMany extends HasBase
|
||||
{
|
||||
|
||||
/**
|
||||
* @param $name
|
||||
* @param $arguments
|
||||
* @return ActiveQuery
|
||||
* @return array|null|Collection
|
||||
* @throws
|
||||
*/
|
||||
public function __call($name, $arguments): mixed
|
||||
public function get(): array|Collection|null
|
||||
{
|
||||
if (method_exists($this, $name)) {
|
||||
return call_user_func([$this, $name], ...$arguments);
|
||||
}
|
||||
return $this->_relation->getQuery($this->model::className())->$name(...$arguments);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array|null|ModelInterface
|
||||
* @throws Exception
|
||||
*/
|
||||
public function get(): array|ModelInterface|null
|
||||
{
|
||||
return $this->_relation->get($this->model::className(), $this->value);
|
||||
$relation = Kiri::getDi()->get(Relation::class);
|
||||
return $relation->get($this->name);
|
||||
}
|
||||
}
|
||||
|
||||
+5
-17
@@ -9,8 +9,9 @@ declare(strict_types=1);
|
||||
|
||||
namespace Database;
|
||||
|
||||
use Exception;
|
||||
use Database\Traits\HasBase;
|
||||
use Exception;
|
||||
use Kiri;
|
||||
|
||||
/**
|
||||
* Class HasOne
|
||||
@@ -20,26 +21,13 @@ use Database\Traits\HasBase;
|
||||
class HasOne extends HasBase
|
||||
{
|
||||
|
||||
/**
|
||||
* @param $name
|
||||
* @param $arguments
|
||||
* @return ActiveQuery
|
||||
*/
|
||||
public function __call($name, $arguments): mixed
|
||||
{
|
||||
if (method_exists($this, $name)) {
|
||||
return call_user_func([$this, $name], ...$arguments);
|
||||
}
|
||||
$this->_relation->getQuery($this->model::className())->$name(...$arguments);
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array|null|ModelInterface
|
||||
* @throws Exception
|
||||
* @throws
|
||||
*/
|
||||
public function get(): array|ModelInterface|null
|
||||
{
|
||||
return $this->_relation->first($this->model::className(), $this->value);
|
||||
$relation = Kiri::getDi()->get(Relation::class);
|
||||
return $relation->first($this->name);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database;
|
||||
|
||||
use Co\Channel;
|
||||
use Exception;
|
||||
use Swoole\Coroutine;
|
||||
use Symfony\Component\Console\Command\Command;
|
||||
use Symfony\Component\Console\Input\InputArgument;
|
||||
use Symfony\Component\Console\Input\InputInterface;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
class ImplodeCommand extends Command
|
||||
{
|
||||
|
||||
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
public string $command = 'db:implode';
|
||||
|
||||
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
public string $description = 'php kiri.php db:implode --database users /Users/admin/snowflake-bi/test.sql';
|
||||
|
||||
|
||||
/**
|
||||
* @var Channel
|
||||
*/
|
||||
protected Channel $channel;
|
||||
|
||||
protected array $data;
|
||||
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
protected function configure(): void
|
||||
{
|
||||
$this->setName('db:implode')
|
||||
->addArgument('path', InputArgument::REQUIRED, "save to path", null)
|
||||
->addOption('database', 'db', InputArgument::OPTIONAL)
|
||||
->setDescription('php kiri.php db:implode --database users /Users/admin/snowflake-bi/test.sql');
|
||||
$this->data = array_flip(get_html_translation_table(ENT_QUOTES | ENT_SUBSTITUTE));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param InputInterface $input
|
||||
* @param OutputInterface $output
|
||||
* @return int
|
||||
* @throws
|
||||
*/
|
||||
public function execute(InputInterface $input, OutputInterface $output): int
|
||||
{
|
||||
try {
|
||||
/** @var Connection $data */
|
||||
$data = \Kiri::getDi()->get(DatabasesProviders::class)->get($input->getOption('database'));
|
||||
|
||||
$path = $input->getArgument('path');
|
||||
if (!str_starts_with($path, '/')) {
|
||||
$path = APP_PATH . $path;
|
||||
}
|
||||
|
||||
$waite = new Coroutine\WaitGroup();
|
||||
$stream = fopen($path, 'r');
|
||||
if ($stream) {
|
||||
while (($line = fgets($stream)) !== false) {
|
||||
if (!str_starts_with(strtoupper($line), 'INSERT INTO')) {
|
||||
continue;
|
||||
}
|
||||
$waite->add();
|
||||
$insert = str_replace(''', "\'", str_replace('"', '"', $line));
|
||||
|
||||
$insert = strtr($insert, $this->data);
|
||||
Coroutine::create(function () use ($waite, $insert, $data) {
|
||||
Coroutine\defer(fn() => $waite->done());
|
||||
$data->createCommand($insert)->exec();
|
||||
});
|
||||
}
|
||||
fclose($stream);
|
||||
}
|
||||
$waite->wait();
|
||||
|
||||
$output->write('dump data success');
|
||||
} catch (\Throwable $throwable) {
|
||||
$output->writeln(throwable($throwable));
|
||||
} finally {
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -10,14 +10,8 @@ declare(strict_types=1);
|
||||
namespace Database;
|
||||
|
||||
|
||||
use Database\Base\Getter;
|
||||
use Database\Traits\HasBase;
|
||||
use Database\Base\ActiveQueryInterface;
|
||||
use Exception;
|
||||
use Kiri\Exception\NotFindClassException;
|
||||
use Kiri\Kiri;
|
||||
use Kiri\ToArray;
|
||||
use ReflectionException;
|
||||
use Swoole\Coroutine;
|
||||
|
||||
defined('SAVE_FAIL') or define('SAVE_FAIL', 3227);
|
||||
defined('FIND_OR_CREATE_MESSAGE') or define('FIND_OR_CREATE_MESSAGE', 'Create a new model, but the data cannot be empty.');
|
||||
@@ -28,6 +22,8 @@ defined('FIND_OR_CREATE_MESSAGE') or define('FIND_OR_CREATE_MESSAGE', 'Create a
|
||||
*
|
||||
* @property $attributes
|
||||
* @property-read $oldAttributes
|
||||
*
|
||||
* @mixin ActiveQueryInterface
|
||||
*/
|
||||
class Model extends Base\Model
|
||||
{
|
||||
@@ -35,11 +31,11 @@ class Model extends Base\Model
|
||||
|
||||
/**
|
||||
* @param string $column
|
||||
* @param int $value
|
||||
* @param int|float $value
|
||||
* @return ModelInterface|false
|
||||
* @throws Exception
|
||||
* @throws
|
||||
*/
|
||||
public function increment(string $column, int $value): bool|ModelInterface
|
||||
public function increment(string $column, int|float $value): bool|ModelInterface
|
||||
{
|
||||
if (!$this->mathematics([$column => $value], '+')) {
|
||||
return false;
|
||||
@@ -51,11 +47,11 @@ class Model extends Base\Model
|
||||
|
||||
/**
|
||||
* @param string $column
|
||||
* @param int $value
|
||||
* @param int|float $value
|
||||
* @return ModelInterface|false
|
||||
* @throws Exception
|
||||
* @throws
|
||||
*/
|
||||
public function decrement(string $column, int $value): bool|ModelInterface
|
||||
public function decrement(string $column, int|float $value): bool|ModelInterface
|
||||
{
|
||||
if (!$this->mathematics([$column => $value], '-')) {
|
||||
return false;
|
||||
@@ -68,7 +64,7 @@ class Model extends Base\Model
|
||||
/**
|
||||
* @param array $columns
|
||||
* @return ModelInterface|false
|
||||
* @throws Exception
|
||||
* @throws
|
||||
*/
|
||||
public function increments(array $columns): bool|static
|
||||
{
|
||||
@@ -85,7 +81,7 @@ class Model extends Base\Model
|
||||
/**
|
||||
* @param array $columns
|
||||
* @return ModelInterface|false
|
||||
* @throws Exception
|
||||
* @throws
|
||||
*/
|
||||
public function decrements(array $columns): bool|static
|
||||
{
|
||||
@@ -101,31 +97,28 @@ class Model extends Base\Model
|
||||
/**
|
||||
* @param array $condition
|
||||
* @param array $attributes
|
||||
* @return bool|ModelInterface
|
||||
* @throws ReflectionException
|
||||
* @throws NotFindClassException
|
||||
* @throws Exception
|
||||
* @return bool|static
|
||||
* @throws
|
||||
*/
|
||||
public static function findOrCreate(array $condition, array $attributes): bool|static
|
||||
{
|
||||
$logger = Kiri::app()->getLogger();
|
||||
if (empty($attributes)) {
|
||||
return $logger->addError(FIND_OR_CREATE_MESSAGE, 'mysql');
|
||||
}
|
||||
Db::beginTransaction();
|
||||
$model = static::instance();
|
||||
$connection = $model->getConnection()->beginTransaction();
|
||||
try {
|
||||
/** @var static $select */
|
||||
$select = static::query()->where($condition)->first();
|
||||
if (empty($select)) {
|
||||
$select = duplicate(static::class);
|
||||
$select->attributes = $attributes;
|
||||
$select->setIsNowExample(true);
|
||||
$select = $model::query()->where($condition)->first();
|
||||
if ($select === null) {
|
||||
$select = $model::populate(array_merge($condition, $attributes));
|
||||
if (!$select->save()) {
|
||||
Db::rollback();
|
||||
return $logger->addError($select->getLastError(), 'mysql');
|
||||
throw new Exception('保存失败: ' . $model->getLastError());
|
||||
}
|
||||
}
|
||||
Db::commit();
|
||||
$connection->commit();
|
||||
return $select;
|
||||
} catch (\Throwable $throwable) {
|
||||
$connection->rollback();
|
||||
return \Kiri::getLogger()->failure($throwable);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -133,266 +126,214 @@ class Model extends Base\Model
|
||||
* @param array $condition
|
||||
* @param array $attributes
|
||||
* @return bool|static
|
||||
* @throws Exception
|
||||
* @throws
|
||||
*/
|
||||
public static function createOrUpdate(array $condition, array $attributes = []): bool|static
|
||||
{
|
||||
$logger = Kiri::app()->getLogger();
|
||||
if (empty($attributes)) {
|
||||
return $logger->addError(FIND_OR_CREATE_MESSAGE, 'mysql');
|
||||
}
|
||||
|
||||
Db::beginTransaction();
|
||||
$model = static::instance();
|
||||
$connection = $model->getConnection()->beginTransaction();
|
||||
try {
|
||||
/** @var static $select */
|
||||
$select = static::query()->where($condition)->first();
|
||||
if (empty($select)) {
|
||||
$select = duplicate(static::class);
|
||||
$select = static::populate($condition);
|
||||
}
|
||||
$select->attributes = $attributes;
|
||||
if (!$select->save()) {
|
||||
Db::rollback();
|
||||
$select = $logger->addError($select->getLastError(), 'mysql');
|
||||
} else {
|
||||
Db::commit();
|
||||
throw new Exception('保存失败: ' . $model->getLastError());
|
||||
}
|
||||
$connection->commit();
|
||||
return $select;
|
||||
} catch (\Throwable $throwable) {
|
||||
$connection->rollback();
|
||||
return \Kiri::getLogger()->failure($throwable);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $action
|
||||
* @param $columns
|
||||
* @param null|array $condition
|
||||
* @return array|bool|int|string|null
|
||||
* @throws Exception
|
||||
* @param string $name
|
||||
* @param array $arguments
|
||||
* @return Model|ActiveQuery
|
||||
*/
|
||||
private function mathematics($columns, $action, ?array $condition = null): int|bool|array|string|null
|
||||
public static function __callStatic(string $name, array $arguments): static|ActiveQuery
|
||||
{
|
||||
if (empty($condition)) {
|
||||
$condition = [$this->getPrimary() => $this->getPrimaryValue()];
|
||||
// TODO: Change the autogenerated stub
|
||||
if (method_exists(static::class, $name)) {
|
||||
return call_user_func(static::class . '::' . $name, ...$arguments);
|
||||
} else {
|
||||
return static::query()->{$name}(...$arguments);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param array $columns
|
||||
* @param string $action
|
||||
* @return array|bool|int|string|null
|
||||
*/
|
||||
private function mathematics(array $columns, string $action): int|bool|array|string|null
|
||||
{
|
||||
$condition = [$this->getPrimary() => $this->getPrimaryValue()];
|
||||
$activeQuery = static::query()->where($condition);
|
||||
$create = SqlBuilder::builder($activeQuery)->mathematics($columns, $action);
|
||||
if (is_bool($create)) {
|
||||
return false;
|
||||
}
|
||||
return $this->getConnection()->createCommand($create[0], $create[1])->exec();
|
||||
return $activeQuery->buildCommand($create)->exec();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param array $fields
|
||||
* @param array $params
|
||||
* @return ModelInterface|bool
|
||||
* @throws Exception
|
||||
* @throws
|
||||
*/
|
||||
public function update(array $fields): static|bool
|
||||
public function update(array $params): static|bool
|
||||
{
|
||||
return $this->save($fields);
|
||||
if (!$this->validator($this->rules(), $params) || !$this->beforeSave($this)) {
|
||||
return FALSE;
|
||||
}
|
||||
return $this->updateInternal(...$this->arrayIntersect($params));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param array $data
|
||||
* @return bool
|
||||
* @throws Exception
|
||||
* @throws
|
||||
*/
|
||||
public static function inserts(array $data): bool
|
||||
{
|
||||
$result = false;
|
||||
if (empty($data)) {
|
||||
error('Insert data empty.', 'mysql');
|
||||
} else {
|
||||
$result = static::query()->batchInsert($data);
|
||||
return trigger_print_error('Insert data empty.', 'mysql');
|
||||
}
|
||||
return $result;
|
||||
return static::query()->insert($data);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
* @throws Exception
|
||||
* @throws
|
||||
*/
|
||||
public function delete(): bool
|
||||
{
|
||||
$primary = $this->getPrimary();
|
||||
if (empty($primary) || !$this->hasPrimaryValue()) {
|
||||
return $this->addError("Only primary key operations are supported.", 'mysql');
|
||||
}
|
||||
if (!$this->beforeDelete()) {
|
||||
$result = static::deleteByCondition([$primary => $this->getPrimaryValue()]);
|
||||
Coroutine::create(function () use ($result) {
|
||||
$this->afterDelete($result);
|
||||
});
|
||||
return $result;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param mixed $condition
|
||||
* @param array $attributes
|
||||
*
|
||||
* @return bool
|
||||
* @throws NotFindClassException
|
||||
* @throws ReflectionException
|
||||
* @throws Exception
|
||||
*/
|
||||
public static function updateAll(mixed $condition, array $attributes = []): bool
|
||||
{
|
||||
$condition = static::query()->where($condition);
|
||||
return $condition->batchUpdate($attributes);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $condition
|
||||
* @return array|Collection
|
||||
* @throws NotFindClassException
|
||||
* @throws ReflectionException
|
||||
*/
|
||||
public static function get($condition): Collection|array
|
||||
{
|
||||
return static::query()->where($condition)->all();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $condition
|
||||
* @param array $attributes
|
||||
*
|
||||
* @return array|Collection
|
||||
* @throws Exception
|
||||
*/
|
||||
public static function findAll($condition, array $attributes = []): array|Collection
|
||||
{
|
||||
$query = static::query()->where($condition);
|
||||
if (!empty($attributes)) {
|
||||
$query->bindParams($attributes);
|
||||
}
|
||||
return $query->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $method
|
||||
* @return mixed
|
||||
* @throws Exception
|
||||
*/
|
||||
private function withRelation($method): mixed
|
||||
{
|
||||
$method = $this->getRelate($method);
|
||||
if (empty($method)) {
|
||||
return null;
|
||||
}
|
||||
$resolve = $this->{$method}();
|
||||
if ($resolve instanceof HasBase) {
|
||||
$resolve = $resolve->get();
|
||||
}
|
||||
if ($resolve instanceof ToArray) {
|
||||
return $resolve->toArray();
|
||||
} else if (is_object($resolve)) {
|
||||
return get_object_vars($resolve);
|
||||
if ($this->hasPrimary()) {
|
||||
$result = static::deleteByCondition(['id' => $this->getPrimaryValue()]);
|
||||
} else {
|
||||
return $resolve;
|
||||
$result = static::deleteByCondition($this->_attributes);
|
||||
}
|
||||
return $this->afterDelete($result);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return array
|
||||
* @throws Exception
|
||||
* @throws
|
||||
*/
|
||||
public function toArray(): array
|
||||
{
|
||||
$data = $this->_attributes;
|
||||
$lists = di(Getter::class)->getGetter(static::class);
|
||||
foreach ($lists as $key => $item) {
|
||||
$data[$key] = $this->{$item}($data[$key] ?? null);
|
||||
foreach ($data as $key => $datum) {
|
||||
$method = 'get' . ucfirst($key) . 'Attribute';
|
||||
if (!method_exists($this, $method)) {
|
||||
continue;
|
||||
}
|
||||
return $this->withRelates($data);
|
||||
$data[$key] = $this->{$method}($datum);
|
||||
}
|
||||
return $this->withs($data);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $relates
|
||||
* @param array $data
|
||||
* @return array
|
||||
*/
|
||||
private function withs(array $data): array
|
||||
{
|
||||
$with = $this->getWith();
|
||||
foreach ($with as $value) {
|
||||
$join = $this->withRelate($value);
|
||||
if ($join instanceof \Arrayable) {
|
||||
$join = $join->toArray();
|
||||
}
|
||||
$data[$value] = $join;
|
||||
}
|
||||
return $data;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param ModelInterface|string $modelName
|
||||
* @param string $foreignKey
|
||||
* @param string $localKey
|
||||
* @return string
|
||||
* @throws Exception
|
||||
*/
|
||||
private function withRelates($relates): array
|
||||
private function _hasBase(ModelInterface|string $modelName, string $foreignKey, string $localKey): string
|
||||
{
|
||||
if (empty($with = $this->getWith())) {
|
||||
return $relates;
|
||||
if (($value = $this->{$localKey}) === null) {
|
||||
throw new Exception("Need join table primary key.");
|
||||
}
|
||||
foreach ($with as $val) {
|
||||
$relates[$val] = $this->withRelation($val);
|
||||
|
||||
$relation = $this->getRelation();
|
||||
|
||||
$primaryKey = $modelName . $foreignKey . $value;
|
||||
if (!$relation->hasIdentification($primaryKey)) {
|
||||
$relation->bindIdentification($primaryKey, $modelName::query()->where([$foreignKey => $value]));
|
||||
}
|
||||
return $relates;
|
||||
return $primaryKey;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $modelName
|
||||
* @param $foreignKey
|
||||
* @param $localKey
|
||||
* @param ModelInterface|string $modelName
|
||||
* @param string $foreignKey
|
||||
* @param string $localKey
|
||||
* @return HasOne|ActiveQuery
|
||||
* @throws Exception
|
||||
*/
|
||||
public function hasOne(string $modelName, $foreignKey, $localKey): HasOne|ActiveQuery
|
||||
public function hasOne(ModelInterface|string $modelName, string $foreignKey, string $localKey): HasOne|ActiveQuery
|
||||
{
|
||||
if (($value = $this->{$localKey}) === null) {
|
||||
throw new Exception("Need join table primary key.");
|
||||
}
|
||||
|
||||
$relation = $this->getRelation();
|
||||
|
||||
return new HasOne($modelName, $foreignKey, $value, $relation);
|
||||
return new HasOne($this->_hasBase($modelName, $foreignKey, $localKey));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $modelName
|
||||
* @param $foreignKey
|
||||
* @param $localKey
|
||||
* @param ModelInterface|string $modelName
|
||||
* @param string $foreignKey
|
||||
* @param string $localKey
|
||||
* @return ActiveQuery|HasCount
|
||||
* @throws Exception
|
||||
*/
|
||||
public function hasCount($modelName, $foreignKey, $localKey): ActiveQuery|HasCount
|
||||
public function hasCount(ModelInterface|string $modelName, string $foreignKey, string $localKey): ActiveQuery|HasCount
|
||||
{
|
||||
if (($value = $this->{$localKey}) === null) {
|
||||
throw new Exception("Need join table primary key.");
|
||||
}
|
||||
|
||||
$relation = $this->getRelation();
|
||||
|
||||
return new HasCount($modelName, $foreignKey, $value, $relation);
|
||||
return new HasCount($this->_hasBase($modelName, $foreignKey, $localKey));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $modelName
|
||||
* @param $foreignKey
|
||||
* @param $localKey
|
||||
* @param ModelInterface|string $modelName
|
||||
* @param string $foreignKey
|
||||
* @param string $localKey
|
||||
* @return ActiveQuery|HasMany
|
||||
* @throws Exception
|
||||
*/
|
||||
public function hasMany($modelName, $foreignKey, $localKey): ActiveQuery|HasMany
|
||||
public function hasMany(ModelInterface|string $modelName, string $foreignKey, string $localKey): ActiveQuery|HasMany
|
||||
{
|
||||
if (($value = $this->{$localKey}) === null) {
|
||||
throw new Exception("Need join table primary key.");
|
||||
}
|
||||
|
||||
$relation = $this->getRelation();
|
||||
|
||||
return new HasMany($modelName, $foreignKey, $value, $relation);
|
||||
return new HasMany($this->_hasBase($modelName, $foreignKey, $localKey));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $modelName
|
||||
* @param $foreignKey
|
||||
* @param $localKey
|
||||
* @param ModelInterface|string $modelName
|
||||
* @param string $foreignKey
|
||||
* @param string $localKey
|
||||
* @return ActiveQuery|HasMany
|
||||
* @throws Exception
|
||||
*/
|
||||
public function hasIn($modelName, $foreignKey, $localKey): ActiveQuery|HasMany
|
||||
public function hasIn(ModelInterface|string $modelName, string $foreignKey, string $localKey): ActiveQuery|HasMany
|
||||
{
|
||||
if (($value = $this->{$localKey}) === null) {
|
||||
throw new Exception("Need join table primary key.");
|
||||
@@ -400,15 +341,21 @@ class Model extends Base\Model
|
||||
|
||||
$relation = $this->getRelation();
|
||||
|
||||
return new HasMany($modelName, $foreignKey, $value, $relation);
|
||||
$primaryKey = $modelName . $foreignKey . json_encode($value, JSON_UNESCAPED_UNICODE);
|
||||
if (!$relation->hasIdentification($primaryKey)) {
|
||||
$relation->bindIdentification($primaryKey, $modelName::query()->whereIn($foreignKey, $value));
|
||||
}
|
||||
|
||||
return new HasMany($primaryKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param bool $result
|
||||
* @return void
|
||||
* @return bool
|
||||
*/
|
||||
public function afterDelete(bool $result): void
|
||||
public function afterDelete(bool $result): bool
|
||||
{
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+62
-7
@@ -18,18 +18,23 @@ interface ModelInterface
|
||||
{
|
||||
|
||||
/**
|
||||
* @param $param
|
||||
* @param null $db
|
||||
* @return ModelInterface
|
||||
* @param array|string|int $param
|
||||
* @return ModelInterface|null
|
||||
*/
|
||||
public static function findOne($param, $db = NULL): mixed;
|
||||
public static function findOne(array|string|int $param): ?static;
|
||||
|
||||
|
||||
/**
|
||||
* @param string|int $param
|
||||
* @return ModelInterface
|
||||
* @return mixed
|
||||
*/
|
||||
public static function find(string|int $param): mixed;
|
||||
public function optimize(): mixed;
|
||||
|
||||
|
||||
/**
|
||||
* @param int $param
|
||||
* @return ModelInterface|null
|
||||
*/
|
||||
public static function primary(int $param): ?static;
|
||||
|
||||
|
||||
/**
|
||||
@@ -46,6 +51,12 @@ interface ModelInterface
|
||||
public static function query(): ActiveQuery;
|
||||
|
||||
|
||||
/**
|
||||
* @return ?string
|
||||
*/
|
||||
public function getPrimary(): ?string;
|
||||
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
@@ -58,4 +69,48 @@ interface ModelInterface
|
||||
public function getConnection(): Connection;
|
||||
|
||||
|
||||
/**
|
||||
* @param string $field
|
||||
* @return mixed
|
||||
*/
|
||||
public function getAttribute(string $field): mixed;
|
||||
|
||||
/**
|
||||
* @param string $field
|
||||
* @return mixed
|
||||
*/
|
||||
public function getOldAttribute(string $field): mixed;
|
||||
|
||||
|
||||
/**
|
||||
* @param string $field
|
||||
* @param mixed $value
|
||||
* @return mixed
|
||||
*/
|
||||
public function setAttribute(string $field, mixed $value): mixed;
|
||||
|
||||
/**
|
||||
* @param string $field
|
||||
* @param mixed $value
|
||||
* @return mixed
|
||||
*/
|
||||
public function setOldAttribute(string $field, mixed $value): mixed;
|
||||
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
public function getOldAttributes(): array;
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
public function getAttributes(): array;
|
||||
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
public function getChanges(): array;
|
||||
|
||||
}
|
||||
|
||||
@@ -1,406 +0,0 @@
|
||||
<?php
|
||||
/**
|
||||
* Created by PhpStorm.
|
||||
* User: admin
|
||||
* Date: 2019-03-18
|
||||
* Time: 17:22
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database\Mysql;
|
||||
|
||||
|
||||
use Database\Connection;
|
||||
use Database\SqlBuilder;
|
||||
use Exception;
|
||||
use JetBrains\PhpStorm\Pure;
|
||||
use Kiri\Abstracts\Component;
|
||||
use Kiri\Core\Json;
|
||||
|
||||
/**
|
||||
* Class Columns
|
||||
* @package Database\Mysql
|
||||
*/
|
||||
class Columns extends Component
|
||||
{
|
||||
|
||||
/**
|
||||
* @var array
|
||||
* field types
|
||||
*/
|
||||
private array $columns = [];
|
||||
|
||||
/**
|
||||
* @var Connection
|
||||
* Mysql client
|
||||
*/
|
||||
public Connection $db;
|
||||
|
||||
/**
|
||||
* @var string
|
||||
* tableName
|
||||
*/
|
||||
public string $table = '';
|
||||
|
||||
/**
|
||||
* @var array
|
||||
* field primary key
|
||||
*/
|
||||
private array $_primary = [];
|
||||
|
||||
/**
|
||||
* @var array
|
||||
* by mysql field auto_increment
|
||||
*/
|
||||
private array $_auto_increment = [];
|
||||
|
||||
|
||||
private array $_fields = [];
|
||||
|
||||
/**
|
||||
* @param string $table
|
||||
* @return $this
|
||||
* @throws Exception
|
||||
*/
|
||||
public function table(string $table): static
|
||||
{
|
||||
$this->structure($this->table = $table);
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getTable(): string
|
||||
{
|
||||
return $this->table;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $key
|
||||
* @param $val
|
||||
* @return mixed
|
||||
* @throws Exception
|
||||
*/
|
||||
public function fieldFormat($key, $val): mixed
|
||||
{
|
||||
return $this->encode($val, $this->get_fields($key));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $data
|
||||
* @return array
|
||||
* @throws
|
||||
*/
|
||||
public function populate($data): array
|
||||
{
|
||||
$column = $this->get_fields();
|
||||
foreach ($data as $key => $val) {
|
||||
if (!isset($column[$key])) {
|
||||
continue;
|
||||
}
|
||||
$data[$key] = $this->decode($val, $column[$key]);
|
||||
}
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $val
|
||||
* @param null $format
|
||||
* @return mixed
|
||||
*/
|
||||
public function decode($val, $format = null): mixed
|
||||
{
|
||||
if (empty($format) || $val === null) {
|
||||
return $val;
|
||||
}
|
||||
$format = strtolower($format);
|
||||
if ($this->isInt($format)) {
|
||||
return (int)$val;
|
||||
} else if ($this->isJson($format)) {
|
||||
return Json::decode($val, true);
|
||||
} else if ($this->isFloat($format)) {
|
||||
return (float)$val;
|
||||
} else {
|
||||
return stripslashes($val);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $name
|
||||
* @param $value
|
||||
* @return mixed
|
||||
* @throws Exception
|
||||
*/
|
||||
public function _decode(string $name, $value): mixed
|
||||
{
|
||||
return $this->decode($value, $this->get_fields($name));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $val
|
||||
* @param null $format
|
||||
* @return float|bool|int|string
|
||||
* @throws Exception
|
||||
*/
|
||||
public function encode($val, $format = null): float|bool|int|string
|
||||
{
|
||||
if (empty($format)) {
|
||||
return $val;
|
||||
}
|
||||
$format = strtolower($format);
|
||||
if ($this->isInt($format)) {
|
||||
return (int)$val;
|
||||
} else if ($this->isJson($format)) {
|
||||
return Json::encode($val);
|
||||
} else if ($this->isFloat($format)) {
|
||||
return (float)$val;
|
||||
} else {
|
||||
return addslashes($val);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $format
|
||||
* @return bool
|
||||
*/
|
||||
#[Pure] public function isInt($format): bool
|
||||
{
|
||||
return in_array($format, ['int', 'bigint', 'tinyint', 'smallint', 'mediumint']);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $format
|
||||
* @return bool
|
||||
*/
|
||||
#[Pure] public function isFloat($format): bool
|
||||
{
|
||||
return in_array($format, ['float', 'double', 'decimal']);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $format
|
||||
* @return bool
|
||||
*/
|
||||
#[Pure] public function isJson($format): bool
|
||||
{
|
||||
return in_array($format, ['json']);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $format
|
||||
* @return bool
|
||||
*/
|
||||
#[Pure] public function isString($format): bool
|
||||
{
|
||||
return in_array($format, ['varchar', 'char', 'text', 'longtext', 'tinytext', 'mediumtext']);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return array
|
||||
* @throws
|
||||
*/
|
||||
public function format(): array
|
||||
{
|
||||
return $this->columns('Default', 'Field');
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return mixed
|
||||
* @throws Exception
|
||||
*/
|
||||
public function getFields(): array
|
||||
{
|
||||
if (empty($this->_fields)) {
|
||||
$this->structure($this->table);
|
||||
}
|
||||
return $this->_fields[$this->table];
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $name
|
||||
* @return bool
|
||||
* @throws Exception
|
||||
*/
|
||||
public function hasField(string $name): bool
|
||||
{
|
||||
return array_key_exists($name, $this->getFields());
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return int|string|null
|
||||
* @throws Exception
|
||||
*/
|
||||
public function getAutoIncrement(): int|string|null
|
||||
{
|
||||
return $this->_auto_increment[$this->table] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array|null|string
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
public function getPrimaryKeys(): array|string|null
|
||||
{
|
||||
if (isset($this->_auto_increment[$this->table])) {
|
||||
return $this->_auto_increment[$this->table];
|
||||
}
|
||||
return $this->_primary[$this->table] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array|null|string
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
#[Pure] public function getFirstPrimary(): array|string|null
|
||||
{
|
||||
if (isset($this->_auto_increment[$this->table])) {
|
||||
return $this->_auto_increment[$this->table];
|
||||
}
|
||||
if (isset($this->_primary[$this->table])) {
|
||||
return current($this->_primary[$this->table]);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $name
|
||||
* @param null $index
|
||||
* @return array
|
||||
* @throws Exception
|
||||
*/
|
||||
private function columns($name, $index = null): array
|
||||
{
|
||||
if (empty($index)) {
|
||||
return array_column($this->getColumns(), $name);
|
||||
} else {
|
||||
return array_column($this->getColumns(), $name, $index);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array|static
|
||||
* @throws Exception
|
||||
*/
|
||||
private function getColumns(): array|static
|
||||
{
|
||||
return $this->structure($this->getTable());
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $table
|
||||
* @return array|Columns
|
||||
* @throws Exception
|
||||
*/
|
||||
private function structure($table): array|static
|
||||
{
|
||||
if (!isset($this->columns[$table]) || empty($this->columns[$table])) {
|
||||
$column = $this->db->createCommand(SqlBuilder::builder(null)->columns($table))->all();
|
||||
if (empty($column)) {
|
||||
throw new Exception("The table " . $table . " not exists.");
|
||||
}
|
||||
return $this->columns[$table] = $this->resolve($column, $table);
|
||||
}
|
||||
return $this->columns[$table];
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param array $column
|
||||
* @param $table
|
||||
* @return array
|
||||
*/
|
||||
private function resolve(array $column, $table): array
|
||||
{
|
||||
foreach ($column as $key => $item) {
|
||||
$this->addPrimary($item, $table);
|
||||
$column[$key]['Type'] = $this->clean($item['Type']);
|
||||
}
|
||||
|
||||
$this->_fields[$table] = array_column($column, 'Default', 'Field');
|
||||
|
||||
return $column;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $item
|
||||
* @param $table
|
||||
*/
|
||||
private function addPrimary($item, $table)
|
||||
{
|
||||
if (!isset($this->_primary[$table])) {
|
||||
$this->_primary[$table] = [];
|
||||
}
|
||||
if ($item['Key'] === 'PRI') {
|
||||
$this->_primary[$table][] = $item['Field'];
|
||||
}
|
||||
$this->addIncrement($item, $table);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $item
|
||||
* @param $table
|
||||
*/
|
||||
private function addIncrement($item, $table)
|
||||
{
|
||||
if ($item['Extra'] !== 'auto_increment') {
|
||||
return;
|
||||
}
|
||||
$this->_auto_increment[$table] = $item['Field'];
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $type
|
||||
* @return string
|
||||
*/
|
||||
public function clean($type): string
|
||||
{
|
||||
if (!str_contains($type, ')')) {
|
||||
return $type;
|
||||
}
|
||||
$replace = preg_replace('/\(\d+(,\d+)?\)(\s+\w+)*/', '', $type);
|
||||
if (str_contains($replace, ' ')) {
|
||||
$replace = explode(' ', $replace)[1];
|
||||
}
|
||||
return $replace;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param null $field
|
||||
* @return array|string|null
|
||||
* @throws Exception
|
||||
*/
|
||||
public function get_fields($field = null): array|string|null
|
||||
{
|
||||
$fields = $this->getAllField();
|
||||
if (empty($field)) {
|
||||
return $fields;
|
||||
}
|
||||
if (isset($fields[$field])) {
|
||||
return strtolower($fields[$field]);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array
|
||||
* @throws Exception
|
||||
*/
|
||||
public function getAllField(): array
|
||||
{
|
||||
return $this->columns('Type', 'Field');
|
||||
}
|
||||
|
||||
}
|
||||
-324
@@ -1,324 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Database\Mysql;
|
||||
|
||||
use Exception;
|
||||
use Kiri\Abstracts\Config;
|
||||
use Kiri\Abstracts\Logger;
|
||||
use Kiri\Kiri;
|
||||
use Kiri\Pool\StopHeartbeatCheck;
|
||||
use PDOStatement;
|
||||
use Swoole\Timer;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
class PDO implements StopHeartbeatCheck
|
||||
{
|
||||
|
||||
const DB_ERROR_MESSAGE = 'The system is busy, please try again later.';
|
||||
|
||||
|
||||
private ?\PDO $pdo = null;
|
||||
|
||||
|
||||
private int $_transaction = 0;
|
||||
|
||||
|
||||
private int $_timer = -1;
|
||||
|
||||
private int $_last = 0;
|
||||
|
||||
public string $dbname;
|
||||
public string $cds;
|
||||
public string $username;
|
||||
public string $password;
|
||||
public string $charset;
|
||||
public int $connect_timeout;
|
||||
public int $read_timeout;
|
||||
|
||||
|
||||
public array $attributes = [];
|
||||
|
||||
|
||||
/**
|
||||
* @param array $config
|
||||
*/
|
||||
public function __construct(array $config)
|
||||
{
|
||||
$this->dbname = $config['dbname'];
|
||||
$this->cds = $config['cds'];
|
||||
$this->username = $config['username'];
|
||||
$this->password = $config['password'];
|
||||
$this->connect_timeout = $config['connect_timeout'] ?? 30;
|
||||
$this->read_timeout = $config['read_timeout'] ?? 10;
|
||||
$this->charset = $config['charset'] ?? 'utf8mb4';
|
||||
$this->attributes = $config['attributes'] ?? [];
|
||||
}
|
||||
|
||||
|
||||
public function init()
|
||||
{
|
||||
$this->heartbeat_check();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
public function inTransaction(): bool
|
||||
{
|
||||
return $this->_transaction > 0;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public function heartbeat_check(): void
|
||||
{
|
||||
if (env('state', 'start') == 'exit') {
|
||||
return;
|
||||
}
|
||||
if ($this->_timer === -1) {
|
||||
$this->_timer = Timer::tick(1000, fn() => $this->waite());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @throws Exception
|
||||
*/
|
||||
private function waite(): void
|
||||
{
|
||||
try {
|
||||
if (env('state', 'start') == 'exit') {
|
||||
Kiri::getDi()->get(Logger::class)->critical('timer end');
|
||||
$this->stopHeartbeatCheck();
|
||||
}
|
||||
if (time() - $this->_last > (int)Config::get('databases.pool.tick', 60)) {
|
||||
$this->stopHeartbeatCheck();
|
||||
$this->pdo = null;
|
||||
}
|
||||
} catch (\Throwable $throwable) {
|
||||
error($throwable);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public function stopHeartbeatCheck(): void
|
||||
{
|
||||
if ($this->_timer > -1) {
|
||||
Timer::clear($this->_timer);
|
||||
}
|
||||
$this->_timer = -1;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public function beginTransaction()
|
||||
{
|
||||
if ($this->_transaction == 0) {
|
||||
$this->_pdo()->beginTransaction();
|
||||
}
|
||||
$this->_transaction++;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public function commit()
|
||||
{
|
||||
if ($this->_transaction == 0) {
|
||||
$this->_pdo()->commit();
|
||||
}
|
||||
$this->_transaction--;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public function rollback()
|
||||
{
|
||||
if ($this->_transaction == 0) {
|
||||
$this->_pdo()->rollBack();
|
||||
}
|
||||
$this->_transaction--;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $sql
|
||||
* @param array $params
|
||||
* @return bool|array|null
|
||||
* @throws Exception
|
||||
*/
|
||||
public function fetchAll(string $sql, array $params = []): bool|null|array
|
||||
{
|
||||
$pdo = $this->queryPrev($sql, $params);
|
||||
|
||||
$result = $pdo->fetchAll(\PDO::FETCH_ASSOC);
|
||||
$pdo->closeCursor();
|
||||
return $result;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $sql
|
||||
* @param array $params
|
||||
* @return bool|array|null
|
||||
* @throws Exception
|
||||
*/
|
||||
public function fetch(string $sql, array $params = []): bool|null|array
|
||||
{
|
||||
$pdo = $this->queryPrev($sql, $params);
|
||||
|
||||
$result = $pdo->fetch(\PDO::FETCH_ASSOC);
|
||||
$pdo->closeCursor();
|
||||
return $result;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $sql
|
||||
* @param array $params
|
||||
* @return bool|array|null
|
||||
* @throws \Exception
|
||||
*/
|
||||
public function fetchColumn(string $sql, array $params = []): bool|null|array
|
||||
{
|
||||
$pdo = $this->queryPrev($sql, $params);
|
||||
|
||||
$result = $pdo->fetchColumn(\PDO::FETCH_ASSOC);
|
||||
$pdo->closeCursor();
|
||||
return $result;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $sql
|
||||
* @param array $params
|
||||
* @return int
|
||||
* @throws Exception
|
||||
*/
|
||||
public function count(string $sql, array $params = []): int
|
||||
{
|
||||
$pdo = $this->queryPrev($sql, $params);
|
||||
|
||||
$result = $pdo->rowCount();
|
||||
$pdo->closeCursor();
|
||||
return $result;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $sql
|
||||
* @param array $params
|
||||
* @return PDOStatement
|
||||
* @throws Exception
|
||||
*/
|
||||
private function queryPrev(string $sql, array $params = []): PDOStatement
|
||||
{
|
||||
$this->_last = time();
|
||||
try {
|
||||
if (($statement = $this->_pdo()->query($sql)) === false) {
|
||||
throw new Exception($this->_pdo()->errorInfo()[1]);
|
||||
}
|
||||
return $this->bindValue($statement, $params);
|
||||
} catch (\PDOException | \Throwable $throwable) {
|
||||
if (str_contains($throwable->getMessage(), 'MySQL server has gone away')) {
|
||||
$this->pdo = null;
|
||||
|
||||
return $this->queryPrev($sql, $params);
|
||||
}
|
||||
throw new Exception($throwable->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param PDOStatement $statement
|
||||
* @param array $params
|
||||
* @return PDOStatement
|
||||
*/
|
||||
private function bindValue(PDOStatement $statement, array $params = []): PDOStatement
|
||||
{
|
||||
if (empty($params)) return $statement;
|
||||
foreach ($params as $key => $param) {
|
||||
$statement->bindValue($key, $param);
|
||||
}
|
||||
return $statement;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $sql
|
||||
* @param array $params
|
||||
* @return int
|
||||
* @throws Exception
|
||||
*/
|
||||
public function execute(string $sql, array $params = []): int
|
||||
{
|
||||
$this->_last = time();
|
||||
$pdo = $this->_pdo();
|
||||
if (!(($prepare = $pdo->prepare($sql)) instanceof PDOStatement)) {
|
||||
throw new Exception($prepare->errorInfo()[2] ?? static::DB_ERROR_MESSAGE);
|
||||
}
|
||||
if ($prepare->execute($params) === false) {
|
||||
throw new Exception($prepare->errorInfo()[2] ?? static::DB_ERROR_MESSAGE);
|
||||
}
|
||||
$result = (int)$pdo->lastInsertId();
|
||||
$prepare->closeCursor();
|
||||
if ($result == 0) {
|
||||
return true;
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return \PDO
|
||||
*/
|
||||
public function _pdo(): \PDO
|
||||
{
|
||||
if ($this->_timer === -1) {
|
||||
$this->heartbeat_check();
|
||||
}
|
||||
if (!($this->pdo instanceof \PDO)) {
|
||||
$this->pdo = $this->newClient();
|
||||
}
|
||||
return $this->pdo;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return \PDO
|
||||
*/
|
||||
private function newClient(): \PDO
|
||||
{
|
||||
$link = new \PDO('mysql:dbname=' . $this->dbname . ';host=' . $this->cds, $this->username, $this->password, [
|
||||
\PDO::ATTR_EMULATE_PREPARES => false,
|
||||
\PDO::ATTR_CASE => \PDO::CASE_NATURAL,
|
||||
\PDO::ATTR_TIMEOUT => $this->connect_timeout,
|
||||
\PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true,
|
||||
\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES ' . $this->charset
|
||||
]);
|
||||
$link->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
|
||||
$link->setAttribute(\PDO::ATTR_STRINGIFY_FETCHES, false);
|
||||
$link->setAttribute(\PDO::ATTR_ORACLE_NULLS, \PDO::NULL_EMPTY_STRING);
|
||||
if (!empty($this->attributes) && is_array($this->attributes)) {
|
||||
foreach ($this->attributes as $key => $attribute) {
|
||||
$link->setAttribute($key, $attribute);
|
||||
}
|
||||
}
|
||||
return $link;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
namespace Database\Mysql;
|
||||
|
||||
|
||||
use Exception;
|
||||
use Kiri\Abstracts\Component;
|
||||
use Database\Connection;
|
||||
|
||||
/**
|
||||
* Class Schema
|
||||
* @package Database\Mysql
|
||||
*/
|
||||
class Schema extends Component
|
||||
{
|
||||
|
||||
/** @var ?Connection */
|
||||
public ?Connection $db = null;
|
||||
|
||||
/** @var ?Columns $_column*/
|
||||
private ?Columns $_column = null;
|
||||
|
||||
|
||||
/**
|
||||
* @return Columns|null
|
||||
* @throws Exception
|
||||
*/
|
||||
public function getColumns(): ?Columns
|
||||
{
|
||||
if ($this->_column === null) {
|
||||
$this->_column = new Columns(['db' => $this->db]);
|
||||
}
|
||||
|
||||
return $this->_column;
|
||||
}
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database\Orm;
|
||||
|
||||
|
||||
use Database\Traits\Builder;
|
||||
use Exception;
|
||||
|
||||
/**
|
||||
* Trait Condition
|
||||
* @package Database\Orm
|
||||
*/
|
||||
trait Condition
|
||||
{
|
||||
|
||||
|
||||
use Builder;
|
||||
|
||||
/**
|
||||
* @param $query
|
||||
* @return string
|
||||
* @throws Exception
|
||||
*/
|
||||
public function getWhere($query): string
|
||||
{
|
||||
return $this->where($query);
|
||||
}
|
||||
}
|
||||
-204
@@ -1,204 +0,0 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database;
|
||||
|
||||
|
||||
use Closure;
|
||||
use Exception;
|
||||
use Kiri\Abstracts\Component;
|
||||
|
||||
/**
|
||||
* Class Pagination
|
||||
* @package Database
|
||||
*/
|
||||
class Pagination extends Component
|
||||
{
|
||||
|
||||
/** @var ActiveQuery */
|
||||
private ActiveQuery $activeQuery;
|
||||
|
||||
/** @var int 从第几个开始查 */
|
||||
private int $_offset = 0;
|
||||
|
||||
/** @var int 每页数量 */
|
||||
private int $_limit = 100;
|
||||
|
||||
/** @var int 最大查询数量 */
|
||||
private int $_max = 0;
|
||||
|
||||
/** @var int 当前已查询数量 */
|
||||
private int $_length = 0;
|
||||
|
||||
/** @var Closure */
|
||||
private Closure $_callback;
|
||||
|
||||
|
||||
/**
|
||||
* PaginationIteration constructor.
|
||||
* @param ActiveQuery $activeQuery
|
||||
* @param array $config
|
||||
* @throws Exception
|
||||
*/
|
||||
public function __construct(ActiveQuery $activeQuery, array $config = [])
|
||||
{
|
||||
parent::__construct($config);
|
||||
$this->activeQuery = $activeQuery;
|
||||
}
|
||||
|
||||
|
||||
public function clean()
|
||||
{
|
||||
unset($this->activeQuery, $this->_callback, $this->_group);
|
||||
$this->_offset = 0;
|
||||
$this->_limit = 100;
|
||||
$this->_max = 0;
|
||||
$this->_length = 0;;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* recover class by clone
|
||||
*/
|
||||
public function __clone()
|
||||
{
|
||||
$this->clean();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param array|Closure $callback
|
||||
* @throws Exception
|
||||
*/
|
||||
public function setCallback(array|Closure $callback)
|
||||
{
|
||||
if (!is_callable($callback, true)) {
|
||||
throw new Exception('非法回调函数~');
|
||||
}
|
||||
$this->_callback = $callback;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param int $number
|
||||
* @return Pagination
|
||||
*/
|
||||
public function setOffset(int $number): static
|
||||
{
|
||||
if ($number < 0) {
|
||||
$number = 0;
|
||||
}
|
||||
$this->_offset = $number;
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param int $number
|
||||
* @return Pagination
|
||||
*/
|
||||
public function setLimit(int $number): static
|
||||
{
|
||||
if ($number < 1) {
|
||||
$number = 100;
|
||||
} else if ($number > 5000) {
|
||||
$number = 5000;
|
||||
}
|
||||
$this->_limit = $number;
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param int $number
|
||||
* @return Pagination
|
||||
*/
|
||||
public function setMax(int $number): static
|
||||
{
|
||||
if ($number < 0) {
|
||||
return $this;
|
||||
}
|
||||
$this->_max = $number;
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param array $param
|
||||
* @return void
|
||||
* @throws Exception
|
||||
*/
|
||||
public function plunk(array $param = [])
|
||||
{
|
||||
$this->loop($param);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 轮训
|
||||
* @param $param
|
||||
* @return array
|
||||
* @throws Exception
|
||||
*/
|
||||
public function loop($param): array
|
||||
{
|
||||
if ($this->_max > 0 && $this->_length >= $this->_max) {
|
||||
return $this->output();
|
||||
}
|
||||
[$length, $data] = $this->get();
|
||||
|
||||
$this->executed($data, $param);
|
||||
|
||||
unset($data);
|
||||
if ($length < $this->_limit) {
|
||||
return $this->output();
|
||||
}
|
||||
return $this->loop($param);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
public function output(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $data
|
||||
* @param $param
|
||||
* @throws Exception
|
||||
*/
|
||||
private function executed($data, $param): void
|
||||
{
|
||||
try {
|
||||
call_user_func($this->_callback, $data, $param);
|
||||
} catch (\Throwable $exception) {
|
||||
$this->addError($exception, 'throwable');
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return array|Collection
|
||||
*/
|
||||
private function get(): Collection|array
|
||||
{
|
||||
if ($this->_max > 0 && $this->_length + $this->_limit > $this->_max) {
|
||||
$this->_limit = $this->_length + $this->_limit - $this->_max;
|
||||
}
|
||||
$data = $this->activeQuery->limit($this->_offset, $this->_limit)->get();
|
||||
$this->_offset += $this->_limit;
|
||||
|
||||
if (is_array($data)) {
|
||||
$size = count($data);
|
||||
} else {
|
||||
$size = $data->size();
|
||||
}
|
||||
$this->_length += $size;
|
||||
return [$size, $data];
|
||||
}
|
||||
|
||||
}
|
||||
@@ -11,39 +11,18 @@ namespace Database;
|
||||
|
||||
|
||||
use Database\Traits\QueryTrait;
|
||||
use Exception;
|
||||
|
||||
/**
|
||||
* Class Query
|
||||
* @package Database
|
||||
*/
|
||||
class Query implements ISqlBuilder
|
||||
class Query extends QueryTrait implements ISqlBuilder
|
||||
{
|
||||
|
||||
use QueryTrait;
|
||||
|
||||
|
||||
/**
|
||||
* @throws Exception
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
$this->builder = SqlBuilder::builder($this);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
* @throws Exception
|
||||
*/
|
||||
public function getSql(): string
|
||||
{
|
||||
return $this->builder->get();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return string
|
||||
* @throws Exception
|
||||
* @throws
|
||||
*/
|
||||
public function getCondition(): string
|
||||
{
|
||||
|
||||
+33
-48
@@ -4,8 +4,8 @@ declare(strict_types=1);
|
||||
namespace Database;
|
||||
|
||||
|
||||
use Exception;
|
||||
use Kiri\Abstracts\Component;
|
||||
use Kiri\Di\Context;
|
||||
|
||||
/**
|
||||
* Class Relation
|
||||
@@ -14,8 +14,6 @@ use Kiri\Abstracts\Component;
|
||||
class Relation extends Component
|
||||
{
|
||||
|
||||
private array $_relations = [];
|
||||
|
||||
/** @var ActiveQuery[] $_query */
|
||||
private array $_query = [];
|
||||
|
||||
@@ -30,6 +28,15 @@ class Relation extends Component
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $identification
|
||||
* @return bool
|
||||
*/
|
||||
public function hasIdentification(string $identification): bool
|
||||
{
|
||||
return isset($this->_query[$identification]) && $this->_query[$identification] instanceof ActiveQuery;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $name
|
||||
* @return ActiveQuery|null
|
||||
@@ -41,71 +48,49 @@ class Relation extends Component
|
||||
|
||||
|
||||
/**
|
||||
* @param string $identification
|
||||
* @param $localValue
|
||||
* @param string $_identification
|
||||
* @return mixed
|
||||
* @throws Exception
|
||||
* @throws
|
||||
*/
|
||||
public function first(string $identification, $localValue): mixed
|
||||
public function first(string $_identification): mixed
|
||||
{
|
||||
$_identification = $identification . '_first_' . $localValue;
|
||||
if (isset($this->_relations[$_identification]) && $this->_relations[$_identification] !== null) {
|
||||
return $this->_relations[$_identification];
|
||||
if (Context::exists($_identification)) {
|
||||
return Context::get($_identification);
|
||||
}
|
||||
|
||||
$activeModel = $this->_query[$identification]->first();
|
||||
if (empty($activeModel)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->_relations[$_identification] = $activeModel;
|
||||
$activeModel = $this->_query[$_identification]->first();
|
||||
unset($this->_query[$_identification]);
|
||||
return Context::set($_identification, $activeModel);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $identification
|
||||
* @param $localValue
|
||||
* @param string $_identification
|
||||
* @return mixed
|
||||
* @throws Exception
|
||||
*/
|
||||
public function count(string $identification, $localValue): mixed
|
||||
public function count(string $_identification): mixed
|
||||
{
|
||||
$_identification = $identification . '_count_' . $localValue;
|
||||
if (isset($this->_relations[$_identification]) && $this->_relations[$_identification] !== null) {
|
||||
return $this->_relations[$_identification];
|
||||
if (Context::exists($_identification)) {
|
||||
return Context::get($_identification);
|
||||
}
|
||||
|
||||
$activeModel = $this->_query[$identification]->count();
|
||||
if (empty($activeModel)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->_relations[$_identification] = $activeModel;
|
||||
$activeModel = $this->_query[$_identification]->count();
|
||||
unset($this->_query[$_identification]);
|
||||
return Context::set($_identification, $activeModel);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $identification
|
||||
* @param $localValue
|
||||
* @param string $_identification
|
||||
* @return mixed
|
||||
* @throws
|
||||
*/
|
||||
public function get(string $identification, $localValue): mixed
|
||||
public function get(string $_identification): mixed
|
||||
{
|
||||
if (is_array($localValue)) {
|
||||
$_identification = $identification . '_get_' . implode('_', $localValue);
|
||||
} else {
|
||||
$_identification = $identification . '_get_' . $localValue;
|
||||
if (Context::exists($_identification)) {
|
||||
return Context::get($_identification);
|
||||
}
|
||||
if (isset($this->_relations[$_identification]) && $this->_relations[$_identification] !== null) {
|
||||
return $this->_relations[$_identification];
|
||||
}
|
||||
|
||||
$activeModel = $this->_query[$identification]->get();
|
||||
if (empty($activeModel)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->_relations[$_identification] = $activeModel;
|
||||
$activeModel = $this->_query[$_identification]->get();
|
||||
unset($this->_query[$_identification]);
|
||||
return Context::set($_identification, $activeModel);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+165
-139
@@ -1,12 +1,12 @@
|
||||
<?php
|
||||
<?php /** @noinspection ALL */
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database;
|
||||
|
||||
|
||||
use Database\Traits\Builder;
|
||||
use Exception;
|
||||
use JetBrains\PhpStorm\Pure;
|
||||
use Kiri;
|
||||
use Kiri\Abstracts\Component;
|
||||
|
||||
|
||||
@@ -17,37 +17,48 @@ use Kiri\Abstracts\Component;
|
||||
class SqlBuilder extends Component
|
||||
{
|
||||
|
||||
use Builder;
|
||||
/**
|
||||
* @var ActiveQuery|Query|ISqlBuilder|null
|
||||
*/
|
||||
public ActiveQuery|Query|ISqlBuilder|null $query;
|
||||
|
||||
|
||||
public ActiveQuery|Query|null $query;
|
||||
/**
|
||||
* @param ActiveQuery|Query|ISqlBuilder|null $config
|
||||
*/
|
||||
public function __construct(ActiveQuery|Query|null|ISqlBuilder $config)
|
||||
{
|
||||
parent::__construct();
|
||||
|
||||
$this->query = $config;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param ISqlBuilder|null $query
|
||||
* @return $this
|
||||
* @throws Exception
|
||||
* @throws
|
||||
*/
|
||||
public static function builder(ISqlBuilder|null $query): static
|
||||
{
|
||||
return new static(['query' => $query]);
|
||||
return new static($query);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return string
|
||||
* @throws Exception
|
||||
* @throws
|
||||
*/
|
||||
public function getCondition(): string
|
||||
{
|
||||
return $this->conditionToString();
|
||||
return $this->where($this->query->where);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param array $compiler
|
||||
* @return string
|
||||
* @throws Exception
|
||||
* @throws
|
||||
*/
|
||||
public function hashCompiler(array $compiler): string
|
||||
{
|
||||
@@ -58,13 +69,17 @@ class SqlBuilder extends Component
|
||||
/**
|
||||
* @param array $attributes
|
||||
* @return bool|array
|
||||
* @throws Exception
|
||||
* @throws
|
||||
*/
|
||||
public function update(array $attributes): bool|array
|
||||
public function update(array $attributes): bool|string
|
||||
{
|
||||
[$string, $array] = $this->builderParams($attributes);
|
||||
|
||||
return $this->__updateBuilder($string, $array);
|
||||
$conditions = $this->query->params;
|
||||
$this->query->params = [];
|
||||
$data = $this->__updateBuilder($this->makeParams($attributes));
|
||||
foreach ($conditions as $condition) {
|
||||
$this->query->pushParam($condition);
|
||||
}
|
||||
return $data;
|
||||
}
|
||||
|
||||
|
||||
@@ -72,39 +87,29 @@ class SqlBuilder extends Component
|
||||
* @param array $attributes
|
||||
* @param string $opera
|
||||
* @return bool|array
|
||||
* @throws Exception
|
||||
* @throws
|
||||
*/
|
||||
public function mathematics(array $attributes, string $opera = '+'): bool|array
|
||||
public function mathematics(array $attributes, string $opera = '+'): bool|string
|
||||
{
|
||||
$string = [];
|
||||
foreach ($attributes as $attribute => $value) {
|
||||
$string[] = $attribute . '=' . $attribute . $opera . $value;
|
||||
}
|
||||
return $this->__updateBuilder($string, []);
|
||||
return $this->__updateBuilder($string);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param array $string
|
||||
* @param array $params
|
||||
* @return array|bool
|
||||
* @throws Exception
|
||||
* @return string|bool
|
||||
* @throws
|
||||
*/
|
||||
private function __updateBuilder(array $string, array $params): array|bool
|
||||
private function __updateBuilder(array $string): string|bool
|
||||
{
|
||||
if (empty($string)) {
|
||||
return $this->addError('None data update.');
|
||||
return Kiri::getLogger()->failure('None data update.');
|
||||
}
|
||||
|
||||
$condition = $this->conditionToString();
|
||||
if (!empty($condition)) {
|
||||
$condition = ' WHERE ' . $condition;
|
||||
}
|
||||
|
||||
$update = 'UPDATE ' . $this->tableName() . ' SET ' . implode(',', $string) . $condition;
|
||||
$update .= $this->builderLimit($this->query, false);
|
||||
|
||||
return [$update, $params];
|
||||
return 'UPDATE ' . $this->query->from . ' SET ' . implode(',', $string) . $this->make();
|
||||
}
|
||||
|
||||
|
||||
@@ -112,39 +117,33 @@ class SqlBuilder extends Component
|
||||
* @param array $attributes
|
||||
* @param false $isBatch
|
||||
* @return array
|
||||
* @throws Exception
|
||||
* @throws
|
||||
*/
|
||||
public function insert(array $attributes, bool $isBatch = false): array
|
||||
public function insert(array $attributes, bool $isBatch = false): string
|
||||
{
|
||||
$update = 'INSERT INTO ' . $this->tableName();
|
||||
$update = 'INSERT INTO ' . $this->query->from;
|
||||
if ($isBatch === false) {
|
||||
$attributes = [$attributes];
|
||||
}
|
||||
$update .= '(' . implode(',', $this->getFields($attributes)) . ') VALUES ';
|
||||
|
||||
$order = 0;
|
||||
$keys = $params = [];
|
||||
$keys = [];
|
||||
foreach ($attributes as $attribute) {
|
||||
[$_keys, $params] = $this->builderParams($attribute, true, $params, $order);
|
||||
$_keys = $this->makeParams($attribute, true);
|
||||
|
||||
$keys[] = implode(',', $_keys);
|
||||
$order++;
|
||||
}
|
||||
return [$update . '(' . implode('),(', $keys) . ')', $params];
|
||||
return $update . '(' . implode('),(', $keys) . ')';
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return string
|
||||
* @throws Exception
|
||||
* @throws
|
||||
*/
|
||||
public function delete(): string
|
||||
{
|
||||
$delete = sprintf('DELETE FROM %s ', $this->query->modelClass->getTable());
|
||||
|
||||
$this->query->from = null;
|
||||
|
||||
return $delete . ' WHERE ' . $this->_prefix(true);
|
||||
return 'DELETE FROM ' . $this->query->from . $this->make();
|
||||
}
|
||||
|
||||
|
||||
@@ -152,7 +151,7 @@ class SqlBuilder extends Component
|
||||
* @param $attributes
|
||||
* @return array
|
||||
*/
|
||||
#[Pure] private function getFields($attributes): array
|
||||
#[Pure] private function getFields(array $attributes): array
|
||||
{
|
||||
return array_keys(current($attributes));
|
||||
}
|
||||
@@ -161,169 +160,174 @@ class SqlBuilder extends Component
|
||||
/**
|
||||
* @param array $attributes
|
||||
* @param bool $isInsert
|
||||
* @param array $params
|
||||
* @param int $order
|
||||
* @return array[]
|
||||
* a=:b,
|
||||
*/
|
||||
#[Pure] private function builderParams(array $attributes, bool $isInsert = false, array $params = [], int $order = 0): array
|
||||
private function makeParams(array $attributes, bool $isInsert = false): array
|
||||
{
|
||||
$keys = [];
|
||||
foreach ($attributes as $key => $value) {
|
||||
if ($isInsert === true) {
|
||||
$keys[] = ':' . $key . $order;
|
||||
$params[$key . $order] = $value;
|
||||
$keys[] = '?';
|
||||
$this->query->pushParam($value);
|
||||
} else {
|
||||
[$keys, $params] = $this->resolveParams($key, $value, $order, $params, $keys);
|
||||
$keys = $this->resolveParams($key, $value, $keys);
|
||||
}
|
||||
}
|
||||
return [$keys, $params];
|
||||
return $keys;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $key
|
||||
* @param mixed $value
|
||||
* @param int $order
|
||||
* @param array $params
|
||||
* @param array $keys
|
||||
* @return array
|
||||
*/
|
||||
private function resolveParams(string $key, mixed $value, int $order, array $params, array $keys): array
|
||||
private function resolveParams(string $key, mixed $value, array $keys): array
|
||||
{
|
||||
if (
|
||||
str_starts_with($value, '+ ') ||
|
||||
str_starts_with($value, '- ')
|
||||
) {
|
||||
if (is_null($value)) {
|
||||
return $keys;
|
||||
}
|
||||
if (is_string($value) && $this->isMath($value)) {
|
||||
$keys[] = $key . '=' . $key . ' ' . $value;
|
||||
} else {
|
||||
$params[$key . $order] = $value;
|
||||
$keys[] = $key . '=:' . $key . $order;
|
||||
$this->query->pushParam($value);
|
||||
$keys[] = $key . '= ?';
|
||||
}
|
||||
return [$keys, $params];
|
||||
return $keys;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $value
|
||||
* @return bool
|
||||
*/
|
||||
private function isMath(string $value): bool
|
||||
{
|
||||
return str_starts_with($value, '+ ') || str_starts_with($value, '- ');
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return string
|
||||
* @throws Exception
|
||||
* @throws
|
||||
*/
|
||||
public function one(): string
|
||||
{
|
||||
$this->query->limit(0, 1);
|
||||
if (empty($this->query->from) && !empty($this->query->modelClass)) {
|
||||
$this->query->from($this->query->getTable());
|
||||
}
|
||||
return $this->_prefix(true);
|
||||
return $this->makeSelect($this->query->select) . $this->make() . $this->makeLimit($this->query->limit(1));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return string
|
||||
* @throws Exception
|
||||
* @throws
|
||||
*/
|
||||
public function all(): string
|
||||
{
|
||||
if (empty($this->query->from) && !empty($this->query->modelClass)) {
|
||||
$this->query->from($this->query->getTable());
|
||||
}
|
||||
return $this->_prefix(true);
|
||||
return $this->makeSelect($this->query->select) . $this->make() . $this->makeLimit($this->query);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return string
|
||||
* @throws Exception
|
||||
* @throws
|
||||
*/
|
||||
public function count(): string
|
||||
{
|
||||
if (empty($this->query->from) && !empty($this->query->modelClass)) {
|
||||
$this->query->from($this->query->getTable());
|
||||
}
|
||||
return $this->_prefix(false, true);
|
||||
return $this->makeSelect() . $this->make();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $table
|
||||
* @param string $table
|
||||
* @return string
|
||||
*/
|
||||
public function columns($table): string
|
||||
public function columns(string $table): string
|
||||
{
|
||||
return 'SHOW FULL FIELDS FROM ' . $table;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param bool $hasOrder
|
||||
* @param bool $isCount
|
||||
* @return string
|
||||
* @throws Exception
|
||||
* @throws
|
||||
*/
|
||||
private function _prefix(bool $hasOrder = false, bool $isCount = false): string
|
||||
private function make(): string
|
||||
{
|
||||
$select = '';
|
||||
if (!empty($this->query->from)) {
|
||||
$select = $this->_selectPrefix($isCount);
|
||||
}
|
||||
$select = $this->_wherePrefix($select);
|
||||
if (!empty($this->query->attributes) && is_array($this->query->attributes)) {
|
||||
$select = strtr($select, $this->query->attributes);
|
||||
$select = $this->makeCondition();
|
||||
$select .= $this->makeGroup();
|
||||
$select .= $this->makeOrder();
|
||||
return $select;
|
||||
}
|
||||
|
||||
if (!empty($this->query->group)) {
|
||||
$select .= $this->builderGroup($this->query->group);
|
||||
/**
|
||||
* @param array $select
|
||||
* @return string
|
||||
*/
|
||||
private function makeSelect(array $select = ['*']): string
|
||||
{
|
||||
$select = "SELECT " . implode(',', $select) . " FROM " . $this->query->from;
|
||||
if ($this->query->alias != "") {
|
||||
$select .= " AS " . $this->query->alias;
|
||||
}
|
||||
if ($hasOrder === true && !empty($this->query->order)) {
|
||||
$select .= $this->builderOrder($this->query->order);
|
||||
if (count($this->query->join) > 0) {
|
||||
$select .= ' ' . implode(' ', $this->query->join);
|
||||
}
|
||||
$sql = $select . $this->builderLimit($this->query);
|
||||
if ($this->query->lock) {
|
||||
$sql .= ' FOR UPDATE';
|
||||
}
|
||||
return $sql;
|
||||
return $select;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $select
|
||||
* @return string
|
||||
* @throws Exception
|
||||
*/
|
||||
private function _wherePrefix($select): string
|
||||
private function makeGroup(): string
|
||||
{
|
||||
$condition = $this->conditionToString();
|
||||
if ($this->query->group != "") {
|
||||
return ' GROUP BY ' . $this->query->group;
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
private function makeOrder(): string
|
||||
{
|
||||
if (count($this->query->order) > 0) {
|
||||
return ' ORDER BY ' . implode(',', $this->query->order);
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
private function makeCondition(): string
|
||||
{
|
||||
$condition = $this->where($this->query->where);
|
||||
if (empty($condition)) {
|
||||
return $select;
|
||||
} else if (empty($select)) {
|
||||
return $condition;
|
||||
return '';
|
||||
}
|
||||
return sprintf('%s WHERE %s', $select, $condition);
|
||||
return ' WHERE ' . $condition;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param bool $isCount
|
||||
* @return string
|
||||
* @throws Exception
|
||||
*/
|
||||
private function _selectPrefix(bool $isCount): string
|
||||
private function makeLimit(): string
|
||||
{
|
||||
$select = $this->builderSelect($this->query->select, $isCount) . ' FROM ' . $this->tableName();
|
||||
if (!empty($this->query->alias)) {
|
||||
$select .= $this->builderAlias($this->query->alias);
|
||||
if ($this->query->offset >= 0 && $this->query->limit >= 1) {
|
||||
return ' LIMIT ' . $this->query->offset . ',' . $this->query->limit;
|
||||
}
|
||||
if (!empty($this->query->join)) {
|
||||
$select .= $this->builderJoin($this->query->join);
|
||||
}
|
||||
return $select;
|
||||
return '';
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param false $isCount
|
||||
* @return string
|
||||
* @throws Exception
|
||||
* @throws
|
||||
*/
|
||||
public function get(bool $isCount = false): string
|
||||
{
|
||||
@@ -336,40 +340,62 @@ class SqlBuilder extends Component
|
||||
|
||||
/**
|
||||
* @return string
|
||||
* @throws Exception
|
||||
* @throws
|
||||
*/
|
||||
public function truncate(): string
|
||||
{
|
||||
return sprintf('TRUNCATE %s', $this->tableName());
|
||||
return sprintf('TRUNCATE %s', $this->query->from);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param array $where
|
||||
* @return string
|
||||
* @throws Exception
|
||||
*/
|
||||
private function conditionToString(): string
|
||||
private function where(array $where): string
|
||||
{
|
||||
return $this->where($this->query->where);
|
||||
if (count($where) < 1) {
|
||||
return '';
|
||||
}
|
||||
$_tmp = [];
|
||||
foreach ($where as $key => $value) {
|
||||
$_tmp[] = $this->resolveCondition($key, $value);
|
||||
}
|
||||
return implode(' AND ', $_tmp);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $field
|
||||
* @param mixed $condition
|
||||
* @return string
|
||||
* @throws Exception
|
||||
*/
|
||||
public function tableName(): string
|
||||
private function resolveCondition(string|int $field, mixed $condition): string
|
||||
{
|
||||
if ($this->query->from instanceof \Closure) {
|
||||
$this->query->from = sprintf('(%s)', $this->query->makeClosureFunction($this->query->from));
|
||||
if (is_string($field)) {
|
||||
$this->query->pushParam($condition);
|
||||
return $field . ' = ?';
|
||||
} else if (is_string($condition)) {
|
||||
return $condition;
|
||||
} else {
|
||||
return implode(' AND ', $this->_hashMap($condition));
|
||||
}
|
||||
if ($this->query->from instanceof ActiveQuery) {
|
||||
$this->query->from = sprintf('%s', SqlBuilder::builder($this->query->from)->get($this->query->from));
|
||||
}
|
||||
if (empty($this->query->from)) {
|
||||
return $this->query->modelClass->getTable();
|
||||
|
||||
|
||||
/**
|
||||
* @param $condition
|
||||
* @return array
|
||||
*/
|
||||
private function _hashMap(array $condition): array
|
||||
{
|
||||
$_array = [];
|
||||
foreach ($condition as $key => $value) {
|
||||
$this->query->pushParam($value);
|
||||
$_array[] = $key . '= ?';
|
||||
}
|
||||
return $this->query->from;
|
||||
return $_array;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -1,232 +0,0 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace Database\Traits;
|
||||
|
||||
|
||||
use Database\ActiveQuery;
|
||||
use Database\Base\ConditionClassMap;
|
||||
use Database\Condition\HashCondition;
|
||||
use Database\Condition\OrCondition;
|
||||
use Database\Query;
|
||||
use Exception;
|
||||
use JetBrains\PhpStorm\Pure;
|
||||
use Kiri\Exception\NotFindClassException;
|
||||
use Kiri\Kiri;
|
||||
use ReflectionException;
|
||||
|
||||
|
||||
/**
|
||||
* Trait Builder
|
||||
* @package Database\Traits
|
||||
*/
|
||||
trait Builder
|
||||
{
|
||||
|
||||
|
||||
/**
|
||||
* @param $alias
|
||||
* @return string
|
||||
*/
|
||||
private function builderAlias($alias): string
|
||||
{
|
||||
return " AS " . $alias;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $table
|
||||
* @return string
|
||||
* @throws Exception
|
||||
*/
|
||||
private function builderFrom($table): string
|
||||
{
|
||||
if ($table instanceof ActiveQuery) {
|
||||
$table = '(' . $table->toSql() . ')';
|
||||
}
|
||||
return " FROM " . $table;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $join
|
||||
* @return string
|
||||
*/
|
||||
#[Pure] private function builderJoin($join): string
|
||||
{
|
||||
if (!empty($join)) {
|
||||
return ' ' . implode(' ', $join);
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param null $select
|
||||
* @param bool $isCount
|
||||
* @return string
|
||||
*/
|
||||
#[Pure] private function builderSelect($select = NULL, bool $isCount = false): string
|
||||
{
|
||||
if ($isCount) {
|
||||
return "SELECT COUNT(*)";
|
||||
}
|
||||
if (empty($select)) {
|
||||
return "SELECT *";
|
||||
}
|
||||
if (is_array($select)) {
|
||||
return "SELECT " . implode(',', $select);
|
||||
} else {
|
||||
return "SELECT " . $select;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $group
|
||||
* @return string
|
||||
*/
|
||||
private function builderGroup($group): string
|
||||
{
|
||||
if (empty($group)) {
|
||||
return '';
|
||||
}
|
||||
return ' GROUP BY ' . $group;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $order
|
||||
* @return string
|
||||
*/
|
||||
#[Pure] private function builderOrder($order): string
|
||||
{
|
||||
if (!empty($order)) {
|
||||
return ' ORDER BY ' . implode(',', $order);
|
||||
} else {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param ActiveQuery|Query $query
|
||||
* @param bool $hasLimit
|
||||
* @return string
|
||||
*/
|
||||
#[Pure] private function builderLimit(ActiveQuery|Query $query, bool $hasLimit = true): string
|
||||
{
|
||||
if (!is_numeric($query->limit) || $query->limit < 1) {
|
||||
return "";
|
||||
}
|
||||
if ($query->offset !== null && $hasLimit) {
|
||||
return ' LIMIT ' . $query->offset . ',' . $query->limit;
|
||||
}
|
||||
return ' LIMIT ' . $query->limit;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $where
|
||||
* @return string
|
||||
* @throws Exception
|
||||
*/
|
||||
private function where($where): string
|
||||
{
|
||||
$_tmp = [];
|
||||
if (empty($where)) return '';
|
||||
if (is_string($where)) return $where;
|
||||
foreach ($where as $key => $value) {
|
||||
if (is_null($value)) continue;
|
||||
|
||||
$_value = $this->resolveCondition($key, $value, $_tmp);
|
||||
|
||||
if (empty($_value)) continue;
|
||||
$_tmp[] = $_value;
|
||||
}
|
||||
if (!empty($_tmp)) {
|
||||
return implode(' AND ', $_tmp);
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $field
|
||||
* @param $condition
|
||||
* @param $_tmp
|
||||
* @return string
|
||||
* @throws NotFindClassException
|
||||
* @throws ReflectionException|Exception
|
||||
*/
|
||||
private function resolveCondition($field, $condition, $_tmp): string
|
||||
{
|
||||
if (is_string($field)) {
|
||||
$_value = sprintf('%s = \'%s\'', $field, $condition);
|
||||
} else if (is_string($condition)) {
|
||||
$_value = $condition;
|
||||
} else {
|
||||
$_value = $this->_arrayMap($condition, $_tmp);
|
||||
}
|
||||
return $_value;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $condition
|
||||
* @param $array
|
||||
* @return string
|
||||
* @throws Exception
|
||||
*/
|
||||
private function _arrayMap($condition, $array): string
|
||||
{
|
||||
if (!isset($condition[0])) {
|
||||
return implode(' AND ', $this->_hashMap($condition));
|
||||
}
|
||||
$stroppier = strtoupper($condition[0]);
|
||||
if (str_contains($stroppier, 'OR')) {
|
||||
if (!is_string($condition[2])) {
|
||||
$condition[2] = $this->_hashMap($condition[2]);
|
||||
}
|
||||
$builder = Kiri::getDi()->get(OrCondition::class);
|
||||
$builder->setValue($condition[2]);
|
||||
$builder->setColumn($condition[1]);
|
||||
$builder->oldParams = $array;
|
||||
} else if (isset(ConditionClassMap::$conditionMap[$stroppier])) {
|
||||
$defaultConfig = ConditionClassMap::$conditionMap[$stroppier];
|
||||
|
||||
$class = $defaultConfig['class'];
|
||||
unset($defaultConfig['class']);
|
||||
|
||||
$builder = Kiri::getDi()->make($class, [], $defaultConfig);
|
||||
$builder->setValue($condition[2]);
|
||||
$builder->setColumn($condition[1]);
|
||||
} else {
|
||||
$builder = Kiri::getDi()->get(HashCondition::class);
|
||||
$builder->setValue($condition);
|
||||
}
|
||||
|
||||
$array[] = $builder->builder();
|
||||
|
||||
return implode(' AND ', $array);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $condition
|
||||
* @return array
|
||||
*/
|
||||
private function _hashMap($condition): array
|
||||
{
|
||||
$_array = [];
|
||||
foreach ($condition as $key => $value) {
|
||||
if (is_null($value)) continue;
|
||||
|
||||
$value = is_numeric($value) ? $value : '\'' . $value . '\'';
|
||||
if (!is_numeric($key)) {
|
||||
$_array[] = sprintf('%s = %s', $key, $value);
|
||||
} else {
|
||||
$_array[] = $value;
|
||||
}
|
||||
}
|
||||
return $_array;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+32
-34
@@ -12,70 +12,68 @@ namespace Database\Traits;
|
||||
use Database\ModelInterface;
|
||||
use Database\Collection;
|
||||
use Database\Relation;
|
||||
use Exception;
|
||||
use Kiri;
|
||||
|
||||
/**
|
||||
* Class HasBase
|
||||
* @package Database
|
||||
*
|
||||
* @include Query
|
||||
*
|
||||
* @method first($name)
|
||||
* @method all($name)
|
||||
* @method count($name)
|
||||
*/
|
||||
abstract class HasBase implements \Database\Traits\Relation
|
||||
{
|
||||
|
||||
/** @var ModelInterface|Collection */
|
||||
protected Collection|ModelInterface $data;
|
||||
protected mixed $data = null;
|
||||
|
||||
/**
|
||||
* @var ModelInterface
|
||||
*/
|
||||
protected mixed $model;
|
||||
|
||||
protected mixed $value = [];
|
||||
|
||||
protected mixed $value = 0;
|
||||
|
||||
/** @var Relation $_relation */
|
||||
protected Relation $_relation;
|
||||
|
||||
/**
|
||||
* HasBase constructor.
|
||||
* @param ModelInterface $model
|
||||
* @param $primaryId
|
||||
* @param $value
|
||||
* @param Relation $relation
|
||||
* @throws Exception
|
||||
* @param string $name
|
||||
*/
|
||||
public function __construct(mixed $model, $primaryId, $value, Relation $relation)
|
||||
public function __construct(public string $name)
|
||||
{
|
||||
if (!class_exists($model)) {
|
||||
throw new Exception('Model must implement ' . $model);
|
||||
}
|
||||
if (!in_array(ModelInterface::class, class_implements($model))) {
|
||||
throw new Exception('Model must implement ' . $model);
|
||||
}
|
||||
if (is_array($value)) {
|
||||
if (empty($value)) $value = [];
|
||||
$_model = $model::query()->whereIn($primaryId, $value);
|
||||
} else {
|
||||
$_model = $model::query()->where(['t1.' . $primaryId => $value]);
|
||||
}
|
||||
|
||||
$this->_relation = $relation->bindIdentification($model, $_model);
|
||||
|
||||
$this->model = $model;
|
||||
$this->value = $value;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $name
|
||||
* @return mixed
|
||||
* @param string $name
|
||||
* @param array $arguments
|
||||
* @return $this|mixed
|
||||
*/
|
||||
public function __get($name): mixed
|
||||
public function __call(string $name, array $arguments)
|
||||
{
|
||||
if (empty($this->value)) {
|
||||
return null;
|
||||
}
|
||||
if ($name !== 'get') {
|
||||
$relation = Kiri::getDi()->get(Relation::class);
|
||||
$relation->getQuery($this->name)->$name(...$arguments);
|
||||
return $this;
|
||||
} else {
|
||||
return $this->get();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $name
|
||||
* @return mixed
|
||||
*/
|
||||
public function __get(string $name): mixed
|
||||
{
|
||||
if ($this->data === null) {
|
||||
$this->data = $this->get();
|
||||
}
|
||||
return $this->data;
|
||||
}
|
||||
}
|
||||
|
||||
+227
-399
File diff suppressed because it is too large
Load Diff
@@ -1,10 +1,15 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database\Traits;
|
||||
|
||||
interface Relation
|
||||
{
|
||||
|
||||
|
||||
/**
|
||||
* @return mixed
|
||||
*/
|
||||
public function get(): mixed;
|
||||
|
||||
}
|
||||
|
||||
+3
-2
@@ -1,4 +1,5 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
|
||||
namespace Database\Traits;
|
||||
@@ -40,7 +41,7 @@ class When
|
||||
* @param string|int $condition
|
||||
* @param string $then
|
||||
* @return $this
|
||||
* @throws Exception
|
||||
* @throws
|
||||
*/
|
||||
public function when(string|int $condition, string $then): static
|
||||
{
|
||||
@@ -53,7 +54,7 @@ class When
|
||||
/**
|
||||
* @param string $alias
|
||||
*/
|
||||
public function else(string $alias)
|
||||
public function else(string $alias): void
|
||||
{
|
||||
$this->else = $alias;
|
||||
}
|
||||
|
||||
+2
-3
@@ -9,11 +9,10 @@
|
||||
],
|
||||
"license": "MIT",
|
||||
"require": {
|
||||
"php": ">=8.0",
|
||||
"php": ">=8.3",
|
||||
"ext-json": "*",
|
||||
"ext-pdo": "*",
|
||||
"game-worker/kiri-validator": "~v2.0",
|
||||
"game-worker/kiri-event": "~v2.0"
|
||||
"game-worker/kiri-pool": "~v1.0"
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
|
||||
Reference in New Issue
Block a user