DbMssql.Class.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. <?php
  2. namespace Mall\Framework\Db;
  3. class DbMssql
  4. {
  5. static $queries = 0;
  6. public $options = array();
  7. public $master = array();
  8. public $slaves = array();
  9. public $slave = array();
  10. public $slave_key;
  11. public $sql;
  12. public $dbname;
  13. public $prefix;
  14. public $charset;
  15. protected $_error;
  16. protected $_cmstop_charset;
  17. protected $_transaction_started;
  18. private $dbh;
  19. private $dbh_master;
  20. private $dbh_slave;
  21. function __construct($master = array(), $slaves = array())
  22. {
  23. $this->master = $master;
  24. $this->options = &$this->master;
  25. if ($slaves) $this->slaves = $slaves;
  26. // 禁止 SQL Server 进行日期格式转换
  27. ini_set('mssql.datetimeconvert', 0);
  28. // 统一编码格式
  29. $this->_cmstop_charset = $this->_normorlize_charset(config('config', 'charset'));
  30. }
  31. function __destruct()
  32. {
  33. if ($this->dbh) {
  34. mssql_close($this->dbh);
  35. }
  36. }
  37. function beginTransaction()
  38. {
  39. if (!$this->_transaction_started) {
  40. $result = $this->exec('BEGIN TRAN');
  41. $this->_transaction_started = true;
  42. return $result;
  43. }
  44. $this->_error = 'Transaction had already begin';
  45. return false;
  46. }
  47. function commit()
  48. {
  49. if ($this->_transaction_started) {
  50. $result = $this->exec('COMMIT TRAN');
  51. $this->_transaction_started = false;
  52. return $result;
  53. }
  54. $this->_error = 'No activied transaction';
  55. return false;
  56. }
  57. function rollBack()
  58. {
  59. if ($this->_transaction_started) {
  60. $result = $this->exec('ROLLBACK TRAN');
  61. $this->_transaction_started = false;
  62. return $result;
  63. }
  64. $this->_error = 'No activied transaction';
  65. return false;
  66. }
  67. function lastInsertId()
  68. {
  69. return $this->exec('SELECT SCOPE_IDENTITY()');
  70. }
  71. static function get_instance($master = array(), $slaves = array())
  72. {
  73. static $instance;
  74. $key = implode('', $master);
  75. if (!isset($instance[$key])) {
  76. $instance[$key] = new DbMssql($master, $slaves);
  77. }
  78. return $instance[$key];
  79. }
  80. function connect($options = array())
  81. {
  82. $host = value($options, 'host');
  83. $port = value($options, 'port');
  84. $dbname = value($options, 'dbname');
  85. $prefix = value($options, 'prefix', '');
  86. $charset = value($options, 'charset');
  87. $username = value($options, 'username');
  88. $password = value($options, 'password');
  89. $pconnect = value($options, 'pconnect');
  90. $handler = $pconnect ? 'mssql_pconnect' : 'mssql_connect';
  91. $server = $port ? ($host . (stripos(PHP_OS, 'win') === 0 ? ',' : ':') . $port) : $host;
  92. if (!function_exists($handler)) {
  93. throw new \Exception("SQL Server extension not enabled");
  94. }
  95. if (!($dbh = $handler($server, $username, $password))) {
  96. return false;
  97. }
  98. if (!$dbname) {
  99. $this->_error = 'No database name specialed';
  100. return false;
  101. }
  102. if (!mssql_select_db($dbname, $dbh)) {
  103. return false;
  104. }
  105. // 处理 SQL Server nchar,nvarchar ... 字段的问题
  106. mssql_query('SET TEXTSIZE 1024000', $dbh);
  107. $this->dbname = $dbname;
  108. $this->prefix = $prefix;
  109. // 统一编码格式
  110. $this->charset = $this->_normorlize_charset($charset);
  111. return $dbh;
  112. }
  113. private function connect_slave()
  114. {
  115. $this->slave_key = array_rand($this->slaves);
  116. $this->slave = $this->slaves[$this->slave_key];
  117. $this->dbh_slave = $this->connect($this->slave);
  118. if (!$this->dbh_slave && count($this->slaves) > 1) {
  119. unset($this->slaves[$this->slave_key]);
  120. return $this->connect_slave();
  121. }
  122. return $this->dbh_slave;
  123. }
  124. function exec($statement, $multiple = false)
  125. {
  126. if (!$this->dbh($statement)) return false;
  127. $query = mssql_query($this->_prepare_sql($this->sql), $this->dbh);
  128. if (!$query) {
  129. return false;
  130. }
  131. if (!is_resource($query)) {
  132. return $query;
  133. }
  134. if ($multiple) {
  135. $result = array();
  136. while ($row = mssql_fetch_assoc($query)) {
  137. $result[] = $row;
  138. }
  139. } else {
  140. $result = mssql_fetch_assoc($query);
  141. if (is_array($result)) {
  142. $result = array_shift(array_values($result));
  143. }
  144. }
  145. mssql_free_result($query);
  146. /*if ($this->charset != $this->_cmstop_charset)
  147. {
  148. $result = str_charset($this->charset, $this->_cmstop_charset, $result);
  149. }*/
  150. return $result;
  151. }
  152. function query($statement)
  153. {
  154. return $this->exec($statement);
  155. }
  156. function get($sql)
  157. {
  158. return $this->exec($sql);
  159. }
  160. function select($sql)
  161. {
  162. return $this->exec($sql, true);
  163. }
  164. function insert($sql)
  165. {
  166. return $this->exec($sql);
  167. }
  168. function update($sql)
  169. {
  170. return $this->exec($sql);
  171. }
  172. function replace($sql)
  173. {
  174. return $this->update($sql);
  175. }
  176. function delete($sql)
  177. {
  178. return $this->exec($sql);
  179. }
  180. function limit($sql, $limit = 0)
  181. {
  182. if ($limit
  183. && preg_match('/^SELECT\s+(.+)\s+FROM\s+(.+?)$/Usim', $sql, $matches)
  184. && !preg_match('/\bTOP\b/sim', $matches[1])
  185. ) {
  186. $fields = $matches[1];
  187. $from = $matches[2];
  188. $sql = "SELECT TOP $limit $fields FROM $from";
  189. }
  190. return $this->select($sql);
  191. }
  192. function select_db($dbname)
  193. {
  194. return $this->exec("USE $dbname");
  195. }
  196. function list_fields($table)
  197. {
  198. static $result = array();
  199. if (!is_array($result[$table])) {
  200. if ($fields = $this->select("
  201. SELECT [column_name], [data_type], [column_default], [is_nullable]
  202. FROM [information_schema].[tables] AS t
  203. JOIN [information_schema].[columns] AS c
  204. ON t.table_catalog = c.table_catalog
  205. AND t.table_schema = c.table_schema
  206. AND t.table_name = c.table_name
  207. WHERE t.table_name = '$table'")
  208. ) {
  209. foreach ($fields as $field) {
  210. $result[$table][$field['column_name']] = array(
  211. 'Field' => $field['column_name'],
  212. 'Type' => $field['data_type'],
  213. 'Null' => $field['is_nullable'] === '' ? 'NO' : 'YES',
  214. 'Key' => '',
  215. 'Default' => $field['column_default'],
  216. 'Extra' => ''
  217. );
  218. }
  219. }
  220. }
  221. return $result[$table];
  222. }
  223. function list_tables()
  224. {
  225. static $result;
  226. if (!is_array($result)) {
  227. if ($fields = $this->select("SELECT [TABLE_NAME] FROM [INFORMATION_SCHEMA].[TABLES] WHERE [TABLE_TYPE] = 'BASE TABLE'")) {
  228. foreach ($fields as $field) {
  229. $result[] = $field['TABLE_NAME'];
  230. }
  231. }
  232. }
  233. return $result;
  234. }
  235. function list_dbs()
  236. {
  237. static $result;
  238. if (!is_array($result)) {
  239. if ($fields = $this->select("SELECT [name] FROM [master]..[sysdatabases] WHERE [name] NOT IN ('master', 'model', 'msdb', 'tempdb') ORDER BY [name]")) {
  240. foreach ($fields as $field) {
  241. $result[] = $field['name'];
  242. }
  243. }
  244. }
  245. return $result;
  246. }
  247. function get_primary($table)
  248. {
  249. static $result = array();
  250. if (!in_array($result, $table)) {
  251. $primarys = array();
  252. foreach ($this->exec("EXEC sp_pkeys '$table'", true) as $primary) {
  253. $primarys[] = $primary['COLUMN_NAME'];
  254. }
  255. $result[$table] = implode(',', $primarys);
  256. }
  257. return $result[$table];
  258. }
  259. function field_type($table, $field)
  260. {
  261. static $result = array();
  262. $key = md5($table . $field);
  263. if (!is_array($result[$key])) {
  264. if ($fields = $this->select("SELECT [DATA_TYPE] FROM [INFORMATION_SCHEMA].[COLUMNS] WHERE [TABLE_NAME] = '$table' AND [COLUMN_NAME] = '$field'")) {
  265. foreach ($fields as $field) {
  266. $result[$key] = $field['DATA_TYPE'];
  267. }
  268. }
  269. }
  270. return $result[$key];
  271. }
  272. function version()
  273. {
  274. return $this->exec('SELECT @@VERSION');
  275. }
  276. function prefix()
  277. {
  278. return $this->master['prefix'];
  279. }
  280. function error()
  281. {
  282. if (is_null($this->_error)) {
  283. $this->_error = mssql_get_last_message();
  284. if ($this->_error && $this->charset != $this->_cmstop_charset) {
  285. $this->_error = str_charset($this->charset, $this->_cmstop_charset, $this->_error);
  286. }
  287. }
  288. return $this->_error;
  289. }
  290. protected function _prepare_sql($sql)
  291. {
  292. $this->sql = str_replace('#table_', $this->master['prefix'], trim($sql));
  293. $this->sql = preg_replace('/(`(\w*)`)/Usim', '[$2]', $this->sql);
  294. return $this->sql;
  295. }
  296. protected function _normorlize_charset($charset)
  297. {
  298. return strtolower(str_replace('-', '', $charset));
  299. }
  300. private function dbh($sql = null)
  301. {
  302. if (is_null($sql)) {
  303. $this->sql = null;
  304. if (is_null($this->dbh)) {
  305. if (is_null($this->dbh_master)) $this->dbh_master = $this->connect($this->master);
  306. $this->dbh = $this->dbh_master;
  307. }
  308. return $this->dbh;
  309. }
  310. self::$queries++;
  311. $this->sql = str_replace('#table_', $this->master['prefix'], trim($sql));
  312. if ($this->slaves && is_null($this->dbh_master) && stripos($this->sql, 'select') === 0) {
  313. if (is_null($this->dbh_slave)) $this->dbh_slave = $this->connect_slave();
  314. $this->dbh = $this->dbh_slave;
  315. } else {
  316. if (is_null($this->dbh_master)) $this->dbh_master = $this->connect($this->master);
  317. $this->dbh = $this->dbh_master;
  318. }
  319. return $this->dbh;
  320. }
  321. }