How to bind an array to a parameter used alongside IN operator in sequelize query - postgresql

I had to write a custom postgres sql query, so I used sequelize.query method. But I am a bit lost in how I can bind an array to a parameter used alongside an IN operator. The current code looks something like this, with obviously doesn't work.
sequelize.query('SELECT * FROM students WHERE grade IN $grades', {
bind: { grades: ['A+', 'A'] },
type: sequelize.QueryTypes.SELECT,
});

Use = any instead of in. Change the query text to
SELECT * FROM students WHERE grade = any(string_to_array($grades, ','))
or
SELECT * FROM students WHERE grade = any(('{'||$grades||'}')::text[])
and bind grades as a string, 'A+,A'.
The second option works for other data types too.

Related

Postgres - Query for nested value in nested array

I have a table called clients with a column called configs containing JSON object.
{
"pos_link": {
"primary_id": "000123",
"sub_ids": ["000123", "000124", "00125", "000126"],
},
"prime_tags": {
"tags": ["Children"]
}
}
How do I find all entries where one of the sub_id is '00124'
select *
from clients c,
jsonb_array_elements(c.configs->'pos_link') pos_link,
jsonb_array_elements(pos_link->'sub_ids') sub_ids
where sub_id IN ('00124')
You can use the contains operator ?
select *
from clients
where configs -> 'pos_link' -> 'sub_ids' ? '000124';
This assumes that configs is defined as jsonb (which it should be). If it's not, you need to cast it: configs::jsonb
Online example

How to concat two columns for search with feathers-sequelize?

I need to search for users by name, their first name and last names are stored in separate columns in a postgresql database. The columns need to be concatenated for search to work properly. Typing the full first and last name of a user should match a result.
What could I pass as a query to the find method of a Feathers service that would allow me to do this?
As in the answer linked you can pass the where clause to the Feathers service by modifying params.query in a before hook:
app.service('users').before({
find(hook) {
const where = Sequelize.where(Sequelize.fn("concat",
Sequelize.col("firstname"),
Sequelize.col("lastname")), {
like: '%John Do%'
}
);
hook.params.query.where = where;
}
})

How to insert a vertex with link type property with the orientjs query builder?

I am trying to insert a vertex with orientjs(previously oriento) query builder. My class has a link type property pointing to another class.
I know I can get it to work with a raw query string but I would love to use the query builder.
Here is what I've tried so far :
db.insert()
.into('VertexClassName')
.set({"prop":"value", "linkProperty":"33:1289287"})
db.insert()
.into('VertexClassName')
.set({"prop":"value", "linkProperty":"#33:1289287"})
I get the following error :
Error on saving record in cluster #13
Am I setting properties in the right way ?
Could the error be related to somtehing else ?
I have sucessfully ran an insert query in the cluster #13 with a raw query string in the studio...
According to the official documentation it seems that the problem might be at the end of your statement
db.insert().into('VertexClassName')
.set({"prop":"value", "linkProperty":"33:1289287"}).one()
.then(function (data) {
// callback
});
Check if your code works adding one() to the pipe line
EDITED: I found this method in orientjs.
db.create('VERTEX', 'V')
.set({
key: 'value',
foo: 'bar'
})
.one()
.then(function (vertex) {
console.log('created vertex', vertex);
});
When using Tinkerpop API they recommend using createVertex instead of insert, because createVertex is intended for graphs and insert for Documents... Could you try with the create() method instead?
I am using SQL and it worked.
sql = "INSERT INTO Station set linked = (select from LinkedClass where LinkedProb = 'value'), prop = 'value'"
OrientVertex vertex = new OrientVertex();
vertex = graph.command(new OCommandSQL(sql)).execute();
I don't think that's possible unless you've added a proper field with the right type 'Link' in your schema. (which I rarely do).
Now instead of having the right 'link' type inserted you can do the opposite, store is as a String, and leverage the query functions to use it correctly:
db.insert().into('table').set({prop: '#15:14'}).one();
And it will be converted as String (which is a bit sad) but then you can use that in your queries:
SELECT eval(prop) FROM table;
And it will be 'eval'-ed to a Node RecordID that you can directly use and call functions like expand() on.
For example:
SELECT name FROM (SELECT expand(eval(prop)) FROM table);
Will eval the node stored in the insert(), grab the node, expand it and collect its name property.

mongo-mongoose how to make this query mongoose?

Models
Models -> id, name, makeid
Makes -> id, name
how to make this query mongoose using the make name and not the id ("mitsubishi") ?ex:
SELECT * FROM models
LEFT JOIN makes on models.makeid = makes.id
where makes.name = "mitsubishi"
How can realize this same query in mongo - mongoose ?
If your Model schema, is written like so:
makeid: {type: Schema.Types.ObjectId, ref: 'Makes'}
Then you can do a population query like so:
Model.findOne({}).populate( {path:'makeid'});
This will return an object that looks like this:
{id:'mirage', 'name':'Mirage', makeid:{id:'mitsubishi', name:'Mitsubishi'}}
I would probably name the "makeid" field of Model to "make" to make it more idiomatic.
You'd also get the _id and any other properties. If you want to filter the properties add a select property:
{path:'makerid', select:'id name'}

MongoDB C# offic. List<BsonObject> query issue and always olds values?

I have not clearly issue during query using two criterials like Id and Other. I use a Repository storing some data like id,iso,value. I have created an index("_id","Iso") to performs queries but queries are only returning my cursor if i use only one criterial like _id, but is returning nothing if a use two (_id, Iso) (commented code).
Are the index affecting the response or the query method are failing?
use :v1.6.5 and C# official.
Sample.
//Getting Data
public List<BsonObject> Get_object(string ID, string Iso)
{
using (var helper = BsonHelper.Create())
{
//helper.Db.Repository.EnsureIndex("_Id","Iso");
var query = Query.EQ("_Id", ID);
//if (!String.IsNullOrEmpty(Iso))
// query = Query.And(query, Query.EQ("Iso", Iso));
var cursor = helper.Db.Repository.FindAs<BsonObject>(query);
return cursor.ToList();
}
}
Data:
{
"_id": "2345019",
"Iso": "UK",
"Data": "Some data"
}
After that I have Updated my data using Update.Set() methods. I can see the changed data using MongoView. The new data are correct but the query is always returning the sames olds values. To see these values i use a page that can eventually cached, but if add a timestamp at end are not changing anything, page is always returning the same olds data. Your comments are welcome, thanks.
I do not recall offhand how the C# driver creates indexes, but the shell command for creating an index is like this:
db.things.ensureIndex({j:1});
Notice the '1' which is like saying 'true'.
In your code, you have:
helper.Db.Repository.EnsureIndex("_Id","Iso");
Perhaps it should be:
helper.Db.Repository.EnsureIndex("_Id", 1);
helper.Db.Repository.EnsureIndex("Iso", 1);
It could also be related to the fact that you are creating indexes on "_Id" and the actual id field is called "_id" ... MongoDB is case sensitive.
Have a quick look through the index documentation: http://www.mongodb.org/display/DOCS/Indexes