简体   繁体   中英

How can I use a Sequel SQL function in an insert statement?

I would like to use a SQL function when inserting a new value into a dataset. However, I keep getting TypeError: can't convert Sequel::SQL::Function into String errors. The Sequel docs explain how to select using functions, but not insert.

Ideally I would like to avoid DB.run since I am inserting dynamically and raw SQL is messy and inflexible.

This is what I'm trying to do:

INSERT INTO dataset (col1, col2, col3) VALUES ('something', 3, func(value))

This is what I have in Sequel:

x = 'something'
y = 3
func_value = Sequel.function(:func, value)
DB[:dataset].insert (:col1 => x, :col2 => y, :col3 => func_value)

Is this possible? If so, what am I missing?

Figured it out. Create a Sequel::function object, and then make it the value in your hash.

irb(main):028:0> tbl
=> #<Sequel::MySQL::Dataset: "SELECT * FROM `foo`.`bar`">
irb(main):029:0> uhex = Sequel.function(:unhex,7)
=> #<Sequel::SQL::Function @args=>[7], @f=>:unhex>
irb(main):030:0>  tbl.insert_sql( {:field_name => uhex })
=> "INSERT INTO `foo`.`bar` (`field_name`) VALUES (unhex(7))"

看起来在语法上有几种不同的方法可以在Sequel中调用SQL函数: http : //sequel.rubyforge.org/rdoc/files/doc/dataset_filtering_rdoc.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM