-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy path04-seeds.php
More file actions
624 lines (550 loc) · 19.6 KB
/
04-seeds.php
File metadata and controls
624 lines (550 loc) · 19.6 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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
<?php
declare(strict_types=1);
/**
* Database Seeds Example
*
* This example demonstrates how to use database seeds to populate your database
* with initial or test data using the PDOdb seed system.
*/
require_once __DIR__ . '/../../vendor/autoload.php';
require_once __DIR__ . '/../helpers.php';
use tommyknocker\pdodb\seeds\SeedRunner;
// Get database connection
$db = createExampleDb();
$driver = getenv('PDODB_DRIVER') ?: 'mysql';
echo "=== Database Seeds Example ===\n";
echo "Driver: {$driver}\n\n";
// Set up seed path
$seedPath = __DIR__ . '/seeds';
if (!is_dir($seedPath)) {
mkdir($seedPath, 0755, true);
}
try {
// Clean up any existing seed files first
cleanupSeedFiles($seedPath);
// Create seed runner
$runner = new SeedRunner($db, $seedPath);
echo "1. Creating example seed files...\n";
// Create users table seed
createUsersSeed($seedPath, $driver);
echo " ✓ Created users seed\n";
// Create categories seed
createCategoriesSeed($seedPath, $driver);
echo " ✓ Created categories seed\n";
// Create products seed
createProductsSeed($seedPath, $driver);
echo " ✓ Created products seed\n";
echo "\n2. Setting up database tables...\n";
// Create tables if they don't exist
$schema = $db->schema();
// Drop tables if they exist (for clean example)
// Disable foreign key checks temporarily (MySQL/MariaDB only)
if ($driver === 'mysql' || $driver === 'mariadb') {
$db->rawQuery('SET FOREIGN_KEY_CHECKS = 0');
}
// Drop in reverse order to avoid foreign key constraints
if ($schema->tableExists('products')) {
$schema->dropTable('products');
}
if ($schema->tableExists('categories')) {
$schema->dropTable('categories');
}
if ($schema->tableExists('users')) {
$schema->dropTable('users');
}
// Note: Don't drop __seeds table as it's needed for seed tracking
// Re-enable foreign key checks (MySQL/MariaDB only)
if ($driver === 'mysql' || $driver === 'mariadb') {
$db->rawQuery('SET FOREIGN_KEY_CHECKS = 1');
}
// Create users table
{
$createdAtDefault = $driver === 'oci' ? 'SYSTIMESTAMP' : 'CURRENT_TIMESTAMP';
$schema->createTable('users', [
'id' => $schema->primaryKey(),
'name' => $schema->string(100)->notNull(),
'email' => $schema->string(255)->notNull()->unique(),
'role' => $schema->string(50)->defaultValue('user'),
'created_at' => $schema->timestamp()->notNull()->defaultExpression($createdAtDefault),
]);
echo " ✓ Created users table\n";
}
// Create categories table
{
$createdAtDefault = $driver === 'oci' ? 'SYSTIMESTAMP' : 'CURRENT_TIMESTAMP';
$schema->createTable('categories', [
'id' => $schema->primaryKey(),
'name' => $schema->string(100)->notNull(),
'slug' => $schema->string(100)->notNull()->unique(),
'description' => $schema->text(),
'created_at' => $schema->timestamp()->notNull()->defaultExpression($createdAtDefault),
]);
echo " ✓ Created categories table\n";
}
// Create products table
{
// For SQLite and Oracle, foreign key must be in CREATE TABLE
if ($driver === 'sqlite' || $driver === 'oci') {
$createdAtDefault = $driver === 'oci' ? 'SYSTIMESTAMP' : 'CURRENT_TIMESTAMP';
$schema->createTable('products', [
'id' => $schema->primaryKey(),
'name' => $schema->string(200)->notNull(),
'category_id' => $schema->integer()->notNull(),
'price' => $schema->decimal(10, 2)->notNull(),
'description' => $schema->text(),
'in_stock' => $schema->boolean()->defaultValue(true),
'created_at' => $schema->timestamp()->notNull()->defaultExpression($createdAtDefault),
], [
'foreignKeys' => [
[
'name' => 'fk_products_category',
'columns' => ['category_id'],
'refTable' => 'categories',
'refColumns' => ['id'],
'onDelete' => 'CASCADE',
'onUpdate' => 'CASCADE',
],
],
]);
} else {
$schema->createTable('products', [
'id' => $schema->primaryKey(),
'name' => $schema->string(200)->notNull(),
'category_id' => $schema->integer()->notNull(),
'price' => $schema->decimal(10, 2)->notNull(),
'description' => $schema->text(),
'in_stock' => $schema->boolean()->defaultValue(true),
'created_at' => $schema->timestamp()->notNull()->defaultExpression('CURRENT_TIMESTAMP'),
]);
$schema->addForeignKey('fk_products_category', 'products', 'category_id', 'categories', 'id', 'CASCADE', 'CASCADE');
}
echo " ✓ Created products table\n";
}
echo "\n3. Listing available seeds...\n";
$allSeeds = $runner->getAllSeeds();
$executedSeeds = $runner->getExecutedSeeds();
$newSeeds = $runner->getNewSeeds();
foreach ($allSeeds as $seed) {
$status = in_array($seed, $executedSeeds, true) ? '[EXECUTED]' : '[PENDING]';
echo " {$status} {$seed}\n";
}
echo "\n Summary: " . count($allSeeds) . " total, " . count($executedSeeds) . " executed, " . count($newSeeds) . " pending\n";
echo "\n4. Running seeds...\n";
$executed = $runner->run();
if (!empty($executed)) {
echo " Successfully executed " . count($executed) . " seed(s):\n";
foreach ($executed as $seedName) {
echo " ✓ {$seedName}\n";
}
} else {
echo " No new seeds to run.\n";
}
echo "\n5. Checking seeded data...\n";
// Check users
$users = $db->find()->table('users')->get();
echo " Users: " . count($users) . " records\n";
foreach ($users as $user) {
echo " - {$user['name']} ({$user['email']}) - {$user['role']}\n";
}
// Check categories
$categories = $db->find()->table('categories')->get();
echo " Categories: " . count($categories) . " records\n";
foreach ($categories as $category) {
echo " - {$category['name']} ({$category['slug']})\n";
}
// Check products
$products = $db->find()->table('products')->get();
echo " Products: " . count($products) . " records\n";
foreach ($products as $product) {
$price = number_format((float)$product['price'], 2);
$stock = $product['in_stock'] ? 'In Stock' : 'Out of Stock';
// Get category name
$category = $db->find()->table('categories')->where('id', $product['category_id'])->first();
$categoryName = $category ? $category['name'] : 'Unknown';
echo " - {$product['name']} (\${$price}) - {$categoryName} - {$stock}\n";
}
echo "\n6. Demonstrating seed rollback...\n";
// Get seed history
$history = $runner->getSeedHistory(3);
if (!empty($history)) {
echo " Recent seeds:\n";
foreach ($history as $record) {
echo " - {$record['seed']} (batch {$record['batch']}) - {$record['executed_at']}\n";
}
// Rollback last batch
echo "\n Rolling back last batch...\n";
$rolledBack = $runner->rollback();
if (!empty($rolledBack)) {
echo " Successfully rolled back " . count($rolledBack) . " seed(s):\n";
foreach ($rolledBack as $seedName) {
echo " ✓ {$seedName}\n";
}
// Check data after rollback
$usersAfter = count($db->find()->table('users')->get());
$categoriesAfter = count($db->find()->table('categories')->get());
$productsAfter = count($db->find()->table('products')->get());
echo "\n Data after rollback:\n";
echo " Users: {$usersAfter} records\n";
echo " Categories: {$categoriesAfter} records\n";
echo " Products: {$productsAfter} records\n";
} else {
echo " No seeds to rollback.\n";
}
}
echo "\n7. Demonstrating dry-run mode...\n";
// Re-run seeds in dry-run mode
$runner->setDryRun(true);
$runner->run();
$queries = $runner->getCollectedQueries();
if (!empty($queries)) {
echo " SQL queries that would be executed:\n";
foreach (array_slice($queries, 0, 10) as $query) { // Show first 10 queries
if (trim($query) !== '') {
echo " " . trim($query) . "\n";
}
}
if (count($queries) > 10) {
echo " ... and " . (count($queries) - 10) . " more queries\n";
}
}
echo "\n✅ Seeds example completed successfully!\n";
} catch (Exception $e) {
echo "❌ Error: " . $e->getMessage() . "\n";
exit(1);
} finally {
// Clean up seed files
cleanupSeedFiles($seedPath);
}
/**
* Create users seed file.
*/
function createUsersSeed(string $seedPath, string $driver): void
{
$timestamp = date('YmdHis');
$filename = "s{$timestamp}_example_users_data.php";
$filepath = $seedPath . '/' . $filename;
// Oracle can use SYSTIMESTAMP directly or rely on DEFAULT
if ($driver === 'oci') {
$content = <<<'EOT'
<?php
declare(strict_types=1);
use tommyknocker\pdodb\seeds\Seed;
use tommyknocker\pdodb\helpers\Db;
class ExampleUsersDataSeed extends Seed
{
public function run(): void
{
$users = [
[
'name' => 'John Doe',
'email' => '[email protected]',
'role' => 'admin',
'created_at' => Db::raw('SYSTIMESTAMP'),
],
[
'name' => 'Jane Smith',
'email' => '[email protected]',
'role' => 'user',
'created_at' => Db::raw('SYSTIMESTAMP'),
],
[
'name' => 'Bob Johnson',
'email' => '[email protected]',
'role' => 'moderator',
'created_at' => Db::raw('SYSTIMESTAMP'),
],
];
$this->insertMulti('users', $users);
}
public function rollback(): void
{
$this->delete('users', ['email' => '[email protected]']);
$this->delete('users', ['email' => '[email protected]']);
$this->delete('users', ['email' => '[email protected]']);
}
}
EOT;
} else {
$content = <<<'PHP'
<?php
declare(strict_types=1);
use tommyknocker\pdodb\seeds\Seed;
class ExampleUsersDataSeed extends Seed
{
public function run(): void
{
$users = [
[
'name' => 'John Doe',
'email' => '[email protected]',
'role' => 'admin',
'created_at' => date('Y-m-d H:i:s'),
],
[
'name' => 'Jane Smith',
'email' => '[email protected]',
'role' => 'user',
'created_at' => date('Y-m-d H:i:s'),
],
[
'name' => 'Bob Johnson',
'email' => '[email protected]',
'role' => 'moderator',
'created_at' => date('Y-m-d H:i:s'),
],
];
$this->insertMulti('users', $users);
}
public function rollback(): void
{
$this->delete('users', ['email' => '[email protected]']);
$this->delete('users', ['email' => '[email protected]']);
$this->delete('users', ['email' => '[email protected]']);
}
}
PHP;
}
file_put_contents($filepath, $content);
sleep(1); // Ensure different timestamps
}
/**
* Create categories seed file.
*/
function createCategoriesSeed(string $seedPath, string $driver): void
{
$timestamp = date('YmdHis');
$filename = "s{$timestamp}_example_categories_data.php";
$filepath = $seedPath . '/' . $filename;
// Oracle can use SYSTIMESTAMP directly or rely on DEFAULT
if ($driver === 'oci') {
$content = <<<'EOT'
<?php
declare(strict_types=1);
use tommyknocker\pdodb\seeds\Seed;
use tommyknocker\pdodb\helpers\Db;
class ExampleCategoriesDataSeed extends Seed
{
public function run(): void
{
$categories = [
[
'name' => 'Electronics',
'slug' => 'electronics',
'description' => 'Electronic devices and gadgets',
'created_at' => Db::raw('SYSTIMESTAMP'),
],
[
'name' => 'Books',
'slug' => 'books',
'description' => 'Books and literature',
'created_at' => Db::raw('SYSTIMESTAMP'),
],
[
'name' => 'Clothing',
'slug' => 'clothing',
'description' => 'Apparel and fashion',
'created_at' => Db::raw('SYSTIMESTAMP'),
],
];
$this->insertMulti('categories', $categories);
}
public function rollback(): void
{
$this->delete('categories', ['slug' => 'electronics']);
$this->delete('categories', ['slug' => 'books']);
$this->delete('categories', ['slug' => 'clothing']);
}
}
EOT;
} else {
$content = <<<'PHP'
<?php
declare(strict_types=1);
use tommyknocker\pdodb\seeds\Seed;
class ExampleCategoriesDataSeed extends Seed
{
public function run(): void
{
$categories = [
[
'name' => 'Electronics',
'slug' => 'electronics',
'description' => 'Electronic devices and gadgets',
'created_at' => date('Y-m-d H:i:s'),
],
[
'name' => 'Books',
'slug' => 'books',
'description' => 'Books and literature',
'created_at' => date('Y-m-d H:i:s'),
],
[
'name' => 'Clothing',
'slug' => 'clothing',
'description' => 'Apparel and fashion',
'created_at' => date('Y-m-d H:i:s'),
],
];
$this->insertMulti('categories', $categories);
}
public function rollback(): void
{
$this->delete('categories', ['slug' => 'electronics']);
$this->delete('categories', ['slug' => 'books']);
$this->delete('categories', ['slug' => 'clothing']);
}
}
PHP;
}
file_put_contents($filepath, $content);
sleep(1); // Ensure different timestamps
}
/**
* Create products seed file.
*/
function createProductsSeed(string $seedPath, string $driver): void
{
$timestamp = date('YmdHis');
$filename = "s{$timestamp}_example_products_data.php";
$filepath = $seedPath . '/' . $filename;
// Oracle can use SYSTIMESTAMP directly or rely on DEFAULT
if ($driver === 'oci') {
$content = <<<'EOT'
<?php
declare(strict_types=1);
use tommyknocker\pdodb\seeds\Seed;
use tommyknocker\pdodb\helpers\Db;
class ExampleProductsDataSeed extends Seed
{
public function run(): void
{
// Get category IDs
$electronics = $this->find()->table('categories')->where('slug', 'electronics')->first();
$books = $this->find()->table('categories')->where('slug', 'books')->first();
$clothing = $this->find()->table('categories')->where('slug', 'clothing')->first();
if (!$electronics || !$books || !$clothing) {
throw new \Exception('Categories must be seeded first');
}
$products = [
[
'name' => 'Smartphone',
'category_id' => $electronics['id'],
'price' => 599.99,
'description' => 'Latest smartphone with advanced features',
'in_stock' => 1,
'created_at' => Db::raw('SYSTIMESTAMP'),
],
[
'name' => 'Laptop',
'category_id' => $electronics['id'],
'price' => 1299.99,
'description' => 'High-performance laptop for work and gaming',
'in_stock' => 1,
'created_at' => Db::raw('SYSTIMESTAMP'),
],
[
'name' => 'Programming Book',
'category_id' => $books['id'],
'price' => 49.99,
'description' => 'Learn programming with this comprehensive guide',
'in_stock' => 1,
'created_at' => Db::raw('SYSTIMESTAMP'),
],
[
'name' => 'T-Shirt',
'category_id' => $clothing['id'],
'price' => 19.99,
'description' => 'Comfortable cotton t-shirt',
'in_stock' => 0,
'created_at' => Db::raw('SYSTIMESTAMP'),
],
];
$this->insertMulti('products', $products);
}
public function rollback(): void
{
$this->delete('products', ['name' => 'Smartphone']);
$this->delete('products', ['name' => 'Laptop']);
$this->delete('products', ['name' => 'Programming Book']);
$this->delete('products', ['name' => 'T-Shirt']);
}
}
EOT;
} else {
$content = <<<'PHP'
<?php
declare(strict_types=1);
use tommyknocker\pdodb\seeds\Seed;
class ExampleProductsDataSeed extends Seed
{
public function run(): void
{
// Get category IDs
$electronics = $this->find()->table('categories')->where('slug', 'electronics')->first();
$books = $this->find()->table('categories')->where('slug', 'books')->first();
$clothing = $this->find()->table('categories')->where('slug', 'clothing')->first();
if (!$electronics || !$books || !$clothing) {
throw new \Exception('Categories must be seeded first');
}
$products = [
[
'name' => 'Smartphone',
'category_id' => $electronics['id'],
'price' => 599.99,
'description' => 'Latest smartphone with advanced features',
'in_stock' => 1,
'created_at' => date('Y-m-d H:i:s'),
],
[
'name' => 'Laptop',
'category_id' => $electronics['id'],
'price' => 1299.99,
'description' => 'High-performance laptop for work and gaming',
'in_stock' => 1,
'created_at' => date('Y-m-d H:i:s'),
],
[
'name' => 'Programming Book',
'category_id' => $books['id'],
'price' => 49.99,
'description' => 'Learn programming with this comprehensive guide',
'in_stock' => 1,
'created_at' => date('Y-m-d H:i:s'),
],
[
'name' => 'T-Shirt',
'category_id' => $clothing['id'],
'price' => 19.99,
'description' => 'Comfortable cotton t-shirt',
'in_stock' => 0,
'created_at' => date('Y-m-d H:i:s'),
],
];
$this->insertMulti('products', $products);
}
public function rollback(): void
{
$this->delete('products', ['name' => 'Smartphone']);
$this->delete('products', ['name' => 'Laptop']);
$this->delete('products', ['name' => 'Programming Book']);
$this->delete('products', ['name' => 'T-Shirt']);
}
}
PHP;
}
file_put_contents($filepath, $content);
}
/**
* Clean up seed files.
*/
function cleanupSeedFiles(string $seedPath): void
{
if (is_dir($seedPath)) {
$files = glob($seedPath . '/s*.php');
if ($files !== false) {
foreach ($files as $file) {
unlink($file);
}
}
}
}