select one output query SPARQL - select

I've written this query in sparql:
SELECT ?spouse
WHERE {
dbr:Zach_Galifianakis dbp:spouse ?spouse.
}
and I have this output:
2012
""#en
"Quinn Lundberg"#en
(https://dbpedia.org/sparql?default-graph-uri=http%3A%2F%2Fdbpedia.org&query=SELECT+%3Fspouse%0D%0AWHERE+%7B%0D%0Adbr%3AZach_Galifianakis+dbp%3Aspouse+%3Fspouse.%0D%0A%7D%0D%0A&format=text%2Fhtml&timeout=30000&signal_void=on&signal_unconnected=on)
I don't understand how to select only the name "Quinn Lundberg"#en. I've tried using FILTER clause but it doesn't work.

Not a generic solution, but this will fetch only the name for your case:
SELECT *
WHERE {
dbr:Zach_Galifianakis dbp:spouse ?spouse.
FILTER (strlen(str(?spouse)) > 0 && lang(?spouse) = 'en')
}
Output

Related

Conditions in prepared statements in postgres

I need to add a condition inside prepared statement in postgres.
Pseudocode (doesn't works, fires an error "argument of WHERE must be type boolean, not type text"):
if (nameFilter) {
whereParam = `name LIKE %${nameFilter}%`
} else {
whereParam = "true"
}
let query = prepare("SELECT * FROM users WHERE $1", whereParam);
Pseudocode (works but looks ugly):
if (nameFilter) {
likeParam = `%${nameFilter}%`
} else {
likeParam = "%"
}
let query = prepare("SELECT * FROM users WHERE name LIKE $1", likeParam);
For some reasons(query is really complex with a bunch of AND) manipulations with a string is not an option, so this will not help
if (nameFilter) {
q = `SELECT * FROM users WHERE name LIKE $1`
} else {
q = "SELECT * FROM users"
}
let query = prepare(q, nameFilter);
Desirable to have statement similar to SELECT * FROM users WHERE $1 AND $2 AND $3 ...
Any suggestions?
This query will work for you.
select * from users where
case
when coalesce($1, '') = '' then true
else (name ~ $1)
end;
The only thing you can pass as a parameter is a constant; you cannot pass part of an SQL query like name LIKE '%pattern%'.
So if your query is really different every time, you have to construct the SQL string in your code, just like you say you cannot do "for some reasons".
It may be annoying, but there is no other way.
When you construct an SQL statement, make sure you never concatenate strings like this:
sql = "SELECT * FROM users WHERE username ='" + username + "'"
because that would be vulnerable to SQL injection.

Use LIKE in WHERE conditions in typeORM Typescript

I'm trying to query on a columns with SQL endswith in a Typescript app
cont tracking_code = '65432'
repo.findValidOne({ where: { tracking_code }});
I want to change it so the tracking_code value ends with the tracking value that I have available on the code
The SQL equivalent would be
SELECT *
FROM repo
WHERE tracking_code LIKE '%65432'
LIMIT 1;
I have tried using a raw query, but it's not what I want.
You need to use Like find operator.
import {Like} from 'typeorm';
cont tracking_code = '65432';
repo.findValidOne({ where: { tracking_code: Like(`%${tracking_code}`) }});

Error when using "ALL" operator when execute query

I need to execute following query using phalcon framework:
"SELECT id FROM table GROUP BY id HAVING '31' = ALL(array_agg(status))"
How can I execute this query using phalcon?
When I do following:
Model::query()
->columns(['id'])
->groupBy('id')
->having('31 = ALL(array_agg(status))')
->execute();
I get this error message:
Syntax error, unexpected token ALL, near to '(array_agg(status)) ', when parsing: SELECT id FROM [SomeNameSpace\Model] GROUP BY [id] HAVING 31 = ALL(array_agg(status)) (137)
I'm not 100% sure which Postgres functions are supported, but you can try like this:
Model::query()
->columns([
'id',
'ALL(array_agg(status)) AS statusCounter'
])
->groupBy('id')
->having('31 = statusCounter')
->execute();
Notice that I moved the aggregation functions in the select, rather in having clause.
UPDATE: here is an example of very custom query. Most functions used are not supported and it's sometimes cleaner just to write a simple SQL query and bind the desired Model to it:
public static function findNearest($params = null)
{
// A raw SQL statement
$sql = '
SELECT *, 111.045 * DEGREES(ACOS(COS(RADIANS(:lat))
* COS(RADIANS(X(coords)))
* COS(RADIANS(Y(coords)) - RADIANS(:lng))
+ SIN(RADIANS(:lat))
* SIN(RADIANS(X(coords)))))
AS distance_in_km
FROM object_locations
ORDER BY distance_in_km ASC
LIMIT 0,5;
';
// Base model
$model = new ObjectLocations();
// Execute the query
return new \Phalcon\Mvc\Model\Resultset\Simple(
null,
$model,
$model->getReadConnection()->query($sql, $params)
);
}
// How to use:
\Models\ObjectLocations::findNearest([
'lat' => 42.4961756,
'lng' => 27.471543300000008
])
You need to add ALL as dialect extension. Check this topic for example https://forum.phalconphp.com/discussion/16363/where-yearcurrenttimestamp-how-to-do-this

Select in Data dictionary

i want get all table names where created person is not "-AOS-" (Dynamics AX). In this code i get only who created first line in table:
for (tablecounter=1; tablecounter<=dict.tableCnt(); tablecounter++)
{
tableId = dict.tableCnt2Id(tablecounter);
common = new DictTable(tableId).makeRecord();
select common where common.createdBy !="";
if(common)
{
info(strFmt('%1---%2',common.createdBy,dict.tableName(common.TableId)));
}
}
You can try with scan over SysModelElement and SysModelElementData tables.
SysModelElement me;
SysModelElementData med;
while select firstOnly10 me
where me.ElementType == UtilElementType::Table
exists join med
where med.ModelElement == me.RecId
&& med.createdBy != '-AOS-'
{
info(me.Name);
}
You could also use the project filter (probably not as fast as a direct SQL query, but depending on your requirements more actionable).

How to sort a query result by the result of a function in mongoDB

How does one sort a query result by the result of a function in mongoDB? In SQL i have the follow code:
select field1,
field2,
myFunction(field1, 0)
from myTable
where field4 = 5
order by 3
I create the function below (inside mongodb) like alternative for my sql query. May not be ideal, but solved my problem:
function() {
var list = Array();
// myColletion is myTable equivalent
db.myCollection.find({ field4: 5}).forEach(
function (vet) {
list.push([ vet.field1,
vet.field2,
myFunction(vet.field1, 0)])
}
);
list.sort(function(a,b){return ((a[1] < b[1]) ? -1 : ((a[1] > b[1]) ? 1 : 0));});
return list;
}