kind of a follow up question to my previous one:
squeryl date to long conversion
I implemented a DateTime(model) to Long(DB) conversion as mentioned in that thread.
I wrote a simple query to delete all records with an expired date:
println("deleting expired")
val now: DateTime = new DateTime()
inTransaction {
MyDB.loginTokens.deleteWhere(t =>
t.expires lt now.getMillis
)
}
println("finished deleting")
but the query just hangs in there and does nothing, no error is thrown...
I only see "deleting expired" printed and never "finished".
I also tried "t.expires lt now" and some other variants without success.
any idea what's causing this and how to fix it?
EDIT
when changing lt to .~ <, there is still a problem
when changing lt to === the query works fine both with now and now.getMillis.
t.expires.~ lt now
Notice the dot tilda.
Not sure why "lt" by itself doesn't work, like === works.
perhaps its a synonym to something else...
Related
Ecto.Model.Callbacks are now deprecated.
I am trying to achieve the same behavior as before_insert but to no avail! I can't even get anything to trigger IO.puts("hello") inside my changeset/2.
Here's what I have:
def changeset(model, params \\ :empty) do
IO.puts "HELLO" # never prints
model
|> cast(params, #required_fields, #optional_fields)
|> put_change(:column_name, "hello")
end
Instead of put_change, I've tried subbing change, cast, and practically everything else inside Ecto.Changeset.
I've also tried the non-piping method, just in case:
chset = cast(model, params, #required_fields, #optional_fields)
put_change(chset, :column_name, "hello")
The end-goal is shifting the row's inserted_at for a new value, so a simple default: "hello" on the Schema won't suffice.
Many thanks!
I ended up solving it via a Postgres fragment.
It's not quite what I was looking for, so I'll leave this question open for someone with an answer involving the changset, because that's still doing absolutely nothing for me.
Here's my temporary solution, involving the postgres Migration file.
create table(:stuffs) do
add :expires_at, :datetime, default: fragment("now() + interval '60 days'")
end
I posted this to the scalikejdbc user group, and should also cross post to github issues.
I've seen in the docs examples of running raw queries against a table, i'm trying to get list of IndexEntry with the following code, and while the query is executed and returns results in the console, i'm not getting anything back in the map(rs =>... portion.
Relevant code is here - when i run this in intellij's debugger the result as "Vector" size = 0. Thanks for any guidance. i'm doing something wrong, hopefully its a simple oversight.
package company.shared.database.models
import company.shared.database.MySQLConnector
import scalikejdbc._
case class IndexEntry(model:String, indexName: String, fieldName: String)
object IndexSchemaModel extends App with MySQLConnector {
implicit val session:DBSession = AutoSession
def indexMap:List[IndexEntry] = {
val result = DB readOnly { implicit session =>
sql"""
SELECT
substring_index(t.name,'/',-1) as model,
i.name AS indexName,
f.name as tableName
FROM information_schema.innodb_sys_tables t
JOIN information_schema.innodb_sys_indexes i USING (table_id)
JOIN information_schema.innodb_sys_fields f USING (index_id)
where t.name like "MyDB/%"
""".map(rs => IndexEntry(
rs.string(0),
rs.string(1),
rs.string(2))).list().apply()
}
println(result) //always List()
List(IndexEntry("foo", "bar", "az")) //to match the return type
}
override def main(args: Array[String]): Unit = {
configureDB
indexMap
}
}
I have tried scalikejdc's other variants - withSql { queryDSL } and the entire bit as SQL Interpolation with full syntax support. The first and the last always execute against the mysql server, which returns 57 rows (small db), the middle throws an NPE, honestly i'm happy to tackle the middle second. I have an issue somewhere in .map and i've tried to have it just return the map, but it always results in an empty list.
Thanks and hopefully no syntax errors copying into SO.
Oh and FWIW, configureDb just sets a connection pool manually since the DB names and servers can vary wildly between sbt tests, dev, test and prod. Currently that is not my issue or i would see "ConnectionPool('default') not initialized" or similar.
Answered here: https://groups.google.com/forum/#!topic/scalikejdbc-users-group/yRjLjuCzuEo
should also cross post to github issues
Please avoid posting questions on GitHub issues. https://github.com/scalikejdbc/scalikejdbc/blob/master/CONTRIBUTING.md#issues
A bit of embarrassment aside. The user in question did not have the process privilege and therefore would not get any rows back from these tables, as soon as a grant process on . to user#host was added, all this worked fine. Permissions in information_schema are driven by what objects the user in question have access to. Meaning items like ROUTINES and in this case PROCESS etc have to be explicitly called out.
Ok, I've been stuggling with this one for a while, and have spent a lot of time trying different things to do something that I have done very easily using PHP.
I am trying to iterate over a list while keeping track of a variable locally, while spitting out HTML attempting to populate a table.
Attempt #1:
#{
var curDate : Date = null
for(ind <- indicators){
if(curDate == null || !curDate.equals(ind.getFirstFound())){
curDate = ind.getFirstFound()
<tr><th colspan='5' class='day'>#(ind.getFirstFound())</th></tr>
<tr><th>Document ID</th><th>Value</th><th>Owner</th><th>Document Title / Comment</th></tr>
}
}
}
I attempt too user a scala block statement to allow me to keep curDate as a variable within the created scope. This block correctly maintains curDate state, but does not allow me to output anything to the DOM. I did not actually expect this to compile, due to my unescaped, randomly thrown in HTML, but it does. this loop simply places nothing on the DOM, although the decision structure is correctly executed on the server.
I tried escaping using #Html('...'), but that produced compile errors.
Attempt #2:
A lot of google searches led me to the "for comprehension":
#for(ind <- indicators; curDate = ind.getFirstFound()){
#if(curDate == null || !curDate.equals(ind.getFirstFound())){
#(curDate = ind.getFirstFound())
}
<tr><th colspan='5' class='day'>#(ind.getFirstFound())</th></tr>
<tr><th>Document ID</th><th>Value</th><th>Owner</th><th>Document Title / Comment</th></tr>
}
Without the if statement in this block, this is the closest I got to doing what I actually wanted, but apparently I am not allowed to reassign a non-reference type, which is why I was hoping attempt #1's reference declaration of curDate : Date = null would work. This attempt gets me the HTML on the page (again, if i remove the nested if statement) but doesn't get me the
My question is, how do i implement this intention? I am very painfully aware of my lack of Scala knowledge, which is being exacerbated by Play templating syntax. I am not sure what to do.
Thanks in advance!
Play's template language is very geared towards functional programming. It might be possible to achieve what you want to achieve using mutable state, but you'll probably be best going with the flow, and using a functional solution.
If you want to maintain state between iterations of a loop in functional programming, that can be done by doing a fold - you start with some state, and on each iteration, you get the previous state and the next element, and you then return the new state based on those two things.
So, looking at your first solution, it looks like what you're trying to do is only print an element out if it's date is different from the previous one, is that correct? Another way of putting this is you want to filter out all the elements that have a date that's the same date as the previous one. Expressing that in terms of a fold, we're going to fold the elements into a sequence (our initial state), and if the last element of the folded sequence has a different date to the current one, we add it, otherwise we ignore it.
Our fold looks like this:
indicators.foldLeft(Vector.empty[Indicator]) { (collected, next) =>
if (collected.lastOption.forall(_.getFirstFound != next.getFirstFound)) {
collected :+ next
} else {
collected
}
}
Just to explain the above, we're folding into a Vector because Vector has constant time append and last, List has n time. The forall will return true if there is no last element in collected, otherwise if there is, it will return true if the passed in lambda evaluates to true. And in Scala, == invokes .equals (after doing a null check), so you don't need to use .equals in Scala.
So, putting this in a template:
#for(ind <- indicators.foldLeft(Vector.empty[Indicator]) { (collected, next) =>
if (collected.lastOption.forall(_.getFirstFound != next.getFirstFound)) {
collected :+ next
} else {
collected
}
}){
...
}
I am using Gatling 2.0.0-SNAPSHOT (from a few months ago) and I have a CSV file:
search,min_results
test,1000
testing,50
...
I would, ideally, like to check that the number of results are equal or greater than the min_results column, something like:
.get(...)
.check(
jsonPath("$..results")
.count
.is(>= "${min_results}".toInt)
The last line doesn't work as it probably isn't valid Scala but also"${min_results}".toInt tries to convert ${min_results} rather than its value to an Int.
I would settle for just fixing the conversion toInt problem but this might result in a slightly less robust script. However, I could then add a max_results column and use the .in(xx to yy).
Thanks
In this case, toInt definitely won't work, as it would be called before the EL has been resolved.
However, this code snippet would achieve what you want :
.get(...)
.check(
jsonPath("$...results")
.count
.greaterThanOrEqual(session => session("min_results").as[String].toInt))
Here, using as[Int] works as expected, since the min_results attribute has already been resolved from the session at this point.
I'm fairly new to Scala and currently using an ORM called Squeryl against our MySQL database.
What I'm trying to do is looking up plural records that fall within a time range.
For example, in plain SQL, I think it would be something like:
SELECT * FROM records WHERE updated_at >= ? AND updated_at < ?
However, my Scala code to achieve similar behavior as below, gives me an error saying "java.util.Date does not take parameters" at the opening bracket in "from(records)"
def getRecordsBetween(from:java.util.Date, til:java.util.Date):List[Record]
transaction {
from(records)(record =>
where(
record.updatedAt gte from and
record.updatedAt lt til
)
select(record)
).toList
}
}
(where val records = tableRecord
What am I doing wrong here? Thanks a lot in advance.
Method parameters and methods are in the same namespace in Scala, so your from method parameter is "shadowing" the from method on the PrimitiveTypeMode (or CustomTypeMode) object that you brought into scope with a line like the following:
import org.squeryl.PrimitiveTypeMode._
Just change the parameter name to fromDate or start or whatever and you should be fine.