From bd0157143f7ef17f7d5739e4345e2d7c921bc05d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michael=20Vo=C5=99=C3=AD=C5=A1ek?= Date: Sat, 1 Jun 2024 00:07:47 +0200 Subject: [PATCH] Improve Expression::getDebugQuery() performance (#1224) --- src/Persistence/Sql/Expression.php | 11 ++++++++--- src/Schema/Migrator.php | 6 ++++-- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/src/Persistence/Sql/Expression.php b/src/Persistence/Sql/Expression.php index e82f48f2a..befe2b1a8 100644 --- a/src/Persistence/Sql/Expression.php +++ b/src/Persistence/Sql/Expression.php @@ -24,6 +24,8 @@ abstract class Expression implements Expressionable, \ArrayAccess { use DiContainerTrait; + private static ?SqlFormatter $debugFormatter = null; + /** "[]" in template, escape as parameter */ protected const ESCAPE_PARAM = 'param'; /** "{}" in template, escape as identifier */ @@ -434,11 +436,14 @@ function ($matches) use ($params, &$i) { return $k; }, $sql); - $sqlFormatter = new SqlFormatter(new NullHighlighter()); - $sql = $sqlFormatter->format($sql); + if (self::$debugFormatter === null) { + self::$debugFormatter = new SqlFormatter(new NullHighlighter()); + } + + $sql = self::$debugFormatter->format($sql); // fix string literal tokenize 2/2 - $sql = str_replace(array_keys($origStringTokens), $origStringTokens, $sqlFormatter->format($sql)); + $sql = str_replace(array_keys($origStringTokens), $origStringTokens, $sql); } return $sql; diff --git a/src/Schema/Migrator.php b/src/Schema/Migrator.php index 328bac475..dd90e37c4 100644 --- a/src/Schema/Migrator.php +++ b/src/Schema/Migrator.php @@ -426,12 +426,14 @@ protected function fixTableNameForListMethod(string $tableName): string public function introspectTableToModel(string $tableName): Model { - $columns = $this->createSchemaManager()->listTableColumns($this->fixTableNameForListMethod($tableName)); + $schemaManager = $this->createSchemaManager(); + + $columns = $schemaManager->listTableColumns($this->fixTableNameForListMethod($tableName)); if ($columns === []) { $this->assertTableExists($tableName); } - $indexes = $this->createSchemaManager()->listTableIndexes($this->fixTableNameForListMethod($tableName)); + $indexes = $schemaManager->listTableIndexes($this->fixTableNameForListMethod($tableName)); $primaryIndexes = array_filter($indexes, static fn ($v) => $v->isPrimary() && count($v->getColumns()) === 1); if (count($primaryIndexes) !== 1) { throw (new Exception('Table must contain exactly one primary key'))