PageRenderTime 35ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/Library/Kumbia/Db/Adapters/Pdo/Mssql.php

http://kumbia-enterprise.googlecode.com/
PHP | 299 lines | 153 code | 23 blank | 123 comment | 31 complexity | 762682edb3bc10e6f7a330dccddee1e8 MD5 | raw file
  1. <?php
  2. /**
  3. * Kumbia Enterprise Framework
  4. *
  5. * LICENSE
  6. *
  7. * This source file is subject to the New BSD License that is bundled
  8. * with this package in the file docs/LICENSE.txt.
  9. *
  10. * If you did not receive a copy of the license and are unable to
  11. * obtain it through the world-wide-web, please send an email
  12. * to license@loudertechnology.com so we can send you a copy immediately.
  13. *
  14. * @category Kumbia
  15. * @package Db
  16. * @subpackage PDOAdapters
  17. * @copyright Copyright (c) 2008-2009 Louder Technology COL. (http://www.loudertechnology.com)
  18. * @copyright Copyright (c) 2005-2009 Andres Felipe Gutierrez (gutierrezandresfelipe at gmail.com)
  19. * @license New BSD License
  20. * @version $Id: Mssql.php 124 2010-03-08 08:55:28Z gutierrezandresfelipe $
  21. */
  22. /**
  23. * PDO Microsoft SQL Server Database Support
  24. *
  25. * Estas funciones permiten acceder a MS SQL Server usando PDO ODBC
  26. *
  27. * @category Kumbia
  28. * @package Db
  29. * @subpackage PDOAdapters
  30. * @copyright Copyright (c) 2008-2009 Louder Technology COL. (http://www.loudertechnology.com)
  31. * @copyright Copyright (c) 2005-2009 Andres Felipe Gutierrez (gutierrezandresfelipe at gmail.com)
  32. * @license New BSD License
  33. * @link http://www.php.net/manual/es/ref.mysql.php
  34. * @access Public
  35. *
  36. */
  37. class DbPdoMsSQL extends DbPDO {
  38. /**
  39. * Nombre del Driver RBDM
  40. */
  41. protected $_dbRBDM = 'odbc';
  42. /**
  43. * Tipo de Dato Integer
  44. *
  45. */
  46. const TYPE_INTEGER = 'INTEGER';
  47. /**
  48. * Tipo de Dato Date
  49. *
  50. */
  51. const TYPE_DATE = 'SMALLDATETIME';
  52. /**
  53. * Tipo de Dato Varchar
  54. *
  55. */
  56. const TYPE_VARCHAR = 'VARCHAR';
  57. /**
  58. * Tipo de Dato Decimal
  59. *
  60. */
  61. const TYPE_DECIMAL = 'DECIMAL';
  62. /**
  63. * Tipo de Dato Datetime
  64. *
  65. */
  66. const TYPE_DATETIME = 'DATETIME';
  67. /**
  68. * Tipo de Dato Char
  69. *
  70. */
  71. const TYPE_CHAR = 'CHAR';
  72. /**
  73. * Ejecuta acciones de incializacion del driver
  74. *
  75. */
  76. public function initialize(){
  77. }
  78. /**
  79. * Verifica si una tabla existe o no
  80. *
  81. * @param string $table
  82. * @param string $schema
  83. * @return boolean
  84. */
  85. public function tableExists($table, $schema=''){
  86. $table = strtolower($table);
  87. $fetchMode = $this->_fetchMode;
  88. $this->setFetchMode(DbBase::DB_NUM);
  89. $num = $this->fetchOne('SELECT COUNT(*) FROM sysobjects WHERE type = \'U\' AND name = \'$table\'');
  90. $this->setFetchMode($fetchMode);
  91. return (bool)$num[0];
  92. }
  93. /**
  94. * Devuelve un LIMIT valido para un SELECT del RBDM
  95. *
  96. * @param integer $number
  97. * @return string
  98. */
  99. public function limit($sql, $number){
  100. if(!is_numeric($number)){
  101. return $sql;
  102. }
  103. $orderby = stristr($sql, 'ORDER BY');
  104. if($orderby!==false){
  105. $sort = (stripos($orderby, 'desc') !== false) ? 'desc' : 'asc';
  106. $order = str_ireplace('ORDER BY', '', $orderby);
  107. $order = trim(preg_replace('/ASC|DESC/i', '', $order));
  108. }
  109. $sql = preg_replace('/^SELECT\s/i', 'SELECT TOP '.($number).' ', $sql);
  110. $sql = 'SELECT * FROM (SELECT TOP '.$number. ' * FROM ('.$sql.') AS itable';
  111. if($orderby !== false) {
  112. $sql.= ' ORDER BY '.$order.' ';
  113. $sql.= (stripos($sort, 'asc') !== false) ? 'DESC' : 'ASC';
  114. }
  115. $sql.= ') AS otable';
  116. if ($orderby!==false) {
  117. $sql.=' ORDER BY '.$order.' '.$sort;
  118. }
  119. return $sql;
  120. }
  121. /**
  122. * Borra una tabla de la base de datos
  123. *
  124. * @param string $table
  125. * @param boolean $ifExists
  126. * @return boolean
  127. */
  128. public function dropTable($table, $ifExists=true){
  129. if($ifExists==true){
  130. if($this->tableExists($table)==true){
  131. return $this->query("DROP TABLE $table");
  132. } else {
  133. return true;
  134. }
  135. } else {
  136. return $this->query("DROP TABLE $table");
  137. }
  138. }
  139. /**
  140. * Crea una tabla utilizando SQL nativo del RDBM
  141. *
  142. * @param string $table
  143. * @param array $definition
  144. * @return boolean
  145. */
  146. public function createTable($table, $definition, $index=array()){
  147. $create_sql = "CREATE TABLE $table (";
  148. if(!is_array($definition)){
  149. new DbException("Definici?n invalida para crear la tabla '$table'");
  150. return false;
  151. }
  152. $create_lines = array();
  153. $index = array();
  154. $unique_index = array();
  155. $primary = array();
  156. $not_null = "";
  157. $size = "";
  158. foreach($definition as $field => $field_def){
  159. if(isset($field_def['not_null'])){
  160. $not_null = $field_def['not_null'] ? 'NOT NULL' : '';
  161. } else {
  162. $not_null = "";
  163. }
  164. if(isset($field_def['size'])){
  165. $size = $field_def['size'] ? '('.$field_def['size'].')' : '';
  166. } else {
  167. $size = "";
  168. }
  169. if(isset($field_def['index'])){
  170. if($field_def['index']){
  171. $index[] = "INDEX($field)";
  172. }
  173. }
  174. if(isset($field_def['unique_index'])){
  175. if($field_def['unique_index']){
  176. $index[] = "UNIQUE($field)";
  177. }
  178. }
  179. if(isset($field_def['primary'])){
  180. if($field_def['primary']){
  181. $primary[] = "$field";
  182. }
  183. }
  184. if(isset($field_def['auto'])){
  185. if($field_def['auto']){
  186. $field_def['extra'] = isset($field_def['extra']) ? $field_def['extra']." IDENTITY" : "IDENTITY";
  187. }
  188. }
  189. if(isset($field_def['extra'])){
  190. $extra = $field_def['extra'];
  191. } else {
  192. $extra = "";
  193. }
  194. $create_lines[] = "$field ".$field_def['type'].$size.' '.$not_null.' '.$extra;
  195. }
  196. $create_sql.= join(',', $create_lines);
  197. $last_lines = array();
  198. if(count($primary)){
  199. $last_lines[] = 'PRIMARY KEY('.join(",", $primary).')';
  200. }
  201. if(count($index)){
  202. $last_lines[] = join(',', $index);
  203. }
  204. if(count($unique_index)){
  205. $last_lines[] = join(',', $unique_index);
  206. }
  207. if(count($last_lines)){
  208. $create_sql.= ','.join(',', $last_lines).')';
  209. }
  210. return $this->query($create_sql);
  211. }
  212. /**
  213. * Listar las tablas en la base de datos
  214. *
  215. * @return array
  216. */
  217. public function listTables(){
  218. return $this->fetchAll("SELECT name FROM sysobjects WHERE type = 'U' ORDER BY name");
  219. }
  220. /**
  221. * Listar los campos de una tabla
  222. *
  223. * @param string $table
  224. * @return array
  225. */
  226. public function describeTable($table, $schema=''){
  227. $describeTable = $this->fetchAll("exec sp_columns @table_name = '$table'");
  228. $finalDescribe = array();
  229. foreach($describeTable as $field){
  230. $finalDescribe[] = array(
  231. 'Field' => $field['COLUMN_NAME'],
  232. 'Type' => $field['LENGTH'] ? $field['TYPE_NAME'] : $field['TYPE_NAME'].'('.$field['LENGTH'].')',
  233. 'Null' => $field['NULLABLE'] == 1 ? 'YES' : 'NO'
  234. );
  235. }
  236. $describeKeys = $this->fetchAll("exec sp_pkeys @table_name = '$table'");
  237. foreach($describeKeys as $field){
  238. for($i=0;$i<=count($finalDescribe)-1;++$i){
  239. if($finalDescribe[$i]['Field']==$field['COLUMN_NAME']){
  240. $finalDescribe[$i]['Key'] = 'PRI';
  241. } else {
  242. $finalDescribe[$i]['Key'] = "";
  243. }
  244. }
  245. }
  246. return $finalDescribe;
  247. }
  248. /**
  249. * Indica si requiere secuencias para reemplazar columnas identidad
  250. *
  251. * @param string $tableName
  252. * @param string $identityColumn
  253. * @param string $sequenceName
  254. * @return boolean
  255. */
  256. public function getRequiredSequence($tableName='', $identityColumn='', $sequenceName=''){
  257. return false;
  258. }
  259. /**
  260. * Indica las extensiones PHP requeridas para utilizar el adaptador
  261. *
  262. * @return string
  263. */
  264. public static function getPHPExtensionRequired(){
  265. return 'pdo_odbc';
  266. }
  267. /**
  268. * Devuelve el SQL Dialect que debe ser usado
  269. *
  270. * @return string
  271. * @static
  272. */
  273. public static function getSQLDialect(){
  274. return null;
  275. }
  276. }