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

DbPdoMySQL::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 MySQL Database Support
28
 *
29
 * @category   Kumbia
30
 * @package    Db
31
 * @subpackage Adapters
32
 */
33
class DbPdoMySQL extends DbPDO
34
{
35
36
    /**
37
     * Nombre de RBDM
38
     */
39
    protected $db_rbdm = "mysql";
40
    /**
41
     * Puerto de Conexión a MySQL
42
     *
43
     * @var integer
44
     */
45
    protected $db_port = 3306;
46
47
    /**
48
     * Tipo de Dato Integer
49
     *
50
     */
51
    const TYPE_INTEGER = "INTEGER";
52
53
    /**
54
     * Tipo de Dato Date
55
     *
56
     */
57
    const TYPE_DATE = "DATE";
58
59
    /**
60
     * Tipo de Dato Varchar
61
     *
62
     */
63
    const TYPE_VARCHAR = "VARCHAR";
64
65
    /**
66
     * Tipo de Dato Decimal
67
     *
68
     */
69
    const TYPE_DECIMAL = "DECIMAL";
70
71
    /**
72
     * Tipo de Dato Datetime
73
     *
74
     */
75
    const TYPE_DATETIME = "DATETIME";
76
77
    /**
78
     * Tipo de Dato Char
79
     *
80
     */
81
    const TYPE_CHAR = "CHAR";
82
83
    /**
84
     * Ejecuta acciones de incialización del driver
85
     *
86
     */
87
    public function initialize()
88
    {
89
90
    }
91
92
    /**
93
     * Verifica si una tabla existe o no
94
     *
95
     * @param string $table
96
     * @return boolean
97
     */
98
    public function table_exists($table, $schema='')
99
    {
100
        $table = addslashes("$table");
101
        if ($schema == '') {
102
            $num = $this->fetch_one("SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '$table'");
103
        } else {
104
            $schema = addslashes("$schema");
105
            $num = $this->fetch_one("SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '$table' AND TABLE_SCHEMA = '$schema'");
106
        }
107
        return $num[0];
108
    }
109
110
    /**
111
     * Devuelve un LIMIT valido para un SELECT del RBDM
112
     *
113
     * @param string $sql consulta sql
114
     * @return string
115
     */
116
    public function limit($sql)
117
    {
118
        $params = Util::getParams(func_get_args());
119
        $sql_new = $sql;
120
121
        if (isset($params['limit']) && is_numeric($params['limit'])) {
122
            $sql_new.=" LIMIT $params[limit]";
123
        }
124
125
        if (isset($params['offset']) && is_numeric($params['offset'])) {
126
            $sql_new.=" OFFSET $params[offset]";
127
        }
128
129
        return $sql_new;
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
            return $this->query("DROP TABLE IF EXISTS $table");
142
        } else {
143
            return $this->query("DROP TABLE $table");
144
        }
145
    }
146
147
    /**
148
     * Crea una tabla utilizando SQL nativo del RDBM
149
     *
150
     * TODO:
151
     * - Falta que el parámetro index funcione. Este debe listar índices compuestos múltipes y únicos
152
     * - Agregar el tipo de tabla que debe usarse (MySQL)
153
     * - Soporte para campos autonumericos
154
     * - Soporte para llaves foraneas
155
     *
156
     * @param string $table
157
     * @param array $definition
158
     * @return boolean
159
     */
160
    public function create_table($table, $definition, $index=array())
161
    {
162
        $create_sql = "CREATE TABLE $table (";
163
        if (!is_array($definition)) {
164
            throw new KumbiaException("Definici&oacute;n invalida para crear la tabla '$table'");
165
        }
166
        $create_lines = array();
167
        $index = array();
168
        $unique_index = array();
169
        $primary = array();
170
        //$not_null = "";
171
        //$size = "";
172
        foreach ($definition as $field => $field_def) {
173
            if (isset($field_def['not_null'])) {
174
                $not_null = $field_def['not_null'] ? 'NOT NULL' : '';
175
            } else {
176
                $not_null = "";
177
            }
178
            if (isset($field_def['size'])) {
179
                $size = $field_def['size'] ? '(' . $field_def['size'] . ')' : '';
180
            } else {
181
                $size = "";
182
            }
183
            if (isset($field_def['index'])) {
184
                if ($field_def['index']) {
185
                    $index[] = "INDEX(`$field`)";
186
                }
187
            }
188
            if (isset($field_def['unique_index'])) {
189
                if ($field_def['unique_index']) {
190
                    $index[] = "UNIQUE(`$field`)";
191
                }
192
            }
193
            if (isset($field_def['primary'])) {
194
                if ($field_def['primary']) {
195
                    $primary[] = "`$field`";
196
                }
197
            }
198
            if (isset($field_def['auto'])) {
199
                if ($field_def['auto']) {
200
                    $field_def['extra'] = isset($field_def['extra']) ? $field_def['extra'] . " AUTO_INCREMENT" : "AUTO_INCREMENT";
201
                }
202
            }
203
            if (isset($field_def['extra'])) {
204
                $extra = $field_def['extra'];
205
            } else {
206
                $extra = "";
207
            }
208
            $create_lines[] = "`$field` " . $field_def['type'] . $size . ' ' . $not_null . ' ' . $extra;
209
        }
210
        $create_sql.= join(',', $create_lines);
211
        $last_lines = array();
212
        if (count($primary)) {
213
            $last_lines[] = 'PRIMARY KEY(' . join(",", $primary) . ')';
214
        }
215
        if (count($index)) {
216
            $last_lines[] = join(',', $index);
217
        }
218
        if (count($unique_index)) {
219
            $last_lines[] = join(',', $unique_index);
220
        }
221
        if (count($last_lines)) {
222
            $create_sql.= ',' . join(',', $last_lines) . ')';
223
        }
224
        return $this->query($create_sql);
225
    }
226
227
    /**
228
     * Listar las tablas en la base de datos
229
     *
230
     * @return array
231
     */
232
    public function list_tables()
233
    {
234
        return $this->fetch_all("SHOW TABLES");
235
    }
236
237
    /**
238
     * Listar los campos de una tabla
239
     *
240
     * @param string $table
241
     * @return array
242
     */
243
    public function describe_table($table, $schema='')
244
    {
245
        if ($schema == '') {
246
            $describe = $this->fetch_all("DESCRIBE `$table`");
247
        } else {
248
            $describe = $this->fetch_all("DESCRIBE `$schema`.`$table`");
249
        }
250
        $final_describe = array();
251
        foreach ($describe as $key => $value) {
252
            $final_describe[] = array(
253
                "Field" => $value["field"],
254
                "Type" => $value["type"],
255
                "Null" => $value["null"],
256
                "Key" => $value["key"]
257
            );
258
        }
259
        return $final_describe;
260
    }
261
262
}
263