-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy path01-macros.php
More file actions
273 lines (214 loc) · 7.21 KB
/
01-macros.php
File metadata and controls
273 lines (214 loc) · 7.21 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
<?php
/**
* Example: Query Builder Macros.
*
* Demonstrates custom query method macros for extending QueryBuilder.
*
* Usage:
* php examples/29-macros/01-macro-examples.php
* PDODB_DRIVER=mysql php examples/29-macros/01-macro-examples.php
* PDODB_DRIVER=pgsql php examples/29-macros/01-macro-examples.php
*/
require_once __DIR__ . '/../../vendor/autoload.php';
require_once __DIR__ . '/../helpers.php';
use tommyknocker\pdodb\helpers\Db;
use tommyknocker\pdodb\query\QueryBuilder;
$db = createExampleDb();
$driver = getCurrentDriver($db);
echo "=== Query Builder Macros Example (on $driver) ===\n\n";
// Create table using fluent API (cross-dialect)
$schema = $db->schema();
$schema->dropTableIfExists('products');
$schema->createTable('products', [
'id' => $schema->primaryKey(),
'name' => $schema->string(255)->notNull(),
'price' => $schema->decimal(10, 2)->notNull(),
'status' => $schema->string(50)->defaultValue('active'),
'category_id' => $schema->integer(),
'created_at' => $schema->timestamp()->defaultExpression('CURRENT_TIMESTAMP'),
]);
echo "✓ Table created\n\n";
// Example 1: Basic Macro Registration
echo "1. Basic Macro Registration\n";
echo "-----------------------------\n";
QueryBuilder::macro('active', function (QueryBuilder $query) {
return $query->where('status', 'active');
});
QueryBuilder::macro('inactive', function (QueryBuilder $query) {
return $query->where('status', 'inactive');
});
// Check if macro exists
echo "Macro 'active' exists: " . (QueryBuilder::hasMacro('active') ? 'Yes' : 'No') . "\n";
echo "Macro 'inactive' exists: " . (QueryBuilder::hasMacro('inactive') ? 'Yes' : 'No') . "\n";
// Use the macro
$db->find()->table('products')->insert([
'name' => 'Product 1',
'price' => 100.00,
'status' => 'active',
]);
$db->find()->table('products')->insert([
'name' => 'Product 2',
'price' => 200.00,
'status' => 'inactive',
]);
$activeProducts = $db->find()
->table('products')
->active()
->get();
echo "Active products: " . count($activeProducts) . "\n";
foreach ($activeProducts as $product) {
echo " - {$product['name']} (status: {$product['status']})\n";
}
echo "\n";
// Example 2: Macro with Arguments
echo "2. Macro with Arguments\n";
echo "------------------------\n";
QueryBuilder::macro('wherePrice', function (QueryBuilder $query, string $operator, float $price) {
return $query->where('price', $price, $operator);
});
QueryBuilder::macro('inCategory', function (QueryBuilder $query, int $categoryId) {
return $query->where('category_id', $categoryId);
});
// Insert test data
$db->find()->table('products')->insert([
'name' => 'Expensive Product',
'price' => 500.00,
'status' => 'active',
'category_id' => 1,
]);
$db->find()->table('products')->insert([
'name' => 'Cheap Product',
'price' => 50.00,
'status' => 'active',
'category_id' => 1,
]);
$db->find()->table('products')->insert([
'name' => 'Another Product',
'price' => 150.00,
'status' => 'active',
'category_id' => 2,
]);
// Use macros with arguments
$expensiveProducts = $db->find()
->table('products')
->wherePrice('>', 100.00)
->get();
echo "Products with price > 100: " . count($expensiveProducts) . "\n";
foreach ($expensiveProducts as $product) {
echo " - {$product['name']} (price: {$product['price']})\n";
}
$category1Products = $db->find()
->table('products')
->inCategory(1)
->get();
echo "\nProducts in category 1: " . count($category1Products) . "\n";
foreach ($category1Products as $product) {
echo " - {$product['name']}\n";
}
echo "\n";
// Example 3: Complex Macro with Multiple Conditions
echo "3. Complex Macro with Multiple Conditions\n";
echo "------------------------------------------\n";
QueryBuilder::macro('available', function (QueryBuilder $query) {
return $query
->where('status', 'active')
->andWhere('price', 0, '>');
});
$availableProducts = $db->find()
->table('products')
->available()
->get();
echo "Available products (active and price > 0): " . count($availableProducts) . "\n";
foreach ($availableProducts as $product) {
echo " - {$product['name']} (price: {$product['price']})\n";
}
echo "\n";
// Example 4: Macro with Default Parameters
echo "4. Macro with Default Parameters\n";
echo "----------------------------------\n";
QueryBuilder::macro('recent', function (QueryBuilder $query, int $days = 7) {
$date = date('Y-m-d H:i:s', strtotime("-{$days} days"));
return $query->where('created_at', $date, '>=');
});
// Insert a recent product
$createdDate = date('Y-m-d H:i:s');
$db->find()->table('products')->insert([
'name' => 'New Product',
'price' => 75.00,
'status' => 'active',
'created_at' => $driver === 'oci' ? Db::toTs($createdDate) : $createdDate,
]);
// Use macro with default parameter
$recentProducts = $db->find()
->table('products')
->recent() // Uses default 7 days
->get();
echo "Recent products (last 7 days): " . count($recentProducts) . "\n";
// Use macro with custom parameter
$veryRecentProducts = $db->find()
->table('products')
->recent(1) // Last 1 day
->get();
echo "Very recent products (last 1 day): " . count($veryRecentProducts) . "\n";
echo "\n";
// Example 5: Chaining Macros
echo "5. Chaining Macros\n";
echo "------------------\n";
$result = $db->find()
->table('products')
->active()
->inCategory(1)
->wherePrice('>', 100.00)
->orderBy('price', 'DESC')
->limit(5)
->get();
echo "Chained macros result: " . count($result) . " products\n";
foreach ($result as $product) {
echo " - {$product['name']} (price: {$product['price']}, category: {$product['category_id']})\n";
}
echo "\n";
// Example 6: Macro Returning Non-QueryBuilder Value
echo "6. Macro Returning Non-QueryBuilder Value\n";
echo "-------------------------------------------\n";
QueryBuilder::macro('countActive', function (QueryBuilder $query) {
return $query->where('status', 'active')->getValue('COUNT(*)');
});
$activeCount = $db->find()
->table('products')
->countActive();
echo "Count of active products: $activeCount\n";
echo "\n";
// Example 7: Macro Overwriting
echo "7. Macro Overwriting\n";
echo "--------------------\n";
// Register original macro
QueryBuilder::macro('special', function (QueryBuilder $query) {
return $query->where('status', 'active');
});
// Overwrite with new implementation
QueryBuilder::macro('special', function (QueryBuilder $query) {
return $query->where('status', 'inactive');
});
$specialProducts = $db->find()
->table('products')
->special()
->get();
echo "Products using overwritten macro: " . count($specialProducts) . "\n";
foreach ($specialProducts as $product) {
echo " - {$product['name']} (status: {$product['status']})\n";
}
echo "\n";
// Example 8: Error Handling - Non-existent Macro
echo "8. Error Handling - Non-existent Macro\n";
echo "----------------------------------------\n";
try {
$db->find()->table('products')->nonExistentMacro();
echo "ERROR: Should have thrown exception\n";
} catch (\RuntimeException $e) {
echo "✓ Correctly caught exception: " . $e->getMessage() . "\n";
}
echo "\n";
// Cleanup
echo "Cleaning up...\n";
$schema->dropTableIfExists('products');
echo "✓ Done\n";