Am using Sequlize 5.8.5 and trying to update a model but, it doesn't seem to be possible unless all fields are provided. For example performing Project.update(args) where args cloud sometimes has a name field with changed value and sometimes not even passed at all, if the name field doesn't need to be updated, am getting an error such as err: { SequelizeValidationError: notNull Violation: projects.name cannot be null ... }.
This method is possible in Sequelize. Here's a test I ran:
let u1 = {username : 'Test User', title_id: 4};
let u2 = {title_id: 4};
User.update(u1, {where : {id : 3}});
User.update(u2, {where : {id : 5}});
Here is the generated SQL:
Executing (default): UPDATE `muser` SET `username`='Test User',`title_id`=4 WHERE `id` = 3
Executing (default): UPDATE `muser` SET `title_id`=4 WHERE `id` = 5
How are you creating your args object? The error suggests something like this: let args = {field1 = null} where Project.field1 does not allow null values.
Related
How can I find a camp name as "campName" ( column name of PSQL table database ) using type ORM. Right now I am using plain SQL query like below one
SELECT
camp.name as "campName"
FROM
campaigns camp
WHERE
camp.id = 13
but when I use findOne() function of type ORM , I am always getting camp name as "name" ( actual colum name )
typeorm fuction :
const user = await this.campRepository.findOne(
{ where:
{ id: 13 }
}
);
I tried to use above function of type orm, I am getting all user data , for example : name: camp one ,
Is there a way to get it as
campName : camp one ?
EXAMPLE TABLE
: table camp
id
name
place
13
camp one
LA
I have a ArrayField in a Peewee model backed by postgresql DB. How can I append to that field on conflict while upserting in bulk?
Model:
class User(Model):
id = BigAutoField(primary_key=True, unique=True)
tags = ArrayField(CharField, null=True)
SQL query I want to execute:
update user as u set tags = array_append(u.tags, val.tag)
from (values (2, 'test'::varchar)) as val(id, tag)
where u.id = val.id;
I've been trying for to figure out even for single insert, but facing issues in typecasting:
User.insert(user).on_conflict(
conflict_target=[User.id],
update={User.tags: fn.array_append(user['tag'])}
).execute()
Error I'm getting:
function array_append(unknown) does not exist
HINT: No function matches the given name and argument types. You might need to add explicit type casts.
How do I type cast the text to varchar in peewee?
You can try the following:
User.insert(user).on_conflict(
conflict_target=[User.id],
update={User.tags: fn.array_append(user['tag'].cast('varchar'))}
).execute()
I have following query which select from employee table where name is "max" and ID not in 123 and 444.
Not in IDs can grow in future. But I am receiving error as
Error
( 8023): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: DatabaseException(near "?": syntax error (code 1 SQLITE_ERROR): , while compiling:
Query
List<String> a = [];
a.add("123");
a.add("444");
var table = await mydb.rawQuery(
"SELECT value from employee WHERE employeename = ? AND id NOT IN ? ORDER BY timestamp DESC",
["max", a]);
If the LIST is unpredictable, one way is that you can use JOIN to create your select statement with required value of NOT IN. Below is one sample.
void main() {
List<String> a = [];
a.add("123");
a.add("444");
var select =
'SELECT value from employee WHERE employeename = ? AND id NOT IN (\'' +
(a.join('\',\'')).toString() +
'\') ORDER BY timestamp DESC';
var table = await mydb.rawQuery(select, ["max"]);
}
If you print the variable select you will get
SELECT value from employee WHERE employeename = ? AND id NOT IN ('123','444')
ORDER BY timestamp DESC.
Then you can pass the above statement to rawquery and get your result.
P.S:Use your single quote and double quote accordingly.
I'd go for #arun-palanisamy 's solution, see his comment. Props go to him. I just tried the following -- with Groovy/Postgres, but the error seems to be the same, so you might want to give it a try:
String[] a = ['123', '444']
// your code, throws 'ERROR: syntax error at or near "$2"':
// def table = sql.execute("SELECT value from employee WHERE employeename = ? AND id NOT IN ? ORDER BY timestamp DESC", ["max", a])
// code of arun-palanisamy, compiles:
def table = sql.execute("SELECT value from employee WHERE employeename = ? AND id NOT IN (${a.join(', ')}) ORDER BY timestamp DESC", ["max", a])
Side notes:
You might want to try a different type for a, such as Array in my code, or even a HashMap.
There are examples (like here) where the number of ? are generated dynamically.
Update: Go for this answer, we posted simultaneously
I have a HQL query like this:
string QueryString = select client, transporter
from BaseClient as client, BaseTrans as transporter
where client.tr = transporter.Id and transporter.badge = 1
order by transporter.date;
But when I use this hql I receive the following error :
The value "System.Object[]" is not of type "xxx" and cannot be used in this generic collection.
Parameter name: value
Just like Example but, when I omit the Transporter entity in my select it works.
Like :
string QueryString = select client
from BaseClient as client, BaseTrans as transporter
where client.tr = transporter.Id and transporter.badge = 1
order by transporter.date;
But I need transporter in my select, because I use order by.
By the way, I have 2 hbm Client.hbm.xml and Transporter.hbm.xml. Each hbm have their own Class and Table.
i call it with :
IQuery requete = this.CreateQuery(QueryString);
IList<Client> executions = requete.List<Client>();
it hang on this line, when hibernate try to convert to the list
This happens because your result-set will likely be a multi-dimensional array where the first column represents a Client and the 2nd column contains a Transporter.
What happens if you change your code like this:
IQuery requete = this.CreateQuery(QueryString);
var result = requete.List();
var clients = result[0] as IEnumerable<Client>;
(I have no NHibernate installed on this system so I cannot just test something out quickly without creating and setting up a new project. :)
I'm trying to do an extremely simple active record query :
#row = Blazer.where(username: 'test').first
PostgreSQL generation :
Blazer.where(username: 'test').to_sql
outputs :
SELECT "blazer".* FROM "blazer" WHERE "username"."value" = 'test'
which causes an error :
ERROR -- : PG::UndefinedTable: ERROR: missing FROM-clause entry for table "username"
I expected the following PostgreSQL result :
SELECT "blazer".* FROM "blazer" WHERE "username" = 'test'
How can I fix this?
I'm using active record with Sinatra and the app runs on Heroku.
My Blazer class is the following :
class Blazer < ActiveRecord::Base
# phone:string username:string location:string
end
Maybe this is not the correct answer, but I was getting the same error.
I was looking for a Venue with a certain name
venue_name = params.require(:season).permit([:venue_name])
venue = Venue.find_by_name(venue_name)
I also tried with
venue = Venue.where(name: venue_name).first
Both failed saying because it was trying this query
SELECT "venues".* FROM "venues" WHERE "name"."venue_name" = 'venue name' LIMIT 1)
When I was trying this in the console everything looked OK. But when I checked what I was looking for was quite obvious
params.require(:season).permit([:venue_name])
Returns a Hash with only venue_name as key, so instead of looking for a key i was looking for a Hash.
I switched to params.require(:season).permit([:venue_name])[:venue_name] and the issue was fixed.