dao.class.php 88 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127
  1. <?php
  2. /**
  3. * ZenTaoPHP的dao和sql类。
  4. * The dao and sql class file of ZenTaoPHP framework.
  5. *
  6. * The author disclaims copyright to this source code. In place of
  7. * a legal notice, here is a blessing:
  8. *
  9. * May you do good and not evil.
  10. * May you find forgiveness for yourself and forgive others.
  11. * May you share freely, never taking more than you give.
  12. */
  13. /**
  14. * DAO类。
  15. * DAO, data access object.
  16. *
  17. * @package framework
  18. */
  19. class baseDAO
  20. {
  21. /* Use these strang strings to avoid conflicting with these keywords in the sql body. */
  22. const WHERE = 'wHeRe';
  23. const GROUPBY = 'gRoUp bY';
  24. const HAVING = 'hAvInG';
  25. const ORDERBY = 'oRdEr bY';
  26. const LIMIT = 'lImiT';
  27. /**
  28. * 缓存未命中标识。
  29. * The cache miss flag.
  30. *
  31. * @var string
  32. * @access public
  33. */
  34. const CACHE_MISS = 'DAO_CAHCE_MISS';
  35. /**
  36. * 全局对象$app
  37. * The global app object.
  38. *
  39. * @var object
  40. * @access public
  41. */
  42. public $app;
  43. /**
  44. * 全局对象$config
  45. * The global config object.
  46. *
  47. * @var object
  48. * @access public
  49. */
  50. public $config;
  51. /**
  52. * 数据库类型。
  53. * The database type.
  54. *
  55. * @var bool
  56. * @access public
  57. */
  58. public $driver = 'mysql';
  59. /**
  60. * 全局对象$lang
  61. * The global lang object.
  62. *
  63. * @var object
  64. * @access public
  65. */
  66. public $lang;
  67. /**
  68. * 全局对象$dbh
  69. * The global dbh(database handler) object.
  70. *
  71. * @var object
  72. * @access public
  73. */
  74. public $dbh;
  75. /**
  76. * 全局对象$slaveDBH。
  77. * The global slaveDBH(database handler) object.
  78. *
  79. * @var object
  80. * @access public
  81. */
  82. public $slaveDBH;
  83. /**
  84. * 全局对象$cache。
  85. * The global cache object.
  86. *
  87. * @var object
  88. * @access public
  89. */
  90. public $cache = null;
  91. /**
  92. * sql对象,用于生成sql语句。
  93. * The sql object, used to create the query sql.
  94. *
  95. * @var object
  96. * @access public
  97. */
  98. public $sqlobj;
  99. /**
  100. * 正在使用的表。
  101. * The table of current query.
  102. *
  103. * @var string
  104. * @access public
  105. */
  106. public $table;
  107. /**
  108. * $this->table的别名。
  109. * The alias of $this->table.
  110. *
  111. * @var string
  112. * @access public
  113. */
  114. public $alias;
  115. /**
  116. * 查询的字段。
  117. * The fields will be returned.
  118. *
  119. * @var string
  120. * @access public
  121. */
  122. public $fields;
  123. /**
  124. * 查询模式,raw模式用于正常的select update等sql拼接操作,magic模式用于findByXXX等魔术方法。
  125. * The query mode, raw or magic.
  126. *
  127. * This var is used to diff dao::from() with sql::from().
  128. *
  129. * @var string
  130. * @access public
  131. */
  132. public $mode;
  133. /**
  134. * 执行方式:insert, select, update, delete, replace。
  135. * The query method: insert, select, update, delete, replace.
  136. *
  137. * @var string
  138. * @access public
  139. */
  140. public $method;
  141. /**
  142. * 是否自动增加lang条件。
  143. * If auto add lang statement.
  144. *
  145. * @var bool
  146. * @access public
  147. */
  148. public $autoLang;
  149. /**
  150. * 是否自动过滤模板数据。
  151. * If auto filter template data.
  152. *
  153. * @var string skip(本次不过滤)|always(总是过滤)|never(从不过滤)
  154. * @access public
  155. */
  156. public static $filterTpl = 'always';
  157. /**
  158. * 上一次插入的数据id。
  159. * Last insert id.
  160. *
  161. * @var int
  162. * @access private
  163. */
  164. protected $_lastInsertID = false;
  165. /**
  166. * 执行的请求,所有的查询都保存在该数组。
  167. * The queries executed. Every query will be saved in this array.
  168. *
  169. * @var array
  170. * @access public
  171. */
  172. public static $querys = array();
  173. /**
  174. * 执行fetchAll是否跳过text类型字段。
  175. * Exclude text fields when fetchAll.
  176. *
  177. * @var bool
  178. * @access public
  179. */
  180. public static $autoExclude = false;
  181. /**
  182. * 存放错误的数组。
  183. * The errors.
  184. *
  185. * @var array
  186. * @access public
  187. */
  188. public static $errors = array();
  189. /**
  190. * 实时记录日志设置,并设置记录文件。
  191. * Open real time log and set real time file.
  192. *
  193. * @var array
  194. * @access public
  195. */
  196. public static $realTimeLog = false;
  197. public static $realTimeFile = '';
  198. /**
  199. * 缓存已经查询过的表结构。
  200. * Cache desc tables.
  201. *
  202. * @var array
  203. * @access public
  204. */
  205. public static $tablesDesc = array();
  206. /**
  207. * 缓存已经查询过的唯一索引。
  208. * Cache unique indexes.
  209. *
  210. * @var array
  211. * @access private
  212. */
  213. protected static $uniqueIndexes = [];
  214. /**
  215. * 构造方法。
  216. * The construct method.
  217. *
  218. * @param object $app
  219. * @access public
  220. * @return void
  221. */
  222. public function __construct($app)
  223. {
  224. global $config, $lang, $dbh, $slaveDBH;
  225. $this->app = $app;
  226. $this->config = $config;
  227. $this->lang = $lang;
  228. $this->dbh = $dbh;
  229. $this->cache = $app->cache;
  230. $this->slaveDBH = $slaveDBH ? $slaveDBH : false;
  231. $this->reset();
  232. }
  233. /**
  234. * 设置$table属性。
  235. * Set the $table property.
  236. *
  237. * @param string $table
  238. * @access public
  239. * @return void
  240. */
  241. public function setTable($table)
  242. {
  243. $this->table = ($table && strpos($table, '`') === false) ? "`{$table}`" : $table;
  244. }
  245. /**
  246. * 设置$alias属性。
  247. * Set the $alias property.
  248. *
  249. * @param string $alias
  250. * @access public
  251. * @return void
  252. */
  253. public function setAlias($alias)
  254. {
  255. $this->alias = $alias;
  256. }
  257. /**
  258. * 设置$fields属性。
  259. * Set the $fields property.
  260. *
  261. * @param string $fields
  262. * @access public
  263. * @return void
  264. */
  265. public function setFields($fields)
  266. {
  267. $this->fields = $fields;
  268. }
  269. /**
  270. * 设置autoLang项。
  271. * Set autoLang item.
  272. *
  273. * @param bool $autoLang
  274. * @access public
  275. * @return void
  276. */
  277. public function setAutoLang($autoLang)
  278. {
  279. $this->autoLang = $autoLang;
  280. return $this;
  281. }
  282. /**
  283. * 设置过滤模板数据的方式。
  284. * Set the way to filter template data.
  285. *
  286. * @param string $method skip(本次不过滤)|always(总是过滤)|never(从不过滤)
  287. * @access public
  288. * @return void
  289. */
  290. public function filterTpl($method = 'always')
  291. {
  292. if($method == 'skip' && dao::$filterTpl == 'never') return $this;
  293. dao::$filterTpl = $method;
  294. return $this;
  295. }
  296. /**
  297. * 重置属性。
  298. * Reset the vars.
  299. *
  300. * @access public
  301. * @return void
  302. */
  303. public function reset()
  304. {
  305. $this->setFields('');
  306. $this->setTable('');
  307. $this->setAlias('');
  308. $this->setMode('');
  309. $this->setMethod('');
  310. $this->setAutoLang(isset($this->config->framework->autoLang) and $this->config->framework->autoLang);
  311. }
  312. //-----根据请求的方式,调用sql类相应的方法(Call according method of sql class by query method. -----//
  313. /**
  314. * 设置请求模式。像findByxxx之类的方法,使用的是magic模式;其他方法使用的是raw模式。
  315. * Set the query mode. If the method if like findByxxx, the mode is magic. Else, the mode is raw.
  316. *
  317. * @param string $mode magic|raw
  318. * @access public
  319. * @return void
  320. */
  321. public function setMode($mode = '')
  322. {
  323. $this->mode = $mode;
  324. }
  325. /**
  326. * 设置请求方法:select|update|insert|delete|replace 。
  327. * Set the query method: select|update|insert|delete|replace
  328. *
  329. * @param string $method
  330. * @access public
  331. * @return void
  332. */
  333. public function setMethod($method = '')
  334. {
  335. $this->method = $method;
  336. }
  337. /**
  338. * 生成缓存的 key。
  339. * Create the cache key.
  340. *
  341. * @param mixed $args
  342. * @access private
  343. * @return string
  344. */
  345. private function createCacheKey(...$args)
  346. {
  347. if(empty($this->cache)) return implode('-', $args);
  348. return $this->cache->createKey('dao', ...$args);
  349. }
  350. /**
  351. * 获取缓存。
  352. * Get the cache.
  353. *
  354. * @param string $key
  355. * @access public
  356. * @return mixed
  357. */
  358. public function getCache($key)
  359. {
  360. if(!$this->app->isServing() || empty($this->cache)) return self::CACHE_MISS;
  361. $cache = $this->cache->getByKey($key);
  362. if($cache === null) return self::CACHE_MISS;
  363. if(count($cache) < 3) return self::CACHE_MISS;
  364. /* 解析缓存的更新时间和值到变量中。 */
  365. /* Parse the cache time and value to variables. */
  366. list($cachedTime, $cachedSQL, $cachedValue) = $cache;
  367. /* 查找 sql 语句中包含的表名。*/
  368. /* Find the table names in the sql. */
  369. preg_match_all("/({$this->config->db->prefix}\w+)[`\" ]/", $cachedSQL, $tables);
  370. if(!isset($tables[1])) return self::CACHE_MISS;
  371. /* 检查 sql 语句中包含的表的更新时间是否大于缓存的更新时间,如果大于则不使用缓存。*/
  372. /* Check if the update time of the tables in the sql is greater than the cache time, if greater, don't use the cache. */
  373. foreach($tables[1] as $table)
  374. {
  375. if(strpos($table, 'boardlayer') !== false) return self::CACHE_MISS;
  376. $tableKey = $this->createCacheKey('table', $table);
  377. $tableCache = $this->cache->getByKey($tableKey);
  378. if($tableCache === null) continue;
  379. if($tableCache[0] > $cachedTime) return self::CACHE_MISS;
  380. }
  381. /* 检查是否可以使用客户端缓存。*/
  382. /* Check if can use the client cache. */
  383. $this->app->useClientCache = $this->app->clientCacheTime > $cachedTime;
  384. return $cachedValue ?: self::CACHE_MISS;
  385. }
  386. /**
  387. * 设置缓存。
  388. * Set the cache.
  389. *
  390. * @param string $key
  391. * @param string $sql
  392. * @param mixed $value
  393. * @param int $ttl
  394. * @access public
  395. * @return void
  396. */
  397. public function setCache($key, $sql = '', $value = null, $ttl = null)
  398. {
  399. if(!$this->app->isServing() || empty($this->cache)) return false;
  400. $this->app->useClientCache = false;
  401. $this->cache->saveByKey($key, array(microtime(true), $sql, $value), $ttl ?? $this->config->cache->dao->lifetime);
  402. }
  403. /**
  404. * 检查 sql 语句中是否包含表名,如果包含则设置表的缓存时间。
  405. * Check if the sql contains the table name, if contains, set the table cache time.
  406. *
  407. * @param string $sql
  408. * @access public
  409. * @return void
  410. */
  411. public function setTableCache($sql)
  412. {
  413. /* 查找 sql 语句中包含的表名。*/
  414. /* Find the table names in the sql. */
  415. preg_match_all("/({$this->config->db->prefix}\w+)[`\" ]/", $sql, $tables);
  416. if(!isset($tables[1])) return;
  417. foreach($tables[1] as $table)
  418. {
  419. /* 更新表的缓存时间。*/
  420. /* Update the table cache time. */
  421. $table = str_replace(array('`', '"'), '', $table);
  422. $key = $this->createCacheKey('table', $table);
  423. $this->setCache($key, '', $table, 0);
  424. }
  425. }
  426. /**
  427. * 清除缓存。
  428. * Clear the cache.
  429. *
  430. * @access public
  431. * @return void
  432. */
  433. public function clearCache()
  434. {
  435. if(!empty($this->cache)) $this->cache->clear();
  436. }
  437. /**
  438. * 开始事务。
  439. * Begin Transaction
  440. *
  441. * @access public
  442. * @return bool
  443. */
  444. public function begin()
  445. {
  446. return $this->dbh->beginTransaction();
  447. }
  448. /**
  449. * 检查是否在事务内。
  450. * Check in transaction.
  451. *
  452. * @access public
  453. * @return bool
  454. */
  455. public function inTransaction()
  456. {
  457. return $this->dbh->inTransaction();
  458. }
  459. /**
  460. * 事务回滚。
  461. * Roll back
  462. *
  463. * @access public
  464. * @return bool
  465. */
  466. public function rollBack()
  467. {
  468. return $this->dbh->rollBack();
  469. }
  470. /**
  471. * 提交事务。
  472. * Commits a transaction.
  473. *
  474. * @access public
  475. * @return bool
  476. */
  477. public function commit()
  478. {
  479. return $this->dbh->commit();
  480. }
  481. /**
  482. * Show tables.
  483. *
  484. * @access public
  485. * @return array
  486. */
  487. public function showTables()
  488. {
  489. return $this->query("SHOW TABLES")->fetchAll(PDO::FETCH_ASSOC);
  490. }
  491. /**
  492. * Get table engines.
  493. *
  494. * @access public
  495. * @return array
  496. */
  497. public function getTableEngines()
  498. {
  499. $tables = $this->query("SHOW TABLE STATUS WHERE `Engine` is not null")->fetchAll();
  500. $tableEngines = array();
  501. foreach($tables as $table) $tableEngines[$table->Name] = $table->Engine;
  502. return $tableEngines;
  503. }
  504. /**
  505. * Clear the cache of tables desc fields.
  506. *
  507. * @access public
  508. * @return void
  509. */
  510. public function clearTablesDescCache()
  511. {
  512. dao::$tablesDesc = array();
  513. }
  514. /**
  515. * Desc table, show fields.
  516. *
  517. * @param string $tableName
  518. * @access public
  519. * @return array
  520. */
  521. public function descTable($tableName)
  522. {
  523. if(isset(dao::$tablesDesc[$tableName])) return dao::$tablesDesc[$tableName];
  524. $dbh = $this->slaveDBH ? $this->slaveDBH : $this->dbh;
  525. $dbh->setAttribute(PDO::ATTR_CASE, PDO::CASE_LOWER);
  526. $fields = array();
  527. $stmt = $dbh->rawQuery("DESC $tableName");
  528. while($field = $stmt->fetch()) $fields[$field->field] = $field;
  529. dao::$tablesDesc[$tableName] = $fields;
  530. $dbh->setAttribute(PDO::ATTR_CASE, PDO::CASE_NATURAL);
  531. return $fields;
  532. }
  533. /**
  534. * select方法,调用sql::select()。
  535. * The select method, call sql::select().
  536. *
  537. * @param string $fields
  538. * @access public
  539. * @return static|sql|baseDAO the dao object self.
  540. */
  541. public function select($fields = '*')
  542. {
  543. $this->setMode('raw');
  544. $this->setMethod('select');
  545. $this->sqlobj = sql::select($fields);
  546. return $this;
  547. }
  548. /**
  549. * 获取查询记录条数。
  550. * The count method, call sql::select() and from().
  551. * use as $this->dao->select()->from(TABLE_BUG)->where()->count();
  552. *
  553. * @param string $distinctField
  554. * @access public
  555. * @return int
  556. */
  557. public function count($distinctField = '')
  558. {
  559. /* 获得SELECT,FROM的位置,使用count(*)替换其字段。 */
  560. /* Get the SELECT, FROM position, thus get the fields, replace it by count(*). */
  561. $sql = $this->get();
  562. $selectPOS = strpos($sql, 'SELECT') + strlen('SELECT');
  563. $fromPOS = strpos($sql, 'FROM');
  564. $fields = substr($sql, $selectPOS, $fromPOS - $selectPOS);
  565. $countField = $distinctField ? 'distinct ' . $distinctField : '*';
  566. $sql = str_replace($fields, " COUNT($countField) AS `recTotal` ", substr($sql, 0, $fromPOS)) . substr($sql, $fromPOS);
  567. /*
  568. * 去掉SQL语句中order和limit之后的部分。
  569. * Remove the part after order and limit.
  570. **/
  571. $subLength = strlen($sql);
  572. $lastRight = strrpos($sql, ')') > 0 ? strrpos($sql, ')') : 0;
  573. $groupPOS = strripos($sql, 'group by', $lastRight);
  574. $orderPOS = strripos($sql, 'order by', $lastRight);
  575. $limitPOS = strripos($sql, 'limit', $lastRight);
  576. if($limitPOS) $subLength = $limitPOS;
  577. if($orderPOS) $subLength = $orderPOS;
  578. if($groupPOS) $subLength = $groupPOS;
  579. $sql = substr($sql, 0, $subLength);
  580. /*
  581. * 获取记录数。
  582. * Get the records count.
  583. **/
  584. try
  585. {
  586. $dbh = $this->slaveDBH ? $this->slaveDBH : $this->dbh;
  587. $row = $dbh->query($sql)->fetch(PDO::FETCH_OBJ);
  588. }
  589. catch (PDOException $e)
  590. {
  591. $this->sqlError($e);
  592. }
  593. return is_object($row) ? $row->recTotal : 0;
  594. }
  595. /**
  596. * update方法,调用sql::update()。
  597. * The update method, call sql::update().
  598. *
  599. * @param string $table
  600. * @access public
  601. * @return static|sql the dao object self.
  602. */
  603. public function update($table)
  604. {
  605. $this->setMode('raw');
  606. $this->setMethod('update');
  607. $this->sqlobj = sql::update($table);
  608. $this->setTable($table);
  609. return $this;
  610. }
  611. /**
  612. * delete方法,调用sql::delete()。
  613. * The delete method, call sql::delete().
  614. *
  615. * @access public
  616. * @return static|sql the dao object self.
  617. */
  618. public function delete()
  619. {
  620. $this->setMode('raw');
  621. $this->setMethod('delete');
  622. $this->sqlobj = sql::delete();
  623. return $this;
  624. }
  625. /**
  626. * insert方法,调用sql::insert()。
  627. * The insert method, call sql::insert().
  628. *
  629. * @param string $table
  630. * @access public
  631. * @return static|sql the dao object self.
  632. */
  633. public function insert($table)
  634. {
  635. $this->setMode('raw');
  636. $this->setMethod('insert');
  637. $this->sqlobj = sql::insert($table);
  638. $this->setTable($table);
  639. return $this;
  640. }
  641. /**
  642. * replace方法,调用sql::replace()。
  643. * The replace method, call sql::replace().
  644. *
  645. * @param string $table
  646. * @access public
  647. * @return static|sql the dao object self.
  648. */
  649. public function replace($table)
  650. {
  651. $this->setMode('raw');
  652. $this->setMethod('replace');
  653. $this->sqlobj = sql::replace($table);
  654. $this->setTable($table);
  655. return $this;
  656. }
  657. /**
  658. * 设置要操作的表。
  659. * Set the from table.
  660. *
  661. * @param string $table
  662. * @access public
  663. * @return static|sql the dao object self.
  664. */
  665. public function from($table)
  666. {
  667. $this->setTable($table);
  668. if($this->mode == 'raw') $this->sqlobj->from($table);
  669. return $this;
  670. }
  671. /**
  672. * 设置字段。
  673. * Set the fields.
  674. *
  675. * @param string $fields
  676. * @access public
  677. * @return static|sql the dao object self.
  678. */
  679. public function fields($fields)
  680. {
  681. $this->setFields($fields);
  682. return $this;
  683. }
  684. /**
  685. * 表别名,相当于sql里的AS。(as是php的关键词,使用alias代替)
  686. * Alias a table, equal the AS keyword. (Don't use AS, because it's a php keyword.)
  687. *
  688. * @param string $alias
  689. * @access public
  690. * @return static|sql the dao object self.
  691. */
  692. public function alias($alias)
  693. {
  694. if(empty($this->alias)) $this->setAlias($alias);
  695. $this->sqlobj->alias($alias);
  696. return $this;
  697. }
  698. /**
  699. * 设置需要更新或插入的数据。
  700. * Set the data to update or insert.
  701. *
  702. * @param object $data the data object or array
  703. * @param string $skipFields the skip fields
  704. * @access public
  705. * @return static|sql the dao object self.
  706. */
  707. public function data($data, $skipFields = '')
  708. {
  709. if(!is_object($data)) $data = (object)$data;
  710. if($this->autoLang and !isset($data->lang))
  711. {
  712. $data->lang = $this->app->getClientLang();
  713. if(isset($this->app->config->cn2tw) and $this->app->config->cn2tw and $data->lang == 'zh-tw') $data->lang = 'zh-cn';
  714. if(defined('RUN_MODE') and RUN_MODE == 'front' and !empty($this->app->config->cn2tw)) $data->lang = str_replace('zh-tw', 'zh-cn', $data->lang);
  715. }
  716. $this->sqlobj->data($data, $skipFields);
  717. return $this;
  718. }
  719. //-------------------- sql相关的方法(The sql related method) --------------------//
  720. /**
  721. * 获取sql字符串。
  722. * Get the sql string.
  723. *
  724. * @access public
  725. * @return string the sql string after process.
  726. */
  727. public function get()
  728. {
  729. return self::processKeywords($this->processSQL());
  730. }
  731. /**
  732. * 打印sql字符串。
  733. * Print the sql string.
  734. *
  735. * @access public
  736. * @return void
  737. */
  738. public function printSQL()
  739. {
  740. echo $this->processSQL();
  741. }
  742. /**
  743. * 解析SQL语句。
  744. * Explain sql.
  745. *
  746. * @param string $sql
  747. * @access public
  748. * @return array|void
  749. */
  750. public function explain($sql = '', $exit = true)
  751. {
  752. $sql = empty($sql) ? $this->processSQL() : $sql;
  753. $result = $this->dbh->rawQuery('explain ' . $sql)->fetchAll();
  754. if($exit) a($result);
  755. return $result;
  756. }
  757. /**
  758. * 处理sql语句,替换表和字段。
  759. * Process the sql, replace the table, fields.
  760. *
  761. * @param string $setIsTpl
  762. * @access public
  763. * @return string the sql string after process.
  764. */
  765. public function processSQL($filterTpl = true)
  766. {
  767. $sql = $this->sqlobj->get();
  768. $needFilterTpl = $filterTpl && empty($this->app->installing) && empty($this->app->upgrading);
  769. /* INSERT INTO table VALUES(...) */
  770. if($this->method == 'insert' and !empty($this->sqlobj->data))
  771. {
  772. $desc = $this->descTable($this->table);
  773. $skipFields = $this->sqlobj->skipFields;
  774. $values = array();
  775. foreach($this->sqlobj->data as $field => $value)
  776. {
  777. if(strpos($skipFields, ",$field,") !== false) continue;
  778. $values[$field] = $this->sqlobj->quote($value);
  779. unset($desc[$field]);
  780. }
  781. /* If field can not null, add this field use default value. */
  782. foreach($desc as $field)
  783. {
  784. if(strtolower($field->null) == 'yes') continue;
  785. if($field->field == 'id') continue;
  786. if($field->default !== '') continue;
  787. $values[$field->field] = "''";
  788. if(strpos($field->type, 'date') !== false) $values[$field->field] = "'0000-00-00'";
  789. if(strpos($field->type, 'int') !== false) $values[$field->field] = "0";
  790. if(strpos($field->type, 'float') !== false) $values[$field->field] = "0";
  791. if(strpos($field->type, 'decimal') !== false) $values[$field->field] = "0";
  792. if(strpos($field->type, 'double') !== false) $values[$field->field] = "0";
  793. }
  794. $sql .= '(`' . implode('`,`', array_keys($values)) . '`)' . ' VALUES(' . implode(',', $values) . ')';
  795. }
  796. elseif($this->method == 'select' && dao::$filterTpl == 'always' && $needFilterTpl)
  797. {
  798. /* 过滤模板类型的数据 */
  799. foreach(array('project', 'task') as $table)
  800. {
  801. $table = $this->config->db->prefix . $table;
  802. if(strpos($sql, "`$table`") === false) continue;
  803. if(preg_match("/`isTpl`\s*=\s*('1'|1)/", $sql) || preg_match("/isTpl\s*=\s*('1'|1)/", $sql)) continue; // 指定查询模板类型的数据则不过滤
  804. preg_match_all('/\(\s*(SELECT\b.*?\bFROM\b.*?)(?=\)\s*(AND|\)|$))/is', $sql, $matches); // 匹配子查询
  805. if(!$matches[1])
  806. {
  807. $alias = preg_match("/`$table`\s+as\s+(\w+)/i", $sql, $matches) ? $matches[1] : '';
  808. $replace = $alias ? "wHeRe ($alias.`isTpl` = '0' OR $alias.`isTpl` IS NULL) AND" : "wHeRe `isTpl` = '0' AND";
  809. $sql = preg_replace("/wHeRE/i", $replace, $sql, 1);
  810. }
  811. else
  812. {
  813. foreach($matches[1] as $index => $subSQL)
  814. {
  815. $sql = str_ireplace($subSQL, "$$index", $sql);
  816. }
  817. if(strpos($sql, "`$table`") !== false)
  818. {
  819. $alias = preg_match("/`$table`\s+as\s+(\w+)/i", $sql, $mainMatches) ? $mainMatches[1] : '';
  820. $replace = $alias ? "wHeRe ($alias.`isTpl` = '0' OR $alias.`isTpl` IS NULL) AND" : "wHeRe `isTpl` = '0' AND";
  821. $sql = preg_replace("/wHeRE/i", $replace, $sql, 1);
  822. }
  823. foreach($matches[1] as $index => $subSQL)
  824. {
  825. if(strpos($sql, "`$table`") !== false && !preg_match("/`isTpl`\s*=\s*('1'|1)/", $subSQL))
  826. {
  827. $alias = preg_match("/`$table`\s+as\s+(\w+)/i", $subSQL, $subMatches) ? $subMatches[1] : '';
  828. $replace = $alias ? "wHeRe ($alias.`isTpl` = '0' OR $alias.`isTpl` IS NULL) AND" : "wHeRe `isTpl` = '0' AND";
  829. $subSQL = preg_replace("/wHeRE/i", $replace, $subSQL, 1);
  830. }
  831. $sql = str_ireplace("$$index", $subSQL, $sql);
  832. }
  833. }
  834. }
  835. }
  836. if(dao::$filterTpl == 'skip') dao::$filterTpl = 'always';
  837. /**
  838. * 如果是magic模式,处理表和字段。
  839. * If the mode is magic, process the $fields and $table.
  840. **/
  841. if($this->mode == 'magic')
  842. {
  843. if($this->fields == '') $this->fields = '*';
  844. if($this->table == '') $this->app->triggerError('Must set the table name', __FILE__, __LINE__, $exit = true);
  845. $sql = sprintf($this->sqlobj->get(), $this->fields, $this->table);
  846. }
  847. /* If the method is select, update or delete, set the lang condition. */
  848. if($this->autoLang and $this->table != '' and $this->method != 'insert' and $this->method != 'replace')
  849. {
  850. $lang = $this->app->getClientLang();
  851. /* Get the position to insert lang = ?. */
  852. $wherePOS = strrpos($sql, DAO::WHERE); // The position of WHERE keyword.
  853. $groupPOS = strrpos($sql, DAO::GROUPBY); // The position of GROUP BY keyword.
  854. $havingPOS = strrpos($sql, DAO::HAVING); // The position of HAVING keyword.
  855. $orderPOS = strrpos($sql, DAO::ORDERBY); // The position of ORDERBY keyword.
  856. $limitPOS = strrpos($sql, DAO::LIMIT); // The position of LIMIT keyword.
  857. $splitPOS = $orderPOS ? $orderPOS : $limitPOS; // If $orderPOS, use it instead of $limitPOS.
  858. $splitPOS = $havingPOS ? $havingPOS : $splitPOS; // If $havingPOS, use it instead of $orderPOS.
  859. $splitPOS = $groupPOS ? $groupPOS : $splitPOS; // If $groupPOS, use it instead of $havingPOS.
  860. /* Set the condition to be appended. */
  861. $tableName = !empty($this->alias) ? $this->alias : $this->table;
  862. if(!empty($this->app->config->cn2tw)) $lang = str_replace('zh-tw', 'zh-cn', $lang);
  863. $langCondition = " $tableName.lang in('{$lang}', 'all') ";
  864. /* If $splitPOS > 0, split the sql at $splitPOS. */
  865. if($splitPOS)
  866. {
  867. $firstPart = substr($sql, 0, $splitPOS);
  868. $lastPart = substr($sql, $splitPOS);
  869. if($wherePOS)
  870. {
  871. $sql = $firstPart . " AND $langCondition " . $lastPart;
  872. }
  873. else
  874. {
  875. $sql = $firstPart . " WHERE $langCondition " . $lastPart;
  876. }
  877. }
  878. else
  879. {
  880. $sql .= $wherePOS ? " AND $langCondition" : " WHERE $langCondition";
  881. }
  882. }
  883. return $sql;
  884. }
  885. /**
  886. * 替换sql常量关键字。
  887. * Process the sql keywords, replace the constants to normal.
  888. *
  889. * @param string $sql
  890. * @access public
  891. * @return string the sql string.
  892. */
  893. public static function processKeywords($sql)
  894. {
  895. return str_replace(array(DAO::WHERE, DAO::GROUPBY, DAO::HAVING, DAO::ORDERBY, DAO::LIMIT), array('WHERE', 'GROUP BY', 'HAVING', 'ORDER BY', 'LIMIT'), $sql);
  896. }
  897. //-------------------- 查询相关方法(Query related methods) --------------------//
  898. /**
  899. * 设置$dbh,数据库连接句柄。
  900. * Set the dbh.
  901. *
  902. * You can use like this: $this->dao->dbh($dbh), thus you can handle two database.
  903. *
  904. * @param object $dbh
  905. * @access public
  906. * @return static|sql the dao object self.
  907. */
  908. public function dbh($dbh)
  909. {
  910. $this->dbh = $dbh;
  911. return $this;
  912. }
  913. /**
  914. * 执行SQL语句,返回PDOStatement结果集。
  915. * Query the sql, return the statement object.
  916. *
  917. * @access public
  918. * @return static|sql the PDOStatement object.
  919. */
  920. public function query($sql = '')
  921. {
  922. if($sql)
  923. {
  924. $sql = $this->dbh->formatSQL($sql);
  925. $sqlMethod = strtolower(substr($sql, 0, strpos($sql, ' ')));
  926. $this->setMethod($sqlMethod);
  927. $this->sqlobj = new sql();
  928. $this->sqlobj->sql = $sql;
  929. }
  930. else
  931. {
  932. $sql = $this->dbh->formatSQL($this->processSQL());
  933. }
  934. try
  935. {
  936. /* Real-time save log. */
  937. if(dao::$realTimeLog && dao::$realTimeFile) file_put_contents(dao::$realTimeFile, $sql . "\n", FILE_APPEND);
  938. $method = $this->method;
  939. $this->reset();
  940. if($this->slaveDBH and in_array($method, array('select', 'desc')))
  941. {
  942. return $this->slaveDBH->rawQuery($sql);
  943. }
  944. else
  945. {
  946. /* Force to query from master db, if db has been changed. */
  947. $this->slaveDBH = false;
  948. return $this->driver == 'sqlite' ? $this->dbh->query($sql) : $this->dbh->rawQuery($sql);
  949. }
  950. }
  951. catch (PDOException $e)
  952. {
  953. $this->sqlError($e);
  954. }
  955. }
  956. /**
  957. * 返回SQL结果的所有字段信息。
  958. * Return the fields meta of PDOStatement.
  959. *
  960. * @param string|PDOStatement $stmt
  961. * @access public
  962. * @return array
  963. */
  964. public function getColumns($stmt)
  965. {
  966. /* 如果$stmt是SQL查询语句,先执行查询获得 PDO stmt. */
  967. /* If $stmt is a SQL string, query to get PDO stmt. */
  968. if(is_string($stmt)) $stmt = $this->query($stmt);
  969. try
  970. {
  971. $columns = array();
  972. for($columnIndex = 0; $columnIndex < $stmt->columnCount(); $columnIndex++)
  973. {
  974. $columns[] = $stmt->getColumnMeta($columnIndex);
  975. }
  976. return $columns;
  977. }
  978. catch (PDOException $e)
  979. {
  980. $this->sqlError($e);
  981. }
  982. }
  983. /**
  984. * 将记录进行分页,自动设置limit语句。
  985. * Page the records, set the limit part auto.
  986. *
  987. * @param object $pager
  988. * @param string $distinctField
  989. * @access public
  990. * @return static|sql the dao object self.
  991. */
  992. public function page($pager, $distinctField = '')
  993. {
  994. if(!is_object($pager)) return $this;
  995. /*
  996. * 重新计算分页数据,并判断是否需要返回上一页。
  997. * Calculate pagination to determine whether to return to the previous page.
  998. */
  999. $originalPageID = $pager->pageID;
  1000. $recTotal = $this->count($distinctField);
  1001. $pager->setRecTotal($recTotal);
  1002. $pager->setPageTotal();
  1003. if($originalPageID > $pager->pageTotal) $pager->setPageID($pager->pageTotal);
  1004. $this->sqlobj->limit($pager->limit());
  1005. return $this;
  1006. }
  1007. /**
  1008. * 获取唯一索引。
  1009. * Get unique indexes.
  1010. *
  1011. * @param string $table
  1012. * @access public
  1013. * @return array
  1014. */
  1015. protected function getUniqueIndexes($table)
  1016. {
  1017. if(isset(dao::$uniqueIndexes[$table])) return dao::$uniqueIndexes[$table];
  1018. $indexes = [];
  1019. $table = trim($table, '`');
  1020. $rows = $this->select('INDEX_NAME, COLUMN_NAME')->from('INFORMATION_SCHEMA.STATISTICS')->where('TABLE_SCHEMA')->eq($this->config->db->name)->andWhere('TABLE_NAME')->eq($table)->andWhere('NON_UNIQUE')->eq(0)->andWhere('INDEX_NAME')->ne('PRIMARY')->query()->fetchAll();
  1021. foreach($rows as $row) $indexes[$row->INDEX_NAME][] = $row->COLUMN_NAME;
  1022. dao::$uniqueIndexes[$table] = $indexes;
  1023. return $indexes;
  1024. }
  1025. /**
  1026. * 把 replace 转换为 delete 和 insert。
  1027. * Convert replace to delete and insert.
  1028. *
  1029. * @param string $table
  1030. * @access private
  1031. * @return int
  1032. */
  1033. protected function convertReplaceToInsert($table)
  1034. {
  1035. $processedData = new stdclass();
  1036. foreach($this->sqlobj->data as $field => $value)
  1037. {
  1038. $field = trim($field, '`');
  1039. $processedData->{$field} = $value;
  1040. }
  1041. $indexes = $this->getUniqueIndexes($table);
  1042. if(!$indexes)
  1043. {
  1044. dao::$errors[] = "The table {$table} has no unique indexes.";
  1045. return 0;
  1046. }
  1047. $this->begin();
  1048. foreach($indexes as $fields)
  1049. {
  1050. $this->delete()->from($table)->where('1=1');
  1051. foreach($fields as $field)
  1052. {
  1053. if(!isset($processedData->$field))
  1054. {
  1055. dao::$errors[] = "The field $field of table {$table} is required.";
  1056. return 0;
  1057. }
  1058. $this->andWhere("`{$field}`")->eq($processedData->$field);
  1059. }
  1060. $this->exec();
  1061. }
  1062. $result = $this->insert($table)->data($processedData)->exec();
  1063. if(!$result) $this->rollback();
  1064. $this->commit();
  1065. return $result;
  1066. }
  1067. /**
  1068. * 执行SQL。query()会返回stmt对象,该方法只返回更改或删除的记录数。
  1069. * Execute the sql. It's different with query(), which return the stmt object. But this not.
  1070. *
  1071. * @param string $sql
  1072. * @access public
  1073. * @return int the modified or deleted records. 更改或删除的记录数。
  1074. */
  1075. public function exec($sql = '')
  1076. {
  1077. if(dao::isError()) return 0;
  1078. if($this->method == 'replace' && !empty($this->sqlobj->data))
  1079. {
  1080. $table = $this->table;
  1081. if(strpos($table, '`') === false) $table = "`{$table}`";
  1082. if(isset($this->config->cache->raw[$table])) return $this->convertReplaceToInsert($table);
  1083. }
  1084. if($sql)
  1085. {
  1086. $this->sqlobj = new sql();
  1087. }
  1088. else
  1089. {
  1090. $sql = $this->processSQL();
  1091. }
  1092. /* Assign the $sql to $this->sqlobj, so sqlError() can print the full sql statement if any exception occurs. */
  1093. $this->sqlobj->sql = $sql;
  1094. try
  1095. {
  1096. /* Real-time save log. */
  1097. if(dao::$realTimeLog && dao::$realTimeFile) file_put_contents(dao::$realTimeFile, $sql . "\n", FILE_APPEND);
  1098. $table = $this->table;
  1099. $method = $this->method;
  1100. $this->reset();
  1101. /* Force to query from master db, if db has been changed. */
  1102. $this->slaveDBH = false;
  1103. if($this->cache) $this->cache->prepare($table, $method, $sql);
  1104. $result = $this->dbh->exec($sql);
  1105. /* See: https://www.php.net/manual/en/pdo.lastinsertid.php .*/
  1106. if($method == 'insert') $this->_lastInsertID = $this->dbh->lastInsertID();
  1107. if($this->cache)
  1108. {
  1109. if($result)
  1110. {
  1111. $this->setTableCache($sql);
  1112. $this->cache->sync();
  1113. }
  1114. else
  1115. {
  1116. $this->cache->reset();
  1117. }
  1118. }
  1119. if(in_array($table, $this->config->userview->relatedTables))
  1120. {
  1121. $this->dbh->exec('UPDATE ' . TABLE_CONFIG . " SET `value` = '" . time() . "' WHERE `owner` = 'system' AND `module` = 'common' AND `section` = 'userview' AND `key` = 'relatedTablesUpdateTime'");
  1122. }
  1123. if($this->config->enableDuckdb)
  1124. {
  1125. $queueTable = TABLE_DUCKDBQUEUE;
  1126. if(!empty($table) && $table != $queueTable)
  1127. {
  1128. $now = helper::now();
  1129. $object = trim($table, '`');
  1130. $this->dbh->exec("UPDATE {$queueTable} SET updatedTime = '$now' WHERE object = '$object'");
  1131. $this->dbh->exec("INSERT INTO {$queueTable} (`object`, `updatedTime`, `syncTime`) SELECT '$object', '$now', NULL WHERE NOT EXISTS (SELECT 1 FROM {$queueTable} WHERE `object` = '$object' );");
  1132. }
  1133. }
  1134. return $result;
  1135. }
  1136. catch (PDOException $e)
  1137. {
  1138. $this->sqlError($e);
  1139. }
  1140. }
  1141. //-------------------- Fetch相关方法(Fetch related methods) -------------------//
  1142. /**
  1143. * 获取一个记录。
  1144. * Fetch one record.
  1145. *
  1146. * @param string $field 如果已经设置获取的字段,则只返回这个字段的值,否则返回这个记录。
  1147. * if the field is set, only return the value of this field, else return this record
  1148. * @access public
  1149. * @return object|mixed
  1150. */
  1151. public function fetch($field = '')
  1152. {
  1153. $sql = $this->processSQL(false);
  1154. $key = $this->createCacheKey('fetch', md5($sql));
  1155. $result = $this->getCache($key);
  1156. if($result === self::CACHE_MISS)
  1157. {
  1158. $table = $this->table;
  1159. $result = $this->query($sql)->fetch(PDO::FETCH_OBJ);
  1160. $result = helper::decodeHtmlSpecialChars($table, $result);
  1161. $this->setCache($key, $sql, $result);
  1162. }
  1163. if(empty($field)) return $result;
  1164. return $result ? $result->$field : '';
  1165. }
  1166. /**
  1167. * 匹配SQL语句中的表别名,返回['t1.*' => 't1', '*' => '']
  1168. * Match table alias name.
  1169. *
  1170. * @param string $sql
  1171. * @access private
  1172. * @return array
  1173. */
  1174. private function matchTableAlias($sql)
  1175. {
  1176. $pattern = '/SELECT\s+((\w+\.\*,?\s*)+|\*)/i';
  1177. if(preg_match($pattern, $sql, $matches))
  1178. {
  1179. if (trim($matches[1]) === '*') return ['*' => ''];
  1180. /* Get table alias name */
  1181. preg_match_all('/(\w+)\.\*/', $matches[1], $aliasName);
  1182. return !empty($aliasName[1]) ? [$aliasName[0][0] => $aliasName[1][0]] : [];
  1183. }
  1184. return [];
  1185. }
  1186. /**
  1187. * 将SQL语句中的*展开为具体的字段。
  1188. * Extract fields in SQL.
  1189. *
  1190. * @param string $sql
  1191. * @access private
  1192. * @return string
  1193. */
  1194. private function extractSQLFields($sql)
  1195. {
  1196. $aliasList = $this->matchTableAlias($sql);
  1197. foreach($aliasList as $selectStr => $tableAlias)
  1198. {
  1199. /* Get fields for selectStr. */
  1200. $tableName = $this->sqlobj->tableAlias[$tableAlias];
  1201. $fields = $this->descTable($tableName);
  1202. /* 使用具体的字段替换星号。 Replace selectStr with fields. */
  1203. $tableFields = [];
  1204. foreach($fields as $field)
  1205. {
  1206. if(strpos($field->type, 'text') !== false || strpos($field->type, 'blob') !== false) continue;
  1207. $tableFields[] = ($tableAlias ? $tableAlias . '.`' : '`') . $field->field . '`';
  1208. }
  1209. $sql = str_replace($selectStr, implode(',', $tableFields), $sql);
  1210. }
  1211. return $sql;
  1212. }
  1213. /**
  1214. * 获取所有记录。
  1215. * Fetch all records.
  1216. *
  1217. * @param string $keyField 返回以该字段做键的记录
  1218. * the key field, thus the return records is keyed by this field
  1219. * @param bool $autoExclude 是否排除text类型字段 exclude field type of text
  1220. * @access public
  1221. * @return array the records
  1222. */
  1223. public function fetchAll($keyField = '', $autoExclude = true)
  1224. {
  1225. $sql = $this->processSQL();
  1226. if(self::$autoExclude && $autoExclude) $sql = $this->extractSQLFields($sql);
  1227. $key = $this->createCacheKey('fetchAll', md5($sql));
  1228. $rows = $this->getCache($key);
  1229. if($rows === self::CACHE_MISS)
  1230. {
  1231. $table = $this->table;
  1232. $rows = $this->query($sql)->fetchAll();
  1233. $rows = helper::decodeHtmlSpecialChars($table, $rows);
  1234. $this->setCache($key, $sql, $rows);
  1235. }
  1236. if(empty($keyField)) return $rows;
  1237. $result = array();
  1238. foreach($rows as $i => $row) $result[$row->$keyField] = $row;
  1239. return $result;
  1240. }
  1241. /**
  1242. * 获取所有记录并将按照字段分组。
  1243. * Fetch all records and group them by one field.
  1244. *
  1245. * @param string $groupField 分组的字段 the field to group by
  1246. * @param string $keyField 键字段 the field of key
  1247. * @access public
  1248. * @return array the records.
  1249. */
  1250. public function fetchGroup($groupField, $keyField = '')
  1251. {
  1252. $sql = $this->processSQL();
  1253. $key = $this->createCacheKey('fetchAll', md5($sql));
  1254. $rows = $this->getCache($key);
  1255. if($rows === self::CACHE_MISS)
  1256. {
  1257. $table = $this->table;
  1258. $rows = $this->query($sql)->fetchAll();
  1259. $rows = helper::decodeHtmlSpecialChars($table, $rows);
  1260. $this->setCache($key, $sql, $rows);
  1261. }
  1262. $result = array();
  1263. foreach($rows as $i => $row)
  1264. {
  1265. empty($keyField) ? $result[$row->$groupField][] = $row : $result[$row->$groupField][$row->$keyField] = $row;
  1266. }
  1267. return $result;
  1268. }
  1269. /**
  1270. * 获取的记录是以关联数组的形式
  1271. * Fetch array like key=>value.
  1272. *
  1273. * 如果没有设置参数,用首末两键作为参数。
  1274. * If the keyFiled and valueField not set, use the first and last in the record.
  1275. *
  1276. * @param string $keyField
  1277. * @param string $valueField
  1278. * @access public
  1279. * @return array
  1280. */
  1281. public function fetchPairs($keyField = '', $valueField = '')
  1282. {
  1283. $sql = $this->processSQL();
  1284. $key = $this->createCacheKey('fetchAll', md5($sql));
  1285. $rows = $this->getCache($key);
  1286. if($rows === self::CACHE_MISS)
  1287. {
  1288. $table = $this->table;
  1289. $rows = $this->query($sql)->fetchAll();
  1290. $rows = helper::decodeHtmlSpecialChars($table, $rows);
  1291. $this->setCache($key, $sql, $rows);
  1292. }
  1293. $ready = false;
  1294. $keyField = trim($keyField, '`');
  1295. $valueField = trim($valueField, '`');
  1296. $result = array();
  1297. foreach($rows as $row)
  1298. {
  1299. $row = (array)$row;
  1300. if(!$ready)
  1301. {
  1302. if(empty($keyField)) $keyField = key($row);
  1303. if(empty($valueField))
  1304. {
  1305. end($row);
  1306. $valueField = key($row);
  1307. }
  1308. $ready = true;
  1309. }
  1310. $result[$row[$keyField]] = $row[$valueField];
  1311. }
  1312. return $result;
  1313. }
  1314. /**
  1315. * 返回最后插入的ID。
  1316. * Return the last insert ID.
  1317. *
  1318. * @access public
  1319. * @return int|false
  1320. */
  1321. public function lastInsertID()
  1322. {
  1323. return $this->_lastInsertID !== false ? (int)$this->_lastInsertID : false;
  1324. }
  1325. //-------------------- 魔术方法(Magic methods) --------------------//
  1326. /**
  1327. * 解析dao的方法名,处理魔术方法。
  1328. * Use it to do some convenient queries.
  1329. *
  1330. * @param string $funcName the function name to be called
  1331. * @param array $funcArgs the params
  1332. * @access public
  1333. * @return static|sql the dao object self.
  1334. */
  1335. public function __call($funcName, $funcArgs)
  1336. {
  1337. $funcName = strtolower($funcName);
  1338. /*
  1339. * 如果是findByxxx,转换为where条件语句。
  1340. * findByxxx, xxx as will be in the where.
  1341. **/
  1342. if(strpos($funcName, 'findby') !== false)
  1343. {
  1344. $this->setMode('magic');
  1345. $this->setFields('');
  1346. $field = str_replace('findby', '', $funcName);
  1347. if(count($funcArgs) == 1)
  1348. {
  1349. $operator = '=';
  1350. $value = $funcArgs[0];
  1351. }
  1352. else
  1353. {
  1354. $operator = $funcArgs[0];
  1355. $value = $funcArgs[1];
  1356. }
  1357. $this->sqlobj = sql::select('%s')->from('%s')->where($field, $operator, $value);
  1358. return $this;
  1359. }
  1360. /*
  1361. * 获取指定个数的记录:fetch10 获取10条记录。
  1362. * Fetch10.
  1363. **/
  1364. elseif(strpos($funcName, 'fetch') !== false)
  1365. {
  1366. $max = str_replace('fetch', '', $funcName);
  1367. $stmt = $this->query();
  1368. $rows = array();
  1369. $key = isset($funcArgs[0]) ? $funcArgs[0] : '';
  1370. $i = 0;
  1371. while($row = $stmt->fetch())
  1372. {
  1373. $key ? $rows[$row->$key] = $row : $rows[] = $row;
  1374. $i ++;
  1375. if($i == $max) break;
  1376. }
  1377. return $rows;
  1378. }
  1379. /*
  1380. * 其他的方法,转到sqlobj对象执行。
  1381. * Others, call the method in sql class.
  1382. **/
  1383. else
  1384. {
  1385. $this->sqlobj->$funcName(...$funcArgs);
  1386. return $this;
  1387. }
  1388. }
  1389. //-------------------- 条件检查( Data Checking)--------------------//
  1390. /**
  1391. * 检查字段是否满足条件。
  1392. * Check a filed is satisfied with the check rule.
  1393. *
  1394. * @param string $fieldName the field to check
  1395. * @param string $funcName the check rule
  1396. * @param string $condition the condition
  1397. * @access public
  1398. * @return static|sql the dao object self.
  1399. */
  1400. public function check($fieldName, $funcName, $condition = '')
  1401. {
  1402. /*
  1403. * 如果没数据中没有该字段,直接返回。
  1404. * If no this field in the data, return.
  1405. **/
  1406. $settedFields = array_keys(get_object_vars($this->sqlobj->data));
  1407. if(!in_array($fieldName, $settedFields)) return $this;
  1408. /* 设置字段值。 */
  1409. /* Set the field label and value. */
  1410. global $lang, $config;
  1411. if(isset($config->db->prefix))
  1412. {
  1413. $table = strtolower(str_replace(array($config->db->prefix, '`'), '', $this->table));
  1414. }
  1415. elseif(strpos($this->table, '_') !== false)
  1416. {
  1417. $table = strtolower(substr($this->table, strpos($this->table, '_') + 1));
  1418. $table = str_replace('`', '', $table);
  1419. }
  1420. else
  1421. {
  1422. $table = strtolower($this->table);
  1423. }
  1424. $fieldLabel = isset($lang->$table->$fieldName) ? $lang->$table->$fieldName : $fieldName;
  1425. $value = isset($this->sqlobj->data->$fieldName) ? $this->sqlobj->data->$fieldName : null;
  1426. /*
  1427. * 检查唯一性。
  1428. * Check unique.
  1429. **/
  1430. if($funcName == 'unique')
  1431. {
  1432. $args = func_get_args();
  1433. $sql = "SELECT COUNT(1) AS `count` FROM $this->table WHERE `$fieldName` = " . $this->sqlobj->quote($value);
  1434. if($condition) $sql .= ' AND ' . $condition;
  1435. try
  1436. {
  1437. $row = $this->dbh->query($sql)->fetch();
  1438. if($row->count != 0) $this->logError($funcName, $fieldName, $fieldLabel, array($value));
  1439. }
  1440. catch (PDOException $e)
  1441. {
  1442. $this->sqlError($e);
  1443. }
  1444. }
  1445. else
  1446. {
  1447. /*
  1448. * 创建参数。
  1449. * Create the params.
  1450. **/
  1451. $funcArgs = func_get_args();
  1452. unset($funcArgs[0]);
  1453. unset($funcArgs[1]);
  1454. for($i = 0; $i < VALIDATER::MAX_ARGS; $i ++)
  1455. {
  1456. ${"arg$i"} = isset($funcArgs[$i + 2]) ? $funcArgs[$i + 2] : null;
  1457. }
  1458. $checkFunc = 'check' . $funcName;
  1459. if(validater::$checkFunc($value, $arg0, $arg1, $arg2) === false)
  1460. {
  1461. $this->logError($funcName, $fieldName, $fieldLabel, $funcArgs);
  1462. }
  1463. }
  1464. return $this;
  1465. }
  1466. /**
  1467. * 检查一个字段是否满足条件。
  1468. * Check a field, if satisfied with the condition.
  1469. *
  1470. * @param string $condition
  1471. * @param string $fieldName
  1472. * @param string $funcName
  1473. * @access public
  1474. * @return static|sql the dao object self.
  1475. */
  1476. public function checkIF($condition, $fieldName, $funcName)
  1477. {
  1478. if(!$condition) return $this;
  1479. $funcArgs = func_get_args();
  1480. for($i = 0; $i < VALIDATER::MAX_ARGS; $i ++)
  1481. {
  1482. ${"arg$i"} = isset($funcArgs[$i + 3]) ? $funcArgs[$i + 3] : null;
  1483. }
  1484. $this->check($fieldName, $funcName, $arg0, $arg1, $arg2);
  1485. return $this;
  1486. }
  1487. /**
  1488. * 批量检查字段。
  1489. * Batch check some fileds.
  1490. *
  1491. * @param string $fields the fields to check, join with ,
  1492. * @param string $funcName
  1493. * @access public
  1494. * @return static|sql the dao object self.
  1495. */
  1496. public function batchCheck($fields, $funcName)
  1497. {
  1498. $fields = explode(',', str_replace(' ', '', $fields));
  1499. $funcArgs = func_get_args();
  1500. for($i = 0; $i < VALIDATER::MAX_ARGS; $i ++)
  1501. {
  1502. ${"arg$i"} = isset($funcArgs[$i + 2]) ? $funcArgs[$i + 2] : null;
  1503. }
  1504. foreach($fields as $fieldName) $this->check($fieldName, $funcName, $arg0, $arg1, $arg2);
  1505. return $this;
  1506. }
  1507. /**
  1508. * 批量检查字段是否满足条件。
  1509. * Batch check fields on the condition is true.
  1510. *
  1511. * @param string $condition
  1512. * @param string $fields
  1513. * @param string $funcName
  1514. * @access public
  1515. * @return static|sql the dao object self.
  1516. */
  1517. public function batchCheckIF($condition, $fields, $funcName)
  1518. {
  1519. if(!$condition) return $this;
  1520. $fields = explode(',', str_replace(' ', '', $fields));
  1521. $funcArgs = func_get_args();
  1522. for($i = 0; $i < VALIDATER::MAX_ARGS; $i ++)
  1523. {
  1524. ${"arg$i"} = isset($funcArgs[$i + 3]) ? $funcArgs[$i + 3] : null;
  1525. }
  1526. foreach($fields as $fieldName) $this->check($fieldName, $funcName, $arg0, $arg1, $arg2);
  1527. return $this;
  1528. }
  1529. /**
  1530. * 根据数据库结构检查字段。
  1531. * Check the fields according the the database schema.
  1532. *
  1533. * @param string $skipFields fields to skip checking
  1534. * @access public
  1535. * @return static|sql the dao object self.
  1536. */
  1537. public function autoCheck($skipFields = '')
  1538. {
  1539. $fields = $this->getFieldsType();
  1540. $skipFields = ",$skipFields,";
  1541. foreach($fields as $fieldName => $validater)
  1542. {
  1543. if(strpos($skipFields, $fieldName) !== false) continue; // skip it.
  1544. if(!isset($this->sqlobj->data->$fieldName)) continue;
  1545. if($validater['rule'] == 'skip') continue;
  1546. $options = array();
  1547. if(isset($validater['options'])) $options = array_values($validater['options']);
  1548. for($i = 0; $i < VALIDATER::MAX_ARGS; $i ++)
  1549. {
  1550. ${"arg$i"} = isset($options[$i]) ? $options[$i] : null;
  1551. }
  1552. $this->check($fieldName, $validater['rule'], $arg0, $arg1, $arg2);
  1553. }
  1554. return $this;
  1555. }
  1556. /**
  1557. * 记录错误到日志。
  1558. * Log the error.
  1559. *
  1560. * module/common/lang中定义了错误提示信息。
  1561. * For the error notice, see module/common/lang.
  1562. *
  1563. * @param string $checkType the check rule
  1564. * @param string $fieldName the field name
  1565. * @param string $fieldLabel the field label
  1566. * @param array $funcArgs the args
  1567. * @access public
  1568. * @return void
  1569. */
  1570. public function logError($checkType, $fieldName, $fieldLabel, $funcArgs = array())
  1571. {
  1572. global $lang;
  1573. $error = $lang->error->$checkType;
  1574. $replaces = array_merge(array($fieldLabel), $funcArgs); // the replace values.
  1575. /*
  1576. * 如果$error错误信息是一个字符串,进行替换。
  1577. * Just a string, cycle the $replaces.
  1578. **/
  1579. if(!is_array($error))
  1580. {
  1581. foreach($replaces as $replace)
  1582. {
  1583. if(is_array($replace)) $replace = implode(',', $replace);
  1584. $pos = strpos($error, '%s');
  1585. if($pos === false) break;
  1586. $error = substr($error, 0, $pos) . $replace . substr($error, $pos + 2);
  1587. }
  1588. }
  1589. /*
  1590. * 如果error错误信息是一个数组,选择一个%s满足替换个数的进行替换。
  1591. * If the error define is an array, select the one which %s counts match the $replaces.
  1592. **/
  1593. else
  1594. {
  1595. /*
  1596. * 去掉空值项。
  1597. * Remove the empty items.
  1598. **/
  1599. foreach($replaces as $key => $value) if(is_null($value)) unset($replaces[$key]);
  1600. $replacesCount = count($replaces);
  1601. foreach($error as $errorString)
  1602. {
  1603. if(substr_count($errorString, '%s') == $replacesCount)
  1604. {
  1605. $error = vsprintf($errorString, $replaces);
  1606. }
  1607. }
  1608. }
  1609. dao::$errors[$fieldName][] = $error;
  1610. }
  1611. /**
  1612. * 判断是否有错误。
  1613. * Judge any error or not.
  1614. *
  1615. * @access public
  1616. * @return bool
  1617. */
  1618. public static function isError()
  1619. {
  1620. return !empty(dao::$errors);
  1621. }
  1622. /**
  1623. * 获取错误。
  1624. * Get the errors.
  1625. *
  1626. * @access public
  1627. * @return array|string
  1628. */
  1629. public static function getError($join = false)
  1630. {
  1631. $errors = dao::$errors;
  1632. dao::$errors = array(); // 清除dao的错误信息(Must clear errors)
  1633. if(!$join) return $errors;
  1634. if(is_array($errors))
  1635. {
  1636. $message = '';
  1637. foreach($errors as $item)
  1638. {
  1639. is_array($item) ? $message .= implode('\n', $item) . "\n" : $message .= $item . "\n";
  1640. }
  1641. return $message;
  1642. }
  1643. }
  1644. /**
  1645. * 获取表的字段类型。
  1646. * Get the defination of fields of the table.
  1647. *
  1648. * @access public
  1649. * @return array
  1650. */
  1651. public function getFieldsType()
  1652. {
  1653. $fields = array();
  1654. $rawFields = $this->descTable($this->table);
  1655. foreach($rawFields as $rawField)
  1656. {
  1657. $firstPOS = strpos($rawField->type, '(');
  1658. if(!$firstPOS) $firstPOS = strpos($rawField->type, ' ');
  1659. $type = substr($rawField->type, 0, $firstPOS > 0 ? $firstPOS : strlen($rawField->type));
  1660. $type = str_replace(array('big', 'small', 'medium', 'tiny', 'var'), '', $type);
  1661. $field = array();
  1662. if($type == 'enum' or $type == 'set')
  1663. {
  1664. $rangeBegin = $firstPOS + 2; // 移除开始的引用符 Remove the first quote.
  1665. $rangeEnd = strrpos($rawField->type, ')') - 1; // 移除结束的引用符 Remove the last quote.
  1666. $range = substr($rawField->type, $rangeBegin, $rangeEnd - $rangeBegin);
  1667. $field['rule'] = 'reg';
  1668. $field['options']['reg'] = '/' . str_replace("','", '|', $range) . '/';
  1669. }
  1670. elseif($type == 'char')
  1671. {
  1672. $begin = $firstPOS + 1;
  1673. $end = strpos($rawField->type, ')', $begin);
  1674. $length = substr($rawField->type, $begin, $end - $begin);
  1675. $field['rule'] = 'length';
  1676. $field['options']['max'] = $length;
  1677. $field['options']['min'] = 0;
  1678. }
  1679. elseif($type == 'int')
  1680. {
  1681. $field['rule'] = 'int';
  1682. }
  1683. elseif($type == 'float' or $type == 'double')
  1684. {
  1685. $field['rule'] = 'float';
  1686. }
  1687. elseif($type == 'date')
  1688. {
  1689. $field['rule'] = 'date';
  1690. }
  1691. elseif($type == 'datetime')
  1692. {
  1693. $field['rule'] = 'datetime';
  1694. }
  1695. else
  1696. {
  1697. $field['rule'] = 'skip';
  1698. }
  1699. $fields[$rawField->field] = $field;
  1700. }
  1701. return $fields;
  1702. }
  1703. /**
  1704. * Process SQL error by code.
  1705. *
  1706. * @param object $exception
  1707. * @access public
  1708. * @return void
  1709. */
  1710. public function sqlError($exception)
  1711. {
  1712. $message = $exception->getMessage();
  1713. $message .= ' ' . helper::checkDB2Repair($exception);
  1714. $sql = $this->sqlobj->get();
  1715. $message .= "<p>The sql is: $sql</p>";
  1716. /*
  1717. * 如果开启了将sql错误作为异常抛出,那么拦截sql错误,不触发错误。
  1718. * If throwing sql errors as exceptions is enabled, sql errors are intercepted and not triggered.
  1719. */
  1720. if($this->app->throwError)
  1721. {
  1722. throw new Exception($message);
  1723. }
  1724. $this->app->triggerError($message, __FILE__, __LINE__, $exit = true);
  1725. }
  1726. /**
  1727. * 获取本次会话的 SQL 语句和执行时间。
  1728. * Get SQL statements and execution time of current session.
  1729. *
  1730. * @access public
  1731. * @return array
  1732. */
  1733. public function getProfiles()
  1734. {
  1735. $profiles = [];
  1736. $basePath = $this->app->getBasePath();
  1737. $sqlTypes = ['SELECT', 'INSERT', 'UPDATE', 'DELETE', 'REPLACE'];
  1738. foreach(dbh::$queries as $key => $query)
  1739. {
  1740. $profile = new stdClass();
  1741. $profile->Query_ID = $key + 1;
  1742. $profile->Query = $query;
  1743. $profile->Explain = [];
  1744. $profile->Error = '';
  1745. $profile->Duration = dbh::$durations[$key] ?? 0;
  1746. $profile->Code = str_replace($basePath, '', dbh::$traces[$key] ?? '');
  1747. $profiles[] = $profile;
  1748. $allowExplain = false;
  1749. foreach($sqlTypes as $type)
  1750. {
  1751. if(stripos($query, $type) === 0)
  1752. {
  1753. $allowExplain = true;
  1754. break;
  1755. }
  1756. }
  1757. if(!$allowExplain) continue;
  1758. try
  1759. {
  1760. $slow = false;
  1761. $rows = $this->explain($query, false);
  1762. foreach($rows as $row)
  1763. {
  1764. if($row->type === 'ALL'
  1765. || stripos($row->Extra, 'temporary') !== false
  1766. || stripos($row->Extra, 'filesort') !== false
  1767. || stripos($row->Extra, 'join buffer') !== false
  1768. || stripos($row->Extra, 'checked for each record') !== false
  1769. || stripos($row->Extra, 'full scan on null key') !== false
  1770. )
  1771. {
  1772. $slow = true;
  1773. break;
  1774. }
  1775. }
  1776. if($slow) $profile->Explain = $rows;
  1777. }
  1778. catch(PDOException $e)
  1779. {
  1780. $profile->Error = 'Can not explain the sql statement.';
  1781. }
  1782. }
  1783. return $profiles;
  1784. }
  1785. /**
  1786. * 获取数据库版本。
  1787. * Get database version.
  1788. *
  1789. * @access public
  1790. * @return string|void
  1791. */
  1792. public function getVersion()
  1793. {
  1794. return $this->dbh->getVersion();
  1795. }
  1796. /**
  1797. * 创建临时表。
  1798. * Create temporary table.
  1799. *
  1800. * @param int $ids 用于创建临时表的 id 列表,字符串或数组。
  1801. * @param string $tableName 临时表的名称,默认值为空,由程序自动生成。
  1802. * @param bool $filterTable 是否过滤重复的表名,默认值为 true。
  1803. * @param int $limit 用于创建临时表的 id 列表的数量限制,数量小于这个值时不创建临时表,0 表示不限制数量。
  1804. * @access public
  1805. * @return false|string
  1806. */
  1807. public function createTemporaryTable($idList, $tableName = '', $filterTable = true, $limit = 100)
  1808. {
  1809. return $this->sqlobj->createTemporaryTable($idList, $tableName, $filterTable, $limit);
  1810. }
  1811. }
  1812. /**
  1813. * SQL类。
  1814. * The SQL class.
  1815. *
  1816. * @package framework
  1817. */
  1818. class baseSQL
  1819. {
  1820. /**
  1821. * 所有方法的最大参数个数。
  1822. * The max count of params of all methods.
  1823. *
  1824. */
  1825. const MAX_ARGS = 3;
  1826. /**
  1827. * SQL字符串。
  1828. * The sql string.
  1829. *
  1830. * @var string
  1831. * @access public
  1832. */
  1833. public $sql = '';
  1834. /**
  1835. * 全局对象$app
  1836. * The global app object.
  1837. *
  1838. * @var object
  1839. * @access public
  1840. */
  1841. public $app;
  1842. /**
  1843. * 全局变量$dbh。
  1844. * The global $dbh.
  1845. *
  1846. * @var object
  1847. * @access public
  1848. */
  1849. public $dbh;
  1850. /**
  1851. * 更新或插入的数据。
  1852. * The data to update or insert.
  1853. *
  1854. * @var mixed
  1855. * @access public
  1856. */
  1857. public $data;
  1858. /**
  1859. * 不需要拼接SQL的字段
  1860. * skipFields
  1861. *
  1862. * @var mixed
  1863. * @access public
  1864. */
  1865. public $skipFields;
  1866. /**
  1867. * SQL 方法, insert, update, delete ...
  1868. * SQL method, insert, update, delete ...
  1869. *
  1870. * @var mixed
  1871. * @access public
  1872. */
  1873. public $method;
  1874. /**
  1875. * setField
  1876. *
  1877. * @var mixed
  1878. * @access public
  1879. */
  1880. public $setField;
  1881. /**
  1882. * 是否是第一次设置。
  1883. * Is the first time to call set.
  1884. *
  1885. * @var bool
  1886. * @access public
  1887. */
  1888. public $isFirstSet = true;
  1889. /**
  1890. * 是否是在条件语句中。
  1891. * If in the logic of judge condition or not.
  1892. *
  1893. * @var bool
  1894. * @access public
  1895. */
  1896. public $inCondition = false;
  1897. /**
  1898. * 条件是否为真。
  1899. * The condition is true or not.
  1900. *
  1901. * @var bool
  1902. * @access public
  1903. */
  1904. public $conditionIsTrue = false;
  1905. /**
  1906. * 条件结果,beginIF 中表达式的结果会存储到这个数组中。
  1907. * Store the result of the expression.
  1908. *
  1909. * @var bool
  1910. * @access public;
  1911. */
  1912. public $conditionResults = array();
  1913. /**
  1914. * 条件层级。
  1915. * The condition level.
  1916. *
  1917. * @var bool
  1918. * @access public;
  1919. */
  1920. public $conditionLevel = 0;
  1921. /**
  1922. * WHERE条件嵌套小括号标记。
  1923. * If in mark or not.
  1924. *
  1925. * @var bool
  1926. * @access public
  1927. */
  1928. public $inMark = false;
  1929. /**
  1930. * 是否开启特殊字符转义。
  1931. * Magic quote or not.
  1932. *
  1933. * @var bool
  1934. * @access public
  1935. */
  1936. public $magicQuote;
  1937. /**
  1938. * 表别名。
  1939. * Table alias.
  1940. *
  1941. * @var array
  1942. * @access public
  1943. */
  1944. public $tableAlias;
  1945. /**
  1946. * 当前操作的表。
  1947. * Current table.
  1948. *
  1949. * @var array
  1950. * @access public
  1951. */
  1952. public $currentTable;
  1953. /**
  1954. * 已创建的临时表。
  1955. * The temporary tables.
  1956. *
  1957. * @var array
  1958. * @access public
  1959. */
  1960. public $tempTables = [];
  1961. /**
  1962. * 构造方法。
  1963. * The construct function.
  1964. *
  1965. * @access public
  1966. * @return void
  1967. */
  1968. public function __construct($table = '')
  1969. {
  1970. global $app, $dbh;
  1971. $this->app = $app;
  1972. $this->dbh = $dbh;
  1973. $this->data = new stdclass();
  1974. $this->skipFields = '';
  1975. $this->tableAlias = [];
  1976. $this->magicQuote = (version_compare(phpversion(), '5.4', '<') and function_exists('get_magic_quotes_gpc') and get_magic_quotes_gpc());
  1977. }
  1978. /**
  1979. * 工厂方法。
  1980. * The factory method.
  1981. *
  1982. * @param string $table
  1983. * @access public
  1984. * @return object the sql object.
  1985. */
  1986. public static function factory($table = '')
  1987. {
  1988. return new sql($table);
  1989. }
  1990. /**
  1991. * 设置SQL的方法。
  1992. * Set SQL method.
  1993. *
  1994. * @param string $method
  1995. * @access public
  1996. * @return void
  1997. */
  1998. public function setMethod($method = '')
  1999. {
  2000. $this->method = $method;
  2001. }
  2002. /**
  2003. * select语句。
  2004. * The sql is select.
  2005. *
  2006. * @param string $field
  2007. * @access public
  2008. * @return object the sql object.
  2009. */
  2010. public static function select($field = '*')
  2011. {
  2012. $sqlobj = self::factory();
  2013. $sqlobj->setMethod('select');
  2014. $sqlobj->sql = "SELECT $field ";
  2015. return $sqlobj;
  2016. }
  2017. /**
  2018. * update语句。
  2019. * The sql is update.
  2020. *
  2021. * @param string $table
  2022. * @access public
  2023. * @return object the sql object.
  2024. */
  2025. public static function update($table)
  2026. {
  2027. $sqlobj = self::factory();
  2028. $sqlobj->setMethod('update');
  2029. $sqlobj->sql = "UPDATE $table SET ";
  2030. return $sqlobj;
  2031. }
  2032. /**
  2033. * insert语句。
  2034. * The sql is insert.
  2035. *
  2036. * @param string $table
  2037. * @access public
  2038. * @return object the sql object.
  2039. */
  2040. public static function insert($table)
  2041. {
  2042. $sqlobj = self::factory();
  2043. $sqlobj->setMethod('insert');
  2044. $sqlobj->sql = "INSERT INTO $table ";
  2045. return $sqlobj;
  2046. }
  2047. /**
  2048. * replace语句。
  2049. * The sql is replace.
  2050. *
  2051. * @param string $table
  2052. * @access public
  2053. * @return object the sql object.
  2054. */
  2055. public static function replace($table)
  2056. {
  2057. $sqlobj = self::factory();
  2058. $sqlobj->setMethod('replace');
  2059. $sqlobj->sql = "REPLACE INTO $table SET ";
  2060. return $sqlobj;
  2061. }
  2062. /**
  2063. * delete语句。
  2064. * The sql is delete.
  2065. *
  2066. * @access public
  2067. * @return object the sql object.
  2068. */
  2069. public static function delete()
  2070. {
  2071. $sqlobj = self::factory();
  2072. $sqlobj->setMethod('delete');
  2073. $sqlobj->sql = "DELETE ";
  2074. return $sqlobj;
  2075. }
  2076. /**
  2077. * 将关联数组转换为sql语句中 `key` = value 的形式。
  2078. * Join the data items by key = value.
  2079. *
  2080. * @param object $data
  2081. * @param string $skipFields the fields to skip.
  2082. * @access public
  2083. * @return object the sql object.
  2084. */
  2085. public function data($data, $skipFields = '')
  2086. {
  2087. $data = (object) $data;
  2088. if($skipFields) $this->skipFields = ',' . str_replace(' ', '', $skipFields) . ',';
  2089. if($this->method != 'insert')
  2090. {
  2091. foreach($data as $field => $value)
  2092. {
  2093. if(!preg_match('|^\w+$|', $field))
  2094. {
  2095. unset($data->$field);
  2096. continue;
  2097. }
  2098. if(strpos($this->skipFields, ",$field,") !== false) continue;
  2099. if($field == 'id' and $this->method == 'update') continue; // primary key not allowed in dmdb.
  2100. $this->sql .= "`$field` = " . $this->quote($value) . ',';
  2101. }
  2102. }
  2103. $this->data = $data;
  2104. $this->sql = rtrim($this->sql, ','); // Remove the last ','.
  2105. return $this;
  2106. }
  2107. /**
  2108. * 在左边添加'('。
  2109. * Add an '(' at left.
  2110. *
  2111. * @param int $count
  2112. * @access public
  2113. * @return static|sql the sql object.
  2114. */
  2115. public function markLeft($count = 1)
  2116. {
  2117. if($this->inCondition and !$this->conditionIsTrue) return $this;
  2118. $this->sql .= str_repeat('(', $count);
  2119. $this->inMark = true;
  2120. return $this;
  2121. }
  2122. /**
  2123. * 在右边增加')'。
  2124. * Add an ')' at right.
  2125. *
  2126. * @param int $count
  2127. * @access public
  2128. * @return static|sql the sql object.
  2129. */
  2130. public function markRight($count = 1)
  2131. {
  2132. if($this->inCondition and !$this->conditionIsTrue) return $this;
  2133. $this->sql .= str_repeat(')', $count);
  2134. $this->inMark = false;
  2135. return $this;
  2136. }
  2137. /**
  2138. * SET部分。
  2139. * The set part.
  2140. *
  2141. * @param string $set
  2142. * @access public
  2143. * @return static|sql the sql object.
  2144. */
  2145. public function set($set)
  2146. {
  2147. if($this->inCondition and !$this->conditionIsTrue) return $this;
  2148. /* DMDB replace will use $this->data. */
  2149. if($this->method == 'insert' or $this->method == 'replace')
  2150. {
  2151. $this->setField = $set;
  2152. $this->data->$set = '';
  2153. }
  2154. if($this->method != 'insert')
  2155. {
  2156. /* Add ` to avoid keywords of mysql. */
  2157. if(strpos($set, '=') === false)
  2158. {
  2159. $set = str_replace(',', '', $set);
  2160. $set = $this->dbh->iqchar . str_replace('`', '', $set) . $this->dbh->iqchar;
  2161. }
  2162. else
  2163. {
  2164. $set = str_replace('`', $this->dbh->iqchar, $set);
  2165. }
  2166. $this->sql .= $this->isFirstSet ? " $set" : ", $set";
  2167. if($this->isFirstSet) $this->isFirstSet = false;
  2168. }
  2169. return $this;
  2170. }
  2171. /**
  2172. * 创建From部分。
  2173. * Create the from part.
  2174. *
  2175. * @param string $table
  2176. * @access public
  2177. * @return static|sql the sql object.
  2178. */
  2179. public function from($table)
  2180. {
  2181. $this->sql .= "FROM $table";
  2182. $this->currentTable = $table;
  2183. /* Default table. */
  2184. $this->tableAlias[''] = $table;
  2185. return $this;
  2186. }
  2187. /**
  2188. * 创建Alias部分,Alias转为AS。
  2189. * Create the Alias part.
  2190. *
  2191. * @param string $alias
  2192. * @access public
  2193. * @return static|sql the sql object.
  2194. */
  2195. public function alias($alias)
  2196. {
  2197. if($this->inCondition and !$this->conditionIsTrue) return $this;
  2198. $this->sql .= " AS $alias ";
  2199. $this->tableAlias[$alias] = $this->currentTable;
  2200. return $this;
  2201. }
  2202. /**
  2203. * 创建LEFT JOIN部分。
  2204. * Create the left join part.
  2205. *
  2206. * @param string $table
  2207. * @access public
  2208. * @return static|sql the sql object.
  2209. */
  2210. public function leftJoin($table)
  2211. {
  2212. if($this->inCondition and !$this->conditionIsTrue) return $this;
  2213. $this->sql .= " LEFT JOIN $table";
  2214. $this->currentTable = $table;
  2215. return $this;
  2216. }
  2217. /**
  2218. * 创建ON部分。
  2219. * Create the on part.
  2220. *
  2221. * @param string $condition
  2222. * @access public
  2223. * @return static|sql the sql object.
  2224. */
  2225. public function on($condition)
  2226. {
  2227. if($this->inCondition and !$this->conditionIsTrue) return $this;
  2228. $this->sql .= " ON $condition ";
  2229. return $this;
  2230. }
  2231. /**
  2232. * 开始条件判断。
  2233. * Begin condition judge.
  2234. *
  2235. * @param bool $condition
  2236. * @access public
  2237. * @return static|sql the sql object.
  2238. */
  2239. public function beginIF($condition)
  2240. {
  2241. $this->inCondition = true;
  2242. $this->conditionLevel += 1;
  2243. $this->conditionResults[$this->conditionLevel] = $condition;
  2244. $this->conditionIsTrue = !in_array(false, $this->conditionResults);
  2245. return $this;
  2246. }
  2247. /**
  2248. * 结束条件判断。
  2249. * End the condition judge.
  2250. *
  2251. * @access public
  2252. * @return static|sql the sql object.
  2253. */
  2254. public function fi()
  2255. {
  2256. unset($this->conditionResults[$this->conditionLevel]);
  2257. $this->conditionLevel -= 1;
  2258. if($this->conditionLevel > 0)
  2259. {
  2260. $this->conditionIsTrue = !in_array(false, $this->conditionResults);
  2261. return $this;
  2262. }
  2263. $this->inCondition = false;
  2264. $this->conditionIsTrue = false;
  2265. return $this;
  2266. }
  2267. /**
  2268. * 创建WHERE部分。
  2269. * Create the where part.
  2270. *
  2271. * @param string $arg1 the field name
  2272. * @param string $arg2 the operator
  2273. * @param string $arg3 the value
  2274. * @access public
  2275. * @return static|sql the sql object.
  2276. */
  2277. public function where($arg1 = '', $arg2 = null, $arg3 = null)
  2278. {
  2279. if($this->inCondition and !$this->conditionIsTrue) return $this;
  2280. if(!$arg1)
  2281. {
  2282. $condition = '';
  2283. }
  2284. elseif($arg3 !== null)
  2285. {
  2286. $condition = "`$arg1` $arg2 " . $this->quote($arg3);
  2287. }
  2288. else
  2289. {
  2290. $condition = (is_string($arg1) && ctype_alnum($arg1)) ? '`' . $arg1 . '`' : $arg1;
  2291. }
  2292. if(!$this->inMark) $this->sql .= ' ' . DAO::WHERE ." $condition ";
  2293. if($this->inMark) $this->sql .= " $condition ";
  2294. return $this;
  2295. }
  2296. /**
  2297. * 创建AND部分。
  2298. * Create the AND part.
  2299. *
  2300. * @param string $condition
  2301. * @access public
  2302. * @return static|sql the sql object.
  2303. */
  2304. public function andWhere($condition, $addMark = false)
  2305. {
  2306. if($this->inCondition and !$this->conditionIsTrue) return $this;
  2307. if(is_string($condition) && ctype_alnum($condition)) $condition = '`' . $condition . '`';
  2308. $mark = $addMark ? '(' : '';
  2309. $this->sql .= " AND {$mark} $condition ";
  2310. return $this;
  2311. }
  2312. /**
  2313. * 创建OR部分。
  2314. * Create the OR part.
  2315. *
  2316. * @param string $condition
  2317. * @access public
  2318. * @return static|sql the sql object.
  2319. */
  2320. public function orWhere($condition)
  2321. {
  2322. if($this->inCondition and !$this->conditionIsTrue) return $this;
  2323. if(is_string($condition) && ctype_alnum($condition)) $condition = '`' . $condition . '`';
  2324. $this->sql .= " OR $condition ";
  2325. return $this;
  2326. }
  2327. /**
  2328. * 创建'='部分。
  2329. * Create the '='.
  2330. *
  2331. * @param string $value
  2332. * @access public
  2333. * @return static|sql the sql object.
  2334. */
  2335. public function eq($value)
  2336. {
  2337. if($this->inCondition and !$this->conditionIsTrue) return $this;
  2338. if($this->method == 'insert' or $this->method == 'replace')
  2339. {
  2340. $field = $this->setField;
  2341. $this->data->$field = $value;
  2342. }
  2343. if($this->method != 'insert')
  2344. {
  2345. $this->sql .= " = " . $this->quote($value);
  2346. }
  2347. return $this;
  2348. }
  2349. /**
  2350. * 创建'!='。
  2351. * Create '!='.
  2352. *
  2353. * @param string $value
  2354. * @access public
  2355. * @return static|sql the sql object.
  2356. */
  2357. public function ne($value)
  2358. {
  2359. if($this->inCondition and !$this->conditionIsTrue) return $this;
  2360. $this->sql .= " != " . $this->quote($value);
  2361. return $this;
  2362. }
  2363. /**
  2364. * 创建'>'。
  2365. * Create '>'.
  2366. *
  2367. * @param string $value
  2368. * @access public
  2369. * @return static|sql the sql object.
  2370. */
  2371. public function gt($value)
  2372. {
  2373. if($this->inCondition and !$this->conditionIsTrue) return $this;
  2374. $this->sql .= " > " . $this->quote($value);
  2375. return $this;
  2376. }
  2377. /**
  2378. * 创建'>='
  2379. * Create '>='.
  2380. *
  2381. * @param string $value
  2382. * @access public
  2383. * @return static|sql the sql object.
  2384. */
  2385. public function ge($value)
  2386. {
  2387. if($this->inCondition and !$this->conditionIsTrue) return $this;
  2388. $this->sql .= " >= " . $this->quote($value);
  2389. return $this;
  2390. }
  2391. /**
  2392. * 创建'<'。
  2393. * Create '<'.
  2394. *
  2395. * @param mixed $value
  2396. * @access public
  2397. * @return static|sql the sql object.
  2398. */
  2399. public function lt($value)
  2400. {
  2401. if($this->inCondition and !$this->conditionIsTrue) return $this;
  2402. $this->sql .= " < " . $this->quote($value);
  2403. return $this;
  2404. }
  2405. /**
  2406. * 创建 '<='。
  2407. * Create '<='.
  2408. *
  2409. * @param mixed $value
  2410. * @access public
  2411. * @return static|sql the sql object.
  2412. */
  2413. public function le($value)
  2414. {
  2415. if($this->inCondition and !$this->conditionIsTrue) return $this;
  2416. $this->sql .= " <= " . $this->quote($value);
  2417. return $this;
  2418. }
  2419. /**
  2420. * 创建"between and"。
  2421. * Create "between and"
  2422. *
  2423. * @param string $min
  2424. * @param string $max
  2425. * @access public
  2426. * @return static|sql the sql object.
  2427. */
  2428. public function between($min, $max)
  2429. {
  2430. if($this->inCondition and !$this->conditionIsTrue) return $this;
  2431. $min = $this->quote($min);
  2432. $max = $this->quote($max);
  2433. $this->sql .= " BETWEEN $min AND $max ";
  2434. return $this;
  2435. }
  2436. /**
  2437. * 创建IN部分。
  2438. * Create in part.
  2439. *
  2440. * @param string|array $ids ','分割的字符串或者数组。List string by ',' or an array.
  2441. * @param bool $useTemporaryTable 是否使用临时表。 Use temporary table or not.
  2442. * @param string $tableName 临时表的名称,默认值为空,由程序自动生成。The name of temporary table, default is empty, generated by program.
  2443. * @param bool $filterTable 是否过滤重复的表名,默认值为 true。Filter duplicate table name or not.
  2444. * @param bool $limit 用于创建临时表的 id 列表的数量限制,数量小于这个值时不创建临时表,0 表示不限制数量。Limit the count of ids to create temporary table, 0 means no limit.
  2445. * @access public
  2446. * @return static|sql the sql object.
  2447. */
  2448. public function in($ids, $useTemporaryTable = false, $tableName = '', $filterTable = true, $limit = 100)
  2449. {
  2450. if($this->inCondition and !$this->conditionIsTrue) return $this;
  2451. if(is_null($ids))
  2452. {
  2453. $this->sql .= ' IS NULL';
  2454. return $this;
  2455. }
  2456. if($useTemporaryTable)
  2457. {
  2458. $tableName = $this->createTemporaryTable($ids, $tableName, $filterTable, $limit, false);
  2459. if($tableName)
  2460. {
  2461. $this->sql .= " IN (SELECT id FROM $tableName)";
  2462. return $this;
  2463. }
  2464. }
  2465. $this->sql .= helper::dbIN($ids);
  2466. return $this;
  2467. }
  2468. /**
  2469. * 创建临时表。
  2470. * Create temporary table.
  2471. *
  2472. * @param int $ids 用于创建临时表的 id 列表,字符串或数组。
  2473. * @param string $tableName 临时表的名称,默认值为空,由程序自动生成。
  2474. * @param bool $filterTable 是否过滤重复的表名,默认值为 true。
  2475. * @param int $limit 用于创建临时表的 id 列表的数量限制,数量小于这个值时不创建临时表,0 表示不限制数量。
  2476. * @param bool $exit 是否停止程序执行,默认值为 true。
  2477. * @access public
  2478. * @return string
  2479. */
  2480. public function createTemporaryTable($ids, $tableName = '', $filterTable = true, $limit = 100, $exit = true)
  2481. {
  2482. if(!is_string($ids) && !is_array($ids))
  2483. {
  2484. $this->app->triggerError('The idList must be a string or an array.', __FILE__, __LINE__, $exit);
  2485. return '';
  2486. }
  2487. if(is_string($ids)) $ids = explode(',', $ids);
  2488. $idList = [];
  2489. foreach($ids as $id)
  2490. {
  2491. if(empty($id)) continue;
  2492. $intID = (int)$id;
  2493. if($intID != $id) continue;
  2494. $idList[$intID] = $intID;
  2495. }
  2496. if($limit && count($idList) < $limit)
  2497. {
  2498. $this->app->triggerError("The idList count must be greater than $limit", __FILE__, __LINE__, $exit);
  2499. return '';
  2500. }
  2501. $rows = '';
  2502. if(empty($tableName))
  2503. {
  2504. if($filterTable)
  2505. {
  2506. /* 如果开启了唯一表名,那么将表名设置为 md5(idList). */
  2507. asort($idList);
  2508. $rows = '(' . implode('),(', $idList) . ')';
  2509. $tableName = "temp_" . md5($rows);
  2510. if(isset($this->tempTables[$tableName])) return $tableName;
  2511. }
  2512. else
  2513. {
  2514. $tableName = 'temp_' . uniqid();
  2515. $rows = '(' . implode('),(', $idList) . ')';
  2516. }
  2517. }
  2518. if(!preg_match('/^temp_\w+$/', $tableName))
  2519. {
  2520. $this->app->triggerError("The table name should be like 'temp_xxx', where xxx is a string only containing letters, numbers and underscores.", __FILE__, __LINE__, $exit);
  2521. return '';
  2522. }
  2523. if($filterTable && isset($this->tempTables[$tableName])) return $tableName;
  2524. try
  2525. {
  2526. $this->dbh->exec("CREATE TEMPORARY TABLE IF NOT EXISTS {$tableName} (id int PRIMARY KEY)");
  2527. $this->dbh->exec("INSERT INTO {$tableName} VALUES {$rows}");
  2528. }
  2529. catch(PDOException $e)
  2530. {
  2531. $message = $e->getMessage() . ' ' . helper::checkDB2Repair($e);
  2532. $this->app->triggerError($message, __FILE__, __LINE__, $exit);
  2533. return '';
  2534. }
  2535. if($filterTable) $this->tempTables[$tableName] = $tableName;
  2536. return $tableName;
  2537. }
  2538. /**
  2539. * 创建'NOT IN'部分。
  2540. * Create not in part.
  2541. *
  2542. * @param string|array $ids list string by ',' or an array
  2543. * @access public
  2544. * @return static|sql the sql object.
  2545. */
  2546. public function notin($ids)
  2547. {
  2548. if($this->inCondition and !$this->conditionIsTrue) return $this;
  2549. if((is_string($ids) && $ids === '') || (is_array($ids) && empty($ids)))
  2550. {
  2551. $pattern = '/\s+(?:(?:[a-zA-Z0-9]+\.)?|)(?:`([^`]+)`|"([^"]+)"|(\w+))\s*$/i';
  2552. $replacement = ' 1=1 ';
  2553. $this->sql = preg_replace($pattern, $replacement, $this->sql);
  2554. return $this;
  2555. }
  2556. $dbIN = helper::dbIN($ids);
  2557. if(strpos($dbIN, '=') === 0) $this->sql .= ' !' . $dbIN;
  2558. else $this->sql .= ' NOT ' . helper::dbIN($ids);
  2559. return $this;
  2560. }
  2561. /**
  2562. * 创建子查询IN部分。
  2563. * Create subquery in part.
  2564. *
  2565. * @param string|dao
  2566. * @access public
  2567. * @return static|sql the sql object.
  2568. */
  2569. public function subIn($subquery)
  2570. {
  2571. if($this->inCondition and !$this->conditionIsTrue) return $this;
  2572. if(!is_string($subquery)) $subquery = $this->dbh->formatSQL($subquery->processSQL());
  2573. $this->sql .= ' IN (' . $subquery . ')';
  2574. return $this;
  2575. }
  2576. /**
  2577. * 创建子查询'NOT IN'部分。
  2578. * Create subquery not in part.
  2579. *
  2580. * @param string|dao
  2581. * @access public
  2582. * @return static|sql the sql object.
  2583. */
  2584. public function subNotIn($subquery)
  2585. {
  2586. if($this->inCondition and !$this->conditionIsTrue) return $this;
  2587. if(!is_string($subquery)) $subquery = $this->dbh->formatSQL($subquery->processSQL());
  2588. $this->sql .= ' NOT IN (' . $subquery . ')';
  2589. return $this;
  2590. }
  2591. /**
  2592. * 创建LIKE部分。
  2593. * Create the like by part.
  2594. *
  2595. * @param string $string
  2596. * @access public
  2597. * @return static|sql the sql object.
  2598. */
  2599. public function like($string)
  2600. {
  2601. if($this->inCondition and !$this->conditionIsTrue) return $this;
  2602. $this->sql .= " LIKE " . $this->quote($string);
  2603. return $this;
  2604. }
  2605. /**
  2606. * 创建NOT LIKE部分。
  2607. * Create the not like by part.
  2608. *
  2609. * @param string $string
  2610. * @access public
  2611. * @return static|sql the sql object.
  2612. */
  2613. public function notLike($string)
  2614. {
  2615. if($this->inCondition and !$this->conditionIsTrue) return $this;
  2616. $this->sql .= "NOT LIKE " . $this->quote($string);
  2617. return $this;
  2618. }
  2619. /**
  2620. * 字段为空。
  2621. * Set the field is null statement part.
  2622. *
  2623. * @access public
  2624. * @return static|sql the sql object.
  2625. */
  2626. public function isNULL()
  2627. {
  2628. if($this->inCondition and !$this->conditionIsTrue) return $this;
  2629. $this->sql .= " IS NULL ";
  2630. return $this;
  2631. }
  2632. /**
  2633. * 字段不为空。
  2634. * Set the field is not null statement part.
  2635. *
  2636. * @access public
  2637. * @return static|sql the sql object.
  2638. */
  2639. public function notNULL()
  2640. {
  2641. if($this->inCondition and !$this->conditionIsTrue) return $this;
  2642. $this->sql .= " IS NOT NULL ";
  2643. return $this;
  2644. }
  2645. /**
  2646. * 不为空日期
  2647. * Create not zero date.
  2648. *
  2649. * @access public
  2650. * @return static|sql the sql object.
  2651. */
  2652. public function notZeroDate()
  2653. {
  2654. if($this->inCondition and !$this->conditionIsTrue) return $this;
  2655. $this->sql .= " > '1970-01-01' ";
  2656. return $this;
  2657. }
  2658. /**
  2659. * 不为空时间
  2660. * Create not zero datetime.
  2661. *
  2662. * @access public
  2663. * @return static|sql the sql object.
  2664. */
  2665. public function notZeroDatetime()
  2666. {
  2667. if($this->inCondition and !$this->conditionIsTrue) return $this;
  2668. $this->sql .= " > '1970-01-01 00:00:01' ";
  2669. return $this;
  2670. }
  2671. /**
  2672. * 创建ORDER BY部分。
  2673. * Create the order by part.
  2674. *
  2675. * @param string $order
  2676. * @access public
  2677. * @return static|sql the sql object.
  2678. */
  2679. public function orderBy($order)
  2680. {
  2681. if($this->inCondition and !$this->conditionIsTrue) return $this;
  2682. $order = str_replace(array('|desc', 'desc', '_desc'), ' desc', $order);
  2683. $order = str_replace(array('|asc', 'asc', '_asc'), ' asc', $order);
  2684. /* Add "`" in order string. */
  2685. /* When order has limit string. */
  2686. $pos = stripos($order, 'limit');
  2687. $orders = $pos ? substr($order, 0, $pos) : $order;
  2688. $limit = $pos ? substr($order, $pos) : '';
  2689. if(!empty($limit))
  2690. {
  2691. $trimmedLimit = trim(str_replace('limit', '', $limit));
  2692. if(!preg_match('/^[0-9]+ *(, *[0-9]+)?$/', $trimmedLimit)) helper::end("Limit is bad query, The limit is " . htmlspecialchars($limit));
  2693. }
  2694. $orders = trim($orders);
  2695. if(empty($orders)) return $this;
  2696. if(!preg_match('/^(\w+\.)?(`\w+`|\w+)( +(desc|asc))?( *(, *(\w+\.)?(`\w+`|\w+)( +(desc|asc))?)?)*$/i', $orders)) helper::end("Order is bad request, The order is " . htmlspecialchars($orders));
  2697. $orders = explode(',', $orders);
  2698. foreach($orders as $i => $order)
  2699. {
  2700. $orderParse = explode(' ', trim($order));
  2701. foreach($orderParse as $key => $value)
  2702. {
  2703. $value = trim($value);
  2704. if(empty($value) or strtolower($value) == 'desc' or strtolower($value) == 'asc') continue;
  2705. $field = $value;
  2706. /* such as t1.id field. */
  2707. if(strpos($value, '.') !== false) list($table, $field) = explode('.', $field);
  2708. if(strpos($field, '`') === false) $field = "`$field`";
  2709. $orderParse[$key] = isset($table) ? $table . '.' . $field : $field;
  2710. unset($table);
  2711. }
  2712. $orders[$i] = implode(' ', $orderParse);
  2713. if(empty($orders[$i])) unset($orders[$i]);
  2714. }
  2715. $order = implode(',', $orders) . ' ' . $limit;
  2716. $this->sql .= ' ' . DAO::ORDERBY . " $order";
  2717. return $this;
  2718. }
  2719. /**
  2720. * 创建LIMIT部分。
  2721. * Create the limit part.
  2722. *
  2723. * @param string $limit
  2724. * @access public
  2725. * @return static|sql the sql object.
  2726. */
  2727. public function limit($limit)
  2728. {
  2729. if($this->inCondition and !$this->conditionIsTrue) return $this;
  2730. if(empty($limit)) return $this;
  2731. /* filter limit. */
  2732. $limit = trim(str_ireplace('limit', '', $limit));
  2733. if(!preg_match('/^[0-9]+ *(, *[0-9]+)?$/', $limit))
  2734. {
  2735. $limit = htmlspecialchars($limit);
  2736. helper::end("Limit is bad query, The limit is $limit");
  2737. }
  2738. $this->sql .= ' ' . DAO::LIMIT . " $limit ";
  2739. return $this;
  2740. }
  2741. /**
  2742. * 创建GROUP BY部分。
  2743. * Create the groupby part.
  2744. *
  2745. * @param string $groupBy
  2746. * @access public
  2747. * @return static|sql the sql object.
  2748. */
  2749. public function groupBy($groupBy)
  2750. {
  2751. if($this->inCondition and !$this->conditionIsTrue) return $this;
  2752. //The dm database cannot use alias for group by
  2753. /*
  2754. if(!preg_match('/^\w+[a-zA-Z0-9_`.]+$/', $groupBy))
  2755. {
  2756. $groupBy = htmlspecialchars($groupBy);
  2757. helper::end("Group is bad query, The group is $groupBy");
  2758. }
  2759. */
  2760. $this->sql .= ' ' . DAO::GROUPBY . " $groupBy";
  2761. return $this;
  2762. }
  2763. /**
  2764. * 创建HAVING部分。
  2765. * Create the having part.
  2766. *
  2767. * @param string $having
  2768. * @access public
  2769. * @return static|sql the sql object.
  2770. */
  2771. public function having($having)
  2772. {
  2773. if($this->inCondition and !$this->conditionIsTrue) return $this;
  2774. $this->sql .= ' ' . DAO::HAVING . " $having";
  2775. return $this;
  2776. }
  2777. /**
  2778. * 获取SQL字符串。
  2779. * Get the sql string.
  2780. *
  2781. * @access public
  2782. * @return static|sql
  2783. */
  2784. public function get()
  2785. {
  2786. return $this->sql;
  2787. }
  2788. /**
  2789. * 对字段加转义。
  2790. * Quote a var.
  2791. *
  2792. * @param mixed $value
  2793. * @access public
  2794. * @return mixed
  2795. */
  2796. public function quote($value)
  2797. {
  2798. if(is_null($value)) return 'NULL';
  2799. if($this->magicQuote) $value = stripslashes($value);
  2800. return $this->dbh->quote((string)$value);
  2801. }
  2802. }