Db.php 6.7 KB

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