Skip to content

Commit

Permalink
reduce string construction time complexity from O(n*n) to O(n)
Browse files Browse the repository at this point in the history
  • Loading branch information
pan committed Dec 1, 2022
1 parent a3134be commit 3f826dc
Showing 1 changed file with 13 additions and 2 deletions.
15 changes: 13 additions & 2 deletions src/adapter/pg.cr
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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

0 comments on commit 3f826dc

Please sign in to comment.