Db.php 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  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. use think\db\Query;
  14. /**
  15. * Class Db
  16. * @package think
  17. * @method Query table(string $table) static 指定数据表(含前缀)
  18. * @method static Query raw($value)
  19. * @method Query name(string $name) static 指定数据表(不含前缀)
  20. * @method Query where(mixed $field, string $op = null, mixed $condition = null) static 查询条件
  21. * @method Query join(mixed $join, mixed $condition = null, string $type = 'INNER') static JOIN查询
  22. * @method Query union(mixed $union, boolean $all = false) static UNION查询
  23. * @method Query limit(mixed $offset, integer $length = null) static 查询LIMIT
  24. * @method Query order(mixed $field, string $order = null) static 查询ORDER
  25. * @method Query cache(mixed $key = null , integer $expire = null) static 设置查询缓存
  26. * @method mixed value(string $field) static 获取某个字段的值
  27. * @method array column(string $field, string $key = '') static 获取某个列的值
  28. * @method Query view(mixed $join, mixed $field = null, mixed $on = null, string $type = 'INNER') static 视图查询
  29. * @method mixed find(mixed $data = null) static 查询单个记录
  30. * @method mixed select(mixed $data = null) static 查询多个记录
  31. * @method integer insert(array $data, boolean $replace = false, boolean $getLastInsID = false, string $sequence = null) static 插入一条记录
  32. * @method integer insertGetId(array $data, boolean $replace = false, string $sequence = null) static 插入一条记录并返回自增ID
  33. * @method integer insertAll(array $dataSet) static 插入多条记录
  34. * @method integer update(array $data) static 更新记录
  35. * @method integer delete(mixed $data = null) static 删除记录
  36. * @method boolean chunk(integer $count, callable $callback, string $column = null) static 分块获取数据
  37. * @method mixed query(string $sql, array $bind = [], boolean $master = false, bool $pdo = false) static SQL查询
  38. * @method integer execute(string $sql, array $bind = [], boolean $fetch = false, boolean $getLastInsID = false, string $sequence = null) static SQL执行
  39. * @method Paginator paginate(integer $listRows = 15, mixed $simple = null, array $config = []) static 分页查询
  40. * @method mixed transaction(callable $callback) static 执行数据库事务
  41. * @method void startTrans() static 启动事务
  42. * @method void commit() static 用于非自动提交状态下面的查询提交
  43. * @method void rollback() static 事务回滚
  44. * @method boolean batchQuery(array $sqlArray) static 批处理执行SQL语句
  45. * @method string quote(string $str) static SQL指令安全过滤
  46. * @method string getLastInsID($sequence = null) static 获取最近插入的ID
  47. */
  48. class Db
  49. {
  50. /**
  51. * @var Connection[] 数据库连接实例
  52. */
  53. private static $instance = [];
  54. /**
  55. * @var int 查询次数
  56. */
  57. public static $queryTimes = 0;
  58. /**
  59. * @var int 执行次数
  60. */
  61. public static $executeTimes = 0;
  62. /**
  63. * 数据库初始化,并取得数据库类实例
  64. * @access public
  65. * @param mixed $config 连接配置
  66. * @param bool|string $name 连接标识 true 强制重新连接
  67. * @return Connection
  68. * @throws Exception
  69. */
  70. public static function connect($config = [], $name = false)
  71. {
  72. if (false === $name) {
  73. $name = md5(serialize($config));
  74. }
  75. if (true === $name || !isset(self::$instance[$name])) {
  76. // 解析连接参数 支持数组和字符串
  77. $options = self::parseConfig($config);
  78. if (empty($options['type'])) {
  79. throw new \InvalidArgumentException('Undefined db type');
  80. }
  81. $class = false !== strpos($options['type'], '\\') ?
  82. $options['type'] :
  83. '\\think\\db\\connector\\' . ucwords($options['type']);
  84. // 记录初始化信息
  85. if (App::$debug) {
  86. Log::record('[ DB ] INIT ' . $options['type'], 'info');
  87. }
  88. if (true === $name) {
  89. $name = md5(serialize($config));
  90. }
  91. self::$instance[$name] = new $class($options);
  92. }
  93. return self::$instance[$name];
  94. }
  95. /**
  96. * 清除连接实例
  97. * @access public
  98. * @return void
  99. */
  100. public static function clear()
  101. {
  102. self::$instance = [];
  103. }
  104. /**
  105. * 数据库连接参数解析
  106. * @access private
  107. * @param mixed $config 连接参数
  108. * @return array
  109. */
  110. private static function parseConfig($config)
  111. {
  112. if (empty($config)) {
  113. $config = Config::get('database');
  114. } elseif (is_string($config) && false === strpos($config, '/')) {
  115. $config = Config::get($config); // 支持读取配置参数
  116. }
  117. return is_string($config) ? self::parseDsn($config) : $config;
  118. }
  119. /**
  120. * DSN 解析
  121. * 格式: mysql://username:passwd@localhost:3306/DbName?param1=val1&param2=val2#utf8
  122. * @access private
  123. * @param string $dsnStr 数据库 DSN 字符串解析
  124. * @return array
  125. */
  126. private static function parseDsn($dsnStr)
  127. {
  128. $info = parse_url($dsnStr);
  129. if (!$info) {
  130. return [];
  131. }
  132. $dsn = [
  133. 'type' => $info['scheme'],
  134. 'username' => isset($info['user']) ? $info['user'] : '',
  135. 'password' => isset($info['pass']) ? $info['pass'] : '',
  136. 'hostname' => isset($info['host']) ? $info['host'] : '',
  137. 'hostport' => isset($info['port']) ? $info['port'] : '',
  138. 'database' => !empty($info['path']) ? ltrim($info['path'], '/') : '',
  139. 'charset' => isset($info['fragment']) ? $info['fragment'] : 'utf8',
  140. ];
  141. if (isset($info['query'])) {
  142. parse_str($info['query'], $dsn['params']);
  143. } else {
  144. $dsn['params'] = [];
  145. }
  146. return $dsn;
  147. }
  148. /**
  149. * 调用驱动类的方法
  150. * @access public
  151. * @param string $method 方法名
  152. * @param array $params 参数
  153. * @return mixed
  154. */
  155. public static function __callStatic($method, $params)
  156. {
  157. return call_user_func_array([self::connect(), $method], $params);
  158. }
  159. }