Use LIKE in WHERE conditions in typeORM Typescript - postgresql

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}`) }});

Related

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

DynamicLinq build select with subquery

I dynamically build select with System.Linq.Dynamic.Core. I want to add another column (subquery). Is this possible?
I need to get same results as this query:
var test = this.DbContext.Countries.Select(t => new
{
t.Id,
t.ISOCode,
lookup = t.Translates.Where(t2 => t2.LangISOCode=="ENG").Select(t2 => t2.Title).FirstOrDefault()
}).ToArray();
I get this far:
this.DbContext.Countries.Select("new(Id,ISOCode)").ToDynamicArrayAsync()
but not sure how to add additional subquery column.
Solution is:
await this.DbContext.Countries.Select("new(Id,ISOCode,Translates.Where(LangISOCode=\"SLV\").Select(Title).FirstOrDefault() as translates)").ToDynamicArrayAsync();
I found solution by combing code from source tests (select, where, firstordefault).

OrientDB select record count from all graph classes

Any way to get record count for each graph class (V, E and their subclasses)?
I tried to build query in SQL format for current case:
SELECT #class, count(*) FROM V GROUP BY #class
SELECT #class, count(*) FROM E GROUP BY #class
But using count() + GROUP BY is extrimply slow combination.
While console command list classes works fast and return values for count of records in each class (field RECORDS), how to extract this counts via SQL query (or via OrientJS API)?
The main idea is find a way to:
Get list of all classes if database
Get count of records that stored in each class
Technical details
In OrientDB functions you have access to orient variable that have .getDatabase() method. And this method return JAVA ODatabaseDocumentTx class instance. This class provides the method .countClass(className) that returns the number of the records of the class className (method documentation) and it works realy fast.
Solution
Create function in OrientDB Studio with name "getClassCounts", language "javascript", idempotent: true:
var db = orient.getDatabase();
var classesRawInfo = db.getMetadata().getImmutableSchemaSnapshot().getClasses().toArray();
var classesList = {};
var i = classesRawInfo.length;
while(--i) {
var className = classesRawInfo[i].name;
classesList[className] = db.countClass(className);
}
return classesList;
Executing:
via SQL: SELECT getClassCounts()
I think it's not possible, also because it wouldn't so fast as in the console

Find distinct value using LokiJS?

Is there any way to find distinct value like using mongo command db.collection.distinct() using lokiJS
There is no in-built facility to get distinct values at the moment, so at the moment you would have to iterate a ResultSet or DynamicView to work that out, which should be pretty easy:
let dist = [];
view.forEach((elem) => {
if (dist.indexOf(elem) === -1) {
dist.push(elem);
}
});
return dist;
I can open an issue on github so the feature gets implemented if you want, as it sounds interesting.

Pagination with native query in slick

I am using Slick to connect to Postgres Database in our application. I have a generic filtering logic, where a Filter object will be passed from the UI, and it should return results with pagination. The Filter object should be generic so that it can be re-used.
Pseudo code of filter object is given below:
Filter = {
type: table
prop: List_of_conditions
page : 1
size : 10
}
Currently, I am building a native SQL from the Filter object and executing it. However, I am not able to use take and drop before the query is actually getting executed. It is currently getting all the results, and then dropping the unnecessary records.
I know how to do it with the slick queries, but not sure how to use pagination with the native queries?
val res = StaticQuery.queryNA[Entity](queryStr).list.drop((filter.pageNo- 1) * filter.pageSize).take(filter.pageSize)
I am using Slick 2.1
When you are using plain sql, you can't use the collection operators to build a query. You have to do it all in SQL:
val limit = filter.pageSize
val offset = (filter.pageNo- 1) * filter.pageSize
val res = StaticQuery.queryNA[Entity](queryStr ++ s" LIMIT $limit OFFSET $offset").list
I haven't tested it but i would suggest you to try to move .list call to the end
val res = StaticQuery.queryNA[Entity](queryStr).drop((filter.pageNo- 1) * filter.pageSize).take(filter.pageSize).list