Completed
Branch master (024767)
by Henry Stivens
01:51
created

DbPdoOracle::create_table()   F

Complexity

Conditions 20
Paths > 20000

Size

Total Lines 66
Code Lines 45

Duplication

Lines 66
Ratio 100 %

Importance

Changes 0
Metric Value
cc 20
eloc 45
nc 23345
nop 3
dl 66
loc 66
rs 2.774
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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