3

By modify I mean counterparts of SQL UPDATE and DELETE.

In both cases I have an object-record and I would like to delete it in the database. The table has always primary key, and it is set in my object-record.

Please note that I don't have query or other source which "created" that object-record, all I have is it and the table. So in general it looks like this:

fetch the Record from Table
...
// forget how I get the Record
...
Record.person_name = "joe"
? update Record ?

How to do it?


I define records and tables as below:
case class Topic(var id : Long,
                 var sectionId : Int,
                 ...

object TopicTable  extends Table[Topic]("Topic") {
       def id = column[Long]("top_Id", O.PrimaryKey) 
       def sectionId = column[Int]("sect_Id")
       ...
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
greenoldman
  • 16,895
  • 26
  • 119
  • 185

1 Answers1

4

It seems there are no direct methods, so you have to create explicitly a recordset in order to modify (for comparison -- I know SQ is not ORM -- in EF you fetch records, modify them and at this point your data context "knows" they were modify, so all you have to do is submit changes).

So first you create RS as you like:

val rs = for (rec <- MyTable if rec.id===10) yield rec;

and the delete records:

rs.mutate(rec => rec.delete())

for update:

rs.update(new MyRecord(...))

or (gossip is, it is faster ;-) )

rs.mutate(rec => rec.row = new MyRecord(...))

Please note I am complete newbie with SQ so I might just misinformed you. I works for me though.

Now, the only missing part is adding some nice wrappers, so delete and update could be done directly per record.

greenoldman
  • 16,895
  • 26
  • 119
  • 185
  • +1, you can also strip down the delete to: "rs.mutate(_.delete)" since compiler infers the object on which delete is to be performed – virtualeyes Feb 06 '12 at 15:14
  • @virtualeyes, it has nothing to do with delete, _ is common in Scala lambdas, but I don't like this style, it is too obscure. – greenoldman Feb 07 '12 at 13:33
  • 2
    agreed re: hieroglyphics, but in this case, given the intent of the operation (find record & delete) it's obvious what is happening, so being explicit gains nothing but extra key strokes – virtualeyes Feb 07 '12 at 16:45