-
-
Notifications
You must be signed in to change notification settings - Fork 322
/
Copy pathEloquentDataSource.php
368 lines (291 loc) · 12.7 KB
/
EloquentDataSource.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
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
<?php namespace Clockwork\DataSource;
use Clockwork\Helpers\{Serializer, StackTrace};
use Clockwork\Request\Request;
use Clockwork\Support\Laravel\Eloquent\{ResolveModelLegacyScope, ResolveModelScope};
use Illuminate\Database\ConnectionResolverInterface;
use Illuminate\Contracts\Events\Dispatcher as EventDispatcher;
// Data source for Eloquent (Laravel ORM), provides database queries, stats, model actions and counts
class EloquentDataSource extends DataSource
{
use Concerns\EloquentDetectDuplicateQueries;
// Database manager instance
protected $databaseManager;
// Event dispatcher instance
protected $eventDispatcher;
// Array of collected queries
protected $queries = [];
// Query counts by type
protected $count = [
'total' => 0, 'slow' => 0, 'select' => 0, 'insert' => 0, 'update' => 0, 'delete' => 0, 'other' => 0
];
// Collected models actions
protected $modelsActions = [];
// Model action counts by model, eg. [ 'retrieved' => [ User::class => 1 ] ]
protected $modelsCount = [
'retrieved' => [], 'created' => [], 'updated' => [], 'deleted' => []
];
// Whether we are collecting database queries or stats only
protected $collectQueries = true;
// Whether we are collecting models actions or stats only
protected $collectModelsActions = true;
// Whether we are collecting retrieved models as well when collecting models actions
protected $collectModelsRetrieved = false;
// Query execution time threshold in ms after which the query is marked as slow
protected $slowThreshold;
// Enable duplicate queries detection
protected $detectDuplicateQueries = false;
// Model name to associate with the next executed query, used to map queries to models
public $nextQueryModel;
// Create a new data source instance, takes a database manager, an event dispatcher as arguments and additional
// options as arguments
public function __construct(ConnectionResolverInterface $databaseManager, EventDispatcher $eventDispatcher, $collectQueries = true, $slowThreshold = null, $slowOnly = false, $detectDuplicateQueries = false, $collectModelsActions = true, $collectModelsRetrieved = false)
{
$this->databaseManager = $databaseManager;
$this->eventDispatcher = $eventDispatcher;
$this->collectQueries = $collectQueries;
$this->slowThreshold = $slowThreshold;
$this->detectDuplicateQueries = $detectDuplicateQueries;
$this->collectModelsActions = $collectModelsActions;
$this->collectModelsRetrieved = $collectModelsRetrieved;
if ($slowOnly) $this->addFilter(function ($query) { return $query['duration'] > $this->slowThreshold; });
}
// Adds ran database queries, query counts, models actions and models counts to the request
public function resolve(Request $request)
{
$request->databaseQueries = array_merge($request->databaseQueries, $this->queries);
$request->databaseQueriesCount += $this->count['total'];
$request->databaseSlowQueries += $this->count['slow'];
$request->databaseSelects += $this->count['select'];
$request->databaseInserts += $this->count['insert'];
$request->databaseUpdates += $this->count['update'];
$request->databaseDeletes += $this->count['delete'];
$request->databaseOthers += $this->count['other'];
$request->modelsActions = array_merge($request->modelsActions, $this->modelsActions);
$request->modelsRetrieved = $this->modelsCount['retrieved'];
$request->modelsCreated = $this->modelsCount['created'];
$request->modelsUpdated = $this->modelsCount['updated'];
$request->modelsDeleted = $this->modelsCount['deleted'];
$this->appendDuplicateQueriesWarnings($request);
return $request;
}
// Reset the data source to an empty state, clearing any collected data
public function reset()
{
$this->queries = [];
$this->count = [
'total' => 0, 'slow' => 0, 'select' => 0, 'insert' => 0, 'update' => 0, 'delete' => 0, 'other' => 0
];
$this->modelsActions = [];
$this->modelsCount = [
'retrieved' => [], 'created' => [], 'updated' => [], 'deleted' => []
];
$this->nextQueryModel = null;
}
// Start listening to Eloquent events
public function listenToEvents()
{
if ($scope = $this->getModelResolvingScope()) {
$this->eventDispatcher->listen('eloquent.booted: *', function ($model, $data = null) use ($scope) {
if (is_string($model) && is_array($data)) { // Laravel 5.4 wildcard event
$model = reset($data);
}
$model->addGlobalScope($scope);
});
}
if (class_exists(\Illuminate\Database\Events\QueryExecuted::class)) {
// Laravel 5.2 and up
$this->eventDispatcher->listen(\Illuminate\Database\Events\QueryExecuted::class, function ($event) {
$this->registerQuery($event);
});
} else {
// Laravel 5.0 to 5.1
$this->eventDispatcher->listen('illuminate.query', function ($event) {
$this->registerLegacyQuery($event);
});
}
// Laravel 5.2 and up
if (class_exists(\Illuminate\Database\Events\TransactionBeginning::class)) {
$this->eventDispatcher->listen(\Illuminate\Database\Events\TransactionBeginning::class, function ($event) {
$this->registerTransactionQuery($event, 'START TRANSACTION');
});
}
if (class_exists(\Illuminate\Database\Events\TransactionCommitted::class)) {
$this->eventDispatcher->listen(\Illuminate\Database\Events\TransactionCommitted::class, function ($event) {
$this->registerTransactionQuery($event, 'COMMIT');
});
}
if (class_exists(\Illuminate\Database\Events\TransactionRolledBack::class)) {
$this->eventDispatcher->listen(\Illuminate\Database\Events\TransactionRolledBack::class, function ($event) {
$this->registerTransactionQuery($event, 'ROLLBACK');
});
}
// register all event listeners individually so we don't have to regex the event type and support Laravel <5.4
$this->listenToModelEvent('retrieved');
$this->listenToModelEvent('created');
$this->listenToModelEvent('updated');
$this->listenToModelEvent('deleted');
}
// Register a listener collecting model events of specified type
protected function listenToModelEvent($event)
{
$this->eventDispatcher->listen("eloquent.{$event}: *", function ($model, $data = null) use ($event) {
if (is_string($model) && is_array($data)) { // Laravel 5.4 wildcard event
$model = reset($data);
}
$this->collectModelEvent($event, $model);
});
}
// Collect an executed database query
protected function registerQuery($event)
{
$trace = StackTrace::get([ 'arguments' => $this->detectDuplicateQueries ])->resolveViewName();
if ($this->detectDuplicateQueries) $this->detectDuplicateQuery($trace);
$query = [
'query' => $this->createRunnableQuery($event->sql, $event->bindings, $event->connectionName),
'duration' => $event->time,
'connection' => $event->connectionName,
'time' => microtime(true) - $event->time / 1000,
'trace' => (new Serializer)->trace($trace),
'model' => $this->nextQueryModel,
'tags' => $this->slowThreshold !== null && $event->time > $this->slowThreshold ? [ 'slow' ] : []
];
$this->nextQueryModel = null;
if (! $this->passesFilters([ $query, $trace ], 'early')) return;
$this->incrementQueryCount($query);
if (! $this->collectQueries || ! $this->passesFilters([ $query, $trace ])) return;
$this->queries[] = $query;
}
// Collect an executed database query (pre Laravel 5.2)
protected function registerLegacyQuery($sql, $bindings, $time, $connection)
{
return $this->registerQuery((object) [
'sql' => $sql,
'bindings' => $bindings,
'time' => $time,
'connectionName' => $connection
]);
}
// Collect an executed transaction query
protected function registerTransactionQuery($event, $name)
{
$trace = StackTrace::get()->resolveViewName();
$query = [
'query' => $name,
'duration' => 0,
'connection' => $event->connectionName,
'time' => microtime(true),
'trace' => (new Serializer)->trace($trace),
'model' => null,
'tags' => []
];
if (! $this->collectQueries) return;
$this->queries[] = $query;
}
// Collect a model event and update stats
protected function collectModelEvent($event, $model)
{
$lastQuery = ($queryCount = count($this->queries)) ? $this->queries[$queryCount - 1] : null;
$action = [
'model' => $modelClass = get_class($model),
'key' => $this->getModelKey($model),
'action' => $event,
'attributes' => $this->collectModelsRetrieved && $event == 'retrieved' ? $model->getOriginal() : [],
'changes' => $this->collectModelsActions && method_exists($model, 'getChanges') ? $model->getChanges() : [],
'time' => microtime(true) / 1000,
'query' => $lastQuery ? $lastQuery['query'] : null,
'duration' => $lastQuery ? $lastQuery['duration'] : null,
'connection' => $lastQuery ? $lastQuery['connection'] : null,
'trace' => null,
'tags' => []
];
if ($lastQuery) $this->queries[$queryCount - 1]['model'] = $modelClass;
if (! $this->passesFilters([ $action ], 'models-early')) return;
$this->incrementModelsCount($action['action'], $action['model']);
if (! $this->collectModelsActions) return;
if (! $this->collectModelsRetrieved && $event == 'retrieved') return;
if (! $this->passesFilters([ $action ], 'models')) return;
$action['trace'] = (new Serializer)->trace(StackTrace::get()->resolveViewName());
$this->modelsActions[] = $action;
}
// Takes a query, an array of bindings and the connection as arguments, returns runnable query with upper-cased keywords
protected function createRunnableQuery($query, $bindings, $connection)
{
// add bindings to query
$bindings = $this->databaseManager->connection($connection)->prepareBindings($bindings);
$index = 0;
$query = preg_replace_callback('/\?/', function ($matches) use ($bindings, $connection, &$index) {
$binding = $this->quoteBinding($bindings[$index++], $connection);
// convert binary bindings to hexadecimal representation
if (! preg_match('//u', (string) $binding)) $binding = '0x' . bin2hex($binding);
// escape backslashes in the binding (preg_replace requires to do so)
return (string) $binding;
}, $query, count($bindings));
// highlight keywords
$keywords = [
'select', 'insert', 'update', 'delete', 'into', 'values', 'set', 'where', 'from', 'limit', 'is', 'null',
'having', 'group by', 'order by', 'asc', 'desc'
];
$regexp = '/\b' . implode('\b|\b', $keywords) . '\b/i';
return preg_replace_callback($regexp, function ($match) { return strtoupper($match[0]); }, $query);
}
// Takes a query binding and a connection name, returns a quoted binding value
protected function quoteBinding($binding, $connection)
{
$connection = $this->databaseManager->connection($connection);
if (! method_exists($connection, 'getPdo')) return;
$pdo = $connection->getPdo();
if ($pdo === null) return;
if ($pdo->getAttribute(\PDO::ATTR_DRIVER_NAME) === 'odbc' || $pdo->getAttribute(\PDO::ATTR_DRIVER_NAME) === 'crate') {
// PDO_ODBC and PDO Crate driver doesn't support the quote method, apply simple MSSQL style quoting instead - Crate sometimes uses a object as a binding - for json support
$binding = is_object($binding) ? json_encode($binding) : $binding;
return "'" . str_replace("'", "''", $binding) . "'";
}
return is_string($binding) ? $pdo->quote($binding) : $binding;
}
// Increment query counts for collected query
protected function incrementQueryCount($query)
{
$sql = ltrim($query['query']);
$this->count['total']++;
if (preg_match('/^select\b/i', $sql)) {
$this->count['select']++;
} elseif (preg_match('/^insert\b/i', $sql)) {
$this->count['insert']++;
} elseif (preg_match('/^update\b/i', $sql)) {
$this->count['update']++;
} elseif (preg_match('/^delete\b/i', $sql)) {
$this->count['delete']++;
} else {
$this->count['other']++;
}
if (in_array('slow', $query['tags'])) {
$this->count['slow']++;
}
}
// Increment model counts for collected model action
protected function incrementModelsCount($action, $model)
{
if (! isset($this->modelsCount[$action][$model])) {
$this->modelsCount[$action][$model] = 0;
}
$this->modelsCount[$action][$model]++;
}
// Returns model resolving scope for the installed Laravel version
protected function getModelResolvingScope()
{
if (interface_exists(\Illuminate\Database\Eloquent\ScopeInterface::class)) {
// Laravel 5.0 to 5.1
return new ResolveModelLegacyScope($this);
}
return new ResolveModelScope($this);
}
// Returns model key without crashing when using Eloquent strict mode and it's not loaded
protected function getModelKey($model)
{
// Some applications use non-string primary keys, even when this is not supported by Laravel
if (! is_string($model->getKeyName())) return;
try {
return $model->getKey();
} catch (\Illuminate\Database\Eloquent\MissingAttributeException $e) {}
}
}