PageRenderTime 32ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/core/libs/db/adapters/pdo/oracle.php

http://github.com/KumbiaPHP/KumbiaPHP
PHP | 265 lines | 134 code | 23 blank | 108 comment | 27 complexity | 67f5b5fe3a7fb1fa6018d7f0c448a882 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. <?php
  2. /**
  3. * KumbiaPHP web & app 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 LICENSE.
  9. *
  10. * @category Kumbia
  11. * @package Db
  12. * @subpackage PDO Adapters
  13. *
  14. * @copyright Copyright (c) 2005 - 2020 KumbiaPHP Team (http://www.kumbiaphp.com)
  15. * @license https://github.com/KumbiaPHP/KumbiaPHP/blob/master/LICENSE New BSD License
  16. */
  17. /**
  18. * @see DbPdo Padre de Drivers Pdo
  19. */
  20. require_once CORE_PATH.'libs/db/adapters/pdo.php';
  21. /**
  22. * PDO Oracle Database Support.
  23. *
  24. * @category Kumbia
  25. */
  26. class DbPdoOracle extends DbPDO
  27. {
  28. /**
  29. * Nombre de RBDM.
  30. */
  31. protected $db_rbdm = 'oci';
  32. /**
  33. * Tipo de Dato Integer.
  34. */
  35. const TYPE_INTEGER = 'INTEGER';
  36. /**
  37. * Tipo de Dato Date.
  38. */
  39. const TYPE_DATE = 'DATE';
  40. /**
  41. * Tipo de Dato Varchar.
  42. */
  43. const TYPE_VARCHAR = 'VARCHAR2';
  44. /**
  45. * Tipo de Dato Decimal.
  46. */
  47. const TYPE_DECIMAL = 'DECIMAL';
  48. /**
  49. * Tipo de Dato Datetime.
  50. */
  51. const TYPE_DATETIME = 'DATETIME';
  52. /**
  53. * Tipo de Dato Char.
  54. */
  55. const TYPE_CHAR = 'CHAR';
  56. /**
  57. * Ejecuta acciones de incializacion del driver.
  58. */
  59. public function initialize()
  60. {
  61. $this->pdo->setAttribute(PDO::ATTR_AUTOCOMMIT, false);
  62. $this->exec("alter session set nls_date_format = 'YYYY-MM-DD'");
  63. $this->begin();
  64. }
  65. /**
  66. * Devuelve un LIMIT valido para un SELECT del RBDM.
  67. *
  68. * @param int $number
  69. *
  70. * @return string
  71. */
  72. public function limit($sql, $number)
  73. {
  74. if (!is_numeric($number) || $number < 0) {
  75. return $sql;
  76. }
  77. if (preg_match("/ORDER[\t\n\r ]+BY/i", $sql)) {
  78. if (stripos($sql, 'WHERE')) {
  79. return preg_replace("/ORDER[\t\n\r ]+BY/i", "AND ROWNUM <= $number ORDER BY", $sql);
  80. }
  81. return preg_replace("/ORDER[\t\n\r ]+BY/i", "WHERE ROWNUM <= $number ORDER BY", $sql);
  82. }
  83. if (stripos($sql, 'WHERE')) {
  84. return "$sql AND ROWNUM <= $number";
  85. }
  86. return "$sql WHERE ROWNUM <= $number";
  87. }
  88. /**
  89. * Borra una tabla de la base de datos.
  90. *
  91. * @param string $table
  92. *
  93. * @return bool
  94. */
  95. public function drop_table($table, $if_exists = true)
  96. {
  97. if ($if_exists) {
  98. if ($this->table_exists($table)) {
  99. return $this->query("DROP TABLE $table");
  100. }
  101. return true;
  102. }
  103. return $this->query("DROP TABLE $table");
  104. }
  105. /**
  106. * Crea una tabla utilizando SQL nativo del RDBM.
  107. *
  108. * TODO:
  109. * - Falta que el parametro index funcione. Este debe listar indices compuestos multipes y unicos
  110. * - Agregar el tipo de tabla que debe usarse (Oracle)
  111. * - Soporte para campos autonumericos
  112. * - Soporte para llaves foraneas
  113. *
  114. * @param string $table
  115. * @param array $definition
  116. * @param array $index
  117. *
  118. * @return bool
  119. */
  120. public function create_table($table, $definition, $index = [])
  121. {
  122. $create_sql = "CREATE TABLE $table (";
  123. if (!is_array($definition)) {
  124. throw new KumbiaException("Definición inválida para crear la tabla '$table'");
  125. }
  126. $create_lines = [];
  127. $index = [];
  128. $unique_index = [];
  129. $primary = [];
  130. //$not_null = "";
  131. //$size = "";
  132. foreach ($definition as $field => $field_def) {
  133. if (isset($field_def['not_null'])) {
  134. $not_null = $field_def['not_null'] ? 'NOT NULL' : '';
  135. } else {
  136. $not_null = '';
  137. }
  138. if (isset($field_def['size'])) {
  139. $size = $field_def['size'] ? '('.$field_def['size'].')' : '';
  140. } else {
  141. $size = '';
  142. }
  143. if (isset($field_def['index']) && $field_def['index']) {
  144. $index[] = "INDEX($field)";
  145. }
  146. if (isset($field_def['unique_index']) && $field_def['unique_index']) {
  147. $index[] = "UNIQUE($field)";
  148. }
  149. if (isset($field_def['primary']) && $field_def['primary']) {
  150. $primary[] = "$field";
  151. }
  152. if (isset($field_def['auto']) && $field_def['auto']) {
  153. $this->query("CREATE SEQUENCE {$table}_{$field}_seq START WITH 1");
  154. }
  155. $extra = isset($field_def['extra']) ? $field_def['extra'] : '';
  156. $create_lines[] = "$field ".$field_def['type'].$size.' '.$not_null.' '.$extra;
  157. }
  158. $create_sql .= join(',', $create_lines);
  159. $last_lines = [];
  160. if (count($primary)) {
  161. $last_lines[] = 'PRIMARY KEY('.join(',', $primary).')';
  162. }
  163. if (count($index)) {
  164. $last_lines[] = join(',', $index);
  165. }
  166. if (count($unique_index)) {
  167. $last_lines[] = join(',', $unique_index);
  168. }
  169. if (count($last_lines)) {
  170. $create_sql .= ','.join(',', $last_lines).')';
  171. }
  172. return $this->query($create_sql);
  173. }
  174. /**
  175. * Listado de Tablas.
  176. *
  177. * @return bool
  178. */
  179. public function list_tables()
  180. {
  181. return $this->fetch_all('SELECT table_name FROM all_tables');
  182. }
  183. /**
  184. * Devuelve el ultimo id autonumerico generado en la BD.
  185. *
  186. * @return int
  187. */
  188. public function last_insert_id($table = '', $primary_key = '')
  189. {
  190. /*
  191. * Oracle No soporta columnas autonum&eacute;ricas
  192. */
  193. if ($table && $primary_key) {
  194. $sequence = $table.'_'.$primary_key.'_seq';
  195. $value = $this->fetch_one("SELECT $sequence.CURRVAL FROM dual");
  196. return $value[0];
  197. }
  198. return false;
  199. }
  200. /**
  201. * Verifica si una tabla existe o no.
  202. *
  203. * @param string $table
  204. *
  205. * @return bool
  206. */
  207. public function table_exists($table, $schema = '')
  208. {
  209. return $this->fetch_one("SELECT COUNT(*) FROM ALL_TABLES WHERE TABLE_NAME = '".strtoupper($table)."'")[0];
  210. }
  211. /**
  212. * Listar los campos de una tabla.
  213. *
  214. * @param string $table
  215. *
  216. * @return array
  217. */
  218. public function describe_table($table, $schema = '')
  219. {
  220. /**
  221. * Soporta schemas?
  222. */
  223. $describe = $this->fetch_all("SELECT LOWER(ALL_TAB_COLUMNS.COLUMN_NAME) AS FIELD,
  224. LOWER(ALL_TAB_COLUMNS.DATA_TYPE) AS TYPE,
  225. ALL_TAB_COLUMNS.DATA_LENGTH AS LENGTH, (
  226. SELECT COUNT(*)
  227. FROM ALL_CONS_COLUMNS
  228. WHERE TABLE_NAME = '".strtoupper($table)."' AND ALL_CONS_COLUMNS.COLUMN_NAME = ALL_TAB_COLUMNS.COLUMN_NAME AND ALL_CONS_COLUMNS.POSITION IS NOT NULL) AS KEY, ALL_TAB_COLUMNS.NULLABLE AS ISNULL FROM ALL_TAB_COLUMNS
  229. WHERE ALL_TAB_COLUMNS.TABLE_NAME = '".strtoupper($table)."'");
  230. $final_describe = [];
  231. foreach ($describe as $field) {
  232. $final_describe[] = array(
  233. 'Field' => $field['field'],
  234. 'Type' => $field['type'],
  235. 'Length' => $field['length'],
  236. 'Null' => $field['isnull'] === 'Y' ? 'YES' : 'NO',
  237. 'Key' => $field['key'] == 1 ? 'PRI' : '',
  238. );
  239. }
  240. return $final_describe;
  241. }
  242. }