如何清理传递给 st_centroid 的 sql 参数

how to sanitize sql parameters pass to st_centroid

我正在尝试清理传递给 ST_Centroid 的参数,但出现语法错误。

st_centroid

"SELECT ST_AsText(ST_Centroid(MULTIPOINT ( 0 0, 0 0, 0 0, 0 0 ))) as centroid"
    
sql = ActiveRecord::Base::sanitize_sql_array(['SELECT ST_AsText(ST_Centroid(MULTIPOINT ( ? ?, ? ?, ? ?, ? ? ))) as centroid', min_longitude, min_latitude, min_longitude, max_latitude, max_longitude, min_latitude, max_longitude, max_latitude])

ActiveRecord::Base.connection.execute(sql)&.to_a&.first["centroid"] || ""

语法错误

from /home/aniket/.rvm/gems/ruby-2.6.5@project/gems/activerecord-6.0.3.7/lib/active_record/connection_adapters/postgresql/database_statements.rb:92:in `exec'
Caused by PG::SyntaxError: ERROR:  syntax error at or near "0"
LINE 1: SELECT ST_AsText(ST_Centroid(MULTIPOINT ( 0 0, 0 0, 0 0, 0 0..

如果我不对它进行消毒,它工作正常

sql = "SELECT ST_AsText(ST_Centroid('MULTIPOINT ( #{min_longitude} #{min_latitude}, #{min_longitude} #{max_latitude}, #{max_longitude} #{min_latitude}, #{max_longitude} #{max_latitude} )')) as centroid";

ActiveRecord::Base.connection.execute(sql)&.to_a&.first["centroid"]
   (0.7ms)  SELECT ST_AsText(ST_Centroid('MULTIPOINT ( 0 0, 0 0, 0 0, 0 0 )')) as centroid
=> "POINT(0 0)"

根据文件 MULTIPOINT 应该被 ' 引用,我看到你在 sanitize_sql_array 时错过了那个,所以试试这个

sql = ActiveRecord::Base::sanitize_sql_array([
 "SELECT ST_AsText(ST_Centroid('MULTIPOINT ( ? ?, ? ?, ? ?, ? ? )')) as centroid", 
 min_longitude, min_latitude, min_longitude, 
 max_latitude, max_longitude, min_latitude, 
 max_longitude, max_latitude
])