Scala case class copy only with some parameters at runtime? - scala

I'm using Play Framework and client can send only some fields to update in database. Then I need to do something like this:
g.copy(
partnumber = jGood.partnumber,
cost = jGood.cost
)
So, most of the fields I will have in jGood will be None and only some of them will be Some. Now how can I filter all those None fields and make a copy of class only with Some fields?

Consider this:
g.copy(
partnumber = jGood.partnumber.orElse(g.partnumber),
cost = jGood.cost.orElse(g.cost)
)

Related

How to do a nested WHERE in Zend Framework 1 using Zend_Db_Select with AND and OR operators?

So... I've inherited this rather large project based on Zend Framework 1.12 and a feature that I'm trying to add involves a more complex database operation than what I'm used to doing with the project. I'm extremely new to Zend Framework, or MVC for that matter. I found an answer for Zend Framework 3 which would have been perfect but I have to make do with this version.
The function basically builds a Zend_Db_Select based on various parameters and the feature I'm trying to add will involve joining two different tables and checking if a specific combination exists in one or the other.
Here's what I have so far:
//SQL that I'm trying to do. Assume table1 and table2 are already joined.
//Ignore the imperfect syntax. I'm trying to get the concept across.
//SELECT * FROM (table1 joined to table2 by a common key)
//WHERE ( (table1.column1 = myParam1) AND (table1.column2 = myParam2) )
//OR WHERE ( (table2.column1 = myParam1) AND (table2.column2 = myParam2) )
public function buildSelect($params){
//Zend code starts here
//This one starts the Zend_Db_Select
$select = $this->select();
$table1Name = get_table_name_from_object($table1);
//lots of preexisting code here
//my code starts here.
$table2Name = get_table_name_from_object($table2);
$select->join($table2Name, "$table1Name.key = $table2Name.key", array('column1', 'column2', 'key');
//After I wrote this, I instantly realized why it won't work the way I intended it but putting it here to show what I tried at which point I got stuck.
$select->where("($table1Name.column1 = ?) OR ($table2Name.column1 = ?)",$params[1]);
$select->where( "($table1Name.column2 = ?) OR ($table2Name.column2 = ?)", $params[2]);
//more preexisting code below.
return $select
}
Obviously, if I tried this as is, the program will happily return results that include a combination of, say, an entry where param1 is in table1.column1 and param2 is in table2.column2.
I received some feedback from a friend and posting here for posterity.
They noticed my code already contains parentheses and recommended that I simply take advantage of orWhere() then write it like this:
$select->where("($tableName1.column1 = ?", $params[param1])
->where("$tableName1.column2 = ?)", $params[param2]);
$select->orWhere("($tableName1.column1 = ?",$params[param1])
->where("$tableName2.column2 = ?)",$params[param2]);

Slick optional query parameters

I'm using Slick to query a database. I pass a Case class to my query method which looks like similar to...
case class queryParams(id:Int, age:Option[Int] = None,
categoryId:Option[Int] = None)
I have a Slick query that is similar to...
val query = this.filter( row =>
(row.id == queryParams.id))
query.list
And this works fine. But what I want to do now is extend the query to include the other queryParams members "if" they are defined but I'm unsure how I should structure this.
What I want is something like this...
for { row <- this.list
if(row.id == queryParams.id)
// include
if(queryParams.age.isDefined) row.age == queryParams.age.get
} yield row
How can I include optional params in the query?
Thanks
I ended up using a custom "MaybeFilter" solution that is posted in various places including...
See https://gist.github.com/studiodev/5c6471cb1d823914ee28

Spyne model for existing Database structure

I have an issue with defining model in spyne to generate several levels "in" SOAP11.
I used example at first, but my task is to generate service for tables already existing, so I got stuck and try to understand wheter to seek in Spyne properties or Sqlalchemy.
To be precise, i'll take example from site and show what i'm trying to reach:
class Permission(TableModel):
__tablename__ = 'permission'
id = UnsignedInteger32(pk=True)
application = Unicode(values=('usermgr', 'accountmgr'))
operation = Unicode(values=('read', 'modify', 'delete'))
perm_user_id = integer
last field is the FK for user table, but its name is different from user_id
class User(TableModel):
__tablename__ = 'user'
id = UnsignedInteger32(pk=True)
user_name = Unicode(32, min_len=4, pattern='[a-z0-9.]+', unique=True)
full_name = Unicode(64, pattern='\w+( \w+)+')
email = Unicode(64, pattern=r'[a-z0-9._%+-]+#[a-z0-9.-]+\.[A-Z]{2,4}')
last_pos = Point(2, index='gist')
permissions = Array(Permission).store_as('table')
--- SQL generated tries to add "WHEN user.id = permission.user_id" but I need another field (perm_user_id) to be filtered
Help me to define class to get correct inner tags.. actually it'll be about 3 more classes deep.
Thanx in Advance, Yury
Your answer is correct. Just as an alternative for simple tables, you can omit column definitions and let sqlalchemy's reflection engine figure it out.
meta = TableModel.Attributes.sqla_metadata
meta.reflect()
class User(TableModel):
__table__ = meta.tables['user']
The User class will be reconstructed using as much information as possible from the table columns and their types.
Found it myself, sorry to disturb anyone,
from spyne.model.complex import table
Permissions= Array(permission).customize(store_as=table(right='perm_user_id'))

How to access a field in a related django model other than the primary key

This seems a silly, simple question. I'm going round in circles trying to get this work, but I can't see the wood for the trees.
Given a simple model such as (I've skipped the imports):
class Location(models.Model):
description = model.CharField(max_length=40)
address1 = model.CharField(max_length=40)
# ..... (and so on)
tel = model.CharField(max_length=12)
and another with a relationship to it:
class InformationRequest(models.Model):
source = models.ForeignKey(Location)
request_date = Models.DateField(default=datetime.now())
# ..... (and so on)
How do I add a field that references the 'tel' field from the Location model in such a way that it can be populated automatically or from a select list in Django admin.
OK, if I get this right than you are, nomen est omen, thoroughly confusing the way that relational databases work :] One of key principles is to eliminate redundancy. There shouldn't be the very same piece of data stored in two tables that are related to one another.
I think that your current models are correct. Given these instances (I'm ignoring the fact that you have other, non-nullable fields)...
>>> loc = Location()
>>> loc.tel = "123"
>>> loc.save()
>>> info = InformationRequest()
>>> info.source = loc
>>> info.save()
...you can access tel from InformationRequest instance just like this:
>>> info.source.tel
'123'
You can also create a method...
class InformationRequest(models.Model):
source = models.ForeignKey(Location, related_name="information_requests")
request_date = Models.DateField(default=datetime.now())
# ..... (and so on)
def contact_tel(self):
return self.source.tel
... and get it like this:
>>> info.contact_tel()
'123'
You can even trick it into being an attribute...
class InformationRequest(models.Model):
source = models.ForeignKey(Location, related_name="information_requests")
request_date = Models.DateField(default=datetime.now())
# ..... (and so on)
#property
def contact_tel(self):
return self.source.tel
... and get it without parentheses:
>>> info.contact_tel
'123'
Anyway, you should work your way around it programatically. Hope that helps.

Is there a generic way of setting field values in mapper from list of values?

Is there a way of creating method for setting the value in the Model's fields without setting the values explicitly like -
ModelName.create.fieldName1("value").fieldName2("value2") and so on
Can we iterate through all available fields of that model and set their values form some list-of-values ?
something like ...
Model.allFields.foreach((fld)=> {
fld.set(valueList(indx)); indx+=1
}
Actually I want to set values into all models using some generic method that works for all models.
According to my comment:
val list = List(...)
val record = YourRecordClass.createRecord
record.allFields.zip(list).foreach {case(field,value) => field.setFromAny(value)}