Db.php 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: liu21st <liu21st@gmail.com>
  10. // +----------------------------------------------------------------------
  11. namespace think;
  12. use think\db\Connection;
  13. /**
  14. * Class Db
  15. * @package think
  16. * @method \think\db\Query master() static 从主服务器读取数据
  17. * @method \think\db\Query readMaster(bool $all = false) static 后续从主服务器读取数据
  18. * @method \think\db\Query table(string $table) static 指定数据表(含前缀)
  19. * @method \think\db\Query name(string $name) static 指定数据表(不含前缀)
  20. * @method \think\db\Expression raw(string $value) static 使用表达式设置数据
  21. * @method \think\db\Query where(mixed $field, string $op = null, mixed $condition = null) static 查询条件
  22. * @method \think\db\Query whereRaw(string $where, array $bind = []) static 表达式查询
  23. * @method \think\db\Query whereExp(string $field, string $condition, array $bind = []) static 字段表达式查询
  24. * @method \think\db\Query when(mixed $condition, mixed $query, mixed $otherwise = null) static 条件查询
  25. * @method \think\db\Query join(mixed $join, mixed $condition = null, string $type = 'INNER') static JOIN查询
  26. * @method \think\db\Query view(mixed $join, mixed $field = null, mixed $on = null, string $type = 'INNER') static 视图查询
  27. * @method \think\db\Query field(mixed $field, boolean $except = false) static 指定查询字段
  28. * @method \think\db\Query fieldRaw(string $field, array $bind = []) static 指定查询字段
  29. * @method \think\db\Query union(mixed $union, boolean $all = false) static UNION查询
  30. * @method \think\db\Query limit(mixed $offset, integer $length = null) static 查询LIMIT
  31. * @method \think\db\Query order(mixed $field, string $order = null) static 查询ORDER
  32. * @method \think\db\Query orderRaw(string $field, array $bind = []) static 查询ORDER
  33. * @method \think\db\Query cache(mixed $key = null , integer $expire = null) static 设置查询缓存
  34. * @method \think\db\Query withAttr(string $name,callable $callback = null) static 使用获取器获取数据
  35. * @method mixed value(string $field) static 获取某个字段的值
  36. * @method array column(string $field, string $key = '') static 获取某个列的值
  37. * @method mixed find(mixed $data = null) static 查询单个记录
  38. * @method mixed select(mixed $data = null) static 查询多个记录
  39. * @method integer insert(array $data, boolean $replace = false, boolean $getLastInsID = false, string $sequence = null) static 插入一条记录
  40. * @method integer insertGetId(array $data, boolean $replace = false, string $sequence = null) static 插入一条记录并返回自增ID
  41. * @method integer insertAll(array $dataSet) static 插入多条记录
  42. * @method integer update(array $data) static 更新记录
  43. * @method integer delete(mixed $data = null) static 删除记录
  44. * @method boolean chunk(integer $count, callable $callback, string $column = null) static 分块获取数据
  45. * @method \Generator cursor(mixed $data = null) static 使用游标查找记录
  46. * @method mixed query(string $sql, array $bind = [], boolean $master = false, bool $pdo = false) static SQL查询
  47. * @method integer execute(string $sql, array $bind = [], boolean $fetch = false, boolean $getLastInsID = false, string $sequence = null) static SQL执行
  48. * @method \think\Paginator paginate(integer $listRows = 15, mixed $simple = null, array $config = []) static 分页查询
  49. * @method mixed transaction(callable $callback) static 执行数据库事务
  50. * @method void startTrans() static 启动事务
  51. * @method void commit() static 用于非自动提交状态下面的查询提交
  52. * @method void rollback() static 事务回滚
  53. * @method boolean batchQuery(array $sqlArray) static 批处理执行SQL语句
  54. * @method string getLastInsID(string $sequence = null) static 获取最近插入的ID
  55. */
  56. class Db
  57. {
  58. /**
  59. * 当前数据库连接对象
  60. * @var Connection
  61. */
  62. protected static $connection;
  63. /**
  64. * 数据库配置
  65. * @var array
  66. */
  67. protected static $config = [];
  68. /**
  69. * 查询次数
  70. * @var integer
  71. */
  72. public static $queryTimes = 0;
  73. /**
  74. * 执行次数
  75. * @var integer
  76. */
  77. public static $executeTimes = 0;
  78. /**
  79. * 配置
  80. * @access public
  81. * @param mixed $config
  82. * @return void
  83. */
  84. public static function init($config = [])
  85. {
  86. self::$config = $config;
  87. if (empty($config['query'])) {
  88. self::$config['query'] = '\\think\\db\\Query';
  89. }
  90. }
  91. /**
  92. * 获取数据库配置
  93. * @access public
  94. * @param string $config 配置名称
  95. * @return mixed
  96. */
  97. public static function getConfig($name = '')
  98. {
  99. if ('' === $name) {
  100. return self::$config;
  101. }
  102. return isset(self::$config[$name]) ? self::$config[$name] : null;
  103. }
  104. /**
  105. * 切换数据库连接
  106. * @access public
  107. * @param mixed $config 连接配置
  108. * @param bool|string $name 连接标识 true 强制重新连接
  109. * @param string $query 查询对象类名
  110. * @return mixed 返回查询对象实例
  111. * @throws Exception
  112. */
  113. public static function connect($config = [], $name = false, $query = '')
  114. {
  115. // 解析配置参数
  116. $options = self::parseConfig($config ?: self::$config);
  117. $query = $query ?: $options['query'];
  118. // 创建数据库连接对象实例
  119. self::$connection = Connection::instance($options, $name);
  120. return new $query(self::$connection);
  121. }
  122. /**
  123. * 数据库连接参数解析
  124. * @access private
  125. * @param mixed $config
  126. * @return array
  127. */
  128. private static function parseConfig($config)
  129. {
  130. if (is_string($config) && false === strpos($config, '/')) {
  131. // 支持读取配置参数
  132. $config = isset(self::$config[$config]) ? self::$config[$config] : self::$config;
  133. }
  134. $result = is_string($config) ? self::parseDsnConfig($config) : $config;
  135. if (empty($result['query'])) {
  136. $result['query'] = self::$config['query'];
  137. }
  138. return $result;
  139. }
  140. /**
  141. * DSN解析
  142. * 格式: mysql://username:passwd@localhost:3306/DbName?param1=val1&param2=val2#utf8
  143. * @access private
  144. * @param string $dsnStr
  145. * @return array
  146. */
  147. private static function parseDsnConfig($dsnStr)
  148. {
  149. $info = parse_url($dsnStr);
  150. if (!$info) {
  151. return [];
  152. }
  153. $dsn = [
  154. 'type' => $info['scheme'],
  155. 'username' => isset($info['user']) ? $info['user'] : '',
  156. 'password' => isset($info['pass']) ? $info['pass'] : '',
  157. 'hostname' => isset($info['host']) ? $info['host'] : '',
  158. 'hostport' => isset($info['port']) ? $info['port'] : '',
  159. 'database' => !empty($info['path']) ? ltrim($info['path'], '/') : '',
  160. 'charset' => isset($info['fragment']) ? $info['fragment'] : 'utf8',
  161. ];
  162. if (isset($info['query'])) {
  163. parse_str($info['query'], $dsn['params']);
  164. } else {
  165. $dsn['params'] = [];
  166. }
  167. return $dsn;
  168. }
  169. public static function __callStatic($method, $args)
  170. {
  171. return call_user_func_array([static::connect(), $method], $args);
  172. }
  173. }