Compare commits
656 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| beb48f41d2 | |||
| 8d917b0f92 | |||
| 08fbc49091 | |||
| 08e49cfa65 | |||
| d58850b158 | |||
| aba45e8cb9 | |||
| ed22201bef | |||
| ccbac52a16 | |||
| 9fe0698d1c | |||
| 55e1f6235e | |||
| ed0d044223 | |||
| 2b85cb4ec3 | |||
| 73b9923740 | |||
| b2c8160314 | |||
| 199312d326 | |||
| 87f568bdfe | |||
| 2fd37f90a3 | |||
| c100190155 | |||
| 71766ee914 | |||
| 3a39eaabf4 | |||
| 722b286f91 | |||
| f9ee3aa014 | |||
| 4341efcb8c | |||
| 8acf74c9ed | |||
| b9750d743b | |||
| 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 | |||
| 2109ed7667 | |||
| a45d71d760 | |||
| e71adc7cf3 | |||
| ef3e874c0c | |||
| 614b601afa | |||
| cf2f26ec21 | |||
| 2a52172af6 | |||
| 5bf8a7feb1 | |||
| 52d26c4481 | |||
| dd369d348c |
+34
-34
@@ -1,34 +1,34 @@
|
||||
# Created by .ignore support plugin (hsz.mobi)
|
||||
### Yii template
|
||||
assets/*
|
||||
!assets/.gitignore
|
||||
protected/runtime/*
|
||||
!protected/runtime/.gitignore
|
||||
protected/data/*.db
|
||||
themes/classic/views/
|
||||
|
||||
### Example user template template
|
||||
### Example user template
|
||||
|
||||
# IntelliJ project files
|
||||
.idea
|
||||
*.iml
|
||||
out
|
||||
gen
|
||||
|
||||
composer.lock
|
||||
|
||||
*.log
|
||||
commands/result
|
||||
config/setting.php
|
||||
tests/
|
||||
vendor/
|
||||
runtime/
|
||||
|
||||
*.xml
|
||||
*.lock
|
||||
|
||||
oot
|
||||
d
|
||||
|
||||
composer.lock
|
||||
# Created by .ignore support plugin (hsz.mobi)
|
||||
### Yii template
|
||||
assets/*
|
||||
!assets/.gitignore
|
||||
protected/runtime/*
|
||||
!protected/runtime/.gitignore
|
||||
protected/data/*.db
|
||||
themes/classic/views/
|
||||
|
||||
### Example user template template
|
||||
### Example user template
|
||||
|
||||
# IntelliJ project files
|
||||
.idea
|
||||
*.iml
|
||||
out
|
||||
gen
|
||||
|
||||
composer.lock
|
||||
|
||||
*.log
|
||||
commands/result
|
||||
config/setting.php
|
||||
tests/
|
||||
vendor/
|
||||
runtime/
|
||||
|
||||
*.xml
|
||||
*.lock
|
||||
|
||||
oot
|
||||
d
|
||||
|
||||
composer.lock
|
||||
|
||||
+18
-18
@@ -1,18 +1,18 @@
|
||||
<?php
|
||||
|
||||
namespace PHPSTORM_META {
|
||||
|
||||
// Reflect
|
||||
use Kiri\Di\Container;
|
||||
use Psr\Container\ContainerInterface;
|
||||
|
||||
override(ContainerInterface::get(0), map('@'));
|
||||
override(Container::make(0), map('@'));
|
||||
override(Container::get(0), map('@'));
|
||||
override(Container::create(0), map('@'));
|
||||
// override(\Hyperf\Utils\Context::get(0), map('@'));
|
||||
// override(\make(0), map('@'));
|
||||
override(\di(0), map('@'));
|
||||
override(\duplicate(0), map('@'));
|
||||
|
||||
}
|
||||
<?php
|
||||
|
||||
namespace PHPSTORM_META {
|
||||
|
||||
// Reflect
|
||||
use Kiri\Di\Container;
|
||||
use Psr\Container\ContainerInterface;
|
||||
|
||||
override(ContainerInterface::get(0), map('@'));
|
||||
override(Container::make(0), map('@'));
|
||||
override(Container::get(0), map('@'));
|
||||
override(Container::create(0), map('@'));
|
||||
// override(\Hyperf\Utils\Context::get(0), map('@'));
|
||||
// override(\make(0), map('@'));
|
||||
override(\di(0), map('@'));
|
||||
override(\duplicate(0), map('@'));
|
||||
|
||||
}
|
||||
|
||||
+229
@@ -0,0 +1,229 @@
|
||||
<?php
|
||||
/**
|
||||
* Created by PhpStorm.
|
||||
* User: whwyy
|
||||
* Date: 2018/4/4 0004
|
||||
* Time: 14:42
|
||||
*/
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database;
|
||||
|
||||
use Closure;
|
||||
use Database\Traits\QueryTrait;
|
||||
use Kiri\Di\Context;
|
||||
use Swoole\Coroutine;
|
||||
|
||||
/**
|
||||
* Class ActiveQuery
|
||||
* @package Database
|
||||
*/
|
||||
class ActiveQuery extends QueryTrait implements ISqlBuilder
|
||||
{
|
||||
|
||||
|
||||
public bool $asArray = FALSE;
|
||||
protected mixed $_mock = null;
|
||||
|
||||
|
||||
/**
|
||||
* @param bool $asArray
|
||||
* @return static
|
||||
*/
|
||||
public function asArray(bool $asArray = true): static
|
||||
{
|
||||
$this->asArray = $asArray;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $methods
|
||||
* @return $this
|
||||
*/
|
||||
public function with(array $methods): static
|
||||
{
|
||||
$this->modelClass->setWith($methods);
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return ModelInterface|array|null|bool
|
||||
* @throws
|
||||
*/
|
||||
public function first(): ModelInterface|null|array|bool
|
||||
{
|
||||
$data = $this->buildCommand($this->builder->one())->one();
|
||||
if (is_array($data)) {
|
||||
return $this->populate($data);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool|Collection
|
||||
*/
|
||||
public function get(): bool|Collection
|
||||
{
|
||||
$data = $this->buildCommand($this->builder->all())->all();
|
||||
if (is_array($data)) {
|
||||
return new Collection($this, $this->modelClass, $data);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @throws
|
||||
*/
|
||||
public function flush(): bool
|
||||
{
|
||||
return (bool)$this->buildCommand($this->builder->truncate())->exec();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param int $size
|
||||
* @param Closure $closure
|
||||
* @return void
|
||||
*/
|
||||
public function chunk(int $size, Closure $closure): void
|
||||
{
|
||||
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|null $setKey
|
||||
*
|
||||
* @return array|null
|
||||
*/
|
||||
public function column(string $field, ?string $setKey = null): ?array
|
||||
{
|
||||
return $this->get()->column($field, $setKey);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param mixed $value
|
||||
* @return $this
|
||||
*/
|
||||
public function withMock(mixed $value): static
|
||||
{
|
||||
$this->_mock = $value;
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return mixed
|
||||
*/
|
||||
public function mock(): mixed
|
||||
{
|
||||
return $this->_mock;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param array $data
|
||||
* @return ModelInterface|array
|
||||
* @throws
|
||||
*/
|
||||
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)) {
|
||||
return (bool)$this->buildCommand($generate)->exec();
|
||||
} else {
|
||||
return $generate;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $data
|
||||
* @return bool
|
||||
*/
|
||||
public function insert(array $data): bool
|
||||
{
|
||||
$sql = $this->builder->insert($data, isset($data[0]));
|
||||
|
||||
return (bool)$this->buildCommand($sql)->exec();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $filed
|
||||
*
|
||||
* @return mixed
|
||||
* @throws
|
||||
*/
|
||||
public function value(string $filed): mixed
|
||||
{
|
||||
return $this->first()[$filed] ?? NULL;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
* @throws
|
||||
*/
|
||||
public function exists(): bool
|
||||
{
|
||||
return $this->buildCommand($this->limit(1)->builder->exists())->exists();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $sql
|
||||
* @param array $params
|
||||
* @return int|bool
|
||||
*/
|
||||
public function execute(string $sql, array $params = []): int|bool
|
||||
{
|
||||
return $this->buildCommand($sql, $params)->exec();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
public function delete(): bool
|
||||
{
|
||||
return $this->buildCommand($this->builder->delete())->delete();
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
<?php
|
||||
|
||||
namespace Database\Affair;
|
||||
|
||||
class BeginTransaction
|
||||
{
|
||||
|
||||
}
|
||||
<?php
|
||||
|
||||
namespace Database\Affair;
|
||||
|
||||
class BeginTransaction
|
||||
{
|
||||
|
||||
}
|
||||
@@ -1,10 +1,8 @@
|
||||
<?php
|
||||
|
||||
namespace Database\Affair;
|
||||
|
||||
use Exception;
|
||||
|
||||
class Commit
|
||||
{
|
||||
|
||||
}
|
||||
<?php
|
||||
|
||||
namespace Database\Affair;
|
||||
|
||||
class Commit
|
||||
{
|
||||
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
<?php
|
||||
|
||||
namespace Database\Affair;
|
||||
|
||||
class Rollback
|
||||
{
|
||||
|
||||
}
|
||||
<?php
|
||||
|
||||
namespace Database\Affair;
|
||||
|
||||
class Rollback
|
||||
{
|
||||
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,161 +1,167 @@
|
||||
<?php
|
||||
/**
|
||||
* Created by PhpStorm.
|
||||
* User: whwyy
|
||||
* Date: 2018/4/9 0009
|
||||
* Time: 9:44
|
||||
*/
|
||||
declare(strict_types=1);
|
||||
|
||||
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 Traversable;
|
||||
|
||||
/**
|
||||
* Class AbstractCollection
|
||||
* @package Database\Base
|
||||
*/
|
||||
abstract class AbstractCollection extends Component implements \IteratorAggregate, \ArrayAccess, ToArray
|
||||
{
|
||||
|
||||
/**
|
||||
* @var ModelInterface[]
|
||||
*/
|
||||
protected array $_item = [];
|
||||
|
||||
protected ModelInterface|string|null $model;
|
||||
|
||||
protected ActiveQuery $query;
|
||||
|
||||
|
||||
public function clean()
|
||||
{
|
||||
unset($this->query, $this->model, $this->_item);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Collection constructor.
|
||||
*
|
||||
* @param $query
|
||||
* @param array $array
|
||||
* @param ModelInterface|null $model
|
||||
* @throws Exception
|
||||
*/
|
||||
public function __construct($query, array $array = [], ModelInterface $model = null)
|
||||
{
|
||||
$this->_item = $array;
|
||||
$this->query = $query;
|
||||
$this->model = $model;
|
||||
|
||||
parent::__construct([]);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return int
|
||||
*/
|
||||
#[Pure] public function getLength(): int
|
||||
{
|
||||
return count($this->_item);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $item
|
||||
*/
|
||||
public function setItems($item)
|
||||
{
|
||||
$this->_item = $item;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $model
|
||||
*/
|
||||
public function setModel($model)
|
||||
{
|
||||
$this->model = $model;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $item
|
||||
*/
|
||||
public function addItem($item)
|
||||
{
|
||||
array_push($this->_item, $item);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Traversable|CollectionIterator|ArrayIterator
|
||||
* @throws Exception
|
||||
*/
|
||||
public function getIterator(): Traversable|CollectionIterator|ArrayIterator
|
||||
{
|
||||
return new CollectionIterator($this->model, $this->query, $this->_item);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return mixed
|
||||
* @throws Exception
|
||||
*/
|
||||
public function getModel(): ModelInterface
|
||||
{
|
||||
return $this->model;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param mixed $offset
|
||||
* @return bool
|
||||
*/
|
||||
public function offsetExists(mixed $offset): bool
|
||||
{
|
||||
return !empty($this->_item) && isset($this->_item[$offset]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $offset
|
||||
* @return ModelInterface|null
|
||||
* @throws Exception
|
||||
*/
|
||||
public function offsetGet(mixed $offset): ?ModelInterface
|
||||
{
|
||||
if (!$this->offsetExists($offset)) {
|
||||
return NULL;
|
||||
}
|
||||
if (!($this->_item[$offset] instanceof ModelInterface)) {
|
||||
return $this->model->populates($this->_item[$offset]);
|
||||
}
|
||||
return $this->_item[$offset];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $offset
|
||||
* @param mixed $value
|
||||
*/
|
||||
public function offsetSet(mixed $offset, mixed $value)
|
||||
{
|
||||
$this->_item[$offset] = $value;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param mixed $offset
|
||||
*/
|
||||
public function offsetUnset(mixed $offset)
|
||||
{
|
||||
if ($this->offsetExists($offset)) {
|
||||
unset($this->_item[$offset]);
|
||||
}
|
||||
}
|
||||
}
|
||||
<?php
|
||||
/**
|
||||
* Created by PhpStorm.
|
||||
* User: whwyy
|
||||
* Date: 2018/4/9 0009
|
||||
* Time: 9:44
|
||||
*/
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database\Base;
|
||||
|
||||
|
||||
use ArrayIterator;
|
||||
use Database\ActiveQuery;
|
||||
use Database\ModelInterface;
|
||||
use JetBrains\PhpStorm\Pure;
|
||||
use Kiri\Abstracts\Component;
|
||||
use ReturnTypeWillChange;
|
||||
use Traversable;
|
||||
|
||||
/**
|
||||
* Class AbstractCollection
|
||||
* @package Database\Base
|
||||
*/
|
||||
abstract class AbstractCollection extends Component implements \IteratorAggregate, \ArrayAccess, \Arrayable
|
||||
{
|
||||
|
||||
/**
|
||||
* @var ModelInterface[]
|
||||
*/
|
||||
private array $_item;
|
||||
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
public function getItems(): array
|
||||
{
|
||||
// TODO: Change the autogenerated stub
|
||||
return $this->_item;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Collection constructor.
|
||||
*
|
||||
* @param ActiveQuery $query
|
||||
* @param array $array
|
||||
* @param ModelInterface|null $model
|
||||
*/
|
||||
public function __construct(public ActiveQuery $query, public ?ModelInterface $model = null, array $array = [])
|
||||
{
|
||||
$this->_item = $array;
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return int
|
||||
*/
|
||||
#[Pure] public function getLength(): int
|
||||
{
|
||||
return count($this->_item);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $item
|
||||
*/
|
||||
public function setItems($item): void
|
||||
{
|
||||
$this->_item = $item;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $model
|
||||
*/
|
||||
public function setModel($model): void
|
||||
{
|
||||
$this->model = $model;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $item
|
||||
*/
|
||||
public function addItem($item): void
|
||||
{
|
||||
$this->_item[] = $item;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Traversable|CollectionIterator|ArrayIterator
|
||||
* @throws
|
||||
*/
|
||||
public function getIterator(): Traversable|CollectionIterator|ArrayIterator
|
||||
{
|
||||
return new CollectionIterator($this->model, $this->_item);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return mixed
|
||||
* @throws
|
||||
*/
|
||||
public function getModel(): ModelInterface
|
||||
{
|
||||
return $this->model;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return ActiveQuery
|
||||
*/
|
||||
public function makeNewQuery(): ActiveQuery
|
||||
{
|
||||
return $this->model::query();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param mixed $offset
|
||||
* @return bool
|
||||
*/
|
||||
public function offsetExists(mixed $offset): bool
|
||||
{
|
||||
return !empty($this->_item) && isset($this->_item[$offset]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $offset
|
||||
* @return ModelInterface|null
|
||||
* @throws
|
||||
*/
|
||||
public function offsetGet(mixed $offset): ?ModelInterface
|
||||
{
|
||||
if (!$this->offsetExists($offset)) {
|
||||
return NULL;
|
||||
}
|
||||
if (!($this->_item[$offset] instanceof ModelInterface)) {
|
||||
return $this->model->populates($this->_item[$offset]);
|
||||
}
|
||||
return $this->_item[$offset];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $offset
|
||||
* @param mixed $value
|
||||
*/
|
||||
#[ReturnTypeWillChange]
|
||||
public function offsetSet(mixed $offset, mixed $value): void
|
||||
{
|
||||
$this->_item[$offset] = $value;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param mixed $offset
|
||||
*/
|
||||
#[ReturnTypeWillChange]
|
||||
public function offsetUnset(mixed $offset): void
|
||||
{
|
||||
if ($this->offsetExists($offset)) {
|
||||
unset($this->_item[$offset]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
<?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|string $column
|
||||
* @param mixed|null $value
|
||||
* @return QueryTrait
|
||||
*/
|
||||
public function where(array|string $column, mixed $value = null): 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;
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database\Base;
|
||||
|
||||
|
||||
use Database\ModelInterface;
|
||||
|
||||
|
||||
/**
|
||||
* Class CollectionIterator
|
||||
* @package Database\Base
|
||||
*/
|
||||
class CollectionIterator extends \ArrayIterator
|
||||
{
|
||||
|
||||
|
||||
/**
|
||||
* @var ModelInterface|string
|
||||
*/
|
||||
private ModelInterface|string $model;
|
||||
|
||||
|
||||
/**
|
||||
* CollectionIterator constructor.
|
||||
* @param $model
|
||||
* @param array $array
|
||||
* @param int $flags
|
||||
* @throws
|
||||
*/
|
||||
public function __construct($model, array $array = [], int $flags = 0)
|
||||
{
|
||||
$this->model = $model;
|
||||
parent::__construct($array, $flags);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $current
|
||||
* @return ModelInterface
|
||||
* @throws
|
||||
*/
|
||||
protected function newModel($current): ModelInterface
|
||||
{
|
||||
return $this->model->populates($current);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @throws
|
||||
*/
|
||||
public function current(): ModelInterface
|
||||
{
|
||||
if (is_array($current = parent::current())) {
|
||||
$current = $this->newModel($current);
|
||||
}
|
||||
return $current;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+835
@@ -0,0 +1,835 @@
|
||||
<?php
|
||||
/** @noinspection ALL */
|
||||
/**
|
||||
* Created by PhpStorm.
|
||||
* User: whwyy
|
||||
* Date: 2018/3/30 0030
|
||||
* Time: 14:39
|
||||
*/
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database\Base;
|
||||
|
||||
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.');
|
||||
|
||||
|
||||
use ArrayAccess;
|
||||
use Database\ActiveQuery;
|
||||
use Database\Collection;
|
||||
use Database\Connection;
|
||||
use Database\DatabasesProviders;
|
||||
use Database\ModelInterface;
|
||||
use Database\Relation;
|
||||
use Database\SqlBuilder;
|
||||
use Exception;
|
||||
use Kiri;
|
||||
use Kiri\Abstracts\Component;
|
||||
use ReturnTypeWillChange;
|
||||
use ReflectionException;
|
||||
use validator\Validator;
|
||||
|
||||
/**
|
||||
* Class BOrm
|
||||
*
|
||||
* @package Kiri\Abstracts
|
||||
*
|
||||
* @property bool $isNowExample
|
||||
* @property array $attributes
|
||||
* @property array $oldAttributes
|
||||
*/
|
||||
abstract class Model extends Component implements ModelInterface, ArrayAccess, \Arrayable
|
||||
{
|
||||
|
||||
/** @var array */
|
||||
protected array $_attributes = [];
|
||||
|
||||
|
||||
/** @var array */
|
||||
protected array $_oldAttributes = [];
|
||||
|
||||
|
||||
/** @var null|string */
|
||||
protected string $primary = '';
|
||||
|
||||
|
||||
/**
|
||||
* @var bool
|
||||
*/
|
||||
protected bool $isNewExample = TRUE;
|
||||
|
||||
|
||||
/**
|
||||
* @var bool
|
||||
*/
|
||||
protected bool $skipValidate = false;
|
||||
|
||||
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
protected string $table = '';
|
||||
|
||||
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
protected string $connection = 'db';
|
||||
|
||||
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
protected array $_with = [];
|
||||
|
||||
|
||||
/**
|
||||
* @throws Exception
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
|
||||
$this->init();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param array $data
|
||||
* @return Model
|
||||
*/
|
||||
public function setWith(array $data): static
|
||||
{
|
||||
$this->_with = $data;
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
public function getWith(): array
|
||||
{
|
||||
return $this->_with;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
public function hasWith(): bool
|
||||
{
|
||||
return count($this->_with) > 0;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* object init
|
||||
*/
|
||||
public function clean(): void
|
||||
{
|
||||
$this->_attributes = [];
|
||||
$this->_oldAttributes = [];
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @throws Exception
|
||||
*/
|
||||
public function init(): void
|
||||
{
|
||||
$container = Kiri::getDi();
|
||||
$container->resolveProperties($container->getReflectionClass(get_called_class()), $this);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
public function getIsNowExample(): bool
|
||||
{
|
||||
return $this->isNewExample === TRUE;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param bool $bool
|
||||
* @return $this
|
||||
*/
|
||||
public function setIsNowExample(bool $bool = FALSE): static
|
||||
{
|
||||
$this->isNewExample = $bool;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
* @throws
|
||||
* get last exception or other error
|
||||
*/
|
||||
public function getLastError(): string
|
||||
{
|
||||
return $this->getLogger()->getLastError('mysql');
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
* @throws
|
||||
*/
|
||||
public function hasPrimary(): bool
|
||||
{
|
||||
return $this->primary != '';
|
||||
}
|
||||
|
||||
/**
|
||||
* @return null|string
|
||||
* @throws
|
||||
*/
|
||||
public function getPrimary(): string
|
||||
{
|
||||
if (!$this->hasPrimary()) {
|
||||
return '';
|
||||
}
|
||||
return $this->primary;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
* @throws
|
||||
*/
|
||||
public function hasPrimaryValue(): bool
|
||||
{
|
||||
if ($this->hasPrimary()) {
|
||||
return $this->getPrimaryValue() === null;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return int|null
|
||||
* @throws
|
||||
*/
|
||||
public function getPrimaryValue(): ?int
|
||||
{
|
||||
if ($this->hasPrimary()) {
|
||||
return (int)$this->_oldAttributes[$this->getPrimary()] ?? null;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int|string|array $param
|
||||
* @return Model|null
|
||||
* @throws
|
||||
*/
|
||||
public static function findOne(int|string|array|null $param): ?static
|
||||
{
|
||||
if (empty($param)) return null;
|
||||
$model = static::instance();
|
||||
$query = new ActiveQuery($model);
|
||||
$query->from($model->getTable())->alias('t1');
|
||||
if (is_numeric($param)) {
|
||||
$query->where([$model->getPrimary() => $param]);
|
||||
} else if (is_array($param)) {
|
||||
$query->where($param);
|
||||
} else {
|
||||
$query->whereRaw($param);
|
||||
}
|
||||
$data = $query->first();
|
||||
if ($data === false) {
|
||||
throw new Exception($model->getLastError());
|
||||
}
|
||||
return $data;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param int $param
|
||||
* @return Model|null
|
||||
* @throws
|
||||
*/
|
||||
public static function primary(int $param): ?static
|
||||
{
|
||||
$model = static::instance();
|
||||
$query = new ActiveQuery($model);
|
||||
$query->from($model->getTable())->alias('t1')->where([$model->getPrimary() => $param]);
|
||||
return $query->first();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return bool|int
|
||||
* @throws Exception
|
||||
*/
|
||||
public function optimize(): bool|int
|
||||
{
|
||||
return static::query()->execute('OPTIMIZE TABLE ' . $this->getTable());
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return static
|
||||
*/
|
||||
protected static function instance(): static
|
||||
{
|
||||
return new static();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param int|string|array $condition
|
||||
* @return static|null
|
||||
* @throws
|
||||
*/
|
||||
public static function first(int|string|array $condition): ?static
|
||||
{
|
||||
return static::findOne($condition);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string|array $condition
|
||||
* @return Collection
|
||||
* @throws
|
||||
*/
|
||||
public static function all(string|array $condition): Collection
|
||||
{
|
||||
$model = new ActiveQuery(static::instance());
|
||||
$model->from($model->getTable())->alias('t1');
|
||||
if (is_array($condition)) {
|
||||
$model->where($condition);
|
||||
} else {
|
||||
$model->whereRaw($condition);
|
||||
}
|
||||
return $model->get();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return ActiveQuery
|
||||
* @throws
|
||||
*/
|
||||
public static function query(): ActiveQuery
|
||||
{
|
||||
$model = new ActiveQuery(static::instance());
|
||||
$model->from($model->getTable())->alias('t1');
|
||||
return $model;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return Connection
|
||||
* @throws
|
||||
*/
|
||||
public function getConnection(): Connection
|
||||
{
|
||||
return Kiri::getDi()->get(DatabasesProviders::class)->get($this->connection);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param array|string $condition
|
||||
* @param array $attributes
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
protected static function deleteByCondition(array|string $condition = [], array $attributes = []): bool
|
||||
{
|
||||
$model = static::query();
|
||||
$model->bindParams($attributes);
|
||||
if (is_string($condition)) {
|
||||
$model->whereRaw($condition);
|
||||
} else {
|
||||
$model->where($condition);
|
||||
}
|
||||
return $model->delete();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return array
|
||||
* @throws
|
||||
*/
|
||||
public function getAttributes(): array
|
||||
{
|
||||
return $this->_attributes;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
public function getOldAttributes(): array
|
||||
{
|
||||
return $this->_oldAttributes;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $name
|
||||
* @param mixed $value
|
||||
* @return mixed
|
||||
*/
|
||||
public function setAttribute(string $name, mixed $value): mixed
|
||||
{
|
||||
$method = 'set' . ucfirst($name) . 'Attribute';
|
||||
if (method_exists($this, $method)) {
|
||||
$value = $this->{$method}($value);
|
||||
}
|
||||
return $this->_attributes[$name] = $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $name
|
||||
* @param mixed $value
|
||||
* @return mixed
|
||||
*/
|
||||
public function setOldAttribute(string $name, mixed $value): mixed
|
||||
{
|
||||
$method = 'set' . ucfirst($name) . 'Attribute';
|
||||
if (method_exists($this, $method)) {
|
||||
$value = $this->{$method}($value);
|
||||
}
|
||||
return $this->_oldAttributes[$name] = $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $param
|
||||
* @return $this
|
||||
* @throws
|
||||
*/
|
||||
public function setAttributes(array $param): static
|
||||
{
|
||||
foreach ($param as $key => $attribute) {
|
||||
$this->setAttribute($key, $attribute);
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param array $param
|
||||
* @return $this
|
||||
*/
|
||||
public function setOldAttributes(array $param): static
|
||||
{
|
||||
foreach ($param as $key => $attribute) {
|
||||
$this->setOldAttribute($key, $attribute);
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return $this|bool
|
||||
* @throws
|
||||
*/
|
||||
private function insert(): bool|static
|
||||
{
|
||||
$sql = SqlBuilder::builder($query = static::query())->insert($this->_attributes);
|
||||
$lastId = $this->getConnection()->createCommand($sql, $query->params)->exec();
|
||||
if ($lastId === false) {
|
||||
return false;
|
||||
}
|
||||
if ($this->hasPrimary()) {
|
||||
$this->_attributes[$this->getPrimary()] = $lastId;
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param array $old
|
||||
* @param array $condition
|
||||
* @param array $change
|
||||
* @return $this|bool
|
||||
* @throws
|
||||
*/
|
||||
protected function updateInternal(array $old, array $condition, array $change): bool|static
|
||||
{
|
||||
$query = static::query()->where($condition);
|
||||
if (count($change) < 1) {
|
||||
return true;
|
||||
}
|
||||
$generate = SqlBuilder::builder($query)->update($change);
|
||||
if ($generate === false) {
|
||||
return false;
|
||||
}
|
||||
if (!$this->getConnection()->createCommand($generate, $query->params)->exec()) {
|
||||
return FALSE;
|
||||
}
|
||||
return $this->refresh()->afterSave($old, $change);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool|$this
|
||||
* @throws
|
||||
*/
|
||||
public function save(): static|bool
|
||||
{
|
||||
if (!$this->validator($this->rules(), $this->_attributes) || !$this->beforeSave($this)) {
|
||||
return FALSE;
|
||||
}
|
||||
if (!$this->isNewExample) {
|
||||
return $this->updateInternal(...$this->arrayIntersect($this->_attributes));
|
||||
} else {
|
||||
return $this->insert();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return array<array, array, array>
|
||||
* @throws
|
||||
*/
|
||||
protected function arrayIntersect(array $params): array
|
||||
{
|
||||
$condition = [];
|
||||
$oldPrams = [];
|
||||
foreach ($this->_oldAttributes as $key => $attribute) {
|
||||
if (!array_key_exists($key, $params) || $params[$key] == $attribute) {
|
||||
$condition[$key] = $attribute;
|
||||
unset($params[$key]);
|
||||
} else {
|
||||
$oldPrams[$key] = $this->_oldAttributes[$key];
|
||||
}
|
||||
}
|
||||
if ($this->hasPrimary()) {
|
||||
$condition = [$this->getPrimary() => $this->getPrimaryValue()];
|
||||
}
|
||||
return [$oldPrams, $condition, $params];
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
public function getChanges(): array
|
||||
{
|
||||
if (!$this->isNewExample) {
|
||||
return \array_intersect_assoc($this->_oldAttributes, $this->_attributes);
|
||||
}
|
||||
return $this->_attributes;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param array $value
|
||||
* @return $this
|
||||
*/
|
||||
public function populates(array $value): static
|
||||
{
|
||||
$this->_attributes = $value;
|
||||
$this->_oldAttributes = $value;
|
||||
$this->setIsNowExample();
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param array $rule
|
||||
* @return bool
|
||||
* @throws
|
||||
*/
|
||||
public function validator(array $rule, array $params): bool
|
||||
{
|
||||
if (count($rule) < 1 || $this->skipValidate) {
|
||||
return TRUE;
|
||||
}
|
||||
$validate = $this->resolve($rule);
|
||||
if (!$validate->validation($params)) {
|
||||
return \Kiri::getLogger()->failure($validate->getError() . PHP_EOL, 'mysql');
|
||||
} else {
|
||||
return TRUE;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param array $rule
|
||||
* @return Validator
|
||||
* @throws
|
||||
*/
|
||||
private function resolve(array $rule): Validator
|
||||
{
|
||||
$validate = new Validator();
|
||||
foreach ($rule as $val) {
|
||||
$field = array_shift($val);
|
||||
if (is_string($field)) {
|
||||
$validate->make($this, [$field], $val);
|
||||
} else {
|
||||
$validate->make($this, $field, $val);
|
||||
}
|
||||
}
|
||||
return $validate;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $name
|
||||
* @return null
|
||||
* @throws
|
||||
*/
|
||||
public function getAttribute(string $name): mixed
|
||||
{
|
||||
return $this->_attributes[$name] ?? NULL;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return Relation|null
|
||||
* @throws
|
||||
*/
|
||||
public function getRelation(): ?Relation
|
||||
{
|
||||
return Kiri::getDi()->get(Relation::class);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $attribute
|
||||
* @return bool
|
||||
* @throws
|
||||
*/
|
||||
public function has(string $attribute): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
/**ƒ
|
||||
* @return string
|
||||
* @throws
|
||||
*/
|
||||
public function getTable(): string
|
||||
{
|
||||
$connection = $this->getConnection();
|
||||
$tablePrefix = $connection->tablePrefix;
|
||||
if (empty($this->table)) {
|
||||
throw new Exception('You need add static method `tableName` and return table name.');
|
||||
}
|
||||
$table = trim($this->table, '{%}');
|
||||
if (!empty($tablePrefix) && !str_starts_with($table, $tablePrefix)) {
|
||||
$table = $tablePrefix . $table;
|
||||
}
|
||||
return '`' . $connection->database . '`.' . $table;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param array $oldAttributes
|
||||
* @param array $changeAttributes
|
||||
* @return bool
|
||||
*/
|
||||
public function afterSave(array $oldAttributes, array $changeAttributes): bool
|
||||
{
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param self $model
|
||||
* @return bool
|
||||
* @throws
|
||||
*/
|
||||
public function beforeSave(self $model): bool
|
||||
{
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return static
|
||||
*/
|
||||
public function refresh(): static
|
||||
{
|
||||
$this->_oldAttributes = $this->_attributes;
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $name
|
||||
* @param mixed $value
|
||||
* @return void
|
||||
*/
|
||||
public function __set(string $name, mixed $value): void
|
||||
{
|
||||
if ($this->hasRelateMethod($name, 'set')) {
|
||||
$this->{'set' . ucfirst($name)}($value);
|
||||
} else {
|
||||
$method = 'set' . ucfirst($name) . 'Attribute';
|
||||
if (method_exists($this, $method)) {
|
||||
$value = $this->{$method} ($value);
|
||||
}
|
||||
$this->_attributes[$name] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $name
|
||||
* @return mixed
|
||||
*/
|
||||
public function __get(string $name): mixed
|
||||
{
|
||||
$value = $this->_attributes[$name] ?? null;
|
||||
if (!$this->hasRelateMethod($name)) {
|
||||
return $this->withPropertyOverride($name, $value);
|
||||
} else {
|
||||
return $this->withRelate($name);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $name
|
||||
* @param mixed|null $value
|
||||
* @return mixed
|
||||
*/
|
||||
protected function withPropertyOverride(string $name, mixed $value = null): mixed
|
||||
{
|
||||
$method = 'get' . ucfirst($name) . 'Attribute';
|
||||
if (method_exists($this, $method)) {
|
||||
return $this->{$method}($value);
|
||||
} else {
|
||||
return $value;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $name
|
||||
* @param string $prefix
|
||||
* @return bool
|
||||
*/
|
||||
protected function hasRelateMethod(string $name, string $prefix = 'get'): bool
|
||||
{
|
||||
return method_exists($this, $prefix . ucfirst($name));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $name
|
||||
* @return mixed
|
||||
*/
|
||||
protected function withRelate(string $name): mixed
|
||||
{
|
||||
$response = $this->{'get' . ucfirst($name)}();
|
||||
if ($response instanceof \Database\Traits\Relation) {
|
||||
$response = $response->get();
|
||||
}
|
||||
return $response;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $name
|
||||
* @return bool
|
||||
*/
|
||||
public function __isset(string $name): bool
|
||||
{
|
||||
return isset($this->_attributes[$name]);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param mixed $offset
|
||||
* @return bool
|
||||
* @throws
|
||||
*/
|
||||
public function offsetExists(mixed $offset): bool
|
||||
{
|
||||
return isset($this->_attributes[$offset]) || isset($this->_oldAttributes[$offset]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $offset
|
||||
* @return mixed
|
||||
* @throws
|
||||
*/
|
||||
public function offsetGet(mixed $offset): mixed
|
||||
{
|
||||
return $this->__get($offset);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $offset
|
||||
* @param mixed $value
|
||||
* @throws
|
||||
*/
|
||||
#[ReturnTypeWillChange] public function offsetSet(mixed $offset, mixed $value): void
|
||||
{
|
||||
$this->__set($offset, $value);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $offset
|
||||
* @throws
|
||||
*/
|
||||
#[ReturnTypeWillChange] public function offsetUnset(mixed $offset): void
|
||||
{
|
||||
if (!isset($this->_attributes[$offset]) && !isset($this->_oldAttributes[$offset])) {
|
||||
return;
|
||||
}
|
||||
unset($this->_attributes[$offset]);
|
||||
unset($this->_oldAttributes[$offset]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string ...$params
|
||||
* @return array
|
||||
*/
|
||||
public function unset(string ...$params): array
|
||||
{
|
||||
return array_diff_assoc($params, $this->_attributes);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param array $data
|
||||
* @return static
|
||||
* @throws
|
||||
*/
|
||||
public static function populate(array $data): static
|
||||
{
|
||||
$model = new static();
|
||||
$model->_attributes = $data;
|
||||
$model->_oldAttributes = $data;
|
||||
$model->setIsNowExample();
|
||||
return $model;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $name
|
||||
* @param array $arguments
|
||||
* @return mixed
|
||||
*/
|
||||
public static function __callStatic(string $name, array $arguments)
|
||||
{
|
||||
return (new static())->{$name}(...$arguments);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $field
|
||||
* @return array
|
||||
*/
|
||||
public function getOldAttribute(string $field): mixed
|
||||
{
|
||||
return $this->_oldAttributes[$field] ?? null;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+234
@@ -0,0 +1,234 @@
|
||||
<?php
|
||||
/**
|
||||
* Created by PhpStorm.
|
||||
* User: whwyy
|
||||
* Date: 2018/4/4 0004
|
||||
* Time: 13:38
|
||||
*/
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database;
|
||||
|
||||
use Database\Base\AbstractCollection;
|
||||
use Exception;
|
||||
use JetBrains\PhpStorm\Pure;
|
||||
|
||||
/**
|
||||
* Class Collection
|
||||
* @package Database
|
||||
* @property-read $length
|
||||
*/
|
||||
class Collection extends AbstractCollection
|
||||
{
|
||||
|
||||
|
||||
/**
|
||||
* @param string $field
|
||||
*
|
||||
* @return array|null
|
||||
*/
|
||||
public function values(string $field): ?array
|
||||
{
|
||||
return array_values($this->column($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 $this->batch()->update($attributes);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $field
|
||||
* @return array|null
|
||||
*/
|
||||
public function keyBy(string $field): ?array
|
||||
{
|
||||
$array = $this->toArray();
|
||||
$column = array_flip(array_column($array, $field));
|
||||
foreach ($column as $key => $value) {
|
||||
$column[$key] = $array[$value];
|
||||
}
|
||||
return $column;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param int $start
|
||||
* @param int $length
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
#[Pure] public function slice(int $start = 0, int $length = 20): array
|
||||
{
|
||||
if (empty($this->getItems())) {
|
||||
return [];
|
||||
}
|
||||
if (\count($this->getItems()) < $length) {
|
||||
return $this->getItems();
|
||||
} else {
|
||||
return array_slice($this->getItems(), $start, $length);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $field
|
||||
* @param string $setKey
|
||||
*
|
||||
* @return array|null
|
||||
*/
|
||||
public function column(string $field, string $setKey = ''): ?array
|
||||
{
|
||||
$data = $this->toArray();
|
||||
if (empty($data)) {
|
||||
return [];
|
||||
}
|
||||
if (!empty($setKey) && is_string($setKey)) {
|
||||
return array_column($data, $field, $setKey);
|
||||
} else {
|
||||
return array_column($data, $field);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $field
|
||||
*
|
||||
* @return float|int|null
|
||||
*/
|
||||
public function sum(string $field): float|int|null
|
||||
{
|
||||
$array = $this->column($field);
|
||||
if (empty($array)) {
|
||||
return NULL;
|
||||
}
|
||||
return array_sum($array);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return ModelInterface|array
|
||||
*/
|
||||
#[Pure] public function current(): ModelInterface|array
|
||||
{
|
||||
return current($this->getItems());
|
||||
}
|
||||
|
||||
/**
|
||||
* @return int
|
||||
*/
|
||||
#[Pure] public function size(): int
|
||||
{
|
||||
return count($this->getItems());
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array
|
||||
* @throws
|
||||
*/
|
||||
public function toArray(): array
|
||||
{
|
||||
$array = [];
|
||||
/** @var Model $value */
|
||||
foreach ($this as $value) {
|
||||
$array[] = $value->toArray();
|
||||
}
|
||||
return $array;
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws
|
||||
* 批量删除
|
||||
*/
|
||||
public function delete(): bool
|
||||
{
|
||||
$model = $this->getModel();
|
||||
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 $this->batch()->delete();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return ActiveQuery
|
||||
* @throws Exception
|
||||
*/
|
||||
private function batch(): ActiveQuery
|
||||
{
|
||||
return $this->makeNewQuery()->whereIn($this->getModel()->getPrimary(),
|
||||
$this->column($this->getModel()->getPrimary()));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $condition
|
||||
* @return Collection
|
||||
* @throws
|
||||
*/
|
||||
public function filter(array $condition): Collection|static
|
||||
{
|
||||
$_filters = [];
|
||||
if (empty($condition)) {
|
||||
return $this;
|
||||
}
|
||||
foreach ($this as $value) {
|
||||
if (!$this->filterCheck($value, $condition)) {
|
||||
continue;
|
||||
}
|
||||
$_filters[] = $value;
|
||||
}
|
||||
return new Collection($this->query, $this->model, $_filters);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param array|ModelInterface $value
|
||||
* @param array $condition
|
||||
* @return bool
|
||||
*/
|
||||
private function filterCheck(array|ModelInterface $value, array $condition): bool
|
||||
{
|
||||
$_value = $value;
|
||||
if ($_value instanceof ModelInterface) {
|
||||
$_value = $_value->toArray();
|
||||
}
|
||||
$_tmp = array_intersect_key($_value, $condition);
|
||||
if (count(array_diff_assoc($_tmp, $condition)) > 0) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $key
|
||||
* @param mixed $value
|
||||
* @return mixed
|
||||
*/
|
||||
public function exists(string $key, mixed $value): mixed
|
||||
{
|
||||
foreach ($this as $item) {
|
||||
if ($item->$key === $value) {
|
||||
return $item;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
#[Pure] public function isEmpty(): bool
|
||||
{
|
||||
return $this->size() < 1;
|
||||
}
|
||||
}
|
||||
+228
@@ -0,0 +1,228 @@
|
||||
<?php
|
||||
/**
|
||||
* Created by PhpStorm.
|
||||
* User: whwyy
|
||||
* Date: 2018/3/30 0030
|
||||
* Time: 15:23
|
||||
*/
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database;
|
||||
|
||||
|
||||
use Exception;
|
||||
use Kiri\Abstracts\Component;
|
||||
use Kiri\Di\Container;
|
||||
use PDO;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Class Command
|
||||
* @package Database
|
||||
*/
|
||||
class Command extends Component
|
||||
{
|
||||
|
||||
public Connection $connection;
|
||||
public ?string $sql = '';
|
||||
public array $params = [];
|
||||
|
||||
/**
|
||||
* @param array $params
|
||||
* @throws
|
||||
*/
|
||||
public function __construct(array $params = [])
|
||||
{
|
||||
parent::__construct();
|
||||
Container::configure($this, $params);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
* @throws
|
||||
*/
|
||||
public function incrOrDecr(): bool
|
||||
{
|
||||
return (bool)$this->_prepare();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return bool|array
|
||||
* @throws
|
||||
*/
|
||||
public function all(): bool|array
|
||||
{
|
||||
return $this->search('fetchAll');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array|bool|null
|
||||
* @throws
|
||||
*/
|
||||
public function one(): array|null|bool
|
||||
{
|
||||
return $this->search('fetch');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
* @throws Exception
|
||||
*/
|
||||
public function exists(): bool
|
||||
{
|
||||
$data = $this->search('fetch');
|
||||
if (!$data) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return mixed
|
||||
* @throws
|
||||
*/
|
||||
public function fetchColumn(): mixed
|
||||
{
|
||||
return $this->search('fetchColumn');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return mixed
|
||||
* @throws
|
||||
*/
|
||||
public function rowCount(): int
|
||||
{
|
||||
$data = $this->search('fetch');
|
||||
|
||||
return !$data ? 0 : +current($data);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
* @throws
|
||||
*/
|
||||
public function flush(): bool
|
||||
{
|
||||
return (bool)$this->_prepare();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return int|bool
|
||||
* @throws
|
||||
*/
|
||||
private function _prepare(): int|bool
|
||||
{
|
||||
$client = $this->connection->getConnection();
|
||||
try {
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param Throwable $throwable
|
||||
* @return bool
|
||||
*/
|
||||
protected function isRefresh(Throwable $throwable): bool
|
||||
{
|
||||
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();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $data
|
||||
* @return $this
|
||||
*/
|
||||
public function bindValues(array $data = []): static
|
||||
{
|
||||
if (count($data) > 0) {
|
||||
$this->params = array_merge($this->params, $data);
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,23 +1,23 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database\Condition;
|
||||
|
||||
|
||||
/**
|
||||
* Class BetweenCondition
|
||||
* @package Database\Condition
|
||||
*/
|
||||
class BetweenCondition extends Condition
|
||||
{
|
||||
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function builder(): string
|
||||
{
|
||||
return $this->column . ' BETWEEN ' . (int)$this->value[0] . ' AND ' . (int)$this->value[1];
|
||||
}
|
||||
|
||||
}
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database\Condition;
|
||||
|
||||
|
||||
/**
|
||||
* Class BetweenCondition
|
||||
* @package Database\Condition
|
||||
*/
|
||||
class BetweenCondition extends Condition
|
||||
{
|
||||
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function builder(): string
|
||||
{
|
||||
return $this->column . ' BETWEEN ' . (int)$this->value[0] . ' AND ' . (int)$this->value[1];
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,22 +1,22 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database\Condition;
|
||||
|
||||
|
||||
/**
|
||||
* Class ChildCondition
|
||||
* @package Database\Condition
|
||||
*/
|
||||
class ChildCondition extends Condition
|
||||
{
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function builder(): string
|
||||
{
|
||||
return $this->column . ' ' . $this->opera . ' (' . $this->value . ')';
|
||||
}
|
||||
|
||||
}
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database\Condition;
|
||||
|
||||
|
||||
/**
|
||||
* Class ChildCondition
|
||||
* @package Database\Condition
|
||||
*/
|
||||
class ChildCondition extends Condition
|
||||
{
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function builder(): string
|
||||
{
|
||||
return $this->column . ' ' . $this->opera . ' (' . $this->value . ')';
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database\Condition;
|
||||
|
||||
|
||||
use JetBrains\PhpStorm\Pure;
|
||||
use Kiri\Abstracts\Component;
|
||||
|
||||
/**
|
||||
* Class Condition
|
||||
* @package Database\Condition
|
||||
*/
|
||||
abstract class Condition extends Component
|
||||
{
|
||||
|
||||
protected string $column = '';
|
||||
protected string $opera = '=';
|
||||
protected mixed $value;
|
||||
protected array $attributes = [];
|
||||
|
||||
abstract public function builder();
|
||||
|
||||
/**
|
||||
* @param string $column
|
||||
*/
|
||||
public function setColumn(string $column): void
|
||||
{
|
||||
$this->column = $column;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $opera
|
||||
*/
|
||||
public function setOpera(string $opera): void
|
||||
{
|
||||
$this->opera = $opera;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $params
|
||||
*/
|
||||
public function setValue($params): void
|
||||
{
|
||||
if (is_array($params)) {
|
||||
$values = [];
|
||||
foreach ($params as $item => $value) {
|
||||
$values[$item] = is_numeric($value) ? $value : '\'' . $value . '\'';
|
||||
}
|
||||
$this->value = $values;
|
||||
} else {
|
||||
$this->value = $this->checkIsSqlString($params);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $params
|
||||
* @return int|string
|
||||
*/
|
||||
#[Pure] private function checkIsSqlString($params): int|string
|
||||
{
|
||||
if (is_numeric($params)) {
|
||||
return $params;
|
||||
}
|
||||
|
||||
$check = ltrim($params, '(');
|
||||
$check = strtolower(substr($check, 0, 6));
|
||||
if (in_array($check, ['update', 'select', 'insert', 'delete'])) {
|
||||
return $params;
|
||||
} else {
|
||||
return sprintf('\'%s\'', $params);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -1,24 +1,24 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database\Condition;
|
||||
|
||||
|
||||
use JetBrains\PhpStorm\Pure;
|
||||
|
||||
/**
|
||||
* Class DefaultCondition
|
||||
* @package Database\Condition
|
||||
*/
|
||||
class DefaultCondition extends Condition
|
||||
{
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
#[Pure] public function builder(): string
|
||||
{
|
||||
return sprintf('%s %s %s', $this->column, $this->opera, addslashes($this->value));
|
||||
}
|
||||
|
||||
}
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database\Condition;
|
||||
|
||||
|
||||
use JetBrains\PhpStorm\Pure;
|
||||
|
||||
/**
|
||||
* Class DefaultCondition
|
||||
* @package Database\Condition
|
||||
*/
|
||||
class DefaultCondition extends Condition
|
||||
{
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
#[Pure] public function builder(): string
|
||||
{
|
||||
return $this->column . ' ' . $this->opera . ' ' . addslashes($this->value);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database\Condition;
|
||||
|
||||
/**
|
||||
* Class HashCondition
|
||||
* @package Yoc\db\condition
|
||||
*/
|
||||
class HashCondition extends Condition
|
||||
{
|
||||
|
||||
/**
|
||||
* @return string
|
||||
* @throws
|
||||
*/
|
||||
public function builder(): string
|
||||
{
|
||||
$array = [];
|
||||
if (count($this->value) < 1) {
|
||||
throw new \Exception('Builder data by a empty array.');
|
||||
}
|
||||
foreach ($this->value as $key => $value) {
|
||||
$array[] = $key . '=' . addslashes($value);
|
||||
}
|
||||
return implode(' AND ', $array);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database\Condition;
|
||||
|
||||
use JetBrains\PhpStorm\Pure;
|
||||
|
||||
/**
|
||||
* Class InCondition
|
||||
* @package Database\Condition
|
||||
*/
|
||||
class InCondition extends Condition
|
||||
{
|
||||
|
||||
|
||||
/**
|
||||
* @return string
|
||||
* @throws
|
||||
*/
|
||||
#[Pure] public function builder(): string
|
||||
{
|
||||
if (is_array($this->value)) {
|
||||
return $this->column . ' IN (' . implode(',', $this->value) . ')';
|
||||
} else {
|
||||
return $this->column . ' IN (' . $this->value . ')';
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,20 +1,24 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace Database\Condition;
|
||||
|
||||
|
||||
/**
|
||||
* Class JsonCondition
|
||||
* @package Database\Condition
|
||||
*/
|
||||
class JsonCondition extends Condition
|
||||
{
|
||||
|
||||
|
||||
public function builder()
|
||||
{
|
||||
// TODO: Implement builder() method.
|
||||
}
|
||||
|
||||
}
|
||||
<?php
|
||||
|
||||
|
||||
namespace Database\Condition;
|
||||
|
||||
|
||||
/**
|
||||
* Class JsonCondition
|
||||
* @package Database\Condition
|
||||
*/
|
||||
class JsonCondition extends Condition
|
||||
{
|
||||
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
public function builder(): bool
|
||||
{
|
||||
// TODO: Implement builder() method.
|
||||
return \json_validate($this->value);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,28 +1,26 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database\Condition;
|
||||
|
||||
use Kiri\Core\Str;
|
||||
|
||||
/**
|
||||
* Class LLikeCondition
|
||||
* @package Database\Condition
|
||||
*/
|
||||
class LLikeCondition extends Condition
|
||||
{
|
||||
|
||||
public string $pos = '';
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function builder(): string
|
||||
{
|
||||
if (!is_string($this->value)) {
|
||||
$this->value = array_shift($this->value);
|
||||
}
|
||||
return $this->column . ' LIKE \'%' . addslashes($this->value) . '\'';
|
||||
}
|
||||
|
||||
}
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database\Condition;
|
||||
|
||||
/**
|
||||
* Class LLikeCondition
|
||||
* @package Database\Condition
|
||||
*/
|
||||
class LLikeCondition extends Condition
|
||||
{
|
||||
|
||||
public string $pos = '';
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function builder(): string
|
||||
{
|
||||
if (!is_string($this->value)) {
|
||||
$this->value = array_shift($this->value);
|
||||
}
|
||||
return $this->column . ' LIKE \'%' . addslashes($this->value) . '\'';
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,28 +1,26 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database\Condition;
|
||||
|
||||
use Kiri\Core\Str;
|
||||
|
||||
/**
|
||||
* Class LikeCondition
|
||||
* @package Database\Condition
|
||||
*/
|
||||
class LikeCondition extends Condition
|
||||
{
|
||||
|
||||
public string $pos = '';
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function builder(): string
|
||||
{
|
||||
if (!is_string($this->value)) {
|
||||
$this->value = array_shift($this->value);
|
||||
}
|
||||
return $this->column . ' LIKE \'%' . addslashes($this->value) . '%\'';
|
||||
}
|
||||
|
||||
}
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database\Condition;
|
||||
|
||||
/**
|
||||
* Class LikeCondition
|
||||
* @package Database\Condition
|
||||
*/
|
||||
class LikeCondition extends Condition
|
||||
{
|
||||
|
||||
public string $pos = '';
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function builder(): string
|
||||
{
|
||||
if (!is_string($this->value)) {
|
||||
$this->value = array_shift($this->value);
|
||||
}
|
||||
return $this->column . ' LIKE \'%' . addslashes($this->value) . '%\'';
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,78 +1,78 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database\Condition;
|
||||
|
||||
/**
|
||||
* Class MathematicsCondition
|
||||
* @package Database\Condition
|
||||
*/
|
||||
class MathematicsCondition extends Condition
|
||||
{
|
||||
|
||||
public string $type = '';
|
||||
|
||||
/**
|
||||
* @return mixed
|
||||
*/
|
||||
public function builder(): mixed
|
||||
{
|
||||
return $this->{strtolower($this->type)}((float)$this->value);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $value
|
||||
* @return string
|
||||
*/
|
||||
public function eq($value): string
|
||||
{
|
||||
return $this->column . ' = ' . $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $value
|
||||
* @return string
|
||||
*/
|
||||
public function neq($value): string
|
||||
{
|
||||
return $this->column . ' <> ' . $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $value
|
||||
* @return string
|
||||
*/
|
||||
public function gt($value): string
|
||||
{
|
||||
return $this->column . ' > ' . $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $value
|
||||
* @return string
|
||||
*/
|
||||
public function egt($value): string
|
||||
{
|
||||
return $this->column . ' >= ' . $value;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $value
|
||||
* @return string
|
||||
*/
|
||||
public function lt($value): string
|
||||
{
|
||||
return $this->column . ' < ' . $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $value
|
||||
* @return string
|
||||
*/
|
||||
public function elt($value): string
|
||||
{
|
||||
return $this->column . ' <= ' . $value;
|
||||
}
|
||||
|
||||
}
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database\Condition;
|
||||
|
||||
/**
|
||||
* Class MathematicsCondition
|
||||
* @package Database\Condition
|
||||
*/
|
||||
class MathematicsCondition extends Condition
|
||||
{
|
||||
|
||||
public string $type = '';
|
||||
|
||||
/**
|
||||
* @return mixed
|
||||
*/
|
||||
public function builder(): mixed
|
||||
{
|
||||
return $this->{strtolower($this->type)}((float)$this->value);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $value
|
||||
* @return string
|
||||
*/
|
||||
public function eq($value): string
|
||||
{
|
||||
return $this->column . ' = ' . $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $value
|
||||
* @return string
|
||||
*/
|
||||
public function neq($value): string
|
||||
{
|
||||
return $this->column . ' <> ' . $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $value
|
||||
* @return string
|
||||
*/
|
||||
public function gt($value): string
|
||||
{
|
||||
return $this->column . ' > ' . $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $value
|
||||
* @return string
|
||||
*/
|
||||
public function egt($value): string
|
||||
{
|
||||
return $this->column . ' >= ' . $value;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $value
|
||||
* @return string
|
||||
*/
|
||||
public function lt($value): string
|
||||
{
|
||||
return $this->column . ' < ' . $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $value
|
||||
* @return string
|
||||
*/
|
||||
public function elt($value): string
|
||||
{
|
||||
return $this->column . ' <= ' . $value;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,22 +1,22 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database\Condition;
|
||||
|
||||
/**
|
||||
* Class NotBetweenCondition
|
||||
* @package Database\Condition
|
||||
*/
|
||||
class NotBetweenCondition extends Condition
|
||||
{
|
||||
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function builder(): string
|
||||
{
|
||||
return $this->column . ' NOT BETWEEN ' . (int)$this->value[0] . ' AND ' . (int)$this->value[1];
|
||||
}
|
||||
|
||||
}
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database\Condition;
|
||||
|
||||
/**
|
||||
* Class NotBetweenCondition
|
||||
* @package Database\Condition
|
||||
*/
|
||||
class NotBetweenCondition extends Condition
|
||||
{
|
||||
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function builder(): string
|
||||
{
|
||||
return $this->column . ' NOT BETWEEN ' . (int)$this->value[0] . ' AND ' . (int)$this->value[1];
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database\Condition;
|
||||
|
||||
use JetBrains\PhpStorm\Pure;
|
||||
|
||||
/**
|
||||
* Class NotInCondition
|
||||
* @package Database\Condition
|
||||
*/
|
||||
class NotInCondition extends Condition
|
||||
{
|
||||
|
||||
|
||||
/**
|
||||
* @return string|null
|
||||
* @throws
|
||||
*/
|
||||
#[Pure] public function builder(): ?string
|
||||
{
|
||||
if (!is_array($this->value)) {
|
||||
throw new \Exception('Builder data by a empty string. need array');
|
||||
}
|
||||
$value = '\'' . implode('\',\'', $this->value) . '\'';
|
||||
return '`' . $this->column . '` not in(' . $value . ')';
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,28 +1,26 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database\Condition;
|
||||
|
||||
use Kiri\Core\Str;
|
||||
|
||||
/**
|
||||
* Class NotLikeCondition
|
||||
* @package Database\Condition
|
||||
*/
|
||||
class NotLikeCondition extends Condition
|
||||
{
|
||||
|
||||
public string $pos = '';
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function builder(): string
|
||||
{
|
||||
if (!is_string($this->value)) {
|
||||
$this->value = array_shift($this->value);
|
||||
}
|
||||
return $this->column . ' NOT LIKE \'%' . addslashes($this->value) . '%\'';
|
||||
}
|
||||
|
||||
}
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database\Condition;
|
||||
|
||||
/**
|
||||
* Class NotLikeCondition
|
||||
* @package Database\Condition
|
||||
*/
|
||||
class NotLikeCondition extends Condition
|
||||
{
|
||||
|
||||
public string $pos = '';
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function builder(): string
|
||||
{
|
||||
if (!is_string($this->value)) {
|
||||
$this->value = array_shift($this->value);
|
||||
}
|
||||
return $this->column . ' NOT LIKE \'%' . addslashes($this->value) . '%\'';
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,27 +1,27 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database\Condition;
|
||||
|
||||
|
||||
use JetBrains\PhpStorm\Pure;
|
||||
|
||||
/**
|
||||
* Class OrCondition
|
||||
* @package Database\Condition
|
||||
*/
|
||||
class OrCondition extends Condition
|
||||
{
|
||||
|
||||
public array $oldParams = [];
|
||||
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
#[Pure] public function builder(): string
|
||||
{
|
||||
return sprintf('(%s) OR %s', implode(' AND ', $this->oldParams), addslashes($this->value));
|
||||
}
|
||||
|
||||
}
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database\Condition;
|
||||
|
||||
|
||||
use JetBrains\PhpStorm\Pure;
|
||||
|
||||
/**
|
||||
* Class OrCondition
|
||||
* @package Database\Condition
|
||||
*/
|
||||
class OrCondition extends Condition
|
||||
{
|
||||
|
||||
public array $oldParams = [];
|
||||
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
#[Pure] public function builder(): string
|
||||
{
|
||||
return '(' . implode(' AND ', $this->oldParams) . ') OR ' . addslashes($this->value);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,28 +1,26 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database\Condition;
|
||||
|
||||
use Kiri\Core\Str;
|
||||
|
||||
/**
|
||||
* Class RLikeCondition
|
||||
* @package Database\Condition
|
||||
*/
|
||||
class RLikeCondition extends Condition
|
||||
{
|
||||
|
||||
public string $pos = '';
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function builder(): string
|
||||
{
|
||||
if (!is_string($this->value)) {
|
||||
$this->value = array_shift($this->value);
|
||||
}
|
||||
return sprintf('%s LIKE \'%s\'', $this->column, addslashes($this->value));
|
||||
}
|
||||
|
||||
}
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database\Condition;
|
||||
|
||||
/**
|
||||
* Class RLikeCondition
|
||||
* @package Database\Condition
|
||||
*/
|
||||
class RLikeCondition extends Condition
|
||||
{
|
||||
|
||||
public string $pos = '';
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function builder(): string
|
||||
{
|
||||
if (!is_string($this->value)) {
|
||||
$this->value = array_shift($this->value);
|
||||
}
|
||||
return sprintf('%s LIKE \'%s\'', $this->column, addslashes($this->value));
|
||||
}
|
||||
|
||||
}
|
||||
+378
@@ -0,0 +1,378 @@
|
||||
<?php
|
||||
/**
|
||||
* Created by PhpStorm.
|
||||
* User: whwyy
|
||||
* Date: 2018/3/30 0030
|
||||
* Time: 14:09
|
||||
*/
|
||||
declare(strict_types=1);
|
||||
|
||||
|
||||
namespace Database;
|
||||
|
||||
|
||||
use Database\Affair\BeginTransaction;
|
||||
use Database\Affair\Commit;
|
||||
use Database\Affair\Rollback;
|
||||
use Exception;
|
||||
use Kiri;
|
||||
use Kiri\Server\Events\OnWorkerExit;
|
||||
use Kiri\Abstracts\Component;
|
||||
use Kiri\Di\Context;
|
||||
use Kiri\Pool\Pool;
|
||||
use Kiri\Events\EventProvider;
|
||||
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;
|
||||
|
||||
//use PDO;
|
||||
|
||||
/**
|
||||
* Class Connection
|
||||
* @package Database
|
||||
*/
|
||||
class Connection extends Component
|
||||
{
|
||||
|
||||
public string $id = 'db';
|
||||
public string $cds = '';
|
||||
public string $password = '';
|
||||
public string $username = '';
|
||||
public string $charset = 'utf-8';
|
||||
public string $tablePrefix = '';
|
||||
public string $database = '';
|
||||
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;
|
||||
public string $cacheDriver = 'redis';
|
||||
public array $attributes = [];
|
||||
public array $slave = [];
|
||||
protected ?\Closure $_println = null;
|
||||
|
||||
|
||||
/**
|
||||
* @var StdoutLogger
|
||||
*/
|
||||
#[Container(LoggerInterface::class)]
|
||||
public StdoutLogger $logger;
|
||||
|
||||
/**
|
||||
* @param Pool $connections
|
||||
*/
|
||||
public function __construct(public Pool $connections)
|
||||
{
|
||||
parent::__construct();
|
||||
|
||||
$this->_println = \config('databases.logger', null);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $sql
|
||||
* @param array $params
|
||||
* @return void
|
||||
*/
|
||||
public function println(string $sql, array $params = []): void
|
||||
{
|
||||
if (is_callable($this->_println)) {
|
||||
call_user_func($this->_println, $sql, $params);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return void
|
||||
* @throws
|
||||
*/
|
||||
public function init(): void
|
||||
{
|
||||
$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->getName(), $this->pool['min'] ?? 1);
|
||||
$length = $pool->size($this->getName());
|
||||
for ($i = 0; $i < $length; $i++) {
|
||||
try {
|
||||
if (($client = $this->validator($pool)) === false) {
|
||||
break;
|
||||
}
|
||||
$pool->push($this->getName(), $client);
|
||||
} catch (\Throwable $exception) {
|
||||
if (!str_contains($exception->getMessage(), 'Client timeout.')) {
|
||||
$this->logger->error(throwable($exception), [$this->cds]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
private function getName(): string
|
||||
{
|
||||
return 'mysql.' . $this->cds;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param Pool $pool
|
||||
* @return PDO|bool
|
||||
* @throws
|
||||
*/
|
||||
protected function validator(Pool $pool): PDO|bool
|
||||
{
|
||||
/** @var $client PDO */
|
||||
if (($client = $pool->get($this->getName())) === false) {
|
||||
return false;
|
||||
}
|
||||
if ($client->query('select 1') === false) {
|
||||
throw new Exception($client->errorInfo()[1]);
|
||||
}
|
||||
return $client;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return PDO
|
||||
* @throws
|
||||
*/
|
||||
public function getConnection(): PDO
|
||||
{
|
||||
if (!$this->inTransaction()) {
|
||||
return $this->getNormalClientHealth();
|
||||
} else {
|
||||
return $this->getTransactionClient();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return PDO
|
||||
* @throws
|
||||
*/
|
||||
protected function getNormalClientHealth(): PDO
|
||||
{
|
||||
$data = $this->pool()->get($this->getName(), $this->waite_time);
|
||||
if ($data === false) {
|
||||
throw new Exception('Client Waite timeout.');
|
||||
}
|
||||
return $data;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return $this
|
||||
* @throws
|
||||
*/
|
||||
public function beginTransaction(): static
|
||||
{
|
||||
if ($this->storey < 0) {
|
||||
$this->storey = 0;
|
||||
}
|
||||
$this->storey++;
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @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(): void
|
||||
{
|
||||
$this->storey--;
|
||||
if ($this->storey == 0) {
|
||||
if (!Context::exists($this->cds)) {
|
||||
return;
|
||||
}
|
||||
$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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return void
|
||||
* @throws
|
||||
*/
|
||||
public function clear(): void
|
||||
{
|
||||
/** @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->getName(), $pdo);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
*
|
||||
* 回收链接
|
||||
* @throws
|
||||
*/
|
||||
public function clear_connection(): void
|
||||
{
|
||||
$this->pool()->flush($this->getName(), 0);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @throws
|
||||
*/
|
||||
public function disconnect(): void
|
||||
{
|
||||
if ($this->timerId > -1) {
|
||||
Timer::clear($this->timerId);
|
||||
}
|
||||
$this->pool()->close($this->getName());
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return PDO
|
||||
*/
|
||||
public function newConnect(): \PDO
|
||||
{
|
||||
$pdo = new PDO($this->database, $this->cds, $this->username, $this->password, [
|
||||
// $pdo = new \PDO('mysql:dbname=' . $this->database . ';host=' . $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->getName())) {
|
||||
$this->connections->created($this->getName(), $this->pool['max'] ?? 1, [$this, 'newConnect']);
|
||||
}
|
||||
return $this->connections;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database;
|
||||
|
||||
|
||||
use Exception;
|
||||
use Kiri;
|
||||
use Kiri\Abstracts\Providers;
|
||||
|
||||
/**
|
||||
* Class DatabasesProviders
|
||||
* @package Database
|
||||
*/
|
||||
class DatabasesProviders extends Providers
|
||||
{
|
||||
|
||||
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
protected array $connections = [];
|
||||
|
||||
|
||||
/**
|
||||
* @return void
|
||||
* @throws
|
||||
*/
|
||||
public function onImport(): void
|
||||
{
|
||||
$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 string $name
|
||||
* @return Connection
|
||||
* @throws Exception
|
||||
*/
|
||||
public function get(string $name): Connection
|
||||
{
|
||||
return $this->connections[$name];
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $key
|
||||
* @param array $connection
|
||||
* @return void
|
||||
* @throws Exception
|
||||
*/
|
||||
protected function set(string $key, array $connection): void
|
||||
{
|
||||
$this->connections[$key] = Kiri::createObject($connection);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param array $database
|
||||
* @return 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'],
|
||||
'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'
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
<?php
|
||||
/**
|
||||
* Created by PhpStorm.
|
||||
* User: whwyy
|
||||
* Date: 2018/4/4 0004
|
||||
* Time: 15:40
|
||||
*/
|
||||
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;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Class Db
|
||||
* @package Database
|
||||
*/
|
||||
class Db extends QueryTrait implements ISqlBuilder
|
||||
{
|
||||
|
||||
private static bool $_inTransaction = false;
|
||||
|
||||
|
||||
/**
|
||||
* @var Connection|null
|
||||
*/
|
||||
private ?Connection $connection = null;
|
||||
|
||||
|
||||
/**
|
||||
* @param string|Connection $dbname
|
||||
* @return Db
|
||||
* @throws
|
||||
*/
|
||||
public static function connect(string|Connection $dbname): Db
|
||||
{
|
||||
$db = new Db();
|
||||
if (is_string($dbname)) {
|
||||
$db->connection = Kiri::getDi()->get(DatabasesProviders::class)->get($dbname);
|
||||
} else {
|
||||
$db->connection = $dbname;
|
||||
}
|
||||
return $db;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return void
|
||||
* @throws
|
||||
*/
|
||||
public static function beginTransaction(): void
|
||||
{
|
||||
fire(new BeginTransaction());
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return void
|
||||
* @throws
|
||||
*/
|
||||
public static function commit(): void
|
||||
{
|
||||
fire(new Commit());
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return void
|
||||
* @throws
|
||||
*/
|
||||
public static function rollback(): void
|
||||
{
|
||||
fire(new Rollback());
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $table
|
||||
* @param string $database
|
||||
* @return static
|
||||
*/
|
||||
public static function table(string $table, string $database = 'db'): Db|static
|
||||
{
|
||||
return self::connect($database)->from($table);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $column
|
||||
* @param string $alias
|
||||
* @return string
|
||||
*/
|
||||
public static function any_value(string $column, string $alias = ''): string
|
||||
{
|
||||
if (empty($alias)) {
|
||||
$alias = $column . '_any_value';
|
||||
}
|
||||
return 'ANY_VALUE(' . $column . ') as ' . $alias;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return int
|
||||
*/
|
||||
public function count(): int
|
||||
{
|
||||
return $this->connection->createCommand(SqlBuilder::builder($this)->count())->rowCount();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
* @throws Exception
|
||||
*/
|
||||
public function exists(): bool
|
||||
{
|
||||
return $this->connection->createCommand(SqlBuilder::builder($this->limit(1))->exists())->exists();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $sql
|
||||
* @param array $attributes
|
||||
* @return array|bool|int|string|null
|
||||
* @throws
|
||||
*/
|
||||
public function fetchAll(string $sql, array $attributes = []): int|bool|array|string|null
|
||||
{
|
||||
return $this->connection->createCommand($sql, $attributes)->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $sql
|
||||
* @param array $attributes
|
||||
* @return array|null
|
||||
*/
|
||||
public function fetch(string $sql, array $attributes = []): ?array
|
||||
{
|
||||
return $this->connection->createCommand($sql, $attributes)->one();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
public function delete(): bool
|
||||
{
|
||||
return $this->connection->createCommand(SqlBuilder::builder($this)->delete())->delete();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return bool|array|null
|
||||
*/
|
||||
public function first(): bool|array|null
|
||||
{
|
||||
return $this->connection->createCommand(SqlBuilder::builder($this)->one())->one();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return bool|array
|
||||
*/
|
||||
public function get(): bool|array
|
||||
{
|
||||
return $this->connection->createCommand(SqlBuilder::builder($this)->all())->all();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $sql
|
||||
* @return mixed
|
||||
*/
|
||||
public function exec(string $sql): mixed
|
||||
{
|
||||
return $this->connection->createCommand($sql)->exec();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $sql
|
||||
* @return array|bool|null
|
||||
*/
|
||||
public function query(string $sql): array|bool|null
|
||||
{
|
||||
return $this->connection->createCommand($sql)->one();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $sql
|
||||
* @return array|bool
|
||||
*/
|
||||
public function queryAll(string $sql): array|bool
|
||||
{
|
||||
return $this->connection->createCommand($sql)->all();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $table
|
||||
* @return array|bool|null
|
||||
* @throws
|
||||
*/
|
||||
public static function show(string $table): array|bool|null
|
||||
{
|
||||
if ($table == '') {
|
||||
return null;
|
||||
}
|
||||
$connection = static::getDefaultConnection();
|
||||
|
||||
$table = [' const TABLE = \'select * from %s where REFERENCED_TABLE_NAME=%s\';'];
|
||||
return $connection->createCommand((new Query())
|
||||
->from('INFORMATION_SCHEMA.KEY_COLUMN_USAGE')
|
||||
->where(['REFERENCED_TABLE_NAME' => $table])
|
||||
->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 string $database
|
||||
* @return mixed
|
||||
* @throws
|
||||
*/
|
||||
public static function getDefaultConnection(?Connection $connection = null, string $database = 'db'): Connection
|
||||
{
|
||||
if ($connection instanceof Connection) {
|
||||
return $connection;
|
||||
}
|
||||
$databases = \config('databases.connections', []);
|
||||
$providers = Kiri::getDi()->get(DatabasesProviders::class);
|
||||
if (empty($databases) || !is_array($databases)) {
|
||||
throw new Exception('Please configure the database link.');
|
||||
}
|
||||
return $providers->get($databases[$database]);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database;
|
||||
|
||||
use Database\Traits\HasBase;
|
||||
use Exception;
|
||||
use Kiri;
|
||||
|
||||
/**
|
||||
* Class HasCount
|
||||
* @package Database
|
||||
*/
|
||||
class HasCount extends HasBase
|
||||
{
|
||||
|
||||
/**
|
||||
* @return array|null|ModelInterface
|
||||
* @throws
|
||||
*/
|
||||
public function get(): array|ModelInterface|null
|
||||
{
|
||||
$relation = Kiri::getDi()->get(Relation::class);
|
||||
return $relation->get($this->name);
|
||||
}
|
||||
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
/**
|
||||
* Created by PhpStorm.
|
||||
* User: whwyy
|
||||
* Date: 2018/4/4 0004
|
||||
* Time: 13:58
|
||||
*/
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database;
|
||||
|
||||
use Database\Traits\HasBase;
|
||||
use Exception;
|
||||
use Kiri;
|
||||
|
||||
/**
|
||||
* Class HasMany
|
||||
* @package Database
|
||||
*
|
||||
* @method with($name)
|
||||
*/
|
||||
class HasMany extends HasBase
|
||||
{
|
||||
|
||||
/**
|
||||
* @return array|null|Collection
|
||||
* @throws
|
||||
*/
|
||||
public function get(): array|Collection|null
|
||||
{
|
||||
$relation = Kiri::getDi()->get(Relation::class);
|
||||
return $relation->get($this->name);
|
||||
}
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
/**
|
||||
* Created by PhpStorm.
|
||||
* User: whwyy
|
||||
* Date: 2018/4/4 0004
|
||||
* Time: 13:47
|
||||
*/
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database;
|
||||
|
||||
use Database\Traits\HasBase;
|
||||
use Exception;
|
||||
use Kiri;
|
||||
|
||||
/**
|
||||
* Class HasOne
|
||||
* @package Database
|
||||
* @internal Query
|
||||
*/
|
||||
class HasOne extends HasBase
|
||||
{
|
||||
|
||||
/**
|
||||
* @return array|null|ModelInterface
|
||||
* @throws
|
||||
*/
|
||||
public function get(): array|ModelInterface|null
|
||||
{
|
||||
$relation = Kiri::getDi()->get(Relation::class);
|
||||
return $relation->first($this->name);
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace Database;
|
||||
|
||||
|
||||
interface ISqlBuilder
|
||||
{
|
||||
|
||||
}
|
||||
<?php
|
||||
|
||||
|
||||
namespace Database;
|
||||
|
||||
|
||||
interface ISqlBuilder
|
||||
{
|
||||
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,369 @@
|
||||
<?php
|
||||
/**
|
||||
* Created by PhpStorm.
|
||||
* User: whwyy
|
||||
* Date: 2018/3/30 0030
|
||||
* Time: 14:39
|
||||
*/
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database;
|
||||
|
||||
|
||||
use Database\Base\ActiveQueryInterface;
|
||||
use Exception;
|
||||
|
||||
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.');
|
||||
|
||||
/**
|
||||
* Class Orm
|
||||
* @package Database
|
||||
*
|
||||
* @property $attributes
|
||||
* @property-read $oldAttributes
|
||||
*
|
||||
* @mixin ActiveQueryInterface
|
||||
*/
|
||||
class Model extends Base\Model
|
||||
{
|
||||
|
||||
|
||||
/**
|
||||
* @param string $column
|
||||
* @param int|float $value
|
||||
* @return ModelInterface|false
|
||||
* @throws
|
||||
*/
|
||||
public function increment(string $column, int|float $value): bool|ModelInterface
|
||||
{
|
||||
if (!$this->mathematics([$column => $value], '+')) {
|
||||
return false;
|
||||
}
|
||||
$this->{$column} += $value;
|
||||
return $this->refresh();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $column
|
||||
* @param int|float $value
|
||||
* @return ModelInterface|false
|
||||
* @throws
|
||||
*/
|
||||
public function decrement(string $column, int|float $value): bool|ModelInterface
|
||||
{
|
||||
if (!$this->mathematics([$column => $value], '-')) {
|
||||
return false;
|
||||
}
|
||||
$this->{$column} -= $value;
|
||||
return $this->refresh();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param array $columns
|
||||
* @return ModelInterface|false
|
||||
* @throws
|
||||
*/
|
||||
public function increments(array $columns): bool|static
|
||||
{
|
||||
if (!$this->mathematics($columns, '+')) {
|
||||
return false;
|
||||
}
|
||||
foreach ($columns as $key => $attribute) {
|
||||
$this->$key += $attribute;
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param array $columns
|
||||
* @return ModelInterface|false
|
||||
* @throws
|
||||
*/
|
||||
public function decrements(array $columns): bool|static
|
||||
{
|
||||
if (!$this->mathematics($columns, '-')) {
|
||||
return false;
|
||||
}
|
||||
foreach ($columns as $key => $attribute) {
|
||||
$this->$key -= $attribute;
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $condition
|
||||
* @param array $attributes
|
||||
* @return bool|static
|
||||
* @throws
|
||||
*/
|
||||
public static function findOrCreate(array $condition, array $attributes): bool|static
|
||||
{
|
||||
$model = static::instance();
|
||||
$connection = $model->getConnection()->beginTransaction();
|
||||
try {
|
||||
/** @var static $select */
|
||||
$select = $model::query()->where($condition)->first();
|
||||
if ($select === null) {
|
||||
$select = $model::populate(array_merge($condition, $attributes));
|
||||
if (!$select->save()) {
|
||||
throw new Exception('保存失败: ' . $model->getLastError());
|
||||
}
|
||||
}
|
||||
$connection->commit();
|
||||
return $select;
|
||||
} catch (\Throwable $throwable) {
|
||||
$connection->rollback();
|
||||
return \Kiri::getLogger()->failure($throwable);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param array $condition
|
||||
* @param array $attributes
|
||||
* @return bool|static
|
||||
* @throws
|
||||
*/
|
||||
public static function createOrUpdate(array $condition, array $attributes = []): bool|static
|
||||
{
|
||||
$model = static::instance();
|
||||
$connection = $model->getConnection()->beginTransaction();
|
||||
try {
|
||||
/** @var static $select */
|
||||
$select = static::query()->where($condition)->first();
|
||||
if (empty($select)) {
|
||||
$select = static::populate($condition);
|
||||
}
|
||||
$select->attributes = $attributes;
|
||||
if (!$select->save()) {
|
||||
throw new Exception('保存失败: ' . $model->getLastError());
|
||||
}
|
||||
$connection->commit();
|
||||
return $select;
|
||||
} catch (\Throwable $throwable) {
|
||||
$connection->rollback();
|
||||
return \Kiri::getLogger()->failure($throwable);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $name
|
||||
* @param array $arguments
|
||||
* @return Model|ActiveQuery
|
||||
*/
|
||||
public static function __callStatic(string $name, array $arguments): static|ActiveQuery
|
||||
{
|
||||
// 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 $activeQuery->buildCommand($create)->exec();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param array $params
|
||||
* @return ModelInterface|bool
|
||||
* @throws
|
||||
*/
|
||||
public function update(array $params): static|bool
|
||||
{
|
||||
if (!$this->validator($this->rules(), $params) || !$this->beforeSave($this)) {
|
||||
return FALSE;
|
||||
}
|
||||
return $this->updateInternal(...$this->arrayIntersect($params));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param array $data
|
||||
* @return bool
|
||||
* @throws
|
||||
*/
|
||||
public static function inserts(array $data): bool
|
||||
{
|
||||
if (empty($data)) {
|
||||
return trigger_print_error('Insert data empty.', 'mysql');
|
||||
}
|
||||
return static::query()->insert($data);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
* @throws
|
||||
*/
|
||||
public function delete(): bool
|
||||
{
|
||||
if (!$this->beforeDelete()) {
|
||||
return false;
|
||||
}
|
||||
if ($this->hasPrimary()) {
|
||||
$result = static::deleteByCondition(['id' => $this->getPrimaryValue()]);
|
||||
} else {
|
||||
$result = static::deleteByCondition($this->_attributes);
|
||||
}
|
||||
return $this->afterDelete($result);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return array
|
||||
* @throws
|
||||
*/
|
||||
public function toArray(): array
|
||||
{
|
||||
$data = $this->_attributes;
|
||||
foreach ($data as $key => $datum) {
|
||||
$method = 'get' . ucfirst($key) . 'Attribute';
|
||||
if (!method_exists($this, $method)) {
|
||||
continue;
|
||||
}
|
||||
$data[$key] = $this->{$method}($datum);
|
||||
}
|
||||
return $this->withs($data);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @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 _hasBase(ModelInterface|string $modelName, string $foreignKey, string $localKey): string
|
||||
{
|
||||
if (($value = $this->{$localKey}) === null) {
|
||||
throw new Exception("Need join table primary key.");
|
||||
}
|
||||
|
||||
$relation = $this->getRelation();
|
||||
|
||||
$primaryKey = $modelName . $foreignKey . $value;
|
||||
if (!$relation->hasIdentification($primaryKey)) {
|
||||
$relation->bindIdentification($primaryKey, $modelName::query()->where([$foreignKey => $value]));
|
||||
}
|
||||
return $primaryKey;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param ModelInterface|string $modelName
|
||||
* @param string $foreignKey
|
||||
* @param string $localKey
|
||||
* @return HasOne|ActiveQuery
|
||||
* @throws Exception
|
||||
*/
|
||||
public function hasOne(ModelInterface|string $modelName, string $foreignKey, string $localKey): HasOne|ActiveQuery
|
||||
{
|
||||
return new HasOne($this->_hasBase($modelName, $foreignKey, $localKey));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param ModelInterface|string $modelName
|
||||
* @param string $foreignKey
|
||||
* @param string $localKey
|
||||
* @return ActiveQuery|HasCount
|
||||
* @throws Exception
|
||||
*/
|
||||
public function hasCount(ModelInterface|string $modelName, string $foreignKey, string $localKey): ActiveQuery|HasCount
|
||||
{
|
||||
return new HasCount($this->_hasBase($modelName, $foreignKey, $localKey));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param ModelInterface|string $modelName
|
||||
* @param string $foreignKey
|
||||
* @param string $localKey
|
||||
* @return ActiveQuery|HasMany
|
||||
* @throws Exception
|
||||
*/
|
||||
public function hasMany(ModelInterface|string $modelName, string $foreignKey, string $localKey): ActiveQuery|HasMany
|
||||
{
|
||||
return new HasMany($this->_hasBase($modelName, $foreignKey, $localKey));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param ModelInterface|string $modelName
|
||||
* @param string $foreignKey
|
||||
* @param string $localKey
|
||||
* @return ActiveQuery|HasMany
|
||||
* @throws Exception
|
||||
*/
|
||||
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.");
|
||||
}
|
||||
|
||||
$relation = $this->getRelation();
|
||||
|
||||
$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 bool
|
||||
*/
|
||||
public function afterDelete(bool $result): bool
|
||||
{
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
* @throws Exception
|
||||
*/
|
||||
public function beforeDelete(): bool
|
||||
{
|
||||
return TRUE;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
<?php
|
||||
/**
|
||||
* Created by PhpStorm.
|
||||
* User: whwyy
|
||||
* Date: 2018/3/30 0030
|
||||
* Time: 14:39
|
||||
*/
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database;
|
||||
|
||||
|
||||
/**
|
||||
* Interface ModelInterface
|
||||
* @package Database
|
||||
*/
|
||||
interface ModelInterface
|
||||
{
|
||||
|
||||
/**
|
||||
* @param array|string|int|null $param
|
||||
* @return ModelInterface|null
|
||||
*/
|
||||
public static function findOne(array|string|int|null $param): ?static;
|
||||
|
||||
|
||||
/**
|
||||
* @return mixed
|
||||
*/
|
||||
public function optimize(): mixed;
|
||||
|
||||
|
||||
/**
|
||||
* @param int $param
|
||||
* @return ModelInterface|null
|
||||
*/
|
||||
public static function primary(int $param): ?static;
|
||||
|
||||
|
||||
/**
|
||||
* @param array $data
|
||||
* @return static
|
||||
*/
|
||||
public static function populate(array $data): static;
|
||||
|
||||
|
||||
/**
|
||||
* @return ActiveQuery
|
||||
* return a sql queryBuilder
|
||||
*/
|
||||
public static function query(): ActiveQuery;
|
||||
|
||||
|
||||
/**
|
||||
* @return ?string
|
||||
*/
|
||||
public function getPrimary(): ?string;
|
||||
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getTable(): string;
|
||||
|
||||
|
||||
/**
|
||||
* @return Connection
|
||||
*/
|
||||
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;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
/**
|
||||
* Created by PhpStorm.
|
||||
* User: whwyy
|
||||
* Date: 2018/6/27 0027
|
||||
* Time: 17:49
|
||||
*/
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database;
|
||||
|
||||
|
||||
use Database\Traits\QueryTrait;
|
||||
|
||||
/**
|
||||
* Class Query
|
||||
* @package Database
|
||||
*/
|
||||
class Query extends QueryTrait implements ISqlBuilder
|
||||
{
|
||||
|
||||
|
||||
/**
|
||||
* @return string
|
||||
* @throws
|
||||
*/
|
||||
public function getCondition(): string
|
||||
{
|
||||
return $this->builder->getCondition();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database;
|
||||
|
||||
|
||||
use Kiri\Abstracts\Component;
|
||||
use Kiri\Di\Context;
|
||||
|
||||
/**
|
||||
* Class Relation
|
||||
* @package Kiri\db
|
||||
*/
|
||||
class Relation extends Component
|
||||
{
|
||||
|
||||
/** @var ActiveQuery[] $_query */
|
||||
private array $_query = [];
|
||||
|
||||
/**
|
||||
* @param string $identification
|
||||
* @param ActiveQuery $query
|
||||
* @return $this
|
||||
*/
|
||||
public function bindIdentification(string $identification, ActiveQuery $query): static
|
||||
{
|
||||
$this->_query[$identification] = $query;
|
||||
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
|
||||
*/
|
||||
public function getQuery(string $name): ?ActiveQuery
|
||||
{
|
||||
return $this->_query[$name] ?? null;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $_identification
|
||||
* @return mixed
|
||||
* @throws
|
||||
*/
|
||||
public function first(string $_identification): mixed
|
||||
{
|
||||
if (Context::exists($_identification)) {
|
||||
return Context::get($_identification);
|
||||
}
|
||||
$activeModel = $this->_query[$_identification]->first();
|
||||
unset($this->_query[$_identification]);
|
||||
return Context::set($_identification, $activeModel);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $_identification
|
||||
* @return mixed
|
||||
*/
|
||||
public function count(string $_identification): mixed
|
||||
{
|
||||
if (Context::exists($_identification)) {
|
||||
return Context::get($_identification);
|
||||
}
|
||||
$activeModel = $this->_query[$_identification]->count();
|
||||
unset($this->_query[$_identification]);
|
||||
return Context::set($_identification, $activeModel);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $_identification
|
||||
* @return mixed
|
||||
* @throws
|
||||
*/
|
||||
public function get(string $_identification): mixed
|
||||
{
|
||||
if (Context::exists($_identification)) {
|
||||
return Context::get($_identification);
|
||||
}
|
||||
$activeModel = $this->_query[$_identification]->get();
|
||||
unset($this->_query[$_identification]);
|
||||
return Context::set($_identification, $activeModel);
|
||||
}
|
||||
|
||||
}
|
||||
+411
@@ -0,0 +1,411 @@
|
||||
<?php /** @noinspection ALL */
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database;
|
||||
|
||||
|
||||
use JetBrains\PhpStorm\Pure;
|
||||
use Kiri;
|
||||
use Kiri\Abstracts\Component;
|
||||
|
||||
|
||||
/**
|
||||
* Class SqlBuilder
|
||||
* @package Database
|
||||
*/
|
||||
class SqlBuilder extends Component
|
||||
{
|
||||
|
||||
/**
|
||||
* @var ActiveQuery|Query|ISqlBuilder|null
|
||||
*/
|
||||
public ActiveQuery|Query|ISqlBuilder|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
|
||||
*/
|
||||
public static function builder(ISqlBuilder|null $query): static
|
||||
{
|
||||
return new static($query);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return string
|
||||
* @throws
|
||||
*/
|
||||
public function getCondition(): string
|
||||
{
|
||||
return $this->where($this->query->getWhere());
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param array $compiler
|
||||
* @return string
|
||||
* @throws
|
||||
*/
|
||||
public function hashCompiler(array $compiler): string
|
||||
{
|
||||
return $this->where($compiler);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param array $attributes
|
||||
* @return bool|array
|
||||
* @throws
|
||||
*/
|
||||
public function update(array $attributes): bool|string
|
||||
{
|
||||
$conditions = $this->query->getParams();
|
||||
$this->query->setParams([]);
|
||||
$data = $this->__updateBuilder($this->makeParams($attributes));
|
||||
foreach ($conditions as $condition) {
|
||||
$this->query->pushParam($condition);
|
||||
}
|
||||
return $data;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param array $attributes
|
||||
* @param string $opera
|
||||
* @return bool|array
|
||||
* @throws
|
||||
*/
|
||||
public function mathematics(array $attributes, string $opera = '+'): bool|string
|
||||
{
|
||||
$string = [];
|
||||
foreach ($attributes as $attribute => $value) {
|
||||
$string[] = $attribute . '=' . $attribute . $opera . $value;
|
||||
}
|
||||
return $this->__updateBuilder($string);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param array $string
|
||||
* @return string|bool
|
||||
* @throws
|
||||
*/
|
||||
private function __updateBuilder(array $string): string|bool
|
||||
{
|
||||
if (empty($string)) {
|
||||
return Kiri::getLogger()->failure('None data update.');
|
||||
}
|
||||
return 'UPDATE ' . $this->query->getFrom() . ' SET ' . implode(',', $string) . $this->make();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param array $attributes
|
||||
* @param false $isBatch
|
||||
* @return array
|
||||
* @throws
|
||||
*/
|
||||
public function insert(array $attributes, bool $isBatch = false): string
|
||||
{
|
||||
$update = 'INSERT INTO ' . $this->query->getFrom();
|
||||
if ($isBatch === false) {
|
||||
$attributes = [$attributes];
|
||||
}
|
||||
$update .= '(' . implode(',', $this->getFields($attributes)) . ') VALUES ';
|
||||
|
||||
$keys = [];
|
||||
foreach ($attributes as $attribute) {
|
||||
$_keys = $this->makeParams($attribute, true);
|
||||
|
||||
$keys[] = implode(',', $_keys);
|
||||
}
|
||||
return $update . '(' . implode('),(', $keys) . ')';
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return string
|
||||
* @throws
|
||||
*/
|
||||
public function delete(): string
|
||||
{
|
||||
return 'DELETE FROM ' . $this->query->getFrom() . $this->make();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $attributes
|
||||
* @return array
|
||||
*/
|
||||
#[Pure] private function getFields(array $attributes): array
|
||||
{
|
||||
return array_keys(current($attributes));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param array $attributes
|
||||
* @param bool $isInsert
|
||||
* @return array[]
|
||||
* a=:b,
|
||||
*/
|
||||
private function makeParams(array $attributes, bool $isInsert = false): array
|
||||
{
|
||||
$keys = [];
|
||||
foreach ($attributes as $key => $value) {
|
||||
if ($isInsert === true) {
|
||||
$keys[] = '?';
|
||||
$this->query->pushParam($value);
|
||||
} else {
|
||||
$keys = $this->resolveParams($key, $value, $keys);
|
||||
}
|
||||
}
|
||||
return $keys;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $key
|
||||
* @param mixed $value
|
||||
* @param array $keys
|
||||
* @return array
|
||||
*/
|
||||
private function resolveParams(string $key, mixed $value, array $keys): array
|
||||
{
|
||||
if (is_null($value)) {
|
||||
return $keys;
|
||||
}
|
||||
if (is_string($value) && $this->isMath($value)) {
|
||||
$keys[] = $key . '=' . $key . ' ' . $value;
|
||||
} else {
|
||||
$this->query->pushParam($value);
|
||||
$keys[] = $key . '= ?';
|
||||
}
|
||||
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
|
||||
*/
|
||||
public function one(): string
|
||||
{
|
||||
return $this->makeSelect($this->query->getSelect()) . $this->make() . $this->makeLimit($this->query->limit(1));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return string
|
||||
* @throws
|
||||
*/
|
||||
public function all(): string
|
||||
{
|
||||
return $this->makeSelect($this->query->getSelect()) . $this->make() . $this->makeLimit($this->query);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return string
|
||||
* @throws
|
||||
*/
|
||||
public function count(): string
|
||||
{
|
||||
return $this->makeSelect(['COUNT(*)']) . $this->make();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return string
|
||||
* @throws
|
||||
*/
|
||||
public function exists(): string
|
||||
{
|
||||
return $this->makeSelect(['0']) . $this->make();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $table
|
||||
* @return string
|
||||
*/
|
||||
public function columns(string $table): string
|
||||
{
|
||||
return 'SHOW FULL FIELDS FROM ' . $table;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return string
|
||||
* @throws
|
||||
*/
|
||||
private function make(): string
|
||||
{
|
||||
$select = $this->makeCondition();
|
||||
$select .= $this->makeGroup();
|
||||
$select .= $this->makeOrder();
|
||||
return $select;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $select
|
||||
* @return string
|
||||
*/
|
||||
private function makeSelect(array $select = ['*']): string
|
||||
{
|
||||
$select = "SELECT " . implode(',', $select) . " FROM " . $this->query->getFrom();
|
||||
if ($this->query->getAlias() != "") {
|
||||
$select .= " AS " . $this->query->getAlias();
|
||||
}
|
||||
if (count($this->query->getJoin()) > 0) {
|
||||
$select .= ' ' . implode(' ', $this->query->getJoin());
|
||||
}
|
||||
return $select;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
private function makeGroup(): string
|
||||
{
|
||||
if ($this->query->getGroup() != "") {
|
||||
return ' GROUP BY ' . $this->query->getGroup();
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
private function makeOrder(): string
|
||||
{
|
||||
if (count($this->query->getOrder()) > 0) {
|
||||
return ' ORDER BY ' . implode(',', $this->query->getOrder());
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
private function makeCondition(): string
|
||||
{
|
||||
$condition = $this->where($this->query->getWhere());
|
||||
if (empty($condition)) {
|
||||
return '';
|
||||
}
|
||||
return ' WHERE ' . $condition;
|
||||
}
|
||||
|
||||
|
||||
private function makeLimit(): string
|
||||
{
|
||||
if ($this->query->getOffset() >= 0 && $this->query->getLimit() >= 1) {
|
||||
return ' LIMIT ' . $this->query->getOffset() . ',' . $this->query->getLimit();
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param false $isCount
|
||||
* @return string
|
||||
* @throws
|
||||
*/
|
||||
public function get(bool $isCount = false): string
|
||||
{
|
||||
if ($isCount === false) {
|
||||
return $this->all();
|
||||
}
|
||||
return $this->count();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return string
|
||||
* @throws
|
||||
*/
|
||||
public function truncate(): string
|
||||
{
|
||||
return sprintf('TRUNCATE %s', $this->query->getFrom());
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param array $where
|
||||
* @return string
|
||||
*/
|
||||
private function where(array $where): string
|
||||
{
|
||||
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
|
||||
*/
|
||||
private function resolveCondition(string|int $field, mixed $condition): string
|
||||
{
|
||||
if (is_string($field)) {
|
||||
$this->query->pushParam($condition);
|
||||
return $field . ' = ?';
|
||||
} else if (is_string($condition)) {
|
||||
return $condition;
|
||||
} else {
|
||||
return implode(' AND ', $this->_hashMap($condition));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $condition
|
||||
* @return array
|
||||
*/
|
||||
private function _hashMap(array $condition): array
|
||||
{
|
||||
$_array = [];
|
||||
foreach ($condition as $key => $value) {
|
||||
$this->query->pushParam($value);
|
||||
$_array[] = $key . '= ?';
|
||||
}
|
||||
return $_array;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
<?php
|
||||
/**
|
||||
* Created by PhpStorm.
|
||||
* User: whwyy
|
||||
* Date: 2018/4/4 0004
|
||||
* Time: 15:47
|
||||
*/
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database\Traits;
|
||||
|
||||
use Database\ModelInterface;
|
||||
use Database\Collection;
|
||||
use Database\Relation;
|
||||
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 mixed $data = null;
|
||||
|
||||
/**
|
||||
* @var ModelInterface
|
||||
*/
|
||||
protected mixed $model;
|
||||
|
||||
|
||||
protected mixed $value = 0;
|
||||
|
||||
|
||||
/**
|
||||
* HasBase constructor.
|
||||
* @param string $name
|
||||
*/
|
||||
public function __construct(public string $name)
|
||||
{
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $name
|
||||
* @param array $arguments
|
||||
* @return $this|mixed
|
||||
*/
|
||||
public function __call(string $name, array $arguments)
|
||||
{
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,984 @@
|
||||
<?php
|
||||
/**
|
||||
* Created by PhpStorm.
|
||||
* User: whwyy
|
||||
* Date: 2018/3/30 0030
|
||||
* Time: 14:56
|
||||
*/
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database\Traits;
|
||||
|
||||
|
||||
use Closure;
|
||||
use Database\Base\ActiveQueryInterface;
|
||||
use Database\Command;
|
||||
use Database\ISqlBuilder;
|
||||
use Database\ModelInterface;
|
||||
use Database\Query;
|
||||
use Database\SqlBuilder;
|
||||
use Exception;
|
||||
use Kiri;
|
||||
use Kiri\Abstracts\Component;
|
||||
|
||||
/**
|
||||
* Trait QueryTrait
|
||||
* @package Database\Traits
|
||||
*/
|
||||
abstract class QueryTrait extends Component implements ActiveQueryInterface, ISqlBuilder
|
||||
{
|
||||
protected array $where = [];
|
||||
protected array $select = ['*'];
|
||||
protected array $join = [];
|
||||
protected array $order = [];
|
||||
protected int $offset = -1;
|
||||
protected int $limit = -1;
|
||||
protected string $group = '';
|
||||
protected string $from = '';
|
||||
protected string $alias = 't1';
|
||||
protected array $filter = [];
|
||||
protected bool $lock = false;
|
||||
protected SqlBuilder $builder;
|
||||
protected array $params = [];
|
||||
protected array $_alias = ['t1'];
|
||||
|
||||
|
||||
/**
|
||||
* @var ModelInterface|string|null
|
||||
*/
|
||||
protected ModelInterface|string|null $modelClass;
|
||||
|
||||
|
||||
/**
|
||||
* Comply constructor.
|
||||
* @throws
|
||||
*/
|
||||
public function __construct($model = null)
|
||||
{
|
||||
if (!is_null($model)) {
|
||||
$this->modelClass = $model;
|
||||
}
|
||||
$this->builder = SqlBuilder::builder($this);
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param array $where
|
||||
* @return void
|
||||
*/
|
||||
public function setWhere(array $where): void
|
||||
{
|
||||
$this->where = $where;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param array $select
|
||||
* @return void
|
||||
*/
|
||||
public function setSelect(array $select): void
|
||||
{
|
||||
$this->select = $select;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param array $join
|
||||
* @return void
|
||||
*/
|
||||
public function setJoin(array $join): void
|
||||
{
|
||||
$this->join = $join;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param array $order
|
||||
* @return void
|
||||
*/
|
||||
public function setOrder(array $order): void
|
||||
{
|
||||
$this->order = $order;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param int $offset
|
||||
* @return void
|
||||
*/
|
||||
public function setOffset(int $offset): void
|
||||
{
|
||||
$this->offset = $offset;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param int $limit
|
||||
* @return void
|
||||
*/
|
||||
public function setLimit(int $limit): void
|
||||
{
|
||||
$this->limit = $limit;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $group
|
||||
* @return void
|
||||
*/
|
||||
public function setGroup(string $group): void
|
||||
{
|
||||
$this->group = $group;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $from
|
||||
* @return void
|
||||
*/
|
||||
public function setFrom(string $from): void
|
||||
{
|
||||
$this->from = $from;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $alias
|
||||
* @return void
|
||||
*/
|
||||
public function setAlias(string $alias): void
|
||||
{
|
||||
$this->alias = $alias;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $params
|
||||
* @return void
|
||||
*/
|
||||
public function setParams(array $params): void
|
||||
{
|
||||
$this->params = $params;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
public function getWhere(): array
|
||||
{
|
||||
return $this->where;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return array|string[]
|
||||
*/
|
||||
public function getSelect(): array
|
||||
{
|
||||
return $this->select;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
public function getJoin(): array
|
||||
{
|
||||
return $this->join;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
public function getOrder(): array
|
||||
{
|
||||
return $this->order;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return int
|
||||
*/
|
||||
public function getOffset(): int
|
||||
{
|
||||
return $this->offset;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return int
|
||||
*/
|
||||
public function getLimit(): int
|
||||
{
|
||||
return $this->limit;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getGroup(): string
|
||||
{
|
||||
return $this->group;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getFrom(): string
|
||||
{
|
||||
return $this->from;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getAlias(): string
|
||||
{
|
||||
return $this->alias;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
public function getParams(): array
|
||||
{
|
||||
return $this->params;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $column
|
||||
* @param callable $callable
|
||||
* @return $this
|
||||
*/
|
||||
public function when(string $column, callable $callable): static
|
||||
{
|
||||
$caseWhen = new When($column, $this);
|
||||
|
||||
call_user_func($callable, $caseWhen);
|
||||
|
||||
$this->where[] = $caseWhen->end();
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param bool $lock
|
||||
* @return $this
|
||||
*/
|
||||
public function lock(bool $lock): static
|
||||
{
|
||||
$this->lock = $lock;
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $whereRaw
|
||||
* @return QueryTrait
|
||||
*/
|
||||
public function whereRaw(string $whereRaw): static
|
||||
{
|
||||
if ($whereRaw == '') {
|
||||
return $this;
|
||||
}
|
||||
$this->where[] = $whereRaw;
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return string
|
||||
* @throws
|
||||
*/
|
||||
public function getTable(): string
|
||||
{
|
||||
return $this->modelClass->getTable();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $column
|
||||
* @param string $value
|
||||
* @return $this
|
||||
*/
|
||||
public function whereLocate(string $column, string $value): static
|
||||
{
|
||||
$this->where[] = 'LOCATE(' . $column . ',\'' . addslashes($value) . '\') > 0';
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $column
|
||||
* @return $this
|
||||
*/
|
||||
public function whereNull(string $column): static
|
||||
{
|
||||
$this->where[] = $column . ' IS NULL';
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $column
|
||||
* @return $this
|
||||
*/
|
||||
public function whereEmpty(string $column): static
|
||||
{
|
||||
$this->where[] = $column . ' = \'\'';
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $column
|
||||
* @return $this
|
||||
*/
|
||||
public function whereNotEmpty(string $column): static
|
||||
{
|
||||
$this->where[] = $column . ' <> \'\'';
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $column
|
||||
* @return $this
|
||||
*/
|
||||
public function whereNotNull(string $column): static
|
||||
{
|
||||
$this->where[] = $column . ' IS NOT NULL';
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $alias
|
||||
*
|
||||
* @return $this
|
||||
*
|
||||
* select * from tableName as t1
|
||||
*/
|
||||
public function alias(string $alias = 't1'): static
|
||||
{
|
||||
$this->alias = $alias;
|
||||
$this->_alias = [$alias];
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string|Closure $tableName
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
public function from(string|Closure $tableName): static
|
||||
{
|
||||
if ($tableName instanceof Closure) {
|
||||
$tableName = call_user_func($tableName, $this->queryInstance());
|
||||
}
|
||||
$this->from = $tableName;
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $tableName
|
||||
* @param string $alias
|
||||
* @param array $on
|
||||
* @param array $param
|
||||
* @return $this
|
||||
* $query->join([$tableName, ['userId'=>'uuvOd']], $param)
|
||||
* $query->join([$tableName, ['userId'=>'uuvOd'], $param])
|
||||
* $query->join($tableName, ['userId'=>'uuvOd',$param])
|
||||
*/
|
||||
private function join(string $tableName, string $alias, array $on, array $param = []): static
|
||||
{
|
||||
if (empty($on)) {
|
||||
return $this;
|
||||
}
|
||||
|
||||
$this->_alias[] = $alias;
|
||||
|
||||
$join[] = $tableName . ' AS ' . $alias;
|
||||
$join[] = 'ON ' . $this->onCondition($on);
|
||||
if (empty($join)) {
|
||||
return $this;
|
||||
}
|
||||
|
||||
$this->join[] = implode(' ', $join);
|
||||
if (!empty($param)) {
|
||||
$this->bindParams($param);
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param array $params
|
||||
* @return void
|
||||
*/
|
||||
public function bindParams(array $params): void
|
||||
{
|
||||
foreach ($params as $param) {
|
||||
$this->pushParam($param);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param array $condition
|
||||
* @return string
|
||||
*/
|
||||
private function onCondition(array $condition): string
|
||||
{
|
||||
$array = [];
|
||||
foreach ($condition as $key => $item) {
|
||||
if (is_numeric($item) || !$this->isAliasField($item)) {
|
||||
$array[] = $key . '= ?';
|
||||
$this->pushParam($item);
|
||||
} else {
|
||||
$array[] = $key . '=' . $item;
|
||||
}
|
||||
}
|
||||
return implode(' AND ', $array);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $value
|
||||
* @return bool
|
||||
*/
|
||||
private function isAliasField(string $value): bool
|
||||
{
|
||||
foreach ($this->_alias as $alias) {
|
||||
if (str_starts_with($value, $alias . '.')) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $tableName
|
||||
* @param string $alias
|
||||
* @param array $onCondition
|
||||
* @param array $param
|
||||
* @return $this
|
||||
* @throws Exception
|
||||
*/
|
||||
public function leftJoin(string $tableName, string $alias, array $onCondition, array $param = []): static
|
||||
{
|
||||
if (class_exists($tableName)) {
|
||||
$model = Kiri::getDi()->get($tableName);
|
||||
if (!($model instanceof ModelInterface)) {
|
||||
throw new Exception('Model must implement ' . ModelInterface::class);
|
||||
}
|
||||
$tableName = $model->getTable();
|
||||
}
|
||||
return $this->join("LEFT JOIN " . $tableName, $alias, $onCondition, $param);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $tableName
|
||||
* @param string $alias
|
||||
* @param array $onCondition
|
||||
* @param array $param
|
||||
* @return $this
|
||||
* @throws Exception
|
||||
*/
|
||||
public function rightJoin(string $tableName, string $alias, array $onCondition, array $param = []): static
|
||||
{
|
||||
if (class_exists($tableName)) {
|
||||
$model = Kiri::getDi()->get($tableName);
|
||||
if (!($model instanceof ModelInterface)) {
|
||||
throw new Exception('Model must implement ' . ModelInterface::class);
|
||||
}
|
||||
$tableName = $model->getTable();
|
||||
}
|
||||
return $this->join("RIGHT JOIN " . $tableName, $alias, $onCondition, $param);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $tableName
|
||||
* @param string $alias
|
||||
* @param array $onCondition
|
||||
* @param array $param
|
||||
* @return $this
|
||||
* @throws Exception
|
||||
*/
|
||||
public function innerJoin(string $tableName, string $alias, array $onCondition, array $param = []): static
|
||||
{
|
||||
if (class_exists($tableName)) {
|
||||
$model = Kiri::getDi()->get($tableName);
|
||||
if (!($model instanceof ModelInterface)) {
|
||||
throw new Exception('Model must implement ' . ModelInterface::class);
|
||||
}
|
||||
$tableName = $model->getTable();
|
||||
}
|
||||
return $this->join("INNER JOIN " . $tableName, $alias, $onCondition, $param);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $field
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
public function sum(string $field): static
|
||||
{
|
||||
$this->select[] = 'SUM(' . $field . ') AS ' . $field;
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $field
|
||||
* @return $this
|
||||
*/
|
||||
public function max(string $field): static
|
||||
{
|
||||
$this->select[] = 'MAX(' . $field . ') AS ' . $field;
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $lngField
|
||||
* @param string $latField
|
||||
* @param int|float $lng1
|
||||
* @param int|float $lat1
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
public function distance(string $lngField, string $latField, int|float $lng1, int|float $lat1): static
|
||||
{
|
||||
$sql = "ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN(($lat1 * PI() / 180 - $lat1 * PI() / 180) / 2),2) + COS($lat1 * PI() / 180) * COS($latField * PI() / 180) * POW(SIN(($lng1 * PI() / 180 - $lngField * PI() / 180) / 2),2))) * 1000) AS distance";
|
||||
$this->select[] = $sql;
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string|array $column
|
||||
* @param string $sort
|
||||
*
|
||||
* @return $this
|
||||
*
|
||||
* [
|
||||
* 'addTime',
|
||||
* 'descTime desc'
|
||||
* ]
|
||||
*/
|
||||
public function orderBy(string|array $column, string $sort = 'DESC'): static
|
||||
{
|
||||
if (empty($column)) {
|
||||
return $this;
|
||||
}
|
||||
if (is_string($column)) {
|
||||
return $this->addOrder(...func_get_args());
|
||||
}
|
||||
|
||||
foreach ($column as $val) {
|
||||
$this->addOrder($val);
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $column
|
||||
* @param string $sort
|
||||
*
|
||||
* @return $this
|
||||
*
|
||||
*/
|
||||
private function addOrder(string $column, string $sort = 'DESC'): static
|
||||
{
|
||||
if (func_num_args() == 1 || str_contains($column, ' ')) {
|
||||
$this->order[] = $column;
|
||||
} else {
|
||||
$this->order[] = "$column $sort";
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param array $column
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
public function select(array $column = ['*']): static
|
||||
{
|
||||
$this->select = $column;
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return $this
|
||||
*/
|
||||
public function rand(): static
|
||||
{
|
||||
$this->order[] = 'RAND()';
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param array|Closure|string $conditionArray
|
||||
* @param string $opera
|
||||
* @param null $value
|
||||
* @return QueryTrait
|
||||
* @throws
|
||||
*/
|
||||
public function whereOr(array|Closure|string $conditionArray = [], string $opera = '=', $value = null): static
|
||||
{
|
||||
if ($conditionArray instanceof Closure) {
|
||||
$conditionArray = $this->makeClosureFunction($conditionArray);
|
||||
}
|
||||
|
||||
if (func_num_args() > 1) {
|
||||
[$conditionArray, $opera, $value] = $this->opera(...func_get_args());
|
||||
|
||||
$conditionArray = $this->sprintf($conditionArray, $value, $opera);
|
||||
}
|
||||
|
||||
$this->where = ['((' . implode(' AND ', $this->where) . ') OR (' . $conditionArray . '))'];
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $column
|
||||
* @param string $value
|
||||
* @return $this
|
||||
*/
|
||||
public function whereLike(string $column, string $value): static
|
||||
{
|
||||
$this->pushParam($value);
|
||||
$this->where[] = $column . ' LIKE \'%?%\'';
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $column
|
||||
* @param string $value
|
||||
* @return $this
|
||||
*/
|
||||
public function whereLeftLike(string $column, string $value): static
|
||||
{
|
||||
$this->pushParam($value);
|
||||
$this->where[] = $column . ' LLike \'%?\'';
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $column
|
||||
* @param string $value
|
||||
* @return $this
|
||||
*/
|
||||
public function whereRightLike(string $column, string $value): static
|
||||
{
|
||||
$this->pushParam($value);
|
||||
$this->where[] = $column . ' RLike \'?%\'';
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $column
|
||||
* @param string $value
|
||||
* @return $this
|
||||
*/
|
||||
public function whereNotLike(string $column, string $value): static
|
||||
{
|
||||
$this->pushParam($value);
|
||||
$this->where[] = $column . ' NOT LIKE \'%?%\'';
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $columns
|
||||
* @param array|Closure $value
|
||||
* @return $this
|
||||
* @throws
|
||||
*/
|
||||
public function whereIn(string $columns, array|Closure $value): static
|
||||
{
|
||||
if ($value instanceof Closure) {
|
||||
$value = $this->makeClosureFunction($value);
|
||||
}
|
||||
if (count($value) < 1) {
|
||||
$value = [-1];
|
||||
}
|
||||
$this->where[] = $columns . ' IN (' . implode(',', $value) . ')';
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return Query
|
||||
* @throws
|
||||
*/
|
||||
public function queryInstance(): Query
|
||||
{
|
||||
return new Query();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $columns
|
||||
* @param array $value
|
||||
* @return $this
|
||||
*/
|
||||
public function whereNotIn(string $columns, array $value): static
|
||||
{
|
||||
if (count($value) < 1) {
|
||||
$value = [-1];
|
||||
}
|
||||
$this->where[] = $columns . ' NOT IN (' . implode(',', $value) . ')';
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $column
|
||||
* @param int|float $start
|
||||
* @param int|float $end
|
||||
* @return $this
|
||||
*/
|
||||
public function whereBetween(string $column, int|float $start, int|float $end): static
|
||||
{
|
||||
if (empty($column) || empty($start) || empty($end)) {
|
||||
return $this;
|
||||
}
|
||||
|
||||
$this->pushParam($start);
|
||||
$this->pushParam($end);
|
||||
$this->where[] = $column . ' BETWEEN ? AND ?';
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $column
|
||||
* @param int|float $start
|
||||
* @param int|float $end
|
||||
* @return $this
|
||||
*/
|
||||
public function whereNotBetween(string $column, int|float $start, int|float $end): static
|
||||
{
|
||||
if (empty($column) || empty($start) || empty($end)) {
|
||||
return $this;
|
||||
}
|
||||
|
||||
$this->pushParam($start);
|
||||
$this->pushParam($end);
|
||||
$this->where[] = $column . ' NOT BETWEEN ? AND ?';
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param mixed $value
|
||||
* @return $this
|
||||
*/
|
||||
public function pushParam(mixed $value): static
|
||||
{
|
||||
$this->params[] = $value;
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param array|string $column
|
||||
* @param mixed $value
|
||||
* @return $this
|
||||
*/
|
||||
public function where(array|string $column, mixed $value = null): static
|
||||
{
|
||||
if (func_num_args() === 2) {
|
||||
return $this->addArray([$column => $value]);
|
||||
}
|
||||
if (is_string($column)) {
|
||||
return $this->whereRaw($column);
|
||||
} else {
|
||||
return $this->addArray($column);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $column
|
||||
* @param string $opera
|
||||
* @param mixed $value
|
||||
* @return $this
|
||||
*/
|
||||
public function whereMath(string $column, string $opera, mixed $value): static
|
||||
{
|
||||
$this->pushParam($value);
|
||||
$this->where[] = $column . ' ' . $opera . ' ?';
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param Closure $closure
|
||||
* @return $this
|
||||
*/
|
||||
public function whereClosure(Closure $closure): static
|
||||
{
|
||||
$this->where[] = $this->makeClosureFunction($closure);
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param Closure|array $closure
|
||||
* @return string
|
||||
* @throws
|
||||
*/
|
||||
public function makeClosureFunction(Closure|array $closure): string
|
||||
{
|
||||
$generate = $this->queryInstance();
|
||||
if ($closure instanceof Closure) {
|
||||
call_user_func($closure, $generate);
|
||||
} else {
|
||||
$generate->addArray($closure);
|
||||
}
|
||||
return $generate->build();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $name
|
||||
* @param string|null $having
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
public function groupBy(string $name, string $having = NULL): static
|
||||
{
|
||||
$this->group = $name;
|
||||
if (empty($having)) {
|
||||
return $this;
|
||||
}
|
||||
$this->group .= ' HAVING ' . $having;
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param int $limit
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
public function limit(int $limit = 20): static
|
||||
{
|
||||
$this->limit = $limit;
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param int $offset
|
||||
* @return $this
|
||||
*/
|
||||
public function offset(int $offset): static
|
||||
{
|
||||
$this->offset = $offset;
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
private function opera(): array
|
||||
{
|
||||
if (func_num_args() == 3) {
|
||||
[$column, $opera, $value] = func_get_args();
|
||||
} else {
|
||||
[$column, $value] = func_get_args();
|
||||
}
|
||||
if (!isset($opera)) {
|
||||
$opera = '=';
|
||||
}
|
||||
return [$column, $opera, $value];
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param array $array
|
||||
* @return $this
|
||||
*/
|
||||
private function addArray(array $array): static
|
||||
{
|
||||
foreach ($array as $key => $value) {
|
||||
if ($value === null) {
|
||||
continue;
|
||||
}
|
||||
$this->where[] = is_numeric($key) ? $value : $this->sprintf($key, $value);
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $column
|
||||
* @param mixed $value
|
||||
* @param string $opera
|
||||
* @return string
|
||||
*/
|
||||
private function sprintf(string $column, mixed $value, string $opera = '='): string
|
||||
{
|
||||
$this->pushParam($value);
|
||||
return $column . ' ' . $opera . ' ?';
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $querySql
|
||||
* @param array $params
|
||||
* @return Command
|
||||
*/
|
||||
public function buildCommand(string $querySql, array $params = []): Command
|
||||
{
|
||||
$connection = $this->modelClass->getConnection();
|
||||
if (count($params) > 0) {
|
||||
$this->bindParams($params);
|
||||
}
|
||||
return $connection->createCommand($querySql, $this->params);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return string
|
||||
* @throws
|
||||
*/
|
||||
public function build(): string
|
||||
{
|
||||
return $this->builder->get();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -1,10 +1,15 @@
|
||||
<?php
|
||||
|
||||
namespace Database\Traits;
|
||||
|
||||
interface Relation
|
||||
{
|
||||
|
||||
public function get(): mixed;
|
||||
|
||||
}
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database\Traits;
|
||||
|
||||
interface Relation
|
||||
{
|
||||
|
||||
|
||||
/**
|
||||
* @return mixed
|
||||
*/
|
||||
public function get(): mixed;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
|
||||
namespace Database\Traits;
|
||||
|
||||
|
||||
use Database\ActiveQuery;
|
||||
use Database\ISqlBuilder;
|
||||
use Exception;
|
||||
use JetBrains\PhpStorm\Pure;
|
||||
|
||||
|
||||
/**
|
||||
* Class CaseWhen
|
||||
* @package Database\Traits
|
||||
*/
|
||||
class When
|
||||
{
|
||||
|
||||
public ActiveQuery|ISqlBuilder $query;
|
||||
|
||||
|
||||
private array $_condition = [];
|
||||
|
||||
private string $else = '';
|
||||
|
||||
|
||||
/**
|
||||
* CaseWhen constructor.
|
||||
* @param string $column
|
||||
* @param ActiveQuery|ISqlBuilder $activeQuery
|
||||
*/
|
||||
public function __construct(public string $column, public ActiveQuery|ISqlBuilder $activeQuery)
|
||||
{
|
||||
$this->_condition[] = 'CASE ' . $column;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string|int $condition
|
||||
* @param string $then
|
||||
* @return $this
|
||||
* @throws
|
||||
*/
|
||||
public function when(string|int $condition, string $then): static
|
||||
{
|
||||
$this->_condition[] = sprintf('WHEN %s THEN %s', $condition, $then);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $alias
|
||||
*/
|
||||
public function else(string $alias): void
|
||||
{
|
||||
$this->else = $alias;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
#[Pure] public function end(): string
|
||||
{
|
||||
if (empty($this->_condition)) {
|
||||
return '';
|
||||
}
|
||||
$prefix = implode(' ', $this->_condition);
|
||||
if (!empty($this->else)) {
|
||||
$prefix .= ' ELSE ' . $this->else;
|
||||
}
|
||||
return '(' . $prefix . ' END)';
|
||||
}
|
||||
|
||||
}
|
||||
+3
-4
@@ -9,15 +9,14 @@
|
||||
],
|
||||
"license": "MIT",
|
||||
"require": {
|
||||
"php": ">=8.0",
|
||||
"php": ">=8.3",
|
||||
"ext-json": "*",
|
||||
"ext-pdo": "*",
|
||||
"game-worker/kiri-validator": "^v1.2",
|
||||
"game-worker/kiri-event": "^v1.0"
|
||||
"game-worker/kiri-pool": "~v1.0"
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"Database\\": "src/"
|
||||
"Database\\": "./"
|
||||
}
|
||||
},
|
||||
"require-dev": {
|
||||
|
||||
@@ -1,340 +0,0 @@
|
||||
<?php
|
||||
/**
|
||||
* Created by PhpStorm.
|
||||
* User: whwyy
|
||||
* Date: 2018/4/4 0004
|
||||
* Time: 14:42
|
||||
*/
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database;
|
||||
|
||||
use Database\Traits\QueryTrait;
|
||||
use Exception;
|
||||
use JetBrains\PhpStorm\ArrayShape;
|
||||
use Kiri\Abstracts\Component;
|
||||
|
||||
/**
|
||||
* Class ActiveQuery
|
||||
* @package Database
|
||||
*/
|
||||
class ActiveQuery extends Component implements ISqlBuilder
|
||||
{
|
||||
|
||||
use QueryTrait;
|
||||
|
||||
/** @var array */
|
||||
public array $with = [];
|
||||
|
||||
/** @var bool */
|
||||
public bool $asArray = FALSE;
|
||||
|
||||
/** @var bool */
|
||||
public bool $useCache = FALSE;
|
||||
|
||||
/**
|
||||
* @var Connection|null
|
||||
*/
|
||||
public ?Connection $db = NULL;
|
||||
|
||||
/**
|
||||
* @var array
|
||||
* 参数绑定
|
||||
*/
|
||||
public array $attributes = [];
|
||||
|
||||
|
||||
/**
|
||||
* Comply constructor.
|
||||
* @param $model
|
||||
* @param array $config
|
||||
* @throws
|
||||
*/
|
||||
public function __construct($model, array $config = [])
|
||||
{
|
||||
$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;
|
||||
}
|
||||
return $this->populate($data);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return string
|
||||
* @throws Exception
|
||||
*/
|
||||
public function toSql(): string
|
||||
{
|
||||
return $this->builder->get();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return array|Collection
|
||||
*/
|
||||
public function get(): Collection|array
|
||||
{
|
||||
return $this->all();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @throws Exception
|
||||
*/
|
||||
public function flush(): array|bool|int|string|null
|
||||
{
|
||||
return $this->execute($this->builder->truncate())->exec();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param int $size
|
||||
* @param callable $callback
|
||||
* @return Pagination
|
||||
* @throws Exception
|
||||
*/
|
||||
public function page(int $size, callable $callback): Pagination
|
||||
{
|
||||
$pagination = new Pagination($this);
|
||||
$pagination->setOffset(0);
|
||||
$pagination->setLimit($size);
|
||||
$pagination->setCallback($callback);
|
||||
return $pagination;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $field
|
||||
* @param string $setKey
|
||||
*
|
||||
* @return array|null
|
||||
* @throws Exception
|
||||
*/
|
||||
public function column(string $field, string $setKey = ''): ?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));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param ModelInterface $model
|
||||
* @return ModelInterface
|
||||
*/
|
||||
public function getWith(ModelInterface $model): ModelInterface
|
||||
{
|
||||
if (empty($this->with) || !is_array($this->with)) {
|
||||
return $model;
|
||||
}
|
||||
return $model->setWith($this->with);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return int
|
||||
* @throws Exception
|
||||
*/
|
||||
public function count(): int
|
||||
{
|
||||
$data = $this->execute($this->builder->count())->one();
|
||||
if ($data && is_array($data)) {
|
||||
return (int)array_shift($data);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param array $data
|
||||
* @return array|Command|bool|int|string
|
||||
* @throws Exception
|
||||
*/
|
||||
public function batchUpdate(array $data): Command|array|bool|int|string
|
||||
{
|
||||
$generate = $this->builder->update($data);
|
||||
if (is_bool($generate)) {
|
||||
return $generate;
|
||||
}
|
||||
return $this->execute(...$generate)->exec();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $data
|
||||
* @return bool
|
||||
* @throws Exception
|
||||
*/
|
||||
public function batchInsert(array $data): bool
|
||||
{
|
||||
[$sql, $params] = $this->builder->insert($data, TRUE);
|
||||
|
||||
|
||||
return $this->execute($sql, $params)->exec();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $filed
|
||||
*
|
||||
* @return null
|
||||
* @throws Exception
|
||||
*/
|
||||
public function value($filed)
|
||||
{
|
||||
return $this->first()[$filed] ?? NULL;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
* @throws Exception
|
||||
*/
|
||||
public function exists(): bool
|
||||
{
|
||||
return !empty($this->execute($this->builder->one())->fetchColumn());
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param bool $getSql
|
||||
* @return int|bool|string|null
|
||||
* @throws Exception
|
||||
*/
|
||||
public function delete(bool $getSql = FALSE): int|bool|string|null
|
||||
{
|
||||
$sql = $this->builder->delete();
|
||||
if ($getSql === FALSE) {
|
||||
return $this->execute($sql)->delete();
|
||||
}
|
||||
return $sql;
|
||||
}
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database\Base;
|
||||
|
||||
|
||||
use Database\ActiveQuery;
|
||||
use Database\ModelInterface;
|
||||
use Exception;
|
||||
|
||||
|
||||
/**
|
||||
* Class CollectionIterator
|
||||
* @package Database\Base
|
||||
*/
|
||||
class CollectionIterator extends \ArrayIterator
|
||||
{
|
||||
|
||||
private ModelInterface|string $model;
|
||||
|
||||
|
||||
/** @var ActiveQuery */
|
||||
private ActiveQuery $query;
|
||||
|
||||
|
||||
private ?ModelInterface $_clone = null;
|
||||
|
||||
|
||||
public function clean()
|
||||
{
|
||||
unset($this->query);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* CollectionIterator constructor.
|
||||
* @param $model
|
||||
* @param $query
|
||||
* @param array $array
|
||||
* @param int $flags
|
||||
* @throws Exception
|
||||
*/
|
||||
public function __construct($model, $query, array $array = [], int $flags = 0)
|
||||
{
|
||||
$this->model = $model;
|
||||
$this->query = $query;
|
||||
parent::__construct($array, $flags);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $current
|
||||
* @return ModelInterface
|
||||
* @throws Exception
|
||||
*/
|
||||
protected function newModel($current): ModelInterface
|
||||
{
|
||||
return $this->model->populates($current);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @throws Exception
|
||||
*/
|
||||
public function current(): ModelInterface
|
||||
{
|
||||
if (is_array($current = parent::current())) {
|
||||
$current = $this->newModel($current);
|
||||
}
|
||||
return $current;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -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] ?? [];
|
||||
}
|
||||
|
||||
}
|
||||
-1090
File diff suppressed because it is too large
Load Diff
@@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,243 +0,0 @@
|
||||
<?php
|
||||
/**
|
||||
* Created by PhpStorm.
|
||||
* User: whwyy
|
||||
* Date: 2018/4/4 0004
|
||||
* Time: 13:38
|
||||
*/
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database;
|
||||
|
||||
use Database\Base\AbstractCollection;
|
||||
use Exception;
|
||||
use JetBrains\PhpStorm\Pure;
|
||||
|
||||
/**
|
||||
* Class Collection
|
||||
* @package Database
|
||||
* @property-read $length
|
||||
*/
|
||||
class Collection extends AbstractCollection
|
||||
{
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
public function getItems(): array
|
||||
{
|
||||
// TODO: Change the autogenerated stub
|
||||
return $this->_item;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $field
|
||||
*
|
||||
* @return array|null
|
||||
* @throws Exception
|
||||
*/
|
||||
public function values($field): ?array
|
||||
{
|
||||
if (empty($field) || !is_string($field)) {
|
||||
return NULL;
|
||||
}
|
||||
$_tmp = [];
|
||||
$data = $this->toArray();
|
||||
foreach ($data as $val) {
|
||||
/** @var ModelInterface $val */
|
||||
$_tmp[] = $val[$field];
|
||||
}
|
||||
return $_tmp;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $field
|
||||
* @return array|null
|
||||
*/
|
||||
public function keyBy(string $field): ?array
|
||||
{
|
||||
$array = $this->toArray();
|
||||
$column = array_flip(array_column($array, $field));
|
||||
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
|
||||
* @param int $length
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
#[Pure] public function slice(int $start = 0, int $length = 20): array
|
||||
{
|
||||
if (empty($this->_item) || !is_array($this->_item)) {
|
||||
return [];
|
||||
}
|
||||
if (count($this->_item) < $length) {
|
||||
return $this->_item;
|
||||
} else {
|
||||
return array_slice($this->_item, $start, $length);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $field
|
||||
* @param string $setKey
|
||||
*
|
||||
* @return array|null
|
||||
*/
|
||||
public function column(string $field, string $setKey = ''): ?array
|
||||
{
|
||||
$data = $this->toArray();
|
||||
if (empty($data)) {
|
||||
return [];
|
||||
}
|
||||
if (!empty($setKey) && is_string($setKey)) {
|
||||
return array_column($data, $field, $setKey);
|
||||
} else {
|
||||
return array_column($data, $field);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $field
|
||||
*
|
||||
* @return float|int|null
|
||||
*/
|
||||
public function sum(string $field): float|int|null
|
||||
{
|
||||
$array = $this->column($field);
|
||||
if (empty($array)) {
|
||||
return NULL;
|
||||
}
|
||||
return array_sum($array);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return ModelInterface|array
|
||||
*/
|
||||
#[Pure] public function current(): ModelInterface|array
|
||||
{
|
||||
return current($this->_item);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return int
|
||||
*/
|
||||
#[Pure] public function size(): int
|
||||
{
|
||||
return (int)count($this->_item);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array
|
||||
* @throws
|
||||
*/
|
||||
public function toArray(): array
|
||||
{
|
||||
$array = [];
|
||||
/** @var Model $value */
|
||||
foreach ($this as $value) {
|
||||
if (!is_object($value)) {
|
||||
continue;
|
||||
}
|
||||
$array[] = $value->setWith($this->query->with)->toArray();
|
||||
}
|
||||
$this->_item = [];
|
||||
return $array;
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws Exception
|
||||
* 批量删除
|
||||
*/
|
||||
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;
|
||||
}
|
||||
}
|
||||
return $model::query()->whereIn($model->getPrimary(), $ids)->delete();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $condition
|
||||
* @return Collection
|
||||
* @throws
|
||||
*/
|
||||
public function filter(array $condition): Collection|static
|
||||
{
|
||||
$_filters = [];
|
||||
if (empty($condition)) {
|
||||
return $this;
|
||||
}
|
||||
foreach ($this as $value) {
|
||||
if (!$this->filterCheck($value, $condition)) {
|
||||
continue;
|
||||
}
|
||||
$_filters[] = $value;
|
||||
}
|
||||
return new Collection($this->query, $_filters, $this->model);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $value
|
||||
* @param $condition
|
||||
* @return bool
|
||||
* @throws Exception
|
||||
*/
|
||||
private function filterCheck($value, $condition): bool
|
||||
{
|
||||
$_value = $value;
|
||||
if ($_value instanceof ModelInterface) {
|
||||
$_value = $_value->toArray();
|
||||
}
|
||||
$_tmp = array_intersect_key($_value, $condition);
|
||||
if (count(array_diff_assoc($_tmp, $condition)) > 0) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $key
|
||||
* @param $value
|
||||
* @return mixed
|
||||
*/
|
||||
public function exists($key, $value): mixed
|
||||
{
|
||||
foreach ($this as $item) {
|
||||
if ($item->$key === $value) {
|
||||
return $item;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
#[Pure] public function isEmpty(): bool
|
||||
{
|
||||
return $this->size() < 1;
|
||||
}
|
||||
}
|
||||
-203
@@ -1,203 +0,0 @@
|
||||
<?php
|
||||
/**
|
||||
* Created by PhpStorm.
|
||||
* User: whwyy
|
||||
* Date: 2018/3/30 0030
|
||||
* Time: 15:23
|
||||
*/
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database;
|
||||
|
||||
|
||||
use Exception;
|
||||
use Kiri\Abstracts\Component;
|
||||
use Kiri\Core\Json;
|
||||
use PDOStatement;
|
||||
|
||||
/**
|
||||
* Class Command
|
||||
* @package Database
|
||||
*/
|
||||
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 ?string $sql = '';
|
||||
|
||||
/** @var array */
|
||||
public array $params = [];
|
||||
|
||||
/** @var string */
|
||||
public string $dbname = '';
|
||||
|
||||
/** @var PDOStatement|null */
|
||||
private ?PDOStatement $prepare = null;
|
||||
|
||||
|
||||
/**
|
||||
* @return array|bool|int|string|PDOStatement|null
|
||||
* @throws Exception
|
||||
*/
|
||||
public function incrOrDecr(): array|bool|int|string|PDOStatement|null
|
||||
{
|
||||
return $this->execute(static::EXECUTE);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param bool $isInsert
|
||||
* @param mixed $hasAutoIncrement
|
||||
* @return int|bool|array|string|null
|
||||
* @throws Exception
|
||||
*/
|
||||
public function save(bool $isInsert = TRUE, mixed $hasAutoIncrement = null): int|bool|array|string|null
|
||||
{
|
||||
return $this->execute(static::EXECUTE);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return int|bool|array|string|null
|
||||
* @throws Exception
|
||||
*/
|
||||
public function all(): int|bool|array|string|null
|
||||
{
|
||||
return $this->execute(static::FETCH_ALL);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array|bool|int|string|null
|
||||
* @throws Exception
|
||||
*/
|
||||
public function one(): null|array|bool|int|string
|
||||
{
|
||||
return $this->execute(static::FETCH);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return int|bool|array|string|null
|
||||
* @throws Exception
|
||||
*/
|
||||
public function fetchColumn(): int|bool|array|string|null
|
||||
{
|
||||
return $this->execute(static::FETCH_COLUMN);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return int|bool|array|string|null
|
||||
* @throws Exception
|
||||
*/
|
||||
public function rowCount(): int|bool|array|string|null
|
||||
{
|
||||
return $this->execute(static::ROW_COUNT);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return int|bool|array|string|null
|
||||
* @throws Exception
|
||||
*/
|
||||
public function flush(): int|bool|array|string|null
|
||||
{
|
||||
return $this->execute(static::EXECUTE);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $type
|
||||
* @return int|bool|array|string|null
|
||||
* @throws Exception
|
||||
*/
|
||||
private function execute($type): int|bool|array|string|null
|
||||
{
|
||||
try {
|
||||
$time = microtime(true);
|
||||
if ($type === static::EXECUTE) {
|
||||
$result = $this->db->getConnect($this->sql)->execute($this->sql,$this->params);
|
||||
} else {
|
||||
$result = $this->search($type);
|
||||
}
|
||||
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');
|
||||
} finally {
|
||||
$this->db->release();
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $type
|
||||
* @return array|int|bool|null
|
||||
* @throws Exception
|
||||
*/
|
||||
private function search($type): array|int|bool|null
|
||||
{
|
||||
$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 int|bool|array|string|null
|
||||
* @throws Exception
|
||||
*/
|
||||
public function delete(): int|bool|array|string|null
|
||||
{
|
||||
return $this->execute(static::EXECUTE);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return int|bool|array|string|null
|
||||
* @throws Exception
|
||||
*/
|
||||
public function exec(): int|bool|array|string|null
|
||||
{
|
||||
return $this->execute(static::EXECUTE);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $data
|
||||
* @return $this
|
||||
*/
|
||||
public function bindValues(array $data = []): static
|
||||
{
|
||||
if (!is_array($this->params)) {
|
||||
$this->params = [];
|
||||
}
|
||||
if (!empty($data)) {
|
||||
$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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,82 +0,0 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database\Condition;
|
||||
|
||||
|
||||
use JetBrains\PhpStorm\Pure;
|
||||
use Kiri\Abstracts\Component;
|
||||
|
||||
/**
|
||||
* Class Condition
|
||||
* @package Database\Condition
|
||||
*/
|
||||
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 array $attributes = [];
|
||||
|
||||
abstract public function builder();
|
||||
|
||||
/**
|
||||
* @param string $column
|
||||
*/
|
||||
public function setColumn(string $column): void
|
||||
{
|
||||
$this->column = $column;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $opera
|
||||
*/
|
||||
public function setOpera(string $opera): void
|
||||
{
|
||||
$this->opera = $opera;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $params
|
||||
*/
|
||||
public function setValue($params): void
|
||||
{
|
||||
if (is_array($params)) {
|
||||
$values = [];
|
||||
foreach ($params as $item => $value) {
|
||||
$values[$item] = is_numeric($value) ? $value : '\'' . $value . '\'';
|
||||
}
|
||||
$this->value = $values;
|
||||
} else {
|
||||
$this->value = $this->checkIsSqlString($params);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $params
|
||||
* @return int|string
|
||||
*/
|
||||
#[Pure] private function checkIsSqlString($params): int|string
|
||||
{
|
||||
if (is_numeric($params)) {
|
||||
return $params;
|
||||
}
|
||||
|
||||
$check = ltrim($params, '(');
|
||||
$check = strtolower(substr($check, 0, 6));
|
||||
if (in_array($check, ['update', 'select', 'insert', 'delete'])) {
|
||||
return $params;
|
||||
} else {
|
||||
return sprintf('\'%s\'', $params);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database\Condition;
|
||||
|
||||
/**
|
||||
* Class HashCondition
|
||||
* @package Yoc\db\condition
|
||||
*/
|
||||
class HashCondition extends Condition
|
||||
{
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function builder(): string
|
||||
{
|
||||
$array = [];
|
||||
if (empty($this->value)) {
|
||||
return '';
|
||||
}
|
||||
foreach ($this->value as $key => $value) {
|
||||
if (is_null($value)) continue;
|
||||
|
||||
$array[] = sprintf("%s = '%s'", $key, addslashes($value));
|
||||
}
|
||||
return implode(' AND ', $array);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database\Condition;
|
||||
|
||||
use Database\ActiveQuery;
|
||||
use Exception;
|
||||
use JetBrains\PhpStorm\Pure;
|
||||
|
||||
/**
|
||||
* Class InCondition
|
||||
* @package Database\Condition
|
||||
*/
|
||||
class InCondition extends Condition
|
||||
{
|
||||
|
||||
|
||||
/**
|
||||
* @return string
|
||||
* @throws Exception
|
||||
*/
|
||||
#[Pure] public function builder(): string
|
||||
{
|
||||
if (is_array($this->value)) {
|
||||
return sprintf('%s IN (%s)', $this->column, implode(',', $this->value));
|
||||
} else {
|
||||
return sprintf('%s IN (%s)', $this->column, $this->value);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database\Condition;
|
||||
|
||||
use JetBrains\PhpStorm\Pure;
|
||||
|
||||
/**
|
||||
* Class NotInCondition
|
||||
* @package Database\Condition
|
||||
*/
|
||||
class NotInCondition extends Condition
|
||||
{
|
||||
|
||||
|
||||
/**
|
||||
* @return string|null
|
||||
*/
|
||||
#[Pure] public function builder(): ?string
|
||||
{
|
||||
if (!is_array($this->value)) {
|
||||
return null;
|
||||
}
|
||||
$value = '\'' . implode('\',\'', $this->value) . '\'';
|
||||
return '`' . $this->column . '` not in(' . $value . ')';
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,355 +0,0 @@
|
||||
<?php
|
||||
/**
|
||||
* Created by PhpStorm.
|
||||
* User: whwyy
|
||||
* Date: 2018/3/30 0030
|
||||
* Time: 14:09
|
||||
*/
|
||||
declare(strict_types=1);
|
||||
|
||||
|
||||
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\Abstracts\Component;
|
||||
use Kiri\Abstracts\Config;
|
||||
use Kiri\Events\EventProvider;
|
||||
use Kiri\Exception\NotFindClassException;
|
||||
use Kiri\Kiri;
|
||||
use Note\Inject;
|
||||
use ReflectionException;
|
||||
use Server\Events\OnWorkerExit;
|
||||
use Server\Events\OnWorkerStop;
|
||||
|
||||
/**
|
||||
* Class Connection
|
||||
* @package Database
|
||||
*/
|
||||
class Connection extends Component
|
||||
{
|
||||
|
||||
public string $id = 'db';
|
||||
public string $cds = '';
|
||||
public string $password = '';
|
||||
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 bool $enableCache = false;
|
||||
|
||||
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
public string $cacheDriver = 'redis';
|
||||
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
public array $slaveConfig = [];
|
||||
public array $attributes = [];
|
||||
|
||||
|
||||
/**
|
||||
* @var Schema
|
||||
*/
|
||||
#[Inject(Schema::class)]
|
||||
public Schema $_schema;
|
||||
|
||||
|
||||
/**
|
||||
* execute by __construct
|
||||
* @throws Exception
|
||||
*/
|
||||
public function init()
|
||||
{
|
||||
$eventProvider = Kiri::getDi()->get(EventProvider::class);
|
||||
$eventProvider->on(OnWorkerStop::class, [$this, 'clear_connection'], 0);
|
||||
$eventProvider->on(OnWorkerExit::class, [$this, 'clear_connection'], 0);
|
||||
$eventProvider->on(BeginTransaction::class, [$this, 'beginTransaction'], 0);
|
||||
$eventProvider->on(Rollback::class, [$this, 'rollback'], 0);
|
||||
$eventProvider->on(Commit::class, [$this, 'commit'], 0);
|
||||
|
||||
if (Db::transactionsActive()) {
|
||||
$this->beginTransaction();
|
||||
}
|
||||
|
||||
$this->_schema->db = $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param null $sql
|
||||
* @return PDO
|
||||
* @throws Exception
|
||||
*/
|
||||
public function getConnect($sql = NULL): PDO
|
||||
{
|
||||
return $this->getPdo($sql);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $config
|
||||
* @return $this
|
||||
*/
|
||||
public function configure($config): static
|
||||
{
|
||||
Kiri::configure($this, $config);
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $sql
|
||||
* @return PDO
|
||||
* @throws Exception
|
||||
*/
|
||||
private function getPdo($sql): PDO
|
||||
{
|
||||
if ($this->isWrite($sql)) {
|
||||
return $this->masterInstance();
|
||||
} else {
|
||||
return $this->slaveInstance();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
public function isWrite($sql): bool
|
||||
{
|
||||
if (empty($sql)) return false;
|
||||
if (str_starts_with(strtolower($sql), 'select')) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return mixed
|
||||
* @throws Exception
|
||||
*/
|
||||
public function getCacheDriver(): mixed
|
||||
{
|
||||
if (!$this->enableCache) {
|
||||
return null;
|
||||
}
|
||||
return Kiri::app()->get($this->cacheDriver);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return PDO
|
||||
* @throws Exception
|
||||
*/
|
||||
public function masterInstance(): 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);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return PDO
|
||||
* @throws Exception
|
||||
*/
|
||||
public function slaveInstance(): PDO
|
||||
{
|
||||
if (empty($this->slaveConfig) || Db::transactionsActive()) {
|
||||
return $this->masterInstance();
|
||||
}
|
||||
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 $this
|
||||
* @throws Exception
|
||||
*/
|
||||
public function beginTransaction(): static
|
||||
{
|
||||
$this->connections()->beginTransaction($this->cds);
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return $this|bool
|
||||
* @throws Exception
|
||||
*/
|
||||
public function inTransaction(): bool|static
|
||||
{
|
||||
return $this->connections()->inTransaction($this->cds);
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws Exception
|
||||
* 事务回滚
|
||||
*/
|
||||
public function rollback()
|
||||
{
|
||||
$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();
|
||||
return;
|
||||
}
|
||||
$connections = $this->connections();
|
||||
$connections->release($this->cds, true);
|
||||
$connections->release($this->slaveConfig['cds'], false);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @throws Exception
|
||||
*/
|
||||
public function recovery()
|
||||
{
|
||||
$connections = $this->connections();
|
||||
|
||||
$connections->release($this->cds, true);
|
||||
$connections->release($this->slaveConfig['cds'], false);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* 回收链接
|
||||
* @throws
|
||||
*/
|
||||
public function clear_connection()
|
||||
{
|
||||
$connections = $this->connections();
|
||||
|
||||
$connections->connection_clear($this->cds, true);
|
||||
$connections->connection_clear($this->slaveConfig['cds'], false);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @throws Exception
|
||||
*/
|
||||
public function disconnect()
|
||||
{
|
||||
$connections = $this->connections();
|
||||
$connections->disconnect($this->cds, true);
|
||||
$connections->disconnect($this->slaveConfig['cds'], false);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,107 +0,0 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database;
|
||||
|
||||
|
||||
use Exception;
|
||||
use Kiri\Abstracts\Config;
|
||||
use Kiri\Abstracts\Providers;
|
||||
use Kiri\Application;
|
||||
use Kiri\Events\EventProvider;
|
||||
use Kiri\Exception\ConfigException;
|
||||
use Kiri\Kiri;
|
||||
use Server\Events\OnWorkerStart;
|
||||
|
||||
/**
|
||||
* Class DatabasesProviders
|
||||
* @package Database
|
||||
*/
|
||||
class DatabasesProviders extends Providers
|
||||
{
|
||||
|
||||
private array $_pooLength = ['min' => 0, 'max' => 1];
|
||||
|
||||
|
||||
/**
|
||||
* @param Application $application
|
||||
* @throws Exception
|
||||
*/
|
||||
public function onImport(Application $application)
|
||||
{
|
||||
$application->set('db', $this);
|
||||
|
||||
$this->_pooLength = Config::get('databases.pool', ['min' => 0, 'max' => 1]);
|
||||
|
||||
$this->eventProvider->on(OnWorkerStart::class, [$this, 'createPool']);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $name
|
||||
* @return Connection
|
||||
* @throws ConfigException
|
||||
* @throws Exception
|
||||
*/
|
||||
public function get($name): Connection
|
||||
{
|
||||
$config = $this->_settings($this->getConfig($name));
|
||||
|
||||
return Kiri::getDi()->get(Connection::class)->configure($config);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @throws ConfigException
|
||||
* @throws Exception
|
||||
*/
|
||||
public function createPool(OnWorkerStart $onWorkerStart)
|
||||
{
|
||||
$databases = Config::get('databases.connections', []);
|
||||
if (empty($databases)) {
|
||||
return;
|
||||
}
|
||||
$connection = Kiri::getDi()->get(Connection::class);
|
||||
foreach ($databases as $database) {
|
||||
/** @var Connection $connection */
|
||||
$connection->configure($database)->fill();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $database
|
||||
* @return array
|
||||
*/
|
||||
private function _settings($database): array
|
||||
{
|
||||
$clientPool = $database['pool'] ?? ['min' => 1, 'max' => 5, 'tick' => 60];
|
||||
return [
|
||||
'id' => $database['id'],
|
||||
'cds' => $database['cds'],
|
||||
'username' => $database['username'],
|
||||
'password' => $database['password'],
|
||||
'tablePrefix' => $database['tablePrefix'],
|
||||
'database' => $database['database'],
|
||||
'connect_timeout' => $database['connect_timeout'] ?? 30,
|
||||
'read_timeout' => $database['read_timeout'] ?? 10,
|
||||
'pool' => $clientPool,
|
||||
'attributes' => $database['attributes'] ?? [],
|
||||
'charset' => $database['charset'] ?? 'utf8mb4',
|
||||
'slaveConfig' => $database['slaveConfig']
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $name
|
||||
* @return mixed
|
||||
* @throws ConfigException
|
||||
*/
|
||||
public function getConfig($name): mixed
|
||||
{
|
||||
return Config::get('databases.connections.' . $name, null, true);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
-365
@@ -1,365 +0,0 @@
|
||||
<?php
|
||||
/**
|
||||
* Created by PhpStorm.
|
||||
* User: whwyy
|
||||
* Date: 2018/4/4 0004
|
||||
* Time: 15:40
|
||||
*/
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database;
|
||||
|
||||
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;
|
||||
|
||||
/**
|
||||
* Class Db
|
||||
* @package Database
|
||||
*/
|
||||
class Db implements ISqlBuilder
|
||||
{
|
||||
use QueryTrait;
|
||||
|
||||
|
||||
private static bool $_inTransaction = false;
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
public static function transactionsActive(): bool
|
||||
{
|
||||
return static::$_inTransaction === true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws Exception
|
||||
*/
|
||||
public static function beginTransaction()
|
||||
{
|
||||
if (!static::transactionsActive()) {
|
||||
di(EventDispatch::class)->dispatch(new BeginTransaction());
|
||||
}
|
||||
static::$_inTransaction = true;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @throws Exception
|
||||
*/
|
||||
public static function commit()
|
||||
{
|
||||
if (static::transactionsActive()) {
|
||||
di(EventDispatch::class)->dispatch(new Commit());
|
||||
}
|
||||
static::$_inTransaction = false;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @throws Exception
|
||||
*/
|
||||
public static function rollback()
|
||||
{
|
||||
if (static::transactionsActive()) {
|
||||
di(EventDispatch::class)->dispatch(new Rollback());
|
||||
}
|
||||
static::$_inTransaction = false;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $table
|
||||
*
|
||||
* @return static
|
||||
*/
|
||||
public static function table($table): Db|static
|
||||
{
|
||||
$connection = new Db();
|
||||
$connection->from($table);
|
||||
return $connection;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $column
|
||||
* @param string $alias
|
||||
* @return string
|
||||
*/
|
||||
public static function any_value(string $column, string $alias = ''): string
|
||||
{
|
||||
if (empty($alias)) {
|
||||
$alias = $column . '_any_value';
|
||||
}
|
||||
return 'ANY_VALUE(' . $column . ') as ' . $alias;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $column
|
||||
* @return string
|
||||
*/
|
||||
public static function increment(string $column): string
|
||||
{
|
||||
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();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $column
|
||||
* @return string
|
||||
*/
|
||||
public static function raw($column): string
|
||||
{
|
||||
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();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $sql
|
||||
* @param array $attributes
|
||||
* @param Connection|null $connection
|
||||
* @return array|bool|int|string|null
|
||||
* @throws Exception
|
||||
*/
|
||||
public static function findAllBySql(string $sql, array $attributes = [], Connection $connection = NULL): int|bool|array|string|null
|
||||
{
|
||||
$connection = static::getDefaultConnection($connection);
|
||||
|
||||
return $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
|
||||
{
|
||||
$data = $this->get();
|
||||
if (empty($data) || empty($field)) {
|
||||
return NULL;
|
||||
}
|
||||
$first = current($data);
|
||||
if (!isset($first[$field])) {
|
||||
return NULL;
|
||||
}
|
||||
return array_column($data, $field);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $field
|
||||
* @return mixed
|
||||
* @throws Exception
|
||||
*/
|
||||
public function value($field): mixed
|
||||
{
|
||||
$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();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $table
|
||||
* @param null $connection
|
||||
* @return bool|int
|
||||
* @throws ConfigException
|
||||
* @throws Exception
|
||||
*/
|
||||
public static function drop(string $table, $connection = null): bool|int
|
||||
{
|
||||
$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)) {
|
||||
return null;
|
||||
}
|
||||
$connection = static::getDefaultConnection($connection);
|
||||
|
||||
$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();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param null|Connection $connection
|
||||
* @param null $name
|
||||
* @return mixed
|
||||
* @throws ConfigException
|
||||
* @throws Exception
|
||||
*/
|
||||
public static function getDefaultConnection(?Connection $connection, $name = null): Connection
|
||||
{
|
||||
if ($connection instanceof Connection) {
|
||||
return $connection;
|
||||
}
|
||||
$databases = Config::get('databases.connections', []);
|
||||
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);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database;
|
||||
|
||||
use Exception;
|
||||
use Database\Traits\HasBase;
|
||||
|
||||
/**
|
||||
* Class HasCount
|
||||
* @package Database
|
||||
*/
|
||||
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
|
||||
*/
|
||||
public function get(): array|ModelInterface|null
|
||||
{
|
||||
return $this->_relation->count($this->model::className(), $this->value);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
<?php
|
||||
/**
|
||||
* Created by PhpStorm.
|
||||
* User: whwyy
|
||||
* Date: 2018/4/4 0004
|
||||
* Time: 13:58
|
||||
*/
|
||||
declare(strict_types=1);
|
||||
namespace Database;
|
||||
|
||||
use Exception;
|
||||
use Database\Traits\HasBase;
|
||||
|
||||
/**
|
||||
* Class HasMany
|
||||
* @package Database
|
||||
*
|
||||
* @method with($name)
|
||||
*/
|
||||
class HasMany 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);
|
||||
}
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
<?php
|
||||
/**
|
||||
* Created by PhpStorm.
|
||||
* User: whwyy
|
||||
* Date: 2018/4/4 0004
|
||||
* Time: 13:47
|
||||
*/
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database;
|
||||
|
||||
use Exception;
|
||||
use Database\Traits\HasBase;
|
||||
|
||||
/**
|
||||
* Class HasOne
|
||||
* @package Database
|
||||
* @internal Query
|
||||
*/
|
||||
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
|
||||
*/
|
||||
public function get(): array|ModelInterface|null
|
||||
{
|
||||
return $this->_relation->first($this->model::className(), $this->value);
|
||||
}
|
||||
}
|
||||
-420
@@ -1,420 +0,0 @@
|
||||
<?php
|
||||
/**
|
||||
* Created by PhpStorm.
|
||||
* User: whwyy
|
||||
* Date: 2018/3/30 0030
|
||||
* Time: 14:39
|
||||
*/
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database;
|
||||
|
||||
|
||||
use Database\Base\Getter;
|
||||
use Database\Traits\HasBase;
|
||||
use Exception;
|
||||
use Kiri\Exception\NotFindClassException;
|
||||
use Kiri\Kiri;
|
||||
use Kiri\ToArray;
|
||||
use ReflectionException;
|
||||
|
||||
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.');
|
||||
|
||||
/**
|
||||
* Class Orm
|
||||
* @package Database
|
||||
*
|
||||
* @property $attributes
|
||||
* @property-read $oldAttributes
|
||||
*/
|
||||
class Model extends Base\Model
|
||||
{
|
||||
|
||||
|
||||
/**
|
||||
* @param string $column
|
||||
* @param int $value
|
||||
* @return ModelInterface|false
|
||||
* @throws Exception
|
||||
*/
|
||||
public function increment(string $column, int $value): bool|ModelInterface
|
||||
{
|
||||
if (!$this->mathematics([$column => $value], '+')) {
|
||||
return false;
|
||||
}
|
||||
$this->{$column} += $value;
|
||||
return $this->refresh();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $column
|
||||
* @param int $value
|
||||
* @return ModelInterface|false
|
||||
* @throws Exception
|
||||
*/
|
||||
public function decrement(string $column, int $value): bool|ModelInterface
|
||||
{
|
||||
if (!$this->mathematics([$column => $value], '-')) {
|
||||
return false;
|
||||
}
|
||||
$this->{$column} -= $value;
|
||||
return $this->refresh();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param array $columns
|
||||
* @return ModelInterface|false
|
||||
* @throws Exception
|
||||
*/
|
||||
public function increments(array $columns): bool|static
|
||||
{
|
||||
if (!$this->mathematics($columns, '+')) {
|
||||
return false;
|
||||
}
|
||||
foreach ($columns as $key => $attribute) {
|
||||
$this->$key += $attribute;
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param array $columns
|
||||
* @return ModelInterface|false
|
||||
* @throws Exception
|
||||
*/
|
||||
public function decrements(array $columns): bool|static
|
||||
{
|
||||
if (!$this->mathematics($columns, '-')) {
|
||||
return false;
|
||||
}
|
||||
foreach ($columns as $key => $attribute) {
|
||||
$this->$key -= $attribute;
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $condition
|
||||
* @param array $attributes
|
||||
* @return bool|ModelInterface
|
||||
* @throws ReflectionException
|
||||
* @throws NotFindClassException
|
||||
* @throws Exception
|
||||
*/
|
||||
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();
|
||||
/** @var static $select */
|
||||
$select = static::query()->where($condition)->first();
|
||||
if (empty($select)) {
|
||||
$select = duplicate(static::class);
|
||||
$select->attributes = $attributes;
|
||||
$select->setIsNowExample(true);
|
||||
if (!$select->save()) {
|
||||
Db::rollback();
|
||||
return $logger->addError($select->getLastError(), 'mysql');
|
||||
}
|
||||
}
|
||||
Db::commit();
|
||||
return $select;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param array $condition
|
||||
* @param array $attributes
|
||||
* @return bool|static
|
||||
* @throws Exception
|
||||
*/
|
||||
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();
|
||||
/** @var static $select */
|
||||
$select = static::query()->where($condition)->first();
|
||||
if (empty($select)) {
|
||||
$select = duplicate(static::class);
|
||||
}
|
||||
$select->attributes = $attributes;
|
||||
if (!$select->save()) {
|
||||
Db::rollback();
|
||||
$select = $logger->addError($select->getLastError(), 'mysql');
|
||||
} else {
|
||||
Db::commit();
|
||||
}
|
||||
return $select;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $action
|
||||
* @param $columns
|
||||
* @param null|array $condition
|
||||
* @return array|bool|int|string|null
|
||||
* @throws Exception
|
||||
*/
|
||||
private function mathematics($columns, $action, ?array $condition = null): int|bool|array|string|null
|
||||
{
|
||||
if (empty($condition)) {
|
||||
$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();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param array $fields
|
||||
* @return ModelInterface|bool
|
||||
* @throws Exception
|
||||
*/
|
||||
public function update(array $fields): static|bool
|
||||
{
|
||||
return $this->save($fields);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param array $data
|
||||
* @return bool
|
||||
* @throws Exception
|
||||
*/
|
||||
public static function inserts(array $data): bool
|
||||
{
|
||||
$result = false;
|
||||
if (empty($data)) {
|
||||
error('Insert data empty.', 'mysql');
|
||||
} else {
|
||||
$result = static::query()->batchInsert($data);
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
* @throws Exception
|
||||
*/
|
||||
public function delete(): bool
|
||||
{
|
||||
$conditions = $this->_oldAttributes;
|
||||
if (empty($conditions)) {
|
||||
return $this->addError("Delete condition do not empty.", 'mysql');
|
||||
}
|
||||
$primary = $this->getPrimary();
|
||||
|
||||
if (!empty($primary)) {
|
||||
$conditions = [$primary => $this->getAttribute($primary)];
|
||||
}
|
||||
return static::deleteByCondition($conditions);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @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);
|
||||
} else {
|
||||
return $resolve;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return array
|
||||
* @throws Exception
|
||||
*/
|
||||
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);
|
||||
}
|
||||
return $this->withRelates($data);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $relates
|
||||
* @return array
|
||||
* @throws Exception
|
||||
*/
|
||||
private function withRelates($relates): array
|
||||
{
|
||||
if (empty($with = $this->getWith())) {
|
||||
return $relates;
|
||||
}
|
||||
foreach ($with as $val) {
|
||||
$relates[$val] = $this->withRelation($val);
|
||||
}
|
||||
return $relates;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $modelName
|
||||
* @param $foreignKey
|
||||
* @param $localKey
|
||||
* @return HasOne|ActiveQuery
|
||||
* @throws Exception
|
||||
*/
|
||||
public function hasOne(string $modelName, $foreignKey, $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);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $modelName
|
||||
* @param $foreignKey
|
||||
* @param $localKey
|
||||
* @return ActiveQuery|HasCount
|
||||
* @throws Exception
|
||||
*/
|
||||
public function hasCount($modelName, $foreignKey, $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);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $modelName
|
||||
* @param $foreignKey
|
||||
* @param $localKey
|
||||
* @return ActiveQuery|HasMany
|
||||
* @throws Exception
|
||||
*/
|
||||
public function hasMany($modelName, $foreignKey, $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);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $modelName
|
||||
* @param $foreignKey
|
||||
* @param $localKey
|
||||
* @return ActiveQuery|HasMany
|
||||
* @throws Exception
|
||||
*/
|
||||
public function hasIn($modelName, $foreignKey, $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 bool
|
||||
* @throws Exception
|
||||
*/
|
||||
public function afterDelete(): bool
|
||||
{
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
* @throws Exception
|
||||
*/
|
||||
public function beforeDelete(): bool
|
||||
{
|
||||
return TRUE;
|
||||
}
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
<?php
|
||||
/**
|
||||
* Created by PhpStorm.
|
||||
* User: whwyy
|
||||
* Date: 2018/3/30 0030
|
||||
* Time: 14:39
|
||||
*/
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database;
|
||||
|
||||
|
||||
/**
|
||||
* Interface ModelInterface
|
||||
* @package Database
|
||||
*/
|
||||
interface ModelInterface
|
||||
{
|
||||
|
||||
/**
|
||||
* @param $param
|
||||
* @param null $db
|
||||
* @return ModelInterface
|
||||
*/
|
||||
public static function findOne($param, $db = NULL): mixed;
|
||||
|
||||
|
||||
/**
|
||||
* @param string|int $param
|
||||
* @return ModelInterface
|
||||
*/
|
||||
public static function find(string|int $param): mixed;
|
||||
|
||||
|
||||
/**
|
||||
* @param array $data
|
||||
* @return static
|
||||
*/
|
||||
public static function populate(array $data): static;
|
||||
|
||||
|
||||
/**
|
||||
* @return ActiveQuery
|
||||
* return a sql queryBuilder
|
||||
*/
|
||||
public static function query(): ActiveQuery;
|
||||
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getTable(): string;
|
||||
|
||||
|
||||
/**
|
||||
* @return Connection
|
||||
*/
|
||||
public function getConnection(): Connection;
|
||||
|
||||
|
||||
}
|
||||
@@ -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');
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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,44 +0,0 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace Database\Note;
|
||||
|
||||
|
||||
use Attribute;
|
||||
use Database\Base\Getter;
|
||||
use Exception;
|
||||
|
||||
|
||||
/**
|
||||
* Class Get
|
||||
* @package Note\Model
|
||||
*/
|
||||
#[Attribute(Attribute::TARGET_METHOD)] class Get extends \Note\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\Note;
|
||||
|
||||
|
||||
use Note\Attribute;
|
||||
use Database\Base\Relate;
|
||||
use Exception;
|
||||
|
||||
|
||||
/**
|
||||
* Class Relation
|
||||
* @package Note\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\Note;
|
||||
|
||||
|
||||
use Note\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;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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];
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
<?php
|
||||
/**
|
||||
* Created by PhpStorm.
|
||||
* User: whwyy
|
||||
* Date: 2018/6/27 0027
|
||||
* Time: 17:49
|
||||
*/
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database;
|
||||
|
||||
|
||||
use Database\Traits\QueryTrait;
|
||||
use Exception;
|
||||
|
||||
/**
|
||||
* Class Query
|
||||
* @package Database
|
||||
*/
|
||||
class Query 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
|
||||
*/
|
||||
public function getCondition(): string
|
||||
{
|
||||
return $this->builder->getCondition();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -1,111 +0,0 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database;
|
||||
|
||||
|
||||
use Exception;
|
||||
use Kiri\Abstracts\Component;
|
||||
|
||||
/**
|
||||
* Class Relation
|
||||
* @package Kiri\db
|
||||
*/
|
||||
class Relation extends Component
|
||||
{
|
||||
|
||||
private array $_relations = [];
|
||||
|
||||
/** @var ActiveQuery[] $_query */
|
||||
private array $_query = [];
|
||||
|
||||
/**
|
||||
* @param string $identification
|
||||
* @param ActiveQuery $query
|
||||
* @return $this
|
||||
*/
|
||||
public function bindIdentification(string $identification, ActiveQuery $query): static
|
||||
{
|
||||
$this->_query[$identification] = $query;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $name
|
||||
* @return ActiveQuery|null
|
||||
*/
|
||||
public function getQuery(string $name): ?ActiveQuery
|
||||
{
|
||||
return $this->_query[$name] ?? null;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $identification
|
||||
* @param $localValue
|
||||
* @return mixed
|
||||
* @throws Exception
|
||||
*/
|
||||
public function first(string $identification, $localValue): mixed
|
||||
{
|
||||
$_identification = $identification . '_first_' . $localValue;
|
||||
if (isset($this->_relations[$_identification]) && $this->_relations[$_identification] !== null) {
|
||||
return $this->_relations[$_identification];
|
||||
}
|
||||
|
||||
$activeModel = $this->_query[$identification]->first();
|
||||
if (empty($activeModel)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->_relations[$_identification] = $activeModel;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $identification
|
||||
* @param $localValue
|
||||
* @return mixed
|
||||
* @throws Exception
|
||||
*/
|
||||
public function count(string $identification, $localValue): mixed
|
||||
{
|
||||
$_identification = $identification . '_count_' . $localValue;
|
||||
if (isset($this->_relations[$_identification]) && $this->_relations[$_identification] !== null) {
|
||||
return $this->_relations[$_identification];
|
||||
}
|
||||
|
||||
$activeModel = $this->_query[$identification]->count();
|
||||
if (empty($activeModel)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->_relations[$_identification] = $activeModel;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $identification
|
||||
* @param $localValue
|
||||
* @return mixed
|
||||
*/
|
||||
public function get(string $identification, $localValue): mixed
|
||||
{
|
||||
if (is_array($localValue)) {
|
||||
$_identification = $identification . '_get_' . implode('_', $localValue);
|
||||
} else {
|
||||
$_identification = $identification . '_get_' . $localValue;
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,375 +0,0 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace Database;
|
||||
|
||||
|
||||
use Database\Traits\Builder;
|
||||
use Exception;
|
||||
use JetBrains\PhpStorm\Pure;
|
||||
use Kiri\Abstracts\Component;
|
||||
|
||||
|
||||
/**
|
||||
* Class SqlBuilder
|
||||
* @package Database
|
||||
*/
|
||||
class SqlBuilder extends Component
|
||||
{
|
||||
|
||||
use Builder;
|
||||
|
||||
|
||||
public ActiveQuery|Query|null $query;
|
||||
|
||||
|
||||
/**
|
||||
* @param ISqlBuilder|null $query
|
||||
* @return $this
|
||||
* @throws Exception
|
||||
*/
|
||||
public static function builder(ISqlBuilder|null $query): static
|
||||
{
|
||||
return new static(['query' => $query]);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return string
|
||||
* @throws Exception
|
||||
*/
|
||||
public function getCondition(): string
|
||||
{
|
||||
return $this->conditionToString();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param array $compiler
|
||||
* @return string
|
||||
* @throws Exception
|
||||
*/
|
||||
public function hashCompiler(array $compiler): string
|
||||
{
|
||||
return $this->where($compiler);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param array $attributes
|
||||
* @return bool|array
|
||||
* @throws Exception
|
||||
*/
|
||||
public function update(array $attributes): bool|array
|
||||
{
|
||||
[$string, $array] = $this->builderParams($attributes);
|
||||
|
||||
return $this->__updateBuilder($string, $array);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param array $attributes
|
||||
* @param string $opera
|
||||
* @return bool|array
|
||||
* @throws Exception
|
||||
*/
|
||||
public function mathematics(array $attributes, string $opera = '+'): bool|array
|
||||
{
|
||||
$string = [];
|
||||
foreach ($attributes as $attribute => $value) {
|
||||
$string[] = $attribute . '=' . $attribute . $opera . $value;
|
||||
}
|
||||
return $this->__updateBuilder($string, []);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param array $string
|
||||
* @param array $params
|
||||
* @return array|bool
|
||||
* @throws Exception
|
||||
*/
|
||||
private function __updateBuilder(array $string, array $params): array|bool
|
||||
{
|
||||
if (empty($string)) {
|
||||
return $this->addError('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];
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param array $attributes
|
||||
* @param false $isBatch
|
||||
* @return array
|
||||
* @throws Exception
|
||||
*/
|
||||
public function insert(array $attributes, bool $isBatch = false): array
|
||||
{
|
||||
$update = 'INSERT INTO ' . $this->tableName();
|
||||
if ($isBatch === false) {
|
||||
$attributes = [$attributes];
|
||||
}
|
||||
$update .= '(' . implode(',', $this->getFields($attributes)) . ') VALUES ';
|
||||
|
||||
$order = 0;
|
||||
$keys = $params = [];
|
||||
foreach ($attributes as $attribute) {
|
||||
[$_keys, $params] = $this->builderParams($attribute, true, $params, $order);
|
||||
|
||||
$keys[] = implode(',', $_keys);
|
||||
$order++;
|
||||
}
|
||||
return [$update . '(' . implode('),(', $keys) . ')', $params];
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return string
|
||||
* @throws Exception
|
||||
*/
|
||||
public function delete(): string
|
||||
{
|
||||
$delete = sprintf('DELETE FROM %s ', $this->query->modelClass->getTable());
|
||||
|
||||
$this->query->from = null;
|
||||
|
||||
return $delete . ' WHERE ' . $this->_prefix(true);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $attributes
|
||||
* @return array
|
||||
*/
|
||||
#[Pure] private function getFields($attributes): array
|
||||
{
|
||||
return array_keys(current($attributes));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @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
|
||||
{
|
||||
$keys = [];
|
||||
foreach ($attributes as $key => $value) {
|
||||
if ($isInsert === true) {
|
||||
$keys[] = ':' . $key . $order;
|
||||
$params[$key . $order] = $value;
|
||||
} else {
|
||||
[$keys, $params] = $this->resolveParams($key, $value, $order, $params, $keys);
|
||||
}
|
||||
}
|
||||
return [$keys, $params];
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @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
|
||||
{
|
||||
if (
|
||||
str_starts_with($value, '+ ') ||
|
||||
str_starts_with($value, '- ')
|
||||
) {
|
||||
$keys[] = $key . '=' . $key . ' ' . $value;
|
||||
} else {
|
||||
$params[$key . $order] = $value;
|
||||
$keys[] = $key . '=:' . $key . $order;
|
||||
}
|
||||
return [$keys, $params];
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return string
|
||||
* @throws Exception
|
||||
*/
|
||||
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 string
|
||||
* @throws Exception
|
||||
*/
|
||||
public function all(): string
|
||||
{
|
||||
if (empty($this->query->from) && !empty($this->query->modelClass)) {
|
||||
$this->query->from($this->query->getTable());
|
||||
}
|
||||
return $this->_prefix(true);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return string
|
||||
* @throws Exception
|
||||
*/
|
||||
public function count(): string
|
||||
{
|
||||
if (empty($this->query->from) && !empty($this->query->modelClass)) {
|
||||
$this->query->from($this->query->getTable());
|
||||
}
|
||||
return $this->_prefix(false, true);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $table
|
||||
* @return string
|
||||
*/
|
||||
public function columns($table): string
|
||||
{
|
||||
return 'SHOW FULL FIELDS FROM ' . $table;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param bool $hasOrder
|
||||
* @param bool $isCount
|
||||
* @return string
|
||||
* @throws Exception
|
||||
*/
|
||||
private function _prefix(bool $hasOrder = false, bool $isCount = false): 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);
|
||||
}
|
||||
|
||||
if (!empty($this->query->group)) {
|
||||
$select .= $this->builderGroup($this->query->group);
|
||||
}
|
||||
if ($hasOrder === true && !empty($this->query->order)) {
|
||||
$select .= $this->builderOrder($this->query->order);
|
||||
}
|
||||
$sql = $select . $this->builderLimit($this->query);
|
||||
if ($this->query->lock) {
|
||||
$sql .= ' FOR UPDATE';
|
||||
}
|
||||
return $sql;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $select
|
||||
* @return string
|
||||
* @throws Exception
|
||||
*/
|
||||
private function _wherePrefix($select): string
|
||||
{
|
||||
$condition = $this->conditionToString();
|
||||
if (empty($condition)) {
|
||||
return $select;
|
||||
} else if (empty($select)) {
|
||||
return $condition;
|
||||
}
|
||||
return sprintf('%s WHERE %s', $select, $condition);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param bool $isCount
|
||||
* @return string
|
||||
* @throws Exception
|
||||
*/
|
||||
private function _selectPrefix(bool $isCount): string
|
||||
{
|
||||
$select = $this->builderSelect($this->query->select, $isCount) . ' FROM ' . $this->tableName();
|
||||
if (!empty($this->query->alias)) {
|
||||
$select .= $this->builderAlias($this->query->alias);
|
||||
}
|
||||
if (!empty($this->query->join)) {
|
||||
$select .= $this->builderJoin($this->query->join);
|
||||
}
|
||||
return $select;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param false $isCount
|
||||
* @return string
|
||||
* @throws Exception
|
||||
*/
|
||||
public function get(bool $isCount = false): string
|
||||
{
|
||||
if ($isCount === false) {
|
||||
return $this->all();
|
||||
}
|
||||
return $this->count();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return string
|
||||
* @throws Exception
|
||||
*/
|
||||
public function truncate(): string
|
||||
{
|
||||
return sprintf('TRUNCATE %s', $this->tableName());
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return string
|
||||
* @throws Exception
|
||||
*/
|
||||
private function conditionToString(): string
|
||||
{
|
||||
return $this->where($this->query->where);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return string
|
||||
* @throws Exception
|
||||
*/
|
||||
public function tableName(): string
|
||||
{
|
||||
if ($this->query->from instanceof \Closure) {
|
||||
$this->query->from = sprintf('(%s)', $this->query->makeClosureFunction($this->query->from));
|
||||
}
|
||||
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();
|
||||
}
|
||||
return $this->query->from;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Database;
|
||||
|
||||
|
||||
use Database\Model;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
class TestModel extends Model
|
||||
{
|
||||
|
||||
|
||||
protected string $connection = '';
|
||||
|
||||
|
||||
protected string $table = '';
|
||||
|
||||
|
||||
public ?string $primary = '';
|
||||
|
||||
}
|
||||
|
||||
|
||||
TestModel::query()->get();
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -1,81 +0,0 @@
|
||||
<?php
|
||||
/**
|
||||
* Created by PhpStorm.
|
||||
* User: whwyy
|
||||
* Date: 2018/4/4 0004
|
||||
* Time: 15:47
|
||||
*/
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database\Traits;
|
||||
|
||||
use Database\ModelInterface;
|
||||
use Database\Collection;
|
||||
use Database\Relation;
|
||||
use Exception;
|
||||
|
||||
/**
|
||||
* Class HasBase
|
||||
* @package Database
|
||||
*
|
||||
* @include Query
|
||||
*/
|
||||
abstract class HasBase implements \Database\Traits\Relation
|
||||
{
|
||||
|
||||
/** @var ModelInterface|Collection */
|
||||
protected Collection|ModelInterface $data;
|
||||
|
||||
/**
|
||||
* @var ModelInterface
|
||||
*/
|
||||
protected mixed $model;
|
||||
|
||||
protected mixed $value = [];
|
||||
|
||||
|
||||
/** @var Relation $_relation */
|
||||
protected Relation $_relation;
|
||||
|
||||
/**
|
||||
* HasBase constructor.
|
||||
* @param ModelInterface $model
|
||||
* @param $primaryId
|
||||
* @param $value
|
||||
* @param Relation $relation
|
||||
* @throws Exception
|
||||
*/
|
||||
public function __construct(mixed $model, $primaryId, $value, Relation $relation)
|
||||
{
|
||||
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
|
||||
*/
|
||||
public function __get($name): mixed
|
||||
{
|
||||
if (empty($this->value)) {
|
||||
return null;
|
||||
}
|
||||
return $this->get();
|
||||
}
|
||||
}
|
||||
@@ -1,963 +0,0 @@
|
||||
<?php
|
||||
/**
|
||||
* Created by PhpStorm.
|
||||
* User: whwyy
|
||||
* Date: 2018/3/30 0030
|
||||
* Time: 14:56
|
||||
*/
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database\Traits;
|
||||
|
||||
|
||||
use Closure;
|
||||
use Database\ActiveQuery;
|
||||
use Database\Condition\MathematicsCondition;
|
||||
use Database\ModelInterface;
|
||||
use Database\Query;
|
||||
use Database\SqlBuilder;
|
||||
use Exception;
|
||||
use Kiri\Exception\NotFindClassException;
|
||||
use Kiri\Kiri;
|
||||
use ReflectionException;
|
||||
|
||||
/**
|
||||
* Trait QueryTrait
|
||||
* @package Database\Traits
|
||||
*/
|
||||
trait QueryTrait
|
||||
{
|
||||
public array $where = [];
|
||||
public array $select = [];
|
||||
public array $join = [];
|
||||
public array $order = [];
|
||||
public ?int $offset = NULL;
|
||||
public ?int $limit = NULL;
|
||||
public string $group = '';
|
||||
public string|Closure|ActiveQuery|null $from = '';
|
||||
public string $alias = 't1';
|
||||
public array $filter = [];
|
||||
|
||||
|
||||
public bool $lock = false;
|
||||
|
||||
public bool $ifNotWhere = false;
|
||||
|
||||
|
||||
private SqlBuilder $builder;
|
||||
|
||||
/**
|
||||
* @var ModelInterface|string|null
|
||||
*/
|
||||
public ModelInterface|string|null $modelClass;
|
||||
|
||||
/**
|
||||
* clear
|
||||
*/
|
||||
public function clear()
|
||||
{
|
||||
$this->where = [];
|
||||
$this->select = [];
|
||||
$this->join = [];
|
||||
$this->order = [];
|
||||
$this->offset = NULL;
|
||||
$this->limit = NULL;
|
||||
$this->group = '';
|
||||
$this->from = '';
|
||||
$this->alias = 't1';
|
||||
$this->filter = [];
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $column
|
||||
* @param callable $callable
|
||||
* @return $this
|
||||
*/
|
||||
public function when(string $column, callable $callable): static
|
||||
{
|
||||
$caseWhen = new When($column, $this);
|
||||
|
||||
call_user_func($callable, $caseWhen);
|
||||
|
||||
$this->where[] = $caseWhen->end();
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param bool $lock
|
||||
* @return $this
|
||||
*/
|
||||
public function lock(bool $lock): static
|
||||
{
|
||||
$this->lock = $lock;
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $whereRaw
|
||||
* @return QueryTrait
|
||||
*/
|
||||
public function whereRaw(string $whereRaw): static
|
||||
{
|
||||
if (empty($whereRaw)) {
|
||||
return $this;
|
||||
}
|
||||
$this->where[] = $whereRaw;
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string|array|Closure $condition
|
||||
* @param string|array|Closure $condition1
|
||||
* @param string|array|Closure $condition2
|
||||
* @return $this
|
||||
* @throws NotFindClassException
|
||||
* @throws ReflectionException
|
||||
*/
|
||||
public function whereIf(string|array|Closure $condition, string|array|Closure $condition1, string|array|Closure $condition2): static
|
||||
{
|
||||
if (!is_string($condition)) {
|
||||
$condition = $this->makeClosureFunction($condition);
|
||||
}
|
||||
|
||||
if (!is_string($condition1)) {
|
||||
$condition1 = $this->makeClosureFunction($condition1);
|
||||
}
|
||||
|
||||
if (!is_string($condition2)) {
|
||||
$condition2 = $this->makeClosureFunction($condition2);
|
||||
}
|
||||
|
||||
$this->where[] = 'IF(' . $condition . ', ' . $condition1 . ', ' . $condition2 . ')';
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $bool
|
||||
* @return $this
|
||||
*/
|
||||
public function ifNotWhere($bool): static
|
||||
{
|
||||
$this->ifNotWhere = $bool;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
* @throws Exception
|
||||
*/
|
||||
public function getTable(): string
|
||||
{
|
||||
return $this->modelClass->getTable();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $column
|
||||
* @param string $value
|
||||
* @return $this
|
||||
*/
|
||||
public function whereLocate(string $column, string $value): static
|
||||
{
|
||||
$this->where[] = 'LOCATE(' . $column . ',\'' . addslashes($value) . '\') > 0';
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $column
|
||||
* @return $this
|
||||
*/
|
||||
public function whereNull(string $column): static
|
||||
{
|
||||
$this->where[] = $column . ' IS NULL';
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $column
|
||||
* @return $this
|
||||
*/
|
||||
public function whereEmpty(string $column): static
|
||||
{
|
||||
$this->where[] = $column . ' = \'\'';
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $column
|
||||
* @return $this
|
||||
*/
|
||||
public function whereNotEmpty(string $column): static
|
||||
{
|
||||
$this->where[] = $column . ' <> \'\'';
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $column
|
||||
* @return $this
|
||||
*/
|
||||
public function whereNotNull(string $column): static
|
||||
{
|
||||
$this->where[] = $column . ' IS NOT NULL';
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array|Closure|string $columns
|
||||
* @return $this
|
||||
*/
|
||||
public function filter(array|Closure|string $columns): static
|
||||
{
|
||||
if (!$columns) {
|
||||
return $this;
|
||||
}
|
||||
if (is_callable($columns, TRUE)) {
|
||||
return call_user_func($columns, $this);
|
||||
}
|
||||
if (is_string($columns)) {
|
||||
$columns = explode(',', $columns);
|
||||
}
|
||||
if (!is_array($columns)) {
|
||||
return $this;
|
||||
}
|
||||
$this->filter = $columns;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $alias
|
||||
*
|
||||
* @return $this
|
||||
*
|
||||
* select * from tableName as t1
|
||||
*/
|
||||
public function alias(string $alias = 't1'): static
|
||||
{
|
||||
$this->alias = $alias;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string|Closure $tableName
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
public function from(string|Closure $tableName): static
|
||||
{
|
||||
$this->from = $tableName;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $tableName
|
||||
* @param string $alias
|
||||
* @param null $on
|
||||
* @param array|null $param
|
||||
* @return $this
|
||||
* $query->join([$tableName, ['userId'=>'uuvOd']], $param)
|
||||
* $query->join([$tableName, ['userId'=>'uuvOd'], $param])
|
||||
* $query->join($tableName, ['userId'=>'uuvOd',$param])
|
||||
*/
|
||||
private function join(string $tableName, string $alias, $on = NULL, array $param = NULL): static
|
||||
{
|
||||
if (empty($on)) {
|
||||
return $this;
|
||||
}
|
||||
$join[] = $tableName . ' AS ' . $alias;
|
||||
$join[] = 'ON ' . $this->onCondition($alias, $on);
|
||||
if (empty($join)) {
|
||||
return $this;
|
||||
}
|
||||
|
||||
$this->join[] = implode(' ', $join);
|
||||
if (!empty($param)) {
|
||||
$this->addParams($param);
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $alias
|
||||
* @param $on
|
||||
* @return string
|
||||
*/
|
||||
private function onCondition($alias, $on): string
|
||||
{
|
||||
$array = [];
|
||||
foreach ($on as $key => $item) {
|
||||
if (!str_contains($item, '.')) {
|
||||
$this->addParam($key, $item);
|
||||
} else {
|
||||
$explode = explode('.', $item);
|
||||
if (isset($explode[1]) && ($explode[0] == $alias || $this->alias == $explode[0])) {
|
||||
$array[] = $key . '=' . $item;
|
||||
} else {
|
||||
$this->addParam($key, $item);
|
||||
}
|
||||
}
|
||||
}
|
||||
return implode(' AND ', $array);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $tableName
|
||||
* @param string $alias
|
||||
* @param $onCondition
|
||||
* @param null $param
|
||||
* @return $this
|
||||
* @throws Exception
|
||||
*/
|
||||
public function leftJoin(string $tableName, string $alias, $onCondition, $param = NULL): static
|
||||
{
|
||||
if (class_exists($tableName)) {
|
||||
$model = Kiri::getDi()->get($tableName);
|
||||
if (!($model instanceof ModelInterface)) {
|
||||
throw new Exception('Model must implement ' . ModelInterface::class);
|
||||
}
|
||||
$tableName = $model->getTable();
|
||||
}
|
||||
return $this->join(...["LEFT JOIN " . $tableName, $alias, $onCondition, $param]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $tableName
|
||||
* @param $alias
|
||||
* @param $onCondition
|
||||
* @param null $param
|
||||
* @return $this
|
||||
* @throws Exception
|
||||
*/
|
||||
public function rightJoin($tableName, $alias, $onCondition, $param = NULL): static
|
||||
{
|
||||
if (class_exists($tableName)) {
|
||||
$model = Kiri::getDi()->get($tableName);
|
||||
if (!($model instanceof ModelInterface)) {
|
||||
throw new Exception('Model must implement ' . ModelInterface::class);
|
||||
}
|
||||
$tableName = $model->getTable();
|
||||
}
|
||||
return $this->join(...["RIGHT JOIN " . $tableName, $alias, $onCondition, $param]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $tableName
|
||||
* @param $alias
|
||||
* @param $onCondition
|
||||
* @param null $param
|
||||
* @return $this
|
||||
* @throws Exception
|
||||
*/
|
||||
public function innerJoin($tableName, $alias, $onCondition, $param = NULL): static
|
||||
{
|
||||
if (class_exists($tableName)) {
|
||||
$model = Kiri::getDi()->get($tableName);
|
||||
if (!($model instanceof ModelInterface)) {
|
||||
throw new Exception('Model must implement ' . ModelInterface::class);
|
||||
}
|
||||
$tableName = $model->getTable();
|
||||
}
|
||||
return $this->join(...["INNER JOIN " . $tableName, $alias, $onCondition, $param]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $array
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
private function toString($array): string
|
||||
{
|
||||
$tmp = [];
|
||||
if (!is_array($array)) {
|
||||
return $array;
|
||||
}
|
||||
foreach ($array as $key => $val) {
|
||||
if (is_array($val)) {
|
||||
$tmp[] = $this->toString($array);
|
||||
} else {
|
||||
$tmp[] = $key . '=:' . $key;
|
||||
$this->attributes[':' . $key] = $val;
|
||||
}
|
||||
}
|
||||
return implode(' AND ', $tmp);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $field
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
public function sum(string $field): static
|
||||
{
|
||||
$this->select[] = 'SUM(' . $field . ') AS ' . $field;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $field
|
||||
* @return $this
|
||||
*/
|
||||
public function max(string $field): static
|
||||
{
|
||||
$this->select[] = 'MAX(' . $field . ') AS ' . $field;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $lngField
|
||||
* @param string $latField
|
||||
* @param int $lng1
|
||||
* @param int $lat1
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
public function distance(string $lngField, string $latField, int $lng1, int $lat1): static
|
||||
{
|
||||
$sql = "ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN(($lat1 * PI() / 180 - $lat1 * PI() / 180) / 2),2) + COS($lat1 * PI() / 180) * COS($latField * PI() / 180) * POW(SIN(($lng1 * PI() / 180 - $lngField * PI() / 180) / 2),2))) * 1000) AS distance";
|
||||
$this->select[] = $sql;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string|array $column
|
||||
* @param string $sort
|
||||
*
|
||||
* @return $this
|
||||
*
|
||||
* [
|
||||
* 'addTime',
|
||||
* 'descTime desc'
|
||||
* ]
|
||||
*/
|
||||
public function orderBy(string|array $column, string $sort = 'DESC'): static
|
||||
{
|
||||
if (empty($column)) {
|
||||
return $this;
|
||||
}
|
||||
if (is_string($column)) {
|
||||
return $this->addOrder(...func_get_args());
|
||||
}
|
||||
|
||||
foreach ($column as $key => $val) {
|
||||
$this->addOrder($val);
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $column
|
||||
* @param string $sort
|
||||
*
|
||||
* @return $this
|
||||
*
|
||||
*/
|
||||
private function addOrder(string $column, string $sort = 'DESC'): static
|
||||
{
|
||||
$column = trim($column);
|
||||
|
||||
if (func_num_args() == 1 || str_contains($column, ' ')) {
|
||||
$this->order[] = $column;
|
||||
} else {
|
||||
$this->order[] = "$column $sort";
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array|string $column
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
public function select(array|string $column = '*'): static
|
||||
{
|
||||
if ($column == '*') {
|
||||
$this->select = $column;
|
||||
} else {
|
||||
if (!is_array($column)) {
|
||||
$column = explode(',', $column);
|
||||
}
|
||||
foreach ($column as $val) {
|
||||
$this->select[] = $val;
|
||||
}
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return $this
|
||||
*/
|
||||
public function orderRand(): static
|
||||
{
|
||||
$this->order[] = 'RAND()';
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array|Closure|string $conditionArray
|
||||
* @param string $opera
|
||||
* @param null $value
|
||||
* @return QueryTrait
|
||||
* @throws NotFindClassException
|
||||
* @throws ReflectionException
|
||||
*/
|
||||
public function whereOr(array|Closure|string $conditionArray = [], string $opera = '=', $value = null): static
|
||||
{
|
||||
if ($conditionArray instanceof Closure) {
|
||||
$conditionArray = $this->makeClosureFunction($conditionArray);
|
||||
}
|
||||
|
||||
if (func_num_args() > 1) {
|
||||
[$conditionArray, $opera, $value] = $this->opera(...func_get_args());
|
||||
|
||||
$conditionArray = $this->sprintf($conditionArray, $value, $opera);
|
||||
}
|
||||
|
||||
$this->where = ['((' . implode(' AND ', $this->where) . ') OR (' . $conditionArray . '))'];
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $columns
|
||||
* @param string|int|bool|null $value
|
||||
*
|
||||
* @param string $opera
|
||||
* @return QueryTrait
|
||||
*/
|
||||
public function whereAnd(string $columns, string $opera = '=', string|int|null|bool $value = NULL): static
|
||||
{
|
||||
[$columns, $opera, $value] = $this->opera(...func_get_args());
|
||||
|
||||
$this->where[] = $this->sprintf($columns, $value, $opera);
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $columns
|
||||
* @param string $value
|
||||
* @return $this
|
||||
* @throws Exception
|
||||
*/
|
||||
public function whereLike(string $columns, string $value): static
|
||||
{
|
||||
if (empty($columns) || (empty($value) && $value != 0)) {
|
||||
return $this;
|
||||
}
|
||||
|
||||
if (is_array($columns)) {
|
||||
$columns = 'CONCAT(' . implode(',^,', $columns) . ')';
|
||||
}
|
||||
|
||||
$this->where[] = $columns . ' LIKE \'%' . addslashes($value) . '%\'';
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $columns
|
||||
* @param string $value
|
||||
* @return $this
|
||||
* @throws Exception
|
||||
*/
|
||||
public function whereLeftLike(string $columns, string $value): static
|
||||
{
|
||||
if (empty($columns) || (empty($value) && $value != 0)) {
|
||||
return $this;
|
||||
}
|
||||
|
||||
if (is_array($columns)) {
|
||||
$columns = 'CONCAT(' . implode(',^,', $columns) . ')';
|
||||
}
|
||||
|
||||
$this->where[] = $columns . ' LLike \'%' . addslashes($value) . '\'';
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $columns
|
||||
* @param string $value
|
||||
* @return $this
|
||||
* @throws Exception
|
||||
*/
|
||||
public function whereRightLike(string $columns, string $value): static
|
||||
{
|
||||
if (empty($columns) || (empty($value) && $value != 0)) {
|
||||
return $this;
|
||||
}
|
||||
|
||||
if (is_array($columns)) {
|
||||
$columns = 'CONCAT(' . implode(',^,', $columns) . ')';
|
||||
}
|
||||
|
||||
$this->where[] = $columns . ' RLike \'' . addslashes($value) . '%\'';
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $columns
|
||||
* @param string $value
|
||||
* @return $this
|
||||
* @throws Exception
|
||||
*/
|
||||
public function whereNotLike(string $columns, string $value): static
|
||||
{
|
||||
if (empty($columns) || (empty($value) && $value != 0)) {
|
||||
return $this;
|
||||
}
|
||||
|
||||
if (is_array($columns)) {
|
||||
$columns = 'CONCAT(' . implode(',^,', $columns) . ')';
|
||||
}
|
||||
|
||||
$this->where[] = $columns . ' NOT LIKE \'%' . addslashes($value) . '%\'';
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $column
|
||||
* @param int $value
|
||||
* @return $this
|
||||
* @throws Exception
|
||||
* @see MathematicsCondition
|
||||
*/
|
||||
public function whereEq(string $column, int $value): static
|
||||
{
|
||||
$this->where[] = ['EQ', $column, $value];
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $column
|
||||
* @param int $value
|
||||
* @return $this
|
||||
* @throws Exception
|
||||
* @see MathematicsCondition
|
||||
*/
|
||||
public function whereNeq(string $column, int $value): static
|
||||
{
|
||||
$this->where[] = ['NEQ', $column, $value];
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $column
|
||||
* @param int $value
|
||||
* @return $this
|
||||
* @throws Exception
|
||||
* @see MathematicsCondition
|
||||
*/
|
||||
public function whereGt(string $column, int $value): static
|
||||
{
|
||||
$this->where[] = ['GT', $column, $value];
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $column
|
||||
* @param int $value
|
||||
* @return $this
|
||||
* @throws Exception
|
||||
* @see MathematicsCondition
|
||||
*/
|
||||
public function whereEgt(string $column, int $value): static
|
||||
{
|
||||
$this->where[] = ['EGT', $column, $value];
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $column
|
||||
* @param int $value
|
||||
* @return $this
|
||||
* @throws Exception
|
||||
* @see MathematicsCondition
|
||||
*/
|
||||
public function whereLt(string $column, int $value): static
|
||||
{
|
||||
$this->where[] = ['LT', $column, $value];
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $column
|
||||
* @param int $value
|
||||
* @return $this
|
||||
* @throws Exception
|
||||
* @see MathematicsCondition
|
||||
*/
|
||||
public function whereElt(string $column, int $value): static
|
||||
{
|
||||
$this->where[] = ['ELT', $column, $value];
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $columns
|
||||
* @param array|Closure $value
|
||||
* @return $this
|
||||
* @throws NotFindClassException
|
||||
* @throws ReflectionException
|
||||
*/
|
||||
public function whereIn(string $columns, array|Closure $value): static
|
||||
{
|
||||
if ($value instanceof Closure) {
|
||||
$value = $this->makeClosureFunction($value);
|
||||
}
|
||||
if (empty($value)) {
|
||||
$value = [-1];
|
||||
}
|
||||
$this->where[] = ['IN', $columns, $value];
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $value
|
||||
* @return ActiveQuery
|
||||
* @throws Exception
|
||||
*/
|
||||
public function makeNewQuery($value): ActiveQuery
|
||||
{
|
||||
$activeQuery = new ActiveQuery($this->modelClass);
|
||||
call_user_func($value, $activeQuery);
|
||||
if (empty($activeQuery->from)) {
|
||||
$activeQuery->from($activeQuery->modelClass->getTable());
|
||||
}
|
||||
return $activeQuery;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return Query
|
||||
* @throws ReflectionException
|
||||
* @throws NotFindClassException
|
||||
*/
|
||||
public function makeNewSqlGenerate(): Query
|
||||
{
|
||||
return Kiri::createObject(['class' => Query::class]);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $columns
|
||||
* @param array $value
|
||||
* @return $this
|
||||
*/
|
||||
public function whereNotIn(string $columns, array $value): static
|
||||
{
|
||||
if (empty($value) || !is_array($value)) {
|
||||
$value = [-1];
|
||||
}
|
||||
$this->where[] = ['NOT IN', $columns, $value];
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $column
|
||||
* @param int $start
|
||||
* @param int $end
|
||||
* @return $this
|
||||
*/
|
||||
public function whereBetween(string $column, int $start, int $end): static
|
||||
{
|
||||
if (empty($column) || empty($start) || empty($end)) {
|
||||
return $this;
|
||||
}
|
||||
|
||||
$this->where[] = $column . ' BETWEEN ' . $start . ' AND ' . $end;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $column
|
||||
* @param int $start
|
||||
* @param int $end
|
||||
* @return $this
|
||||
*/
|
||||
public function whereNotBetween(string $column, int $start, int $end): static
|
||||
{
|
||||
if (empty($column) || empty($start) || empty($end)) {
|
||||
return $this;
|
||||
}
|
||||
|
||||
$this->where[] = $column . 'NOT BETWEEN' . $start . ' AND ' . $end;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $params
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
public function bindParams(array $params = []): static
|
||||
{
|
||||
if (empty($params)) {
|
||||
return $this;
|
||||
}
|
||||
$this->attributes = $params;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Closure|array|string $column
|
||||
* @param string $opera
|
||||
* @param null $value
|
||||
* @return $this
|
||||
* @throws NotFindClassException
|
||||
* @throws ReflectionException
|
||||
*/
|
||||
public function where(Closure|array|string $column, string $opera = '=', $value = null): static
|
||||
{
|
||||
if (is_array($column)) {
|
||||
return $this->addArray($column);
|
||||
}
|
||||
if ($column instanceof Closure) {
|
||||
$this->where[] = $this->makeClosureFunction($column);
|
||||
return $this;
|
||||
}
|
||||
if (is_string($column)) {
|
||||
$this->where[] = $column;
|
||||
} else {
|
||||
[$column, $opera, $value] = $this->opera(...func_get_args());
|
||||
$this->where[] = "$column $opera $value";
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param Closure|array $closure
|
||||
* @return string
|
||||
* @throws NotFindClassException
|
||||
* @throws ReflectionException
|
||||
* @throws Exception
|
||||
*/
|
||||
public function makeClosureFunction(Closure|array $closure): string
|
||||
{
|
||||
$generate = $this->makeNewSqlGenerate();
|
||||
if ($closure instanceof Closure) {
|
||||
call_user_func($closure, $generate);
|
||||
} else {
|
||||
$generate->where($closure);
|
||||
}
|
||||
return $generate->getSql();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $name
|
||||
* @param string|null $having
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
public function groupBy(string $name, string $having = NULL): static
|
||||
{
|
||||
$this->group = $name;
|
||||
if (empty($having)) {
|
||||
return $this;
|
||||
}
|
||||
$this->group .= ' HAVING ' . $having;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $offset
|
||||
* @param int $limit
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
public function limit(int $offset, int $limit = 20): static
|
||||
{
|
||||
$this->offset = $offset;
|
||||
$this->limit = $limit;
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
private function opera(): array
|
||||
{
|
||||
if (func_num_args() == 3) {
|
||||
[$column, $opera, $value] = func_get_args();
|
||||
} else {
|
||||
[$column, $value] = func_get_args();
|
||||
}
|
||||
if (!isset($opera)) {
|
||||
$opera = '=';
|
||||
}
|
||||
return [$column, $opera, $value];
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param array $array
|
||||
* @return $this
|
||||
*/
|
||||
private function addArray(array $array): static
|
||||
{
|
||||
foreach ($array as $key => $value) {
|
||||
if (is_null($value)) continue;
|
||||
if (is_numeric($key)) {
|
||||
[$column, $opera, $value] = $this->opera(...$value);
|
||||
|
||||
$this->where[] = $this->sprintf($column, $value, $opera);
|
||||
} else {
|
||||
$this->where[] = $this->sprintf($key, $value);
|
||||
}
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param $column
|
||||
* @param $value
|
||||
* @param string $opera
|
||||
* @return string
|
||||
*/
|
||||
private function sprintf($column, $value, string $opera = '='): string
|
||||
{
|
||||
if (is_string($value)) {
|
||||
$value = trim($value, '\'"');
|
||||
}
|
||||
return "$column $opera '$value'";
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return $this
|
||||
*/
|
||||
public function oneLimit(): static
|
||||
{
|
||||
$this->limit = 1;
|
||||
return $this;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace Database\Traits;
|
||||
|
||||
|
||||
use Database\ActiveQuery;
|
||||
use Database\ISqlBuilder;
|
||||
use Exception;
|
||||
use JetBrains\PhpStorm\Pure;
|
||||
|
||||
|
||||
/**
|
||||
* Class CaseWhen
|
||||
* @package Database\Traits
|
||||
*/
|
||||
class When
|
||||
{
|
||||
|
||||
public ActiveQuery|ISqlBuilder $query;
|
||||
|
||||
|
||||
private array $_condition = [];
|
||||
|
||||
private string $else = '';
|
||||
|
||||
|
||||
/**
|
||||
* CaseWhen constructor.
|
||||
* @param string $column
|
||||
* @param ActiveQuery|ISqlBuilder $activeQuery
|
||||
*/
|
||||
public function __construct(public string $column, public ActiveQuery|ISqlBuilder $activeQuery)
|
||||
{
|
||||
$this->_condition[] = 'CASE ' . $column;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string|int $condition
|
||||
* @param string $then
|
||||
* @return $this
|
||||
* @throws Exception
|
||||
*/
|
||||
public function when(string|int $condition, string $then): static
|
||||
{
|
||||
$this->_condition[] = sprintf('WHEN %s THEN %s', $condition, $then);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $alias
|
||||
*/
|
||||
public function else(string $alias)
|
||||
{
|
||||
$this->else = $alias;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
#[Pure] public function end(): string
|
||||
{
|
||||
if (empty($this->_condition)) {
|
||||
return '';
|
||||
}
|
||||
$prefix = implode(' ', $this->_condition);
|
||||
if (!empty($this->else)) {
|
||||
$prefix .= ' ELSE ' . $this->else;
|
||||
}
|
||||
return '(' . $prefix . ' END)';
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user