Prepared statements everywhere

This commit is contained in:
Roberto Alsina 2024-05-16 15:31:09 -03:00
parent 76e16ca803
commit f2ee8aa6e8
2 changed files with 45 additions and 49 deletions

View File

@ -88,57 +88,52 @@ class Handler
year = year.to_i?
datos = [] of Tuple(Int32, String)
DB.open(DB_URL) do |cursor|
if prefijo.nil? && year.nil?
# Global totals
sql = %(
result_set = cursor.query("
SELECT total::integer, nombre
FROM totales
ORDER BY total DESC
LIMIT 50
)
LIMIT 50")
elsif prefijo.nil? && !year.nil?
# Per-year totals
sql = %(
result_set = cursor.query("
SELECT contador::integer, nombre
FROM nombres
WHERE
anio = '#{year}'
anio = $1
ORDER BY contador DESC
LIMIT 50
)
LIMIT 50", year)
elsif !prefijo.nil? && year.nil?
# Filter only by prefix
sql = %(
SELECT total, nombre
result_set = cursor.query("
SELECT total::integer, nombre
FROM totales
WHERE
nombre LIKE '#{prefijo}%'
nombre LIKE $1
ORDER BY total DESC
LIMIT 50
)
else
LIMIT 50", prefijo + "%")
elsif !prefijo.nil? && !year.nil?
# We have both
sql = %(
SELECT contador, nombre
result_set = cursor.query("
SELECT contador::integer, nombre
FROM nombres
WHERE
anio = '#{year}' AND
nombre LIKE '#{prefijo}%'
anio = $1 AND
nombre LIKE $2
ORDER BY contador DESC
LIMIT 50
)
LIMIT 50", year, prefijo + "%")
end
puts "QUERY: #{sql}"
datos = [] of Tuple(Int32, String)
DB.open(DB_URL) do |cursor|
cursor.query sql do |result_set|
if !result_set.nil?
result_set.each do
valor = result_set.read(Int32)
nombre = result_set.read(String)
datos.push({valor, nombre})
end
result_set.close
end
end

View File

@ -9,6 +9,8 @@ require "pg"
USER = File.read("/var/openfaas/secrets/nombres-user").strip
PASS = File.read("/var/openfaas/secrets/nombres-pass").strip
DB_URL = "postgres://#{USER}:#{PASS}@10.61.0.1:5432/nombres"
class Handler
def format_buffer(buffer, canvas_name, title = "")
@ -41,14 +43,14 @@ class Handler
html.gsub("gnuplot_canvas", canvas_name)
end
def query(sql)
def query(sql, nombre)
# Runs a SQL query against the database.
#
# Returns an array of values [[Year,Count]...]
# Or nil if there are no results
DB.open("postgres://#{USER}:#{PASS}@10.61.0.1:5432/nombres") do |cursor|
cursor.query sql do |result_set|
DB.open(DB_URL) do |cursor|
cursor.query(sql, nombre) do |result_set|
result = [] of Tuple(Int32, Int32)
result_set.each do
year = result_set.read(Int32)
@ -96,10 +98,9 @@ class Handler
show_key(true)
xrange(1922..2015)
nombres.map { |nombre|
sql = "SELECT anio::integer, contador::integer FROM nombres WHERE nombre = '#{nombre}' ORDER BY anio"
x = Array(Int32).new
y = Array(Int32).new
results = query(sql)
results = query("SELECT anio::integer, contador::integer FROM nombres WHERE nombre = $1 ORDER BY anio", nombre)
if results.nil? # No results, all 0s
x = (1922..2015).to_a
y = x.map { |_| 0 }