I'm trying to create a transaction in my MMSQL database with Javascript.
I have tried this command which inserts some elements to a table myTable:
const sql = require('mssql');
const sqlConfig = {
user: 'xxx',
password: 'xxx',
server: 'xxx',
database: 'myDatabase',
options: {
encrypt: false
}
};
const result = await connection.query("INSERT INTO [myTable] ([ID],[ClassId],[Active],[LastUpdateDateTime] ,
[LastUpdateUser] ,[Number] ,[ExternalId] ,
[MaterialDefinitionId] ,[CompanyId] ,[IsBlanket] ,
[Type] ,[Subtype] ,[CreatedDate] ,[ValidFromDate] ,
[ValidToDate] ,[OrderedQuantity] ,[DeliveredQuantity] ,
[ReservedQuantity] ,[UnitOfMeasurement] ,[Status],
[Note],[RowVer])
VALUES ('0','0','0','0','0','0','0','0','0','0','0',
'0','0','0','0','0','0','0')");
But i get this timestamp error:
RequestError: Cannot insert an explicit value into a timestamp column. Use INSERT with a column list to exclude the timestamp column, or insert a DEFAULT into the timestamp column.
So i removed all the probably time dependent elements (LastUpdateDateTime , CreatedDate , ValidFromDate , ValidToDate).
But i still get a new error:
RequestError: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_MaterialLot_Company". The conflict occurred in database "myDatabase", table "myTable", column 'ID'.
So i'm a bit lost here. Does someone have an idea about the problem?
Thanks a lot!
RequestError: The INSERT statement conflicted with the FOREIGN KEY
constraint "FK_MaterialLot_Company". The conflict occurred in database
"myDatabase", table "myTable", column 'ID'.
The ID value you are attempting to INSERT needs to already exist in another table. Check to see how FK_MaterialLot_Company is defined. Possibly relates to a table called "MaterialLot_Company"?
Related
I cannot figure out how to proceed with an Upsert & "multiple" onConflict constraints. I want to push a data batch in a Supabase table.
My data array would be structured as follows:
items = [
{ date: "2023-01-26", url: "https://wwww.hello.com"},
{ date: "2023-01-26", url: "https://wwww.goodbye.com"},
...]
I would like to use the Upsert method to push this new batch in my Supabase table, unless if it already exists. To check if it already exists, I would like to use the date, and the url as onConflict criteria, if I understood well.
When I'm running this method
const { error } = await supabase
.from('items')
.upsert(items, { onConflict: ['date','url'] })
.select();
I'm having the following error:
{
code: '42P10',
details: null,
hint: null,
message: 'there is no unique or exclusion constraint matching the ON CONFLICT specification'
}
What am I missing? Where am I wrong?
You can pass more than one column in the upsert into by adding a column in a string (instead of using an array):
const { data, error } = await supabase
.from('items')
.upsert(items, { onConflict: 'date, url'} )
Postgres performs unique index inference as mentioned in https://www.postgresql.org/docs/current/sql-insert.html#SQL-ON-CONFLICT
It is necessary to have unique or indexes for this to work, as you can read in the documentation above:
INSERT into tables that lack unique indexes will not be blocked by
concurrent activity. Tables with unique indexes might block if
concurrent sessions perform actions that lock or modify rows matching
the unique index values being inserted; the details are covered in
Section 64.5. ON CONFLICT can be used to specify an alternative action
to raising a unique constraint or exclusion constraint violation
error.
My goal is to dynamically insert data into a table via knex.
Code looks like this:
const knexService = require("../knexService.js")
async function insertObjectToKnex() {
const insertObject = {
id: "DEFAULT",
someKey: "someValue"
};
await knexService.db("table").insert(inserObject);
}
On DEFAULT the next free id should be used as database id - table is configured and it works with raw sql. With knex.js I get the following error:
invalid input syntax for type integer: "DEFAULT"
Using the useNullAsDefault: true, config is not possible, because the id is not nullable.
How can I trigger the default value in knex - I did not find anything in the documentation or with google, that could at least give a hint to this issue!
While it is not mentioned in the documentation of knex.js one should simply not add fields with a DEFAULT assignement to a query. This will set the default value to the row column.
I am using sequelize for migration. here I execute an INSERT query with following options but its didnot return created records:
const res = oldUsers.map(u => sequelize.query(
`INSERT INTO ${LP_LOCATIONS_TABLE} (name, address, city)
VALUES (
'${u.email}', '${u.address}', '${u.city}');`,
{ type: DataTypes.QueryTypes.INSERT, raw: true },
))
the output is an array of array like below:
[ [[0],[1]] ]
i expect to get created recorders. specially PK. how can I fix it?
I forgot to put RETURNING * at the end of the raw SQL query.
From the doc, you may have to specify the option returning:true to make this happen. I use mySql, so can't test (the returning option is only for postgres).
Objective:
I am trying to do bulk delete in sqlite table, instead of deleting each data with for loop. So, I am trying to use "IN".
Case:
I have two parameters in executing the query. First is type and second is order_id. I want to delete data where the type is "order_book" and order_id are ["B001", "B002", ...].
What I've try but not working:
window.sqlitePlugin.openDatabase({ name: 'dbname.db', location: 'default' }).executeSql("DELETE FROM table_name WHERE type='order_book' AND order_id IN ('B001', 'B002')", [], (res) => { console.log(res.rows); });
// => this is not work
What I've try and works, but, it miss the type parameter:
window.sqlitePlugin.openDatabase({ name: 'dbname.db', location: 'default' }).executeSql("DELETE FROM table_name WHERE order_id IN ('B001', 'B002')", [], (res) => { console.log(res.rows); });
// => data with order_id B001 and B002 deleted
So, whats wrong here? I need to also define what is the type because different type may have same order_id (don't ask why this is happen ...)
Thanks in advance for anyhelp!
If data is stored in mixed case or upper case in the type column then SQLite's case sensitive comparison will not find it. You could check against the data stored or compare strings like this:
WHERE type='order_book' COLLATE NOCASE ...
I have table A one-to-many table B like below.
A.associate = function(models) {
A.hasMany(models.B, {
foreignKey: 'a_id',
as: 'Bs'
});
}
When I insert record B, I use a random a_id which does not exist in A. Therefore, I expect it to report error of foreign key constraint. But it doesn't report error, instead it adds B with a_id set to NULL.
Is there a setting to configure the model definition so that it can fail the operation and report error in such case?
Thanks.
ANSWER MYSELF
Use "allowNull: false" in foreignKey.
https://github.com/sequelize/sequelize/issues/2837