DB.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  1. <?php
  2. class DB
  3. {
  4. /**
  5. * 批量插入
  6. *
  7. * @param $table
  8. * @param array $data
  9. * @param array $header 可以不传 但 $data 必须是关联数组集合
  10. * @return int
  11. * @throws CDbException
  12. */
  13. public static function safeBatchInsert($table, array $data, array $header = [])
  14. {
  15. $params = [];
  16. if (!$data) {
  17. return false;
  18. }
  19. if (!$header) {
  20. $header = array_keys($data[0]);
  21. }
  22. $headerStr = implode(',', $header);
  23. $sql = "INSERT INTO {$table} ({$headerStr}) values ";
  24. foreach ($data as $k => $datum) {
  25. $tempValues = [];
  26. $i = 0;
  27. foreach ($datum as $ik => $item) {
  28. $paramKey = ':'.$header[$i].$k;
  29. $paramValue = is_numeric($item) ? $item : "{$item}";
  30. $params[$paramKey] = $paramValue;
  31. $tempValues[] = $paramKey;
  32. $i++;
  33. }
  34. $valueStr = implode(',', $tempValues);
  35. $sql .= "({$valueStr}),";
  36. }
  37. return Yii::app()->db->createCommand(rtrim($sql, ','))->execute($params);
  38. }
  39. /**
  40. * 获取sql操作command对象
  41. *
  42. * @param string $dbName
  43. * @return \CDbCommand
  44. */
  45. public static function getDbCommand($dbName = 'db')
  46. {
  47. $command = \Yii::app()->$dbName->createCommand();
  48. $command->reset();
  49. return $command;
  50. }
  51. /**
  52. * 从数据库获取数据的通用方法
  53. *
  54. * @param string $tableName 表名
  55. * @param array $filters 筛选条件
  56. * @param string $fields 字段
  57. * @param string $group
  58. * @param string $order
  59. * @param integer $page 分页,如果为0,就不分页
  60. * @param integer $pageSize
  61. * @param string $index 强制指定的索引
  62. * @param string $dbName 数据库名
  63. * @return array
  64. */
  65. public static function getDataByCondition(
  66. $tableName,
  67. $filters,
  68. $fields = '*',
  69. $group = '',
  70. $order = '',
  71. $page = 0,
  72. $pageSize = 0,
  73. $index = '',
  74. $dbName = 'db'
  75. ): array {
  76. $db = self::getDbCommand($dbName);
  77. if (!empty($index)) {
  78. $tableName .= " FORCE INDEX (`{$index}`)";
  79. }
  80. $criteria = new \CDbCriteria();
  81. if (!empty($filters)) {
  82. foreach ($filters as $key => $value) {
  83. if (is_array($value) && 'like' === reset($value)) {
  84. $criteria->compare($key, array_pop($value), true);
  85. } elseif (is_array($value) && 'condition' === reset($value)) {
  86. $criteria->addCondition(array_pop($value));
  87. } elseif (is_array($value) && 'betweenCondition' === reset($value)) {
  88. $criteria->addBetweenCondition($key, $value[1], $value[2]);
  89. } elseif (is_array($value) && $value === array()) {
  90. $criteria->addInCondition($key, $value);
  91. } elseif (empty($value)) {
  92. $criteria->addCondition("{$key} = :{$key}");
  93. $criteria->params[':'.$key] = $value;
  94. } else {
  95. $criteria->compare($key, $value);
  96. }
  97. }
  98. }
  99. $build = $db->select($fields)
  100. ->from($tableName)
  101. ->where($criteria->condition, $criteria->params);
  102. !empty($group) && $build->group($group);
  103. !empty($order) && $build->order($order);
  104. if ($page > 0) {
  105. $page = intval($page);
  106. $pageSize = intval($pageSize);
  107. $offset = $pageSize * ($page - 1);
  108. $build->limit($pageSize, $offset);
  109. }
  110. /* if ($isLock) {
  111. $sql = $build->getText() . " FOR UPDATE";
  112. return $this->queryAllBySql($sql, $build->params);
  113. } */
  114. return $build->queryAll();
  115. }
  116. /**
  117. * 从数据库获取数据的通用方法
  118. *
  119. * @param string $tableName 表名
  120. * @param array $filters 筛选条件
  121. * @param string $fields 字段
  122. * @param string $group
  123. * @param string $order
  124. * @param integer $page 分页,如果为0,就不分页
  125. * @param integer $pageSize
  126. * @param string $index 强制指定的索引
  127. * @param string $dbName 数据库名
  128. * @return array
  129. */
  130. public static function updateData($tableName, $filters, $dbName = 'db')
  131. {
  132. $db = self::getDbCommand($dbName);
  133. if (!isset($filters['id'])) {
  134. return false;
  135. }
  136. $id = $filters['id'];
  137. unset($filters['id']);
  138. return $db->update($tableName, $filters, "id=:id", array(':id' => $id));
  139. }
  140. public static function updateById($tableName, $info, $id)
  141. {
  142. $id = intval($id);
  143. if ($id <= 0) {
  144. return false;
  145. }
  146. $db = self::getDbCommand();
  147. return $db->update(self::formTableName($tableName), $info, "id=:id", [':id' => $id]);
  148. }
  149. public static function getInfoById($tableName, $id, $fields = '*')
  150. {
  151. $id = intval($id);
  152. if ($id <= 0) {
  153. return [];
  154. }
  155. return self::getInfoWithCriteria($tableName, DbCriteria::simpleCompare(['id' => $id])->setSelect($fields));
  156. }
  157. public static function deleteById($tableName, $id)
  158. {
  159. $id = intval($id);
  160. if ($id <= 0) {
  161. return false;
  162. }
  163. $db = self::getDbCommand();
  164. return $db->delete(self::formTableName($tableName), "id=:id", [':id' => $id]);
  165. }
  166. public static function formTableName($tableName)
  167. {
  168. return 'wx_' . str_replace('wx_', '', $tableName);
  169. }
  170. /**
  171. * 从数据库获取数据的通用方法,与上面的方法相比,就是多了分页的内容
  172. *
  173. * @param string $tableName 表名
  174. * @param array $filters 筛选条件
  175. * @param string $fields 字段
  176. * @param string $group
  177. * @param string $order
  178. * @param integer $page 分页,如果为0,就不分页
  179. * @param integer $pageSize
  180. * @param string $index 强制指定的索引
  181. * @param string $dbName 数据库名
  182. * @return array
  183. */
  184. public static function getWebDataByCondition(
  185. $tableName,
  186. $filters,
  187. $fields = '*',
  188. $group = '',
  189. $order = '',
  190. $page = 0,
  191. $pageSize = 0,
  192. $index = '',
  193. $dbName = 'db'
  194. ) {
  195. $return = [
  196. 'page' => $page,
  197. 'pageSize' => $pageSize,
  198. 'totalPage' => -1,
  199. 'counts' => -1,
  200. 'records' => [],
  201. ];
  202. $db = self::getDbCommand($dbName);
  203. if (!empty($index)) {
  204. $tableName .= " FORCE INDEX (`{$index}`)";
  205. }
  206. $criteria = new \CDbCriteria();
  207. if (!empty($filters)) {
  208. foreach ($filters as $key => $value) {
  209. if (is_array($value) && 'like' === reset($value)) {
  210. $criteria->compare($key, array_pop($value), true);
  211. } elseif (is_array($value) && 'condition' === reset($value)) {
  212. $criteria->addCondition(array_pop($value));
  213. } elseif (is_array($value) && 'betweenCondition' === reset($value)) {
  214. $criteria->addBetweenCondition($key, $value[1], $value[2]);
  215. } elseif (is_array($value) && $value === array()) {
  216. $criteria->addInCondition($key, $value);
  217. } elseif (empty($value)) {
  218. $criteria->addCondition("{$key} = :{$key}");
  219. $criteria->params[':'.$key] = $value;
  220. } else {
  221. $criteria->compare($key, $value);
  222. }
  223. }
  224. }
  225. // 如果有分页,则查询总记录数
  226. $counts = -1;
  227. if ($page > 0) {
  228. if (empty($group)) {
  229. $counts = $db->select("count(*) as total")
  230. ->from($tableName)
  231. ->where($criteria->condition, $criteria->params)
  232. ->queryScalar();
  233. $db->reset();
  234. } else {
  235. $count_data = $db->select("{$group}")
  236. ->from($tableName)
  237. ->where($criteria->condition, $criteria->params)
  238. ->group($group)
  239. ->queryAll();
  240. $db->reset();
  241. $counts = count($count_data);
  242. }
  243. $counts = intval($counts);
  244. if ($counts < 1) {
  245. return $return; // 数据为空
  246. }
  247. }
  248. $build = $db->select($fields)
  249. ->from($tableName)
  250. ->where($criteria->condition, $criteria->params);
  251. !empty($group) && $build->group($group);
  252. !empty($order) && $build->order($order);
  253. // 如果有分页,则对查询条件做处理
  254. $totalPages = -1;
  255. if ($pageSize > 0) {
  256. //计算总页数
  257. $totalPages = ceil($counts / $pageSize);
  258. $offset = $pageSize * ($page - 1);
  259. $build->limit($pageSize, $offset);
  260. $return['totalPage'] = $totalPages;
  261. $return['counts'] = $counts;
  262. }
  263. $return['records'] = $build->queryAll();
  264. return $return;
  265. }
  266. /**
  267. * 从数据库获取数据的通用方法,只获取一条数据
  268. *
  269. * @param string $tableName 表名
  270. * @param array $filters 筛选条件
  271. * @param string $fields 字段
  272. * @param string $group
  273. * @param string $order
  274. * @param integer $page 分页,如果为0,就不分页
  275. * @param integer $pageSize
  276. * @param string $index 强制指定的索引
  277. * @param string $dbName 数据库名
  278. * @return array
  279. */
  280. public static function getOneByCondition(
  281. $tableName,
  282. $filters,
  283. $fields = '*',
  284. $group = '',
  285. $index = '',
  286. $dbName = 'db'
  287. ) {
  288. $data = self::getDataByCondition($tableName, $filters, $fields, $group, '', 0, 0, $index, $dbName);
  289. return !empty($data) ? reset($data) : [];
  290. }
  291. /**
  292. * 向数据库插入数据
  293. *
  294. * @param string $tableName 表名
  295. * @param array $info
  296. * @param string $dbName
  297. * @return int
  298. */
  299. public static function addData($tableName, $info, $dbName = 'db')
  300. {
  301. if (empty($info)) {
  302. return false;
  303. }
  304. $command = self::getDbCommand($dbName);
  305. $ret = $command->insert(self::formTableName($tableName), $info);
  306. if ($ret) {
  307. return $command->getConnection()->getLastInsertID();
  308. }
  309. return false;
  310. }
  311. /**
  312. * 根据条件删除数据库内容
  313. *
  314. * @param string $tableName
  315. * @param array $filters
  316. * @param string $dbName
  317. * @return int
  318. */
  319. public static function deleteByCondition($tableName, $filters, $dbName = 'db')
  320. {
  321. if (empty($filters)) {
  322. return false;
  323. }
  324. $command = self::getDbCommand($dbName);
  325. $condition = '';
  326. $params = [];
  327. foreach ($filters as $key => $value) {
  328. $condition .= " {$key}=:{$key} AND";
  329. $params[':'.$key] = $value;
  330. }
  331. $condition = trim($condition, 'AND');
  332. $condition = trim($condition);
  333. return $command->delete($tableName, $condition, $params);
  334. }
  335. /**
  336. * 获取model的错误信息
  337. *
  338. * @param object $model
  339. * @return string
  340. */
  341. public static function getModelErrorMsg($model)
  342. {
  343. $str = '';
  344. if ($model->hasErrors()) {
  345. $errors = [];
  346. foreach ($model->getErrors() as $error) {
  347. $errors += $error;
  348. }
  349. $str = implode("<br/>", $errors);
  350. }
  351. return $str;
  352. }
  353. /**
  354. * 通过 DbCriteria 来搜索
  355. * @param string $table_name 表名
  356. * @param DbCriteria $criteria 分页通过 setPage 设置,否则不会查询分页信息
  357. * @return array|\CDbDataReader 格式: ['current'=>1, 'size'=>1, 'totalPage'=>1, 'total'=>1, 'records'=>[]]
  358. * @throws \CException
  359. */
  360. public static function getListWithCriteria(string $table_name, DbCriteria $criteria)
  361. {
  362. // 数据返回格式
  363. $retData = [
  364. 'current' => $criteria->getPage(),
  365. 'size' => $criteria->getPageSize(),
  366. 'totalPage' => 0,
  367. 'total' => 0,
  368. 'records' => [],
  369. ];
  370. $table_name = self::formTableName($table_name);
  371. if ($criteria->alias) {
  372. $table_name .= ' as '.$criteria->alias;
  373. }
  374. // 指定索引
  375. if (!empty($criteria->forceIndex)) {
  376. $table_name .= " FORCE INDEX (`{$criteria->forceIndex}`)";
  377. }
  378. // 根据 DbCriteria 构建查询
  379. $build = self::getDbCommand()->select($criteria->select)
  380. ->from($table_name)
  381. ->where($criteria->condition, $criteria->params);
  382. !empty($criteria->group) && $build->group($criteria->group);
  383. !empty($criteria->having) && $build->having($criteria->having);
  384. !empty($criteria->join) && $build->setJoin($criteria->join);
  385. // 有分页需要先查询总数 然后再恢复 builder
  386. if ($criteria->isFenye()) {
  387. if (!empty($criteria->group)) {
  388. // 使用group以后 需要子查询来统计总条数
  389. $subQuery = $build->select($criteria->getCountSelectStr())->getText();
  390. $totalNum = self::getDbCommand()->select('count(*)')->from("($subQuery) t")->queryScalar(
  391. $criteria->params
  392. );
  393. } else {
  394. $totalNum = $build->select($criteria->getCountSelectStr())->queryScalar();
  395. }
  396. $retData['total'] = $totalNum;
  397. $retData['totalPage'] = ceil($totalNum / $criteria->getPageSize());
  398. $build = self::getDbCommand()->select($criteria->select)
  399. ->from($table_name)
  400. ->where($criteria->condition, $criteria->params);
  401. !empty($criteria->group) && $build->group($criteria->group);
  402. !empty($criteria->having) && $build->having($criteria->having);
  403. !empty($criteria->join) && $build->setJoin($criteria->join);
  404. $build->limit($criteria->limit, $criteria->offset);
  405. } elseif ($criteria->limit > 0) {
  406. // 不做分页 单纯控制偏移及数量
  407. $build->limit($criteria->limit, $criteria->offset);
  408. }
  409. !empty($criteria->order) && $build->order($criteria->order);
  410. $retData['records'] = $build->queryAll() ?: [];
  411. // debug
  412. if ($criteria->getDebugMode() || LWM_ENV != 'prod') {
  413. Logger::info(
  414. json_encode(
  415. [
  416. 'DbCriteriaDebug' => $criteria->getSql($build->getText(), $criteria->params),
  417. 'tag' => $criteria->getDebugTag(),
  418. ],
  419. JSON_UNESCAPED_UNICODE
  420. )
  421. );
  422. }
  423. return $retData;
  424. }
  425. /**
  426. * 通过 DbCriteria 来搜索
  427. * @param string $table_name 表名
  428. * @param DbCriteria $criteria
  429. * @return array|\CDbDataReader
  430. * @throws \CException
  431. */
  432. public static function getInfoWithCriteria(string $table_name, DbCriteria $criteria)
  433. {
  434. $table_name = self::formTableName($table_name);
  435. // 指定索引
  436. if (!empty($criteria->forceIndex)) {
  437. $table_name .= " FORCE INDEX (`{$criteria->forceIndex}`)";
  438. }
  439. // 根据 DbCriteria 构建查询
  440. $build = self::getDbCommand()->select($criteria->select)
  441. ->from($table_name)
  442. ->limit(1)
  443. ->where($criteria->condition, $criteria->params);
  444. !empty($criteria->group) && $build->group($criteria->group);
  445. !empty($criteria->having) && $build->having($criteria->having);
  446. !empty($criteria->order) && $build->order($criteria->order);
  447. // debug
  448. if ($criteria->getDebugMode() || LWM_ENV != 'prod') {
  449. Logger::info(
  450. json_encode(
  451. [
  452. 'DbCriteriaDebug' => $criteria->getSql($build->getText(), $criteria->params),
  453. 'tag' => $criteria->getDebugTag(),
  454. ],
  455. JSON_UNESCAPED_UNICODE
  456. )
  457. );
  458. }
  459. return $build->queryRow();
  460. }
  461. public static function getScalerWithCriteria(string $table_name, DbCriteria $criteria)
  462. {
  463. $data = self::getInfoWithCriteria($table_name, $criteria);
  464. return $data ? reset($data) : '';
  465. }
  466. }