Sequelize select distinct rows - node.js

Is there a way to select distinct rows from a table using sequelize.js?
I looked through the documentation but the "finder methods" do not specify a way to accomplish this task.

Assuming you want to apply DISTINCT to the following query:
Tuple.findAll({attributes: ['key', 'value']});
then this is a (hackish) way to achieve what you want without having to write the whole query yourself:
Tuple.findAll({attributes: [[Sequelize.literal('DISTINCT `key`'), 'key'], 'value']});
(Tested with Sequelize v2.1.0)
Edit 2015-06-08: Still works with Sequelize v3.1.1

You can do the following:
myModel.findAll({
attributes: [[sequelize.fn('DISTINCT', sequelize.col('col_name')), 'alias_name']],
where:{}
}).then(data => {}).....
taken from issues and it works.

edit your "node_modules/sequelize/lib/dialects/mysql/query-generator.js"
at around line 118
change
var query = "SELECT <%= attributes %> FROM <%= table %>"
into
var query = "SELECT " + ((options.distinct)? 'DISTINCT ':'') +"<%= attributes %> FROM <%= table %>",
now you can add an option distinct: true in your sequelize request
hope it helps -_^

Model.findAll({Attributes: ['col_name1', 'col_name2'], group: ['col_name1', 'col_name2']});
it's perfectly fine with Sequelize 5.21

It's not possible automatically but if you don't mind creating the sql on your own, you could do this:
sequelize.query('sql goes here', null, { raw: plain }).success(function(data){
console.log(data)
})
Have fun :)
UPDATE
Sequelize now uses then instead of success as promise function.
Sequelize.query has been refactored to only use paramters sql and options
raw accepts true/false but no plain as value.
So, according to the new version, the code should look like this:
sequelize.query('sql goes here', { raw: true }).then(function(data){
console.log(data);
});

This is somewhat similar to the solution proposed by Pascal Ludwig, but for those landing here looking to get a list of distinct values for a given column, you can do the following:
MyModel.aggregate('teh_field', 'DISTINCT', { plain: false }).then(...)
// Resolves to: [ { DISTINCT: value1 }, { DISTINCT: value2 }, ... ]
With that, it's easy to transform it into a standard list:
MyModel.aggregate('teh_field', 'DISTINCT', { plain: false })
.map(function (row) { return row.DISTINCT })
.then(function (tehValueList) {
// tehValueList = [ value1, value2, ... ]
})
;

As of Sequelize version 1.7, the select query has been moved into lib/dialects/abstract/query-generator.js.
Around line 1167, change
mainQueryItems.push("SELECT "+mainAttributes.join ....)
to
mainQueryItems.push('SELECT ');
if (options.distinct) {
mainQueryItems.push('DISTINCT ');
}
mainQueryItems.push(mainAttributes.join(', ') + ' FROM ' + options.table);
By the way, I use Sqlite and Postgres, both of which support "DISTINCT". If you're using a dialect that doesn't support distinct, then obviously this line will cause problems for you, since it will be generated for all the SQL flavors that you're using. I suspect this is why this simple change hasn't made it into the main Sequelize source tree.

Related

TypeORM how to do deep-relational queries with relations properties / property?

Atm I'm diving into Nest.js using TypeORM and its query builder.
I've discovered the relations property which can be used and I'm curious if it is possible to achieve the same result from the 2nd return statement in the snippet below by using the "relations syntax" in the first result statement.
It works for just one relation, but if I wanna combine more relations, I don't know how to do this.
I switched to try-hard mode and tried wrapping two objects like this: { ChildEntity_name, ParentEntity.ChildEntity_name }, since I could not spot this subject in the TypeORM docs, but (of course) it resulted in an error.
Any help and resource woulda be highly appreciated.
async getAllDeep(): Promise<Order[]> {
return this.orderRepository.find({
relations: [
'Orderposition',
'Order.Orderposition,
],
});
return this.orderRepository
.createQueryBuilder('order')
.leftJoinAndSelect(
'Order.Orderposition',
'Orderposition',
)
.leftJoinAndSelect(
'Orderposition.Article',
'Article',
)
.leftJoinAndSelect(
'Article.Supplier',
'Supplier',
)
.getMany();
}
}
}
Yes, you can do this. You need to pass relations as a nested object like this:
this.orderRepository.find({
relations: {
Orderposition: {
Article: {
Supplier: true
}
}
},
});
This will result in this query:
SELECT * FROM "Order"
LEFT JOIN "Orderposition" ON "Orderposition"."order_id" = "Order"."id"
LEFT JOIN "Article" ON "Article"."Orderposition_id" = "Orderposition"."id"
LEFT JOIN "Supplier" ON "Supplier"."Article_id" = "Article"."id"

Optional parameters on sequelize query

Good morning.
I'm quite new to NodeJS / sequelize world and I'm currently facing a problem while trying to display a dashboard on screen.
This dashboard has three filters: two dates (period), client name, and employee name. The user can select none, one, two, or all the filters and my database needs to work accordingly.
That being said, my problem is with Sequelize because I don't know how to treat this problem of parameters not being "always" there.
I've seen this question:
Sequelize optional where clause parameters?
but this answer doesn't work anymore. I also tried another way of building the where clause, but I failed on it as well (mainly due to sequelize operators).
The last thing I tried was to make a single query with all parameters included but try to find some value (or flag) that would make sequelize ignore the parameter, for the case when the parameter was no there*, but it looks like Sequelize doesn't have anything like that.
* I've read a question here that has an answer saying that {} would do the trick but I tried that as well but didn't work.
In summary: I need to make a query that can "change" over time, for example:
Foo.findAll({
where: {
id : 1,
}
});
Foo.findAll({
where: {
id {
[Op.in] : [1,2,3,4,5]
},
name: "palmeiira",
}
});
Do you know a way of doing it without the need of using a lot if / switch statements?
I'm currently using Sequelize v. 5.5.1.
Update
I tried doing as suggested by #Anatoly and created a function to build the parameters. It was something like that. (I tried a "smaller" version just to test)
async function test() {
const where = {};
where[Op.and] = [];
where[Op.eq].push({
id: {
[Op.in]: [1,2,3]
}
});
return where;
}
I setted the return value to a const:
const query = await test()
And tried console.log(query)
The result was: { [Symbol(and)]: [ { id: [Object] } ] }, which made me believe that the problem was parsing the Op part so i tried using 'Op.and' and 'Op.in' to avoid that and it solved this problem, but led to another on sequelize that said Invalid value
Do you have any idea where is my error ?
P.S.: #Anatoly very nice idea you gave me on original answer. Thank you very much.
If these three conditions should work together then you can use Op.and with an array of conditions:
const where = {}
if (datesFilter || clientNameFilter || employeenameFilter) {
where[Op.and] = []
if (datesFilter) {
where[Op.and].push({
dateField: {
[Op.between]: [datesFilter.start, datesFilter.finish]
}
})
}
if (clientNameFilter) {
where[Op.and].push({
name: {
[Op.iLike]: `%${clientNameFilter.value}%`
}
})
}
if (employeenameFilter) {
where[Op.and].push({
employeeName: {
[Op.iLike]: `%${employeenameFilter.value}%`
}
})
}
}
const dashboardItems = await DashboardItem.findAll({ where }, {
// some options here
})
If the conditions should work as alternatives then just replace Op.and with Op.or

How to insert an integer with nextval function in an multirow insert in pg-promise

Is it possible to use the nextval function in a pg-promise multirow insert?
I have a database (that I sadly can't change) where the id has to be inserted via the client like this:
INSERT INTO some_object (object_id, object_name)
VALUES (nextval('some_object_seq'), ${object_name})
RETURNING object_id;
This works fine for one insert. But now I have to insert multiple rows at once and tried pgp.helpers.insert:
const cs = pgp.helpers.ColumnSet(['object_id', 'object_name'], { table });
const query = pgp.helpers.insert(values, cs) + 'RETURNING object_id';
database.many(query).then(data => {
return data
}).catch(error => {
logger.error(error, query);
});
Is there any way to use nextval('some_object_seq') in this scenario? Sadly I can't change the default value of the id column in the table definition.
Your column should be defined as this:
{
name: `object_id`,
init: () => `nextval('some_object_seq')`,
mod: `:raw`
}
As opposed to the answer by #baal, you do not need to use def, because you are not providing a default value, rather a complete override for the value, which is what init for.
And it can be used within upsert queries too.
As Bergi wrote, it is possible to add a default expression to the column set like this:
const cs = pgp.helpers.ColumnSet(
[{
name: "object_id",
// setting the DEFAULT value for this column
def: "nextval('some_object_seq')",
// use raw-text modifier to inject string directly
mod: "^",
}, 'object_name'], { table });

Firestore in Datastore mode, query using OR [duplicate]

From the docs:
You can also chain multiple where() methods to create more specific queries (logical AND).
How can I perform an OR query?
Example:
Give me all documents where the field status is open OR upcoming
Give me all documents where the field status == open OR createdAt <= <somedatetime>
OR isn't supported as it's hard for the server to scale it (requires keeping state to dedup). The work around is to issue 2 queries, one for each condition, and dedup on the client.
Edit (Nov 2019):
Cloud Firestore now supports IN queries which are a limited type of OR query.
For the example above you could do:
// Get all documents in 'foo' where status is open or upcmoming
db.collection('foo').where('status','in',['open','upcoming']).get()
However it's still not possible to do a general OR condition involving multiple fields.
With the recent addition of IN queries, Firestore supports "up to 10 equality clauses on the same field with a logical OR"
A possible solution to (1) would be:
documents.where('status', 'in', ['open', 'upcoming']);
See Firebase Guides: Query Operators | in and array-contains-any
suggest to give value for status as well.
ex.
{ name: "a", statusValue = 10, status = 'open' }
{ name: "b", statusValue = 20, status = 'upcoming'}
{ name: "c", statusValue = 30, status = 'close'}
you can query by ref.where('statusValue', '<=', 20) then both 'a' and 'b' will found.
this can save your query cost and performance.
btw, it is not fix all case.
I would have no "status" field, but status related fields, updating them to true or false based on request, like
{ name: "a", status_open: true, status_upcoming: false, status_closed: false}
However, check Firebase Cloud Functions. You could have a function listening status changes, updating status related properties like
{ name: "a", status: "open", status_open: true, status_upcoming: false, status_closed: false}
one or the other, your query could be just
...where('status_open','==',true)...
Hope it helps.
This doesn't solve all cases, but for "enum" fields, you can emulate an "OR" query by making a separate boolean field for each enum-value, then adding a where("enum_<value>", "==", false) for every value that isn't part of the "OR" clause you want.
For example, consider your first desired query:
Give me all documents where the field status is open OR upcoming
You can accomplish this by splitting the status: string field into multiple boolean fields, one for each enum-value:
status_open: bool
status_upcoming: bool
status_suspended: bool
status_closed: bool
To perform your "where status is open or upcoming" query, you then do this:
where("status_suspended", "==", false).where("status_closed", "==", false)
How does this work? Well, because it's an enum, you know one of the values must have true assigned. So if you can determine that all of the other values don't match for a given entry, then by deduction it must match one of the values you originally were looking for.
See also
in/not-in/array-contains-in: https://firebase.google.com/docs/firestore/query-data/queries#in_and_array-contains-any
!=: https://firebase.googleblog.com/2020/09/cloud-firestore-not-equal-queries.html
I don't like everyone saying it's not possible.
it is if you create another "hacky" field in the model to build a composite...
for instance, create an array for each document that has all logical or elements
then query for .where("field", arrayContains: [...]
you can bind two Observables using the rxjs merge operator.
Here you have an example.
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/merge';
...
getCombinatedStatus(): Observable<any> {
return Observable.merge(this.db.collection('foo', ref => ref.where('status','==','open')).valueChanges(),
this.db.collection('foo', ref => ref.where('status','==','upcoming')).valueChanges());
}
Then you can subscribe to the new Observable updates using the above method:
getCombinatedStatus.subscribe(results => console.log(results);
I hope this can help you, greetings from Chile!!
We have the same problem just now, luckily the only possible values for ours are A,B,C,D (4) so we have to query for things like A||B, A||C, A||B||C, D, etc
As of like a few months ago firebase supports a new query array-contains so what we do is make an array and we pre-process the OR values to the array
if (a) {
array addObject:#"a"
}
if (b) {
array addObject:#"b"
}
if (a||b) {
array addObject:#"a||b"
}
etc
And we do this for all 4! values or however many combos there are.
THEN we can simply check the query [document arrayContains:#"a||c"] or whatever type of condition we need.
So if something only qualified for conditional A of our 4 conditionals (A,B,C,D) then its array would contain the following literal strings: #["A", "A||B", "A||C", "A||D", "A||B||C", "A||B||D", "A||C||D", "A||B||C||D"]
Then for any of those OR combinations we can just search array-contains on whatever we may want (e.g. "A||C")
Note: This is only a reasonable approach if you have a few number of possible values to compare OR with.
More info on Array-contains here, since it's newish to firebase docs
If you have a limited number of fields, definitely create new fields with true and false like in the example above. However, if you don't know what the fields are until runtime, you have to just combine queries.
Here is a tags OR example...
// the ids of students in class
const students = [studentID1, studentID2,...];
// get all docs where student.studentID1 = true
const results = this.afs.collection('classes',
ref => ref.where(`students.${students[0]}`, '==', true)
).valueChanges({ idField: 'id' }).pipe(
switchMap((r: any) => {
// get all docs where student.studentID2...studentIDX = true
const docs = students.slice(1).map(
(student: any) => this.afs.collection('classes',
ref => ref.where(`students.${student}`, '==', true)
).valueChanges({ idField: 'id' })
);
return combineLatest(docs).pipe(
// combine results by reducing array
map((a: any[]) => {
const g: [] = a.reduce(
(acc: any[], cur: any) => acc.concat(cur)
).concat(r);
// filter out duplicates by 'id' field
return g.filter(
(b: any, n: number, a: any[]) => a.findIndex(
(v: any) => v.id === b.id) === n
);
}),
);
})
);
Unfortunately there is no other way to combine more than 10 items (use array-contains-any if < 10 items).
There is also no other way to avoid duplicate reads, as you don't know the ID fields that will be matched by the search. Luckily, Firebase has good caching.
For those of you that like promises...
const p = await results.pipe(take(1)).toPromise();
For more info on this, see this article I wrote.
J
OR isn't supported
But if you need that you can do It in your code
Ex : if i want query products where (Size Equal Xl OR XXL : AND Gender is Male)
productsCollectionRef
//1* first get query where can firestore handle it
.whereEqualTo("gender", "Male")
.addSnapshotListener((queryDocumentSnapshots, e) -> {
if (queryDocumentSnapshots == null)
return;
List<Product> productList = new ArrayList<>();
for (DocumentSnapshot snapshot : queryDocumentSnapshots.getDocuments()) {
Product product = snapshot.toObject(Product.class);
//2* then check your query OR Condition because firestore just support AND Condition
if (product.getSize().equals("XL") || product.getSize().equals("XXL"))
productList.add(product);
}
liveData.setValue(productList);
});
For Flutter dart language use this:
db.collection("projects").where("status", whereIn: ["public", "unlisted", "secret"]);
actually I found #Dan McGrath answer working here is a rewriting of his answer:
private void query() {
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("STATUS")
.whereIn("status", Arrays.asList("open", "upcoming")) // you can add up to 10 different values like : Arrays.asList("open", "upcoming", "Pending", "In Progress", ...)
.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot queryDocumentSnapshots, #Nullable FirebaseFirestoreException e) {
for (DocumentSnapshot documentSnapshot : queryDocumentSnapshots) {
// I assume you have a model class called MyStatus
MyStatus status= documentSnapshot.toObject(MyStatus.class);
if (status!= null) {
//do somthing...!
}
}
}
});
}

Increment a column with the default value as null

I need to increment a column with 1 on some occasions, but the default value of that column is null and not zero. How do I handle this case using sequelize? What method could be utilized?
I could do by checking the column for null in one query and updating it accordingly in the second query using sequelize but I am looking for something better. Could I handle this one call?
I'll confess that I'm not terribly experienced with sequelize, but in general you'll want to utilize IFNULL. Here's what the raw query might look like:
UPDATE SomeTable
SET some_column = IFNULL(some_column, 0) + 1
WHERE <some predicate>
Going back to sequelize, I imagine you're trying to use .increment(), but judging from the related source, it doesn't look like it accepts anything that will do the trick for you.
Browsing the docs, it looks like you might be able to get away with something like this:
SomeModel.update({
some_column: sequelize.literal('IFNULL(some_column, 0) + 1')
}, {
where: {...}
});
If that doesn't work, you're probably stuck with a raw query.
First you need to find the model instance and update via itself, or update directly via Sequelize Static Model API.
Then you'll check whether the updated field got nullable value or not ? If fails then do the manual update as JMar propose above
await model.transaction({isolationLevel: ISOLATION_LEVELS.SERIALIZABLE}, async (tx) => {
const user = await model.User.findOne({
where: {
username: 'username',
},
rejectOnEmpty: true,
transaction: tx,
});
const updatedRecord = await user.increment(['field_tag'], {
transaction: tx,
});
if (!updatedRecord.field_tag) {
/** Manual update & Convert nullable value into Integer !*/
await model.User.update({
field_tag: Sequelize.literal('IFNULL(field_tag, 0) + 1')
}, {
where: {
username: 'username',
},
transaction: tx,
});
}
});

Resources