-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy path10-materialized-cte.php
More file actions
234 lines (207 loc) · 7.7 KB
/
10-materialized-cte.php
File metadata and controls
234 lines (207 loc) · 7.7 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
<?php
declare(strict_types=1);
require_once __DIR__ . '/../../vendor/autoload.php';
require_once __DIR__ . '/../helpers.php';
use tommyknocker\pdodb\helpers\Db;
use tommyknocker\pdodb\PdoDb;
$driverEnv = getenv('PDODB_DRIVER') ?: 'sqlite';
$config = getExampleConfig();
$driver = $config['driver'] ?? $driverEnv;
echo "=== Materialized Common Table Expressions (CTEs) Examples ===\n\n";
echo "Database: $driver\n\n";
$pdoDb = createExampleDb($config);
$query = $pdoDb->find();
$dialect = $query->getDialect();
// Check if materialized CTE is supported
if (!$dialect->supportsMaterializedCte()) {
echo "⚠️ Materialized CTE is not supported by {$driver} dialect.\n";
echo "This example will be skipped.\n\n";
exit(0);
}
// Create test tables using fluent API (cross-dialect)
$schema = $pdoDb->schema();
$schema->dropTableIfExists('orders');
$schema->dropTableIfExists('order_items');
$schema->dropTableIfExists('customers');
$schema->createTable('customers', [
'id' => $schema->integer()->notNull(),
'name' => $schema->string(100),
'email' => $schema->string(100),
], ['primaryKey' => ['id']]);
$schema->createTable('orders', [
'id' => $schema->primaryKey(),
'customer_id' => $schema->integer(),
'order_date' => $schema->date(),
'total' => $schema->decimal(10, 2),
]);
$schema->createTable('order_items', [
'id' => $schema->primaryKey(),
'order_id' => $schema->integer(),
'product_name' => $schema->string(100),
'quantity' => $schema->integer(),
'price' => $schema->decimal(10, 2),
]);
// Insert sample data
$pdoDb->find()->table('customers')->insertMulti([
['id' => 1, 'name' => 'Alice', 'email' => '[email protected]'],
['id' => 2, 'name' => 'Bob', 'email' => '[email protected]'],
['id' => 3, 'name' => 'Charlie', 'email' => '[email protected]'],
]);
// Oracle requires TO_DATE() for date literals
if ($driver === 'oci') {
$pdoDb->find()->table('orders')->insertMulti([
['customer_id' => 1, 'order_date' => Db::raw("TO_DATE('2024-01-15', 'YYYY-MM-DD')"), 'total' => 150.00],
['customer_id' => 1, 'order_date' => Db::raw("TO_DATE('2024-02-10', 'YYYY-MM-DD')"), 'total' => 250.00],
['customer_id' => 2, 'order_date' => Db::raw("TO_DATE('2024-01-20', 'YYYY-MM-DD')"), 'total' => 300.00],
['customer_id' => 3, 'order_date' => Db::raw("TO_DATE('2024-02-05', 'YYYY-MM-DD')"), 'total' => 100.00],
]);
} else {
$pdoDb->find()->table('orders')->insertMulti([
['customer_id' => 1, 'order_date' => '2024-01-15', 'total' => 150.00],
['customer_id' => 1, 'order_date' => '2024-02-10', 'total' => 250.00],
['customer_id' => 2, 'order_date' => '2024-01-20', 'total' => 300.00],
['customer_id' => 3, 'order_date' => '2024-02-05', 'total' => 100.00],
]);
}
$pdoDb->find()->table('order_items')->insertMulti([
['order_id' => 1, 'product_name' => 'Widget A', 'quantity' => 2, 'price' => 50.00],
['order_id' => 1, 'product_name' => 'Widget B', 'quantity' => 1, 'price' => 50.00],
['order_id' => 2, 'product_name' => 'Widget C', 'quantity' => 5, 'price' => 50.00],
['order_id' => 3, 'product_name' => 'Widget D', 'quantity' => 3, 'price' => 100.00],
['order_id' => 4, 'product_name' => 'Widget E', 'quantity' => 1, 'price' => 100.00],
]);
// Example 1: Basic materialized CTE
echo "1. Basic Materialized CTE - High-value orders:\n";
echo " (Result is cached and computed once)\n";
$results = $pdoDb->find()
->withMaterialized('high_value_orders', function ($q) {
$q->from('orders')->where('total', 200, '>');
})
->from('high_value_orders')
->orderBy('total', 'DESC')
->get();
foreach ($results as $order) {
printf(" - Order ID %d: $%.2f on %s\n",
$order['id'],
$order['total'],
$order['order_date']
);
}
// Show SQL to verify MATERIALIZED keyword
$sqlData = $pdoDb->find()
->withMaterialized('high_value_orders', function ($q) {
$q->from('orders')->where('total', 200, '>');
})
->from('high_value_orders')
->toSQL();
echo "\n Generated SQL:\n";
if ($driver === 'pgsql') {
echo " " . str_replace("\n", "\n ", $sqlData['sql']) . "\n";
if (str_contains($sqlData['sql'], 'MATERIALIZED')) {
echo " ✓ SQL contains MATERIALIZED keyword\n";
}
} elseif ($driver === 'mysql' || $driver === 'mariadb') {
echo " " . str_replace("\n", "\n ", $sqlData['sql']) . "\n";
if (str_contains($sqlData['sql'], 'MATERIALIZE')) {
echo " ✓ SQL contains MATERIALIZE optimizer hint\n";
}
}
echo "\n";
// Example 2: Materialized CTE with multiple references
echo "2. Materialized CTE referenced multiple times:\n";
echo " (CTE is computed once and reused)\n";
$results = $pdoDb->find()
->withMaterialized('customer_stats', function ($q) {
$q->from('orders')
->select([
'customer_id',
'order_count' => Db::count('*'),
'total_spent' => Db::sum('total'),
'avg_order' => Db::avg('total'),
])
->groupBy('customer_id');
})
->from('customers')
->join('customer_stats', 'customers.id = customer_stats.customer_id')
->select([
'customers.name',
'customers.email',
'customer_stats.order_count',
'customer_stats.total_spent',
'customer_stats.avg_order',
])
->where('customer_stats.total_spent', 200, '>')
->orderBy('customer_stats.total_spent', 'DESC')
->get();
foreach ($results as $customer) {
printf(" - %s (%s): %d orders, $%.2f total, $%.2f avg\n",
$customer['name'],
$customer['email'],
$customer['order_count'],
$customer['total_spent'],
$customer['avg_order']
);
}
echo "\n";
// Example 3: Materialized CTE with explicit column list
echo "3. Materialized CTE with explicit column list:\n";
$results = $pdoDb->find()
->withMaterialized('order_summary', function ($q) {
$q->from('orders')
->select(['id', 'total', 'order_date'])
->where('total', 150, '>');
}, ['order_id', 'amount', 'date'])
->from('order_summary')
->where('amount', 200, '>')
->orderBy('amount')
->get();
foreach ($results as $order) {
printf(" - Order %d: $%.2f on %s\n",
$order['order_id'],
$order['amount'],
$order['date']
);
}
echo "\n";
// Example 4: Multiple materialized CTEs
echo "4. Multiple Materialized CTEs:\n";
$results = $pdoDb->find()
->withMaterialized('recent_orders', function ($q) {
$q->from('orders')
->where('order_date', '2024-02-01', '>=');
})
->withMaterialized('order_details', function ($q) {
$q->from('order_items')
->select([
'order_id',
'item_count' => Db::count('*'),
'total_items' => Db::sum('quantity'),
])
->groupBy('order_id');
})
->from('recent_orders')
->join('order_details', 'recent_orders.id = order_details.order_id')
->select([
'recent_orders.id',
'recent_orders.total',
'order_details.item_count',
'order_details.total_items',
])
->orderBy('recent_orders.order_date')
->get();
foreach ($results as $order) {
printf(" - Order %d: $%.2f with %d items (%d total units)\n",
$order['id'],
$order['total'],
$order['item_count'],
$order['total_items']
);
}
echo "\n";
// Example 5: Performance comparison (conceptual)
echo "5. When to use Materialized CTE:\n";
echo " - Expensive computations that are referenced multiple times\n";
echo " - Complex aggregations in CTEs\n";
echo " - Queries with multiple CTEs where optimization matters\n";
echo "\n";
echo "=== All materialized CTE examples completed successfully ===\n";