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

DbPdoSQLite::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
 * PDO SQLite Database Support
16
 *
17
 * @category   Kumbia
18
 * @package    Db
19
 * @subpackage Adapters
20
 * @copyright  Copyright (c) 2005 - 2017 Kumbia Team (http://www.kumbiaphp.com)
21
 * @license    http://wiki.kumbiaphp.com/Licencia     New BSD License
22
 */
23
/**
24
 * @see DbPdo Padre de Drivers Pdo
25
 */
26
require_once CORE_PATH . 'libs/db/adapters/pdo.php';
27
28
/**
29
 * PDO SQLite Database Support
30
 *
31
 * @category   Kumbia
32
 * @package    Db
33
 * @subpackage Adapters
34
 */
35
class DbPdoSQLite extends DbPDO
36
{
37
38
    /**
39
     * Nombre de RBDM
40
     */
41
    protected $db_rbdm = "sqlite";
42
43
    /**
44
     * Tipo de Dato Integer
45
     *
46
     */
47
    const TYPE_INTEGER = "INTEGER";
48
49
    /**
50
     * Tipo de Dato Date
51
     *
52
     */
53
    const TYPE_DATE = "DATE";
54
55
    /**
56
     * Tipo de Dato Varchar
57
     *
58
     */
59
    const TYPE_VARCHAR = "VARCHAR";
60
61
    /**
62
     * Tipo de Dato Decimal
63
     *
64
     */
65
    const TYPE_DECIMAL = "DECIMAL";
66
67
    /**
68
     * Tipo de Dato Datetime
69
     *
70
     */
71
    const TYPE_DATETIME = "DATETIME";
72
73
    /**
74
     * Tipo de Dato Char
75
     *
76
     */
77
    const TYPE_CHAR = "CHAR";
78
79
    /**
80
     * Ejecuta acciones de incializacion del driver
81
     *
82
     */
83
    public function initialize()
84
    {
85
86
    }
87
88
    /**
89
     * Verifica si una tabla existe o no
90
     *
91
     * @param string $table
92
     * @return boolean
93
     */
94
    public function table_exists($table, $schema='')
95
    {
96
        $table = strtolower($table);
97
        $num = $this->fetch_one("SELECT COUNT(*) FROM sqlite_master WHERE name = '$table'");
98
        return $num[0];
99
    }
100
101
    /**
102
     * Devuelve un LIMIT valido para un SELECT del RBDM
103
     *
104
     * @param string $sql consulta sql
105
     * @return string
106
     */
107
    public function limit($sql)
108
    {
109
        $params = Util::getParams(func_get_args());
110
        $sql_new = $sql;
111
112
        if (isset($params['limit']) && is_numeric($params['limit'])) {
113
            $sql_new.=" LIMIT $params[limit]";
114
        }
115
116
        if (isset($params['offset']) && is_numeric($params['offset'])) {
117
            $sql_new.=" OFFSET $params[offset]";
118
        }
119
120
        return $sql_new;
121
    }
122
123
    /**
124
     * Borra una tabla de la base de datos
125
     *
126
     * @param string $table
127
     * @return boolean
128
     */
129
    public function drop_table($table, $if_exists=true)
130
    {
131
        if ($if_exists) {
132
            return $this->query("DROP TABLE IF EXISTS $table");
133
        }
134
        return $this->query("DROP TABLE $table");
135
    }
136
137
    /**
138
     * Crea una tabla utilizando SQL nativo del RDBM
139
     *
140
     * TODO:
141
     * - Falta que el parametro index funcione. Este debe listar indices compuestos multipes y unicos
142
     * - Agregar el tipo de tabla que debe usarse (MySQL)
143
     * - Soporte para campos autonumericos
144
     * - Soporte para llaves foraneas
145
     *
146
     * @param string $table
147
     * @param array $definition
148
     * @return boolean
149
     */
150
    public function create_table($table, $definition, $index=array())
151
    {
152
        $create_sql = "CREATE TABLE $table (";
153
        if (!is_array($definition)) {
154
            throw new KumbiaException("Definici&oacute;n invalida para crear la tabla '$table'");
155
        }
156
        $create_lines = array();
157
        $index = array();
158
        $unique_index = array();
159
        $primary = array();
160
        //$not_null = "";
161
        //$size = "";
162
        foreach ($definition as $field => $field_def) {
163
            if (isset($field_def['not_null'])) {
164
                $not_null = $field_def['not_null'] ? 'NOT NULL' : '';
165
            } else {
166
                $not_null = "";
167
            }
168
            if (isset($field_def['size'])) {
169
                $size = $field_def['size'] ? '(' . $field_def['size'] . ')' : '';
170
            } else {
171
                $size = "";
172
            }
173
            if (isset($field_def['index'])) {
174
                if ($field_def['index']) {
175
                    $index[] = "INDEX($field)";
176
                }
177
            }
178
            if (isset($field_def['unique_index'])) {
179
                if ($field_def['unique_index']) {
180
                    $index[] = "UNIQUE($field)";
181
                }
182
            }
183
            if (isset($field_def['primary'])) {
184
                if ($field_def['primary']) {
185
                    $primary[] = "$field";
186
                }
187
            }
188
            if (isset($field_def['auto'])) {
189
                if ($field_def['auto']) {
190
                    $not_null = "";
191
                }
192
            }
193
            if (isset($field_def['extra'])) {
194
                $extra = $field_def['extra'];
195
            } else {
196
                $extra = "";
197
            }
198
            $create_lines[] = "$field " . $field_def['type'] . $size . ' ' . $not_null . ' ' . $extra;
199
        }
200
        $create_sql.= join(',', $create_lines);
201
        $last_lines = array();
202
        if (count($primary)) {
203
            $last_lines[] = 'PRIMARY KEY(' . join(",", $primary) . ')';
204
        }
205
        if (count($index)) {
206
            $last_lines[] = join(',', $index);
207
        }
208
        if (count($unique_index)) {
209
            $last_lines[] = join(',', $unique_index);
210
        }
211
        if (count($last_lines)) {
212
            $create_sql.= ',' . join(',', $last_lines) . ')';
213
        }
214
        return $this->exec($create_sql);
215
    }
216
217
    /**
218
     * Listar las tablas en la base de datos
219
     *
220
     * @return array
221
     */
222
    public function list_tables()
223
    {
224
        return $this->fetch_all("SELECT name FROM sqlite_master WHERE type='table' " .
225
                "UNION ALL SELECT name FROM sqlite_temp_master " .
226
                "WHERE type='table' ORDER BY name");
227
    }
228
229
    /**
230
     * Listar los campos de una tabla
231
     *
232
     * @param string $table
233
     * @return array
234
     */
235
    public function describe_table($table, $schema='')
236
    {
237
        $fields = array();
238
        if (!$schema) {
239
            $results = $this->fetch_all("PRAGMA table_info($table)", self::DB_ASSOC);
240
        } else {
241
            $results = $this->fetch_all("PRAGMA table_info($schema.$table)", self::DB_ASSOC);
242
        }
243
        foreach ($results as $field) {
244
            $fields[] = array(
245
                "Field" => $field["name"],
246
                "Type" => $field["type"],
247
                "Null" => $field["notnull"] == 99 ? "YES" : "NO",
248
                "Key" => $field['pk'] == 1 ? "PRI" : ""
249
            );
250
        }
251
        return $fields;
252
    }
253
254
}
255