How to Check if value exists in sql column? - javascript

I want Chack If Value exists in coulmn, If value exist do not insert to table.
If not exist insert to table a new data.
I tried this but not works..
my code in node.js
`
//add new meeting
async function addNewMeeting(meeting: Meeting): Promise<Meeting>{
const sql = `INSERT INTO meetings Values (
DEFAULT,
${meeting.meeting_code},
'${meeting.meeting_start_date}',
'${meeting.meeting_end_date}',
'${meeting.meeting_description}',
'${meeting.meeting_room}'
)`;
const result:OkPacket = await dal.execute(sql);
meeting.id = result.insertId;
return meeting;
}
`
I tried to chack if the value - '2022-10-15 07:03:42' exist or not.
If not exists insert to table a new data.
if exist send a error that cannot insert a new meeting because there is already meeting at this time.
thanks :)

You can solve this at the SQL level by using the keyword UNIQUE when defining that column in the table. This will prevent you from being able to insert duplicate values.
SQL UNIQUE
Note that this will throw an error and depending on the package you are using to connect to your database, you might need some error handling.
Alternatively in your javascript you can select all values in the column that should be unique, and then only proceed with the insertion code if there is not a match.

Related

Updating with INSERT INTO on Conflict Error

TWO QUESTIONS IN ONE:
Number one: This returns Failing row contains for name column and some more columns when trying to do it in SQL. However I know for a fact that the id allready exsist in the table. So how can I prevent it from giving this error?
Number two: The code returns error: syntax error at or near "$1" when ran in node? Is it beacuse values is a string and how can i prevent this?
This gives error error: syntax error at or near "$1". I have a feeling
let values = ("("+req.body.oldid+","+false+"),("+req.body.newid+","+true+")")
console.log(values) // returns (70,false),(4,true)
const results = await db.query("INSERT INTO practiceSite (id,frontpage) VALUES $1 ON CONFLICT DO UPDATE frontpage = values(frontpage);",[values])
Based on your use case, it looks like you'll only ever be inserting 2 entries at a time, so this should work.
In your example values is seen as a string, so we need to be more granular and pass in each parameter, and create the rows.
const results = await db.query(`
INSERT INTO practiceSite (id, frontpage)
VALUES ($1, FALSE), ($2, TRUE)
ON CONFLICT
DO UPDATE SET frontpage = EXCLUDED.frontpage;
`,
[req.body.oldid, req.body.newid]
)

Return inserted values from 'insert' query

I have simple table and I need to insert in to it values from array, but only values which are not exists in table and return from query inserted values, how I can do this?
I have next query, but it just inserts values:
INSERT INTO my_table(id, card_id, size)
VALUES ${myArray.map(item => `($${addDbValue(item.id, dbValues)},
$${dbValues.push(item.card_id)}::int, '24')`)}
`, dbValues)
unique is card_id
You seem to want on conflict and returning:
insert into my_table(id, card_id, size)
values (?, ?, ?)
on conflict (card_id) do nothing
returning *
The query inserts the new row, and returns the entire row (including columns that were not initially given for insert). If a row already exists with the same card_id, the insert is not performed (for this to work, you need a unique index or constraint on card_id).
Note that you should be using query parameters (as shown above) rather than concatenating variables in the query string. Have a look at the parameterized query feature of your client.

How to prevent the sequelize from creating the output clause

When I do a create using sequelize it returns me the response i.e. the newly created entry row in the response,
Sequelize Create Object Code:
let createdObj= await sequelize.ModelName.create(modelObject,{ transaction :t, //more options can be added here, need some value of option that prevents the output inserted })
Below is the query created:
INSERT INTO [TABLE_NAME] ([COL1],[COL2],[COL3],[COL4]) OUTPUT INSERTED.* VALUES (#0,#1,#2,#3,#4)
Now I don't want the output clause to be part of the query, I want a simple insert like:
INSERT INTO [TABLE_NAME] ([COL1],[COL2],[COL3],[COL4]) VALUES (#0,#1,#2,#3,#4)
I don't want the output clause to be part of the query.
How can I achieve this in at the query level as well as at the model level? In some Create operations, I want the output clause and in some create operations, I don't want.
EDIT 1
On Further research I found an option called { returning: false } this does what is required i.e. create an insert query like this INSERT INTO [TABLE_NAME] ([COL1],[COL2],[COL3],[COL4]) VALUES (#0,#1,#2,#3,#4) but now the Sequelize is breaking because it's expecting those values back in return idk why?
C:\Users\MG265X1\project\node_modules\sequelize\lib\dialects\mssql\query.js:389
id = id || results && results[0][this.getInsertIdField()];
^
TypeError: Cannot read property 'id' of undefined
at Query.handleInsertQuery (C:\Users\MG265X1\project\node_modules\sequelize\lib\dialects\mssql\query.js:389:39)
Turns out if an autoIncrementAttribute is present in the model, it will look for the output clause, removing the attribute {autoIncrement: true } from the model hasn't helped as IDENTITY_INSERT cannot be null. How do I move ahead on this??
Edit 2 I could get it working with a combination of { returning: false } and {hasTriggers: true}. Have hasTriggers Attribute as true in your Model, this will allow you to single creates but for bulk Creates pass option returning: false at the time of bulkCreate.
Note: When using bulkCreate with { returning: false } you'll not be able to get the autogenerated Id, It's a trade-off that we had to live with as we want
bulkCreate to work with triggers, we ended up fetching the Id later from DB
Seems I raised this issue but was closed as it wasn't good SSCCE

Objection.js How to use outer values in inner query?

I'm struggling with a somewhat more complex SQL Query which HAS TO BE in Objection.js.
Below is the code so far
const tagEntry = await Tag_overview.query()
.where('playable') //the playable column is a boolean
.whereExists(
InnerTableName.query().findById([<normal variable>, tag.id]) //<= tag.id is the id of the row in the outer query
)
)
.orderBy(raw('random()'))// this randomly orders the selection
.limit(1)
"tag.id" should be the value of the row in the top/outer query thats currently being checked. In SQL I'd solve it with a simple line like (< normal variable> is a Javascript variable passed into the query and can be trated as a hardcoded value, it and tagid are a compound key)
and EXISTS (SELECT tagid, othercolumn FROM kunstmakler_preselection WHERE tag.id = tagid AND <normal variable> = othercolumn)
But I have absolutely no clue how to do this in Objection.js. Yes, it needs an inner Query, but HOW do I pass this tag.id in there? I'm completely lost and neither the API Reference nor the Recipe Book is any help (found here: https://vincit.github.io/objection.js/recipes/ )
Is a join necessary here? Would it be worth it? [The tagoverview Table is rather small while "InnerTableName" is quite large]. I feel like that can't really be the solution since in ülain SQL it'd be such a smooth one liner
First make sure that you have declared composite key correctly in model InnerTableName https://vincit.github.io/objection.js/recipes/composite-keys.html
Then you should be able to do:
.whereExists(
InnerTableName.query().findById([theJsVariable, ref("Tag_overview.id")])
)

Cannot delete from mysql (file.size)

First I inserted a new record into a database with a field file_size. It all works fine. Then I want to delete the record with a given name and size from the database. It works with name, but when I add AND statement it doesnt work.
$conn->query("DELETE FROM mytable WHERE name LIKE '%{$t}' AND file_size = '$file_size'");
file_size is passed through $file_size= $_POST['size']; and it works correctly. The number in the database and the one passed is the same. I have no idea why the above doesnt work...at first I thought that maybe these are different data types and hence I am comparing string with integer, but in Javascript it shouldnt matter...Any advice would be greately appreciated.
Maybe prepare request
$query=$conn->prepare("DELETE FROM mytable WHERE name LIKE :like_param AND file_size = :filesize");
$query->excute(array(':like_param' => '%'.$t, ':filesize' => $file_size));

Categories