lib/pgslice/helpers.rb in pgslice-0.5.0 vs lib/pgslice/helpers.rb in pgslice-0.6.0
- old
+ new
@@ -33,15 +33,19 @@
params = CGI.parse(uri.query.to_s)
# remove schema
@schema = Array(params.delete("schema") || "public")[0]
uri.query = params.any? ? URI.encode_www_form(params) : nil
- ENV["PGCONNECT_TIMEOUT"] ||= "1"
+ ENV["PGCONNECT_TIMEOUT"] ||= "3"
conn = PG::Connection.new(uri.to_s)
conn.set_notice_processor do |message|
say message
end
+ @server_version_num = conn.exec("SHOW server_version_num")[0]["server_version_num"].to_i
+ if @server_version_num < 110000
+ abort "This version of pgslice requires Postgres 11+"
+ end
conn
end
rescue PG::ConnectionBad => e
abort e.message
rescue URI::InvalidURIError
@@ -84,22 +88,23 @@
run_query(query)
end
end
def server_version_num
- execute("SHOW server_version_num")[0]["server_version_num"].to_i
+ connection # ensure called first
+ @server_version_num
end
# helpers
def sql_date(time, cast, add_cast = true)
if cast == "timestamptz"
fmt = "%Y-%m-%d %H:%M:%S UTC"
else
fmt = "%Y-%m-%d"
end
- str = "'#{time.strftime(fmt)}'"
+ str = escape_literal(time.strftime(fmt))
add_cast ? "#{str}::#{cast}" : str
end
def name_format(period)
case period.to_sym
@@ -150,10 +155,14 @@
def quote_ident(value)
PG::Connection.quote_ident(value)
end
+ def escape_literal(value)
+ connection.escape_literal(value)
+ end
+
def quote_table(table)
table.quote_table
end
def quote_no_schema(table)
@@ -173,8 +182,15 @@
index_def.sub(/ ON \S+ USING /, " ON #{quote_table(table)} USING ").sub(/ INDEX .+ ON /, " INDEX ON ") + ";"
end
def make_fk_def(fk_def, table)
"ALTER TABLE #{quote_table(table)} ADD #{fk_def};"
+ end
+
+ def make_stat_def(stat_def, table)
+ m = /ON (.+) FROM/.match(stat_def)
+ # errors on duplicate names, but should be rare
+ stat_name = "#{table}_#{m[1].split(", ").map { |v| v.gsub(/\W/i, "") }.join("_")}_stat"
+ stat_def.sub(/ FROM \S+/, " FROM #{quote_table(table)}").sub(/ STATISTICS .+ ON /, " STATISTICS #{quote_ident(stat_name)} ON ") + ";"
end
end
end