Squeryl geo queries with a postgres backend? - squeryl

How can I perform geo queries using Squeryl with a postgres backend? The sort of queries I want to run are "return all users within x kilometres", etc.
If geo queries aren't supported directly/through a plugin, how can I run raw SQL queries? I saw one gist and it looked complicated.
Update
Specifically I want to run the following query:
SELECT events.id, events.name FROM events
WHERE earth_box( {current_user_lat}, {current_user_lng},
{radius_in_metres}) #> ll_to_earth(events.lat, events.lng);
This is taken from http://johanndutoit.net/searching-in-a-radius-using-postgres/

This object should solve your problem.
object object RawSql {
def q(query: String, args: Any*) =
new RawTupleQuery(query, args)
class RawTupleQuery(query: String, args: Seq[Any]) {
private def prep = {
val s = Session.currentSession
val st = s.connection.prepareStatement(query)
def unwrap(o: Any) = o match {
case None => null
case Some(ob) => ob.asInstanceOf[AnyRef]
case null => null
case a#AnyRef => a
case a#_ => a
}
for(z <- args.zipWithIndex) {
st.setObject(z._2 + 1, unwrap(z._1))
}
st
}
def toSeq[A1]()(implicit f1 : TypedExpressionFactory[A1,_]) = {
val st = prep
val rs = st.executeQuery
try {
val ab = new ArrayBuffer[A1]
val m1 = f1.thisMapper.asInstanceOf[PrimitiveJdbcMapper[A1]]
while(rs.next)
ab.append(m1.convertFromJdbc(m1.extractNativeJdbcValue(rs, 1)))
ab
}
finally {
rs.close()
st.close()
}
}
def toTupleSeq[A1,A2]()(implicit f1 : TypedExpressionFactory[A1,_], f2 : TypedExpressionFactory[A2,_]) = {
val st = prep
val rs = st.executeQuery
try {
val ab = new ArrayBuffer[(A1,A2)]
val m1 = f1.thisMapper.asInstanceOf[PrimitiveJdbcMapper[A1]]
val m2 = f2.thisMapper.asInstanceOf[PrimitiveJdbcMapper[A2]]
while(rs.next)
ab.append(
(m1.convertFromJdbc(m1.extractNativeJdbcValue(rs, 1)),
m2.convertFromJdbc(m2.extractNativeJdbcValue(rs, 2))))
ab
}
finally {
rs.close()
st.close()
}
}
}
}
I got from this gist:
https://gist.github.com/max-l/9250053

Related

Select one row with same id and match value in another column from another table

I'm currently working on a Spring Boot Webapp where I want to retreive tasks with JPA.
A Task can have multiple requirements and my customer creates requirement_answers which are connected to his wedding. I now want to select all tasks where all the requirement.answer_value are answered with 'true'.
My relevant Database Schema is:
My current query is this:
I now want to check that the task with the same uuid has all requirement_answer with true?
How can I achieve this?
Greetings
EDIT:
My Solution, filtered in Code instead of jpql as I could not get it working
#Query("""
select t, ra
from
Task t,
RequirementAnswer ra,
Requirement r,
Wedding w
where
ra.requirement = r and
w.id = :weddingId and
t member of r.tasks"
""")
fun findByWedding(weddingId: Long): List<Tuple>?
}
Here is the filtering:
fun getTasksByWedding(wedding: Wedding?): List<Task> {
val tasks: MutableMap<Task,String> = mutableMapOf()
wedding?.id?.let { taskRepository.findByWedding(it) } ?.map {
val task = it.get(0) as Task
val requirementAnswer = it.get(1) as RequirementAnswer
tasks[task]?.let { taskAnswer ->
if(taskAnswer != requirementAnswer.answerValue){
tasks.remove(task)
}
}?: let {
if(requirementAnswer.answerValue == "true"){
tasks[task] = requirementAnswer.answerValue
}
}
} ?: throw ResponseStatusException(HttpStatus.BAD_REQUEST, "Wedding doesn't exist")
return tasks.map { it.key }
}
With SQL you can do use subselects to compare the counts:
select t.*
from task t
join task_requirement tr on t.uuid = tr.task_id
join requirement r on tr.requirement_id = r.id
join requirement_answer ra1 on r.id = ra1.requirement_id
join wedding_requirement_answer wra1 on ra1.id = wra1.requirement_answer_id
where wra1.wedding_id = 1
and ( (select ra2.requirement_id
from requirement_answer ra2
join wedding_requirement_answer wra2 on ra2.id = wra2.requirement_answer_id
where wra2.wedding_id = wra1.wedding_id
and ra2.requirement_id = ra1.requirement_id))
=
(select ra3.requirement_id
from requirement_answer ra3
join wedding_requirement_answer wra3 on ra3.id = wra3.requirement_answer_id
where wra3.wedding_id = wra1.wedding_id
and ra3.requirement_id = ra1.requirement_id
and ra3.answer_value = 'true');

kotlin SQLite database always writing default values, never new ones

here is the class I set up for my database. database handler being the inner class.
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import android.content.ContentValues
import android.util.Log
import java.sql.Date
class Scores {
var id : Int = 0
var dataBaseName = "ScoreDatabase"
var averageTime = 0.0f
val date = Date(System.currentTimeMillis()).toString()
constructor(averageTime:Float) {
this.averageTime = averageTime
Log.d("Poop", averageTime.toString())
}
constructor()
inner class DataBaseHandler(var context:Context, tableName:String): SQLiteOpenHelper(context, dataBaseName, null,1){
val TABLE_NAME = tableName
val COL_ID = "id"
val COL_AVG = "Average_Time"
val COL_DATE = "Date"
override fun onCreate(db: SQLiteDatabase?) {
val createTable = "CREATE TABLE " + TABLE_NAME +" (" +
COL_ID +" INTEGER PRIMARY KEY AUTOINCREMENT," +
COL_AVG + " VARCHAR(256)," +
COL_DATE +" VARCHAR(256)"
db?.execSQL(createTable)
}
override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
fun insertData(score: Scores){
val db = this.writableDatabase
var cv = ContentValues()
cv.put(COL_AVG,score.averageTime)
cv.put(COL_DATE,score.date)
var result = db.insert(TABLE_NAME,null,cv)
if(result == -1.toLong())
Log.d("POOP", "fail score table in addition")
else
Log.d("POOP", "Success score table in addition" )
}
fun readData(): MutableList<Scores>{
var list: MutableList<Scores> = ArrayList()
val db = this.readableDatabase
val query = "Select * from $TABLE_NAME"
val result = db.rawQuery(query,null)
if (result.moveToFirst()){
do {
var score = Scores()
var id = result.getString(0).toInt()
var AvgTime = result.getString(1).toFloat()
var date = result.getString(2).toString()
list.add(score)
}while (result.moveToNext())
}
result.close()
db.close()
return list
}
}
}
I tried this where the scores class and the handler were two separate classes, but it generated the same results.
here is how I write to the database (from 4 separate activities. in each activity the tablename is different. in this one for example it is 'additionDataBase')
val scores = Scores("%.3f".format(timeKeeper.averageNumber).toFloat())
val db = scores.DataBaseHandler(context, "additionDataBase")
db.insertData(scores)
and here is how I read from the database which is in a different activity that shows the averageTime from each table. here is the code for one of them
val context: Context? = activity
val adb = Scores().DataBaseHandler(context!!,"additionDataBase")
val data = adb.readData()
TextViewAdScore.text = data[0].averageTime.toString() + " " + data[1].date
I think I am missing something, but I can't seem to find what it is.
so far, no matter how many times I do this. the output is always 0.0f
Look at what you do in readData:
var score = Scores()
var id = result.getString(0).toInt()
var AvgTime = result.getString(1).toFloat()
var date = result.getString(2).toString()
list.add(score)
id, AvgTime, and date are retrieved but not used in any way, so your code is equivalent to just writing list.add(Scores()). (Side note: there's no reason for them to be var, and why the case inconsistency between AvgTime and the rest?)

Use method in sql interpolator

Using scala 2.11 and Slick 2.11
In a scala class, I have 2 methods:
getSQL which returns String SQL
getSqlStreamingAction which returns a composed SqlStreamingAction using sql interpolator
The code
def getSQL(id: Int): String = {
var fields_string = "";
for ((k,v) <- field_map) fields_string += k + ", ";
fields_string = fields_string.dropRight(2) // remove last ", "
"SELECT "+ fields_string +" FROM my_table WHERE id = " + id
}
def getSqlStreamingAction (id: Int): SqlStreamingAction[Vector[OtherObject], OtherObject, Effect] = {
val r = GetResult(r => OtherObject(r.<<, r.<<))
// this works
var fields_string = "";
for ((k,v) <- field_map) fields_string += k + ", ";
sql"""SELECT #$fields_string FROM my_table WHERE id = #$id""".as(r)
// But I want to use the method getSQL to retrieve the SQL String
// I imagine something like this, but of course it doesn't work :)
//sql"getSQL($id)".as(r)
I want to have separated methods for unit tests purposes, so I want to use getSQL method for sql interpolator
So, how can I use a method for Slick sql interpolator?
Note: I'm pretty new in Scala
-1 for me.
Solution:
def getSqlStreamingAction (id: Int): SqlStreamingAction[Vector[OtherObject], OtherObject, Effect] = {
val r = GetResult(r => OtherObject(r.<<, r.<<))
var sql_string: String = getSQL(id)
sql"""#$sql_string""".as(r)

Squeryl partial update does not compile

I'm not sure what squeryl is trying to tell me here:
Error: Cannot prove that org.squeryl.dsl.fsm.Unconditioned =:= org.squeryl.dsl.fsm.Conditioned.
On:
inTransaction {
update(AppDB.postTable) { p =>
where(p.id === postId)
set(p.upVotes := p.upVotes.~ + 1)
}
The error is on the set clause
schema:
object AppDB extends Schema {
val postTable = table[Post]("post")
val replyTable = table[Reply]("reply")
val postToReplies = oneToManyRelation(postTable, replyTable)
.via((p,r) => p.id === r.postId)
}
case class Post(body: String, image:Option[String]) extends KeyedEntity[Long] {
val id: Long = 0
val posted: Date = new Date()
var upVotes: Long = 0
var downVotes: Long = 0
}
case class Reply(postId: Long, body: String, image:Option[String]) extends KeyedEntity[Long] {
val id: Long = 0
val posted: Date = new Date()
}
Thanks for any help.
Try using () instead of {} around your where and set clauses, like:
inTransaction {
update(AppDB.postTable) ( p =>
where(p.id === postId)
set(p.upVotes := p.upVotes.~ + 1)
)
}
I am not sure why, but I have had issues with {} in the past. When I tested the change against your code, the problem seemed to get resolved.

How to use ScalaQuery to insert a BLOB field?

I used ScalaQuery and Scala.
If I have an Array[Byte] object, how do I insert it into the table?
object TestTable extends BasicTable[Test]("test") {
def id = column[Long]("mid", O.NotNull)
def extInfo = column[Blob]("mbody", O.Nullable)
def * = id ~ extInfo <> (Test, Test.unapply _)
}
case class Test(id: Long, extInfo: Blob)
Can I define the method used def extInfo = column[Array[Byte]]("mbody", O.Nullable), how to operate(UPDATE, INSERT, SELECT) with the BLOB type field?
BTW: no ScalaQuery tag
Since the BLOB field is nullable, I suggest changing its Scala type to Option[Blob], for the following definition:
object TestTable extends Table[Test]("test") {
def id = column[Long]("mid")
def extInfo = column[Option[Blob]]("mbody")
def * = id ~ extInfo <> (Test, Test.unapply _)
}
case class Test(id: Long, extInfo: Option[Blob])
You can use a raw, nullable Blob value if you prefer, but then you need to use orElse(null) on the column to actually get a null value out of it (instead of throwing an Exception):
def * = id ~ extInfo.orElse(null) <> (Test, Test.unapply _)
Now for the actual BLOB handling. Reading is straight-forward: You just get a Blob object in the result which is implemented by the JDBC driver, e.g.:
Query(TestTable) foreach { t =>
println("mid=" + t.id + ", mbody = " +
Option(t.extInfo).map { b => b.getBytes(1, b.length.toInt).mkString })
}
If you want to insert or update data, you need to create your own BLOBs. A suitable implementation for a stand-alone Blob object is provided by JDBC's RowSet feature:
import javax.sql.rowset.serial.SerialBlob
TestTable insert Test(1, null)
TestTable insert Test(2, new SerialBlob(Array[Byte](1,2,3)))
Edit: And here's a TypeMapper[Array[Byte]] for Postgres (whose BLOBs are not yet supported by ScalaQuery):
implicit object PostgresByteArrayTypeMapper extends
BaseTypeMapper[Array[Byte]] with TypeMapperDelegate[Array[Byte]] {
def apply(p: BasicProfile) = this
val zero = new Array[Byte](0)
val sqlType = java.sql.Types.BLOB
override val sqlTypeName = "BYTEA"
def setValue(v: Array[Byte], p: PositionedParameters) {
p.pos += 1
p.ps.setBytes(p.pos, v)
}
def setOption(v: Option[Array[Byte]], p: PositionedParameters) {
p.pos += 1
if(v eq None) p.ps.setBytes(p.pos, null) else p.ps.setBytes(p.pos, v.get)
}
def nextValue(r: PositionedResult) = {
r.pos += 1
r.rs.getBytes(r.pos)
}
def updateValue(v: Array[Byte], r: PositionedResult) {
r.pos += 1
r.rs.updateBytes(r.pos, v)
}
override def valueToSQLLiteral(value: Array[Byte]) =
throw new SQueryException("Cannot convert BYTEA to literal")
}
I just post an updated code for Scala and SQ, maybe it will save some time for somebody:
object PostgresByteArrayTypeMapper extends
BaseTypeMapper[Array[Byte]] with TypeMapperDelegate[Array[Byte]] {
def apply(p: org.scalaquery.ql.basic.BasicProfile) = this
val zero = new Array[Byte](0)
val sqlType = java.sql.Types.BLOB
override val sqlTypeName = "BYTEA"
def setValue(v: Array[Byte], p: PositionedParameters) {
p.pos += 1
p.ps.setBytes(p.pos, v)
}
def setOption(v: Option[Array[Byte]], p: PositionedParameters) {
p.pos += 1
if(v eq None) p.ps.setBytes(p.pos, null) else p.ps.setBytes(p.pos, v.get)
}
def nextValue(r: PositionedResult) = {
r.nextBytes()
}
def updateValue(v: Array[Byte], r: PositionedResult) {
r.updateBytes(v)
}
override def valueToSQLLiteral(value: Array[Byte]) =
throw new org.scalaquery.SQueryException("Cannot convert BYTEA to literal")
}
and then usage, for example:
...
// defining a column
def content = column[Array[Byte]]("page_Content")(PostgresByteArrayTypeMapper)