forked from codeigniter4/CodeIgniter4
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathShowTableInfo.php
285 lines (230 loc) · 7.46 KB
/
ShowTableInfo.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <[email protected]>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Commands\Database;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;
use CodeIgniter\Database\BaseConnection;
use Config\Database;
/**
* Get table data if it exists in the database.
*
* @see \CodeIgniter\Commands\Database\ShowTableInfoTest
*/
class ShowTableInfo extends BaseCommand
{
/**
* The group the command is lumped under
* when listing commands.
*
* @var string
*/
protected $group = 'Database';
/**
* The Command's name
*
* @var string
*/
protected $name = 'db:table';
/**
* the Command's short description
*
* @var string
*/
protected $description = 'Retrieves information on the selected table.';
/**
* the Command's usage
*
* @var string
*/
protected $usage = <<<'EOL'
db:table [<table_name>] [options]
Examples:
db:table --show
db:table --metadata
db:table my_table --metadata
db:table my_table
db:table my_table --limit-rows 5 --limit-field-value 10 --desc
EOL;
/**
* The Command's arguments
*
* @var array<string, string>
*/
protected $arguments = [
'table_name' => 'The table name to show info',
];
/**
* The Command's options
*
* @var array<string, string>
*/
protected $options = [
'--show' => 'Lists the names of all database tables.',
'--metadata' => 'Retrieves list containing field information.',
'--desc' => 'Sorts the table rows in DESC order.',
'--limit-rows' => 'Limits the number of rows. Default: 10.',
'--limit-field-value' => 'Limits the length of field values. Default: 15.',
];
/**
* @var list<list<int|string>> Table Data.
*/
private array $tbody;
private BaseConnection $db;
/**
* @var bool Sort the table rows in DESC order or not.
*/
private bool $sortDesc = false;
private string $DBPrefix;
public function run(array $params)
{
$this->db = Database::connect();
$this->DBPrefix = $this->db->getPrefix();
$tables = $this->db->listTables();
if (array_key_exists('desc', $params)) {
$this->sortDesc = true;
}
if ($tables === []) {
CLI::error('Database has no tables!', 'light_gray', 'red');
CLI::newLine();
return;
}
if (array_key_exists('show', $params)) {
$this->showAllTables($tables);
return;
}
$tableName = $params[0] ?? null;
$limitRows = (int) ($params['limit-rows'] ?? 10);
$limitFieldValue = (int) ($params['limit-field-value'] ?? 15);
while (! in_array($tableName, $tables, true)) {
$tableNameNo = CLI::promptByKey(
['Here is the list of your database tables:', 'Which table do you want to see?'],
$tables,
'required'
);
CLI::newLine();
$tableName = $tables[$tableNameNo] ?? null;
}
if (array_key_exists('metadata', $params)) {
$this->showFieldMetaData($tableName);
return;
}
$this->showDataOfTable($tableName, $limitRows, $limitFieldValue);
}
private function removeDBPrefix(): void
{
$this->db->setPrefix('');
}
private function restoreDBPrefix(): void
{
$this->db->setPrefix($this->DBPrefix);
}
private function showDataOfTable(string $tableName, int $limitRows, int $limitFieldValue)
{
CLI::write("Data of Table \"{$tableName}\":", 'black', 'yellow');
CLI::newLine();
$this->removeDBPrefix();
$thead = $this->db->getFieldNames($tableName);
$this->restoreDBPrefix();
// If there is a field named `id`, sort by it.
$sortField = null;
if (in_array('id', $thead, true)) {
$sortField = 'id';
}
$this->tbody = $this->makeTableRows($tableName, $limitRows, $limitFieldValue, $sortField);
CLI::table($this->tbody, $thead);
}
private function showAllTables(array $tables)
{
CLI::write('The following is a list of the names of all database tables:', 'black', 'yellow');
CLI::newLine();
$thead = ['ID', 'Table Name', 'Num of Rows', 'Num of Fields'];
$this->tbody = $this->makeTbodyForShowAllTables($tables);
CLI::table($this->tbody, $thead);
CLI::newLine();
}
private function makeTbodyForShowAllTables(array $tables): array
{
$this->removeDBPrefix();
foreach ($tables as $id => $tableName) {
$table = $this->db->protectIdentifiers($tableName);
$db = $this->db->query("SELECT * FROM {$table}");
$this->tbody[] = [
$id + 1,
$tableName,
$db->getNumRows(),
$db->getFieldCount(),
];
}
$this->restoreDBPrefix();
if ($this->sortDesc) {
krsort($this->tbody);
}
return $this->tbody;
}
private function makeTableRows(
string $tableName,
int $limitRows,
int $limitFieldValue,
?string $sortField = null
): array {
$this->tbody = [];
$this->removeDBPrefix();
$builder = $this->db->table($tableName);
$builder->limit($limitRows);
if ($sortField !== null) {
$builder->orderBy($sortField, $this->sortDesc ? 'DESC' : 'ASC');
}
$rows = $builder->get()->getResultArray();
$this->restoreDBPrefix();
foreach ($rows as $row) {
$row = array_map(
static fn ($item): string => mb_strlen((string) $item) > $limitFieldValue
? mb_substr((string) $item, 0, $limitFieldValue) . '...'
: (string) $item,
$row
);
$this->tbody[] = $row;
}
if ($sortField === null && $this->sortDesc) {
krsort($this->tbody);
}
return $this->tbody;
}
private function showFieldMetaData(string $tableName): void
{
CLI::write("List of Metadata Information in Table \"{$tableName}\":", 'black', 'yellow');
CLI::newLine();
$thead = ['Field Name', 'Type', 'Max Length', 'Nullable', 'Default', 'Primary Key'];
$this->removeDBPrefix();
$fields = $this->db->getFieldData($tableName);
$this->restoreDBPrefix();
foreach ($fields as $row) {
$this->tbody[] = [
$row->name,
$row->type,
$row->max_length,
isset($row->nullable) ? $this->setYesOrNo($row->nullable) : 'n/a',
$row->default,
isset($row->primary_key) ? $this->setYesOrNo($row->primary_key) : 'n/a',
];
}
if ($this->sortDesc) {
krsort($this->tbody);
}
CLI::table($this->tbody, $thead);
}
private function setYesOrNo(bool $fieldValue): string
{
if ($fieldValue) {
return CLI::color('Yes', 'green');
}
return CLI::color('No', 'red');
}
}