-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathDatabaseTestCase.php
More file actions
477 lines (399 loc) · 13 KB
/
DatabaseTestCase.php
File metadata and controls
477 lines (399 loc) · 13 KB
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2025 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace OCA\Tables\Tests\Unit\Database;
use OC\DB\Connection;
use OC\DB\ConnectionAdapter;
use OC\DB\ConnectionFactory;
use OC\DB\MigrationService;
use OC\Migration\NullOutput;
use OC\SystemConfig;
use OCP\DB\QueryBuilder\IQueryBuilder;
use OCP\Server;
use PHPUnit\Framework\TestCase;
/**
* Base class for tests that require database operations.
*/
abstract class DatabaseTestCase extends TestCase {
private static ?Connection $connectionStatic = null;
private static ?ConnectionAdapter $connectionAdapterStatic = null;
protected ?Connection $connection = null;
protected ?ConnectionAdapter $connectionAdapter = null;
protected function setUp(): void {
parent::setUp();
if (self::$connectionStatic === null) {
$envMode = getenv('TEST_MODE');
if ($envMode === 'local') {
self::$connectionStatic = $this->createInMemoryDatabase();
} else {
self::$connectionStatic = Server::get(Connection::class);
}
self::$connectionAdapterStatic = new ConnectionAdapter(self::$connectionStatic);
$this->applyMigrations();
}
$this->connection = self::$connectionStatic;
$this->connectionAdapter = self::$connectionAdapterStatic;
}
/**
* Creates SQLite database in memory
*/
private function createInMemoryDatabase(): Connection {
// Create mock SystemConfig for unit tests (without DI container)
$systemConfig = $this->createMock(SystemConfig::class);
$systemConfig->method('getValue')
->willReturnCallback(function ($key, $default = null) {
$testConfig = [
'dbtype' => 'sqlite',
];
return $testConfig[$key] ?? $default;
});
$connectionFactory = new ConnectionFactory($systemConfig);
$connectionParams = [
'path' => ':memory:',
'tablePrefix' => 'oc_',
];
return $connectionFactory->getConnection('sqlite', $connectionParams);
}
/**
* Applies all migrations to the database
*/
private function applyMigrations(): void {
$output = new NullOutput();
// Use MigrationService to apply migrations
$migrationService = new MigrationService('tables', self::$connectionStatic, $output);
// Apply all migrations to the latest version
$migrationService->migrate('latest');
}
/**
* Cleans up all tables_ tables for tests
*/
protected function cleanupTablesData(): void {
$qb = $this->connection->getQueryBuilder();
// Get all tables that start with 'tables_'
$tables = $this->connection->createSchema()->getTableNames();
$tablesToClean = array_map(function ($table) {
$table = substr($table, strpos($table, '.') + 1);
return str_replace($this->connection->getPrefix(), '', $table);
}, $tables);
$tablesToClean = array_filter($tablesToClean, function ($table) {
return strpos($table, 'tables_') === 0;
});
// Sort tables by deletion priority due to foreign key constraints
usort($tablesToClean, function ($tableA, $tableB) {
$getPriority = function ($table) {
// 1. row_cells tables (depend on row_sleeves and columns) - highest priority
if (strpos($table, 'tables_row_cells_') === 0) {
return 1;
}
// 2. row_sleeves (depend on tables)
if ($table === 'tables_row_sleeves') {
return 2;
}
// 3. columns (depend on tables)
if ($table === 'tables_columns') {
return 3;
}
// 4. tables (no dependencies)
if ($table === 'tables_tables') {
return 4;
}
// 5. Any other tables_ tables - lowest priority
return 5;
};
return $getPriority($tableA) - $getPriority($tableB);
});
// Delete all tables in the sorted order
foreach ($tablesToClean as $table) {
$qb->delete($table)->executeStatement();
}
}
/**
* Gets database connection
*/
protected function getConnection(): Connection {
return self::$connectionStatic;
}
/**
* Creates a test table with basic data
*/
protected function createTestTable(array $data = []) {
$defaultData = [
'title' => 'Test Table',
'ownership' => 'user1',
'created_by' => 'user1',
'created_at' => date('Y-m-d H:i:s'),
'last_edit_by' => 'user1',
'last_edit_at' => date('Y-m-d H:i:s'),
'description' => 'Test table description'
];
$testIdent = $data['test_ident'] ?? null;
unset($data['test_ident']); // Remove test_ident from data before insertion
$data = array_merge($defaultData, $data);
$qb = $this->connection->getQueryBuilder();
$qb->insert('tables_tables');
foreach ($data as $key => $value) {
$qb->setValue($key, $qb->createNamedParameter($value));
}
$qb->executeStatement();
$result = [
'id' => (int)$this->connection->lastInsertId(),
];
if ($testIdent !== null) {
$result['test_ident'] = $testIdent;
}
return $result;
}
/**
* Creates a test column
*/
protected function createTestColumn(int $tableId, array $data = []) {
$defaultData = [
'table_id' => $tableId,
'title' => 'Test Column',
'created_by' => 'user1',
'created_at' => date('Y-m-d H:i:s'),
'last_edit_by' => 'user1',
'last_edit_at' => date('Y-m-d H:i:s'),
'type' => 'text',
'subtype' => '',
'mandatory' => false,
'order_weight' => 0,
'number_prefix' => '',
'number_suffix' => '',
'text_default' => '',
'number_default' => null,
'datetime_default' => '',
'selection_default' => '',
'usergroup_default' => '',
];
$testIdent = $data['test_ident'] ?? null;
unset($data['test_ident']); // Remove test_ident from data before insertion
$data = array_merge($defaultData, $data);
$qb = $this->connection->getQueryBuilder();
$qb->insert('tables_columns');
foreach ($data as $key => $value) {
if ($key === 'mandatory') {
$qb->setValue($key, $qb->createNamedParameter($value, IQueryBuilder::PARAM_BOOL));
} else {
$qb->setValue($key, $qb->createNamedParameter($value));
}
}
$qb->executeStatement();
$result = [
'id' => (int)$this->connection->lastInsertId(),
];
if ($testIdent !== null) {
$result['test_ident'] = $testIdent;
}
return $result;
}
/**
* Creates a test row sleeve
*/
protected function createTestRow(int $tableId, array $data = []) {
$defaultData = [
'table_id' => $tableId,
'created_by' => 'user1',
'created_at' => date('Y-m-d H:i:s'),
'last_edit_by' => 'user1',
'last_edit_at' => date('Y-m-d H:i:s')
];
$testIdent = $data['test_ident'] ?? null;
unset($data['test_ident']); // Remove test_ident from data before insertion
$data = array_merge($defaultData, $data);
$qb = $this->connection->getQueryBuilder();
$qb->insert('tables_row_sleeves');
foreach ($data as $key => $value) {
$qb->setValue($key, $qb->createNamedParameter($value));
}
$qb->executeStatement();
$result = [
'id' => (int)$this->connection->lastInsertId(),
];
if ($testIdent !== null) {
$result['test_ident'] = $testIdent;
}
return $result;
}
/**
* Checks if a table exists in the database
*/
protected function tableExists(string $tableName): bool {
$schema = $this->connection->createSchema();
return $schema->hasTable($this->connection->getPrefix() . $tableName);
}
/**
* Gets the number of records in a table
*/
protected function getTableCount(string $tableName): int {
$qb = $this->connection->getQueryBuilder();
return (int)$qb->select($qb->func()->count('*'))
->from($tableName)
->executeQuery()
->fetchOne();
}
/**
* Creates a test row with cell data
*/
protected function createTestRowWithData(int $tableId, array $rowData = [], array $cellsData = [], array $columnMapping = []) {
$result = $this->createTestRow($tableId, $rowData);
// Extract the actual row ID from the result
$rowId = $result['id'];
if (!empty($cellsData)) {
$this->addCellsToRow($rowId, $cellsData, $columnMapping);
}
return $result;
}
/**
* Adds cell data to an existing row
*/
protected function addCellsToRow(int $rowId, array $cellsData, array $columnMapping = []): void {
foreach ($cellsData as $columnIdentifier => $value) {
// Convert test_ident to actual column ID if mapping is provided
if (is_string($columnIdentifier) && isset($columnMapping[$columnIdentifier])) {
$columnId = $columnMapping[$columnIdentifier];
} else {
$columnId = $columnIdentifier;
}
$this->insertCellData($rowId, $columnId, $value);
}
}
/**
* Inserts cell data into appropriate table based on column type
*/
protected function insertCellData(int $rowId, int $columnId, $value): void {
$qb = $this->connection->getQueryBuilder();
$result = $qb->select('type', 'subtype')
->from('tables_columns')
->where($qb->expr()->eq('id', $qb->createNamedParameter($columnId)))
->executeQuery();
$column = $result->fetch();
$result->closeCursor();
if (!$column) {
throw new \InvalidArgumentException("Column with ID $columnId not found");
}
$this->insertCellIntoTypeTable($rowId, $columnId, $value, $column['type'], $column['subtype']);
}
/**
* Inserts cell data into the appropriate type-specific table
*/
protected function insertCellIntoTypeTable(int $rowId, int $columnId, $value, string $columnType, string $columnSubtype): void {
$tableName = 'tables_row_cells_' . $columnType;
// Handle selection type - convert values to IDs based on selection_options
if ($columnType === 'selection' && $columnSubtype !== 'check') {
$value = $this->convertSelectionValuesToIds($columnId, $value);
}
$qb = $this->connection->getQueryBuilder();
$qb->insert($tableName)
->setValue('row_id', $qb->createNamedParameter($rowId))
->setValue('column_id', $qb->createNamedParameter($columnId))
->setValue('value', $qb->createNamedParameter($value))
->setValue('last_edit_at', $qb->createNamedParameter(date('Y-m-d H:i:s')))
->setValue('last_edit_by', $qb->createNamedParameter('user1'));
$qb->executeStatement();
}
/**
* Creates a complete test table with columns and rows with data
*/
protected function createCompleteTestTable(array $tableData = [], array $columnsData = [], array $rowsData = []): array {
$tableResult = $this->createTestTable($tableData);
$tableId = $tableResult['id'];
$columnResults = [];
foreach ($columnsData as $columnData) {
$columnResult = $this->createTestColumn($tableId, $columnData);
$columnResults[] = $columnResult;
}
// Create column mapping for test_ident -> id conversion
$columnMapping = [];
foreach ($columnResults as $columnResult) {
if (isset($columnResult['test_ident'])) {
$columnMapping[$columnResult['test_ident']] = $columnResult['id'];
}
}
$rowResults = [];
foreach ($rowsData as $rowData) {
$cellsData = $rowData['cells'] ?? [];
unset($rowData['cells']);
$rowResult = $this->createTestRowWithData($tableId, $rowData, $cellsData, $columnMapping);
$rowResults[] = $rowResult;
}
$result = [
'table' => $tableResult,
'columns' => $columnResults,
'rows' => $rowResults
];
return $result;
}
/**
* Extracts test_ident -> id mapping from creation results
* @param array $results Array of creation results
* @return array Mapping of test_ident => id
*/
protected function extractTestIdentMapping(array $results): array {
$mapping = [];
foreach ($results as $result) {
if (isset($result['test_ident'])) {
$mapping[$result['test_ident']] = $result['id'];
}
}
return $mapping;
}
/**
* Converts selection values to IDs based on selection_options
*/
protected function convertSelectionValuesToIds(int $columnId, $value) {
// Get column configuration to find selection_options
$qb = $this->connection->getQueryBuilder();
$result = $qb->select('selection_options')
->from('tables_columns')
->where($qb->expr()->eq('id', $qb->createNamedParameter($columnId)))
->executeQuery();
$selectionOptions = $result->fetchOne();
$result->closeCursor();
if (!$selectionOptions) {
throw new \InvalidArgumentException("Column with ID $columnId not found");
}
$selectionOptions = json_decode($selectionOptions, true);
// Create mapping from label to id
$optionMapping = [];
foreach ($selectionOptions as $option) {
if (isset($option['label']) && isset($option['id'])) {
$optionMapping[$option['label']] = $option['id'];
}
}
// Convert single value or array of values
if (is_array($value)) {
// Multiple selection - convert each value to ID and return as JSON
$convertedValues = [];
foreach ($value as $optionText) {
if (isset($optionMapping[$optionText])) {
$convertedValues[] = $optionMapping[$optionText];
}
}
return json_encode($convertedValues);
} else {
// Single selection - convert to ID
if (isset($optionMapping[$value])) {
return $optionMapping[$value];
}
return null;
}
}
/**
* Gets ID by test_ident from creation results
* @param array $results Array of creation results
* @param string $testIdent Test identifier to find
* @return int|null Returns ID if found, null otherwise
*/
protected function getIdByTestIdent(array $results, string $testIdent): ?int {
foreach ($results as $result) {
if (isset($result['test_ident']) && $result['test_ident'] === $testIdent) {
return $result['id'];
}
}
return null;
}
}