On Fri, Dec 24, 2021 at 9:47 AM Sébastien Lamy <lamys...@free.fr> wrote:
> Hi! > > I have a model "Adherent" correspondint to a table "adherents" in my > Postgres database. In this table, when I create a row from my app, I want > to set the "creator_id" column to same value as id. With Sequel the > folowing intruction works ok > > DB[:adherents].insert(:name => "foo", :creator_id => > Sequel.function("currval","adherents_id_seq")) > > But this one does fail: > Adherent.new(:name => "foo", :creator_id => > Sequel.function("currval","adherents_id_seq")) > > This fail at validation, because the sequel function object is not an > integer as expected. > > To bypass validation, I affect the value in the "before_create" hook: > def before_create > super > self.creator_id ||= Sequel.lit("currval('adherents_id_seq')") > end > > This is also failing > using Sequel.lit("currval('adherents_id_seq')") the error is: > ERROR -- : PG::InvalidTextRepresentation: ERREUR: syntaxe en entrée > invalide pour le type integer : « currval('adherents_id_seq') » > using Sequel.function("currval","adherents_id_seq") the error is: > ERREUR: syntaxe en entrée invalide pour le type integer : « > #<Sequel::SQL::Function:0x000055f8811d3fd8> » > (PG::InvalidTextRepresentation) > > I feel this is because of the auto-generated PREPARE statement > PREPARE smpsp_1 AS INSERT INTO "adherents" ("name", "creator_id") VALUES > ($1, $2) RETURNING "id", "prenom", "nom", "annee_naissance", "email", > "tel_portable", "motivations", "commentaires", "echeance_SEPA", > "envoi_papier", "adresse_id", "premiere_adhesion", "stop_relance", > "perdu_trace", "updated_at", "created_at", "titre", "date_naissance", > "sceau", "creator_id", "updater_id" > > the $2 variable should not be declared, instead it should be written the > raw sql > currval('adherents_id_seq') > > When using a Sequel::Model instance, is there a way to put a sql function > as a value for a given field ? > Not directly. By design, a model object deals with values, not expressions. If you want to use expressions when inserting/updating, you need to drop down to the dataset level. You can still use the model typecasting and validations for most of the work: x = Adherent.new(...) x.this.insert(x.values.merge(:creator_id => Sequel.function("currval","adherents_id_seq"))) if x.valid? Thanks, Jeremy -- You received this message because you are subscribed to the Google Groups "sequel-talk" group. To unsubscribe from this group and stop receiving emails from it, send an email to sequel-talk+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sequel-talk/CADGZSSd%2BLDbhymT8L%2BwaUvG5rrxWPN3qsCcJ65pVPOsPNZWn1g%40mail.gmail.com.