From 3f826dc10e451dadac4b16ea2258c75c643293e2 Mon Sep 17 00:00:00 2001 From: Pan GaoYong Date: Thu, 1 Dec 2022 19:46:17 +0800 Subject: [PATCH] reduce string construction time complexity from O(n*n) to O(n) --- src/adapter/pg.cr | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/src/adapter/pg.cr b/src/adapter/pg.cr index 5d017d7d..5624d77a 100644 --- a/src/adapter/pg.cr +++ b/src/adapter/pg.cr @@ -44,7 +44,7 @@ class Granite::Adapter::Pg < Granite::Adapter::Base stmt << "INSERT INTO #{quote(table_name)} (" stmt << fields.map { |name| "#{quote(name)}" }.join(", ") stmt << ") VALUES (" - stmt << fields.map { |name| "$#{fields.index(name).not_nil! + 1}" }.join(", ") + stmt << position_str(fields.size) stmt << ")" stmt << " RETURNING #{quote(lastval)}" if lastval @@ -116,7 +116,7 @@ class Granite::Adapter::Pg < Granite::Adapter::Base def update(table_name : String, primary_name : String, fields, params) statement = String.build do |stmt| stmt << "UPDATE #{quote(table_name)} SET " - stmt << fields.map { |name| "#{quote(name)}=$#{fields.index(name).not_nil! + 1}" }.join(", ") + stmt << fields.map_with_index { |name, i| "#{quote(name)}=$#{i + 1}" }.join(", ") stmt << " WHERE #{quote(primary_name)}=$#{fields.size + 1}" end @@ -153,4 +153,15 @@ class Granite::Adapter::Pg < Granite::Adapter::Base clause end + + private def position_str(n : Int32) : String + i = 1 + String.build do |str| + while i <= n + str << "$" << i + i += 1 + str << ", " if i <= n + end + end + end end