Completed
Push — master ( 49228f...024767 )
by Henry Stivens
02:39
created

DbPdoAccess::create_table()   F

Complexity

Conditions 21
Paths > 20000

Size

Total Lines 66
Code Lines 45

Duplication

Lines 66
Ratio 100 %

Importance

Changes 0
Metric Value
cc 21
eloc 45
nc 31121
nop 3
dl 66
loc 66
rs 2.79
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 Microsoft SQL Server Database Support
28
 *
29
 * @category   Kumbia
30
 * @package    Db
31
 * @subpackage Adapters
32
 */
33
class DbPdoAccess extends DbPDO
34
{
35
36
    /**
37
     * Nombre del Driver RBDM
38
     */
39
    protected $db_rbdm = "odbc";
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 = "DATETIME";
52
53
    /**
54
     * Tipo de Dato Varchar
55
     *
56
     */
57
    const TYPE_VARCHAR = "VARCHAR";
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
        /**
84
         * Permite insertar valores en columnas identidad
85
         */
86
        //$this->exec("SET IDENTITY_INSERT ON");
87
    }
88
89
    /**
90
     * Verifica si una tabla existe o no
91
     *
92
     * @param string $table
93
     * @return boolean
94
     */
95
    public function table_exists($table, $schema='')
96
    {
97
        $table = addslashes("$table");
98
        $num = $this->fetch_one("SELECT COUNT(*) FROM sysobjects WHERE type = 'U' AND name = '$table'");
99
        return $num[0];
100
    }
101
102
    /**
103
     * Devuelve un LIMIT valido para un SELECT del RBDM
104
     *
105
     * @param integer $number
106
     * @return string
107
     */
108
    public function limit($sql, $number)
109
    {
110
        if (!is_numeric($number)) {
111
            return $sql;
112
        }
113
        $orderby = stristr($sql, 'ORDER BY');
114
        if ($orderby !== false) {
115
            $sort = (stripos($orderby, 'desc') !== false) ? 'desc' : 'asc';
116
            $order = str_ireplace('ORDER BY', '', $orderby);
117
            $order = trim(preg_replace('/ASC|DESC/i', '', $order));
118
        }
119
        $sql = preg_replace('/^SELECT\s/i', 'SELECT TOP ' . ($number) . ' ', $sql);
120
        $sql = 'SELECT * FROM (SELECT TOP ' . $number . ' * FROM (' . $sql . ') AS itable';
121
        if ($orderby !== false) {
122
            $sql.= ' ORDER BY ' . $order . ' ';
123
            $sql.= ( stripos($sort, 'asc') !== false) ? 'DESC' : 'ASC';
124
        }
125
        $sql.= ') AS otable';
126
        if ($orderby !== false) {
127
            $sql.=' ORDER BY ' . $order . ' ' . $sort;
128
        }
129
        return $sql;
130
    }
131
132
    /**
133
     * Borra una tabla de la base de datos
134
     *
135
     * @param string $table
136
     * @return boolean
137
     */
138
    public function drop_table($table, $if_exists=true)
139
    {
140
        if ($if_exists) {
141
            if ($this->table_exists($table)) {
142
                return $this->query("DROP TABLE $table");
143
            } else {
144
                return true;
145
            }
146
        } else {
147
            return $this->query("DROP TABLE $table");
148
        }
149
    }
150
151
    /**
152
     * Crea una tabla utilizando SQL nativo del RDBM
153
     *
154
     * TODO:
155
     * - Falta que el parametro index funcione. Este debe listar indices compuestos multipes y unicos
156
     * - Agregar el tipo de tabla que debe usarse (MySQL)
157
     * - Soporte para campos autonumericos
158
     * - Soporte para llaves foraneas
159
     *
160
     * @param string $table
161
     * @param array $definition
162
     * @return boolean
163
     */
164
    public function create_table($table, $definition, $index=array())
165
    {
166
        $create_sql = "CREATE TABLE $table (";
167
        if (!is_array($definition)) {
168
            throw new KumbiaException("Definición inválida para crear la tabla '$table'");
169
        }
170
        $create_lines = array();
171
        $index = array();
172
        $unique_index = array();
173
        $primary = array();
174
        //$not_null = "";
175
        //$size = "";
176
        foreach ($definition as $field => $field_def) {
177
            if (isset($field_def['not_null'])) {
178
                $not_null = $field_def['not_null'] ? 'NOT NULL' : '';
179
            } else {
180
                $not_null = "";
181
            }
182
            if (isset($field_def['size'])) {
183
                $size = $field_def['size'] ? '(' . $field_def['size'] . ')' : '';
184
            } else {
185
                $size = "";
186
            }
187
            if (isset($field_def['index'])) {
188
                if ($field_def['index']) {
189
                    $index[] = "INDEX($field)";
190
                }
191
            }
192
            if (isset($field_def['unique_index'])) {
193
                if ($field_def['unique_index']) {
194
                    $index[] = "UNIQUE($field)";
195
                }
196
            }
197
            if (isset($field_def['primary'])) {
198
                if ($field_def['primary']) {
199
                    $primary[] = "$field";
200
                }
201
            }
202
            if (isset($field_def['auto'])) {
203
                if ($field_def['auto']) {
204
                    $field_def['extra'] = isset($field_def['extra']) ? $field_def['extra'] . " IDENTITY" : "IDENTITY";
205
                }
206
            }
207
            if (isset($field_def['extra'])) {
208
                $extra = $field_def['extra'];
209
            } else {
210
                $extra = "";
211
            }
212
            $create_lines[] = "$field " . $field_def['type'] . $size . ' ' . $not_null . ' ' . $extra;
213
        }
214
        $create_sql.= join(',', $create_lines);
215
        $last_lines = array();
216
        if (count($primary)) {
217
            $last_lines[] = 'PRIMARY KEY(' . join(",", $primary) . ')';
218
        }
219
        if (count($index)) {
220
            $last_lines[] = join(',', $index);
221
        }
222
        if (count($unique_index)) {
223
            $last_lines[] = join(',', $unique_index);
224
        }
225
        if (count($last_lines)) {
226
            $create_sql.= ',' . join(',', $last_lines) . ')';
227
        }
228
        return $this->query($create_sql);
229
    }
230
231
    /**
232
     * Listar las tablas en la base de datos
233
     *
234
     * @return array
235
     */
236
    public function list_tables()
237
    {
238
        return $this->fetch_all("SELECT name FROM sysobjects WHERE type = 'U' ORDER BY name");
239
    }
240
241
    /**
242
     * Listar los campos de una tabla
243
     *
244
     * @param string $table
245
     * @return array
246
     */
247
    public function describe_table($table, $schema='')
248
    {
249
        $describe_table = $this->fetch_all("exec sp_columns @table_name = '$table'");
250
        $final_describe = array();
251
        foreach ($describe_table as $field) {
252
            $final_describe[] = array(
253
                "Field" => $field["COLUMN_NAME"],
254
                "Type" => $field['LENGTH'] ? $field["TYPE_NAME"] : $field["TYPE_NAME"] . "(" . $field['LENGTH'] . ")",
255
                "Null" => $field['NULLABLE'] == 1 ? "YES" : "NO"
256
            );
257
        }
258
        $describe_keys = $this->fetch_all("exec sp_pkeys @table_name = '$table'");
259
        foreach ($describe_keys as $field) {
260
            for ($i = 0; $i <= count($final_describe) - 1; $i++) {
261
                if ($final_describe[$i]['Field'] == $field['COLUMN_NAME']) {
262
                    $final_describe[$i]['Key'] = 'PRI';
263
                } else {
264
                    $final_describe[$i]['Key'] = "";
265
                }
266
            }
267
        }
268
        return $final_describe;
269
    }
270
271
    /**
272
     * Devuelve el ultimo id autonumerico generado en la BD
273
     *
274
     * @return integer
275
     */
276
    public function last_insert_id($table='', $primary_key='')
277
    {
278
        /**
279
         * Porque no funciona SELECT SCOPE_IDENTITY()?
280
         */
281
        $num = $this->fetch_one("SELECT MAX($primary_key) FROM $table");
282
        return (int) $num[0];
283
    }
284
285
}
286