I have a little problem on delete datas on my database.
I'm doing a app to create notes for movies (rating, comments, etc.) and I'm using two ways to set my database:
I created the table "users" manully using node and migrations:
const createUsers = `
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name VARCHAR,
email VARCHAR,
password VARCHAR,
avatar VARCHAR NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
`
module.exports = createUsers;
And I created the tables 'movie_notes' and 'movie_tags' using the library 'knex' with migrations
exports.up = knex => knex.schema.createTable("movie_notes", table => {
table.increments("id");
table.text("title");
table.text("description");
table.integer("rating");
table.integer("user_id").references("id").inTable("users").onDelete("CASCADE");
table.timestamp("created_at").default(knex.fn.now());
table.timestamp("updated_at").default(knex.fn.now());
})
exports.down = knex => knex.schema.dropTable("movie_notes");
exports.up = knex => knex.schema.createTable("movie_tags", table => {
table.increments("id");
table.integer("movie_id").references("id").inTable("movie_notes").onDelete("CASCADE");
table.integer("user_id").references("id").inTable("users").onDelete("CASCADE");
table.text("name");
})
exports.down = knex => knex.schema.dropTable("movie_tags");
MY PROBLEM:
When I delete my notes, tags are also deleted (delete on cascade working very well), BUT when i delete a user who created notes and tags, these notes and tags aren't deleting (delete on cascade not working)
what can i do to fix it?
I expect delete all user notes and tags when i delete the user on database
Related
Here i am trying to update data in mysql database using bulkcreate [updateonduplicate] in sequelize and i don't have any primary key in my table. So what happing is, instead of updating the data the new entries are entering in database with updated value. I want to update old values only
Here is my code
let insertArray = [];
insertArray.push({
order_id: 62924376,
delivery_status : 80
});
insertArray.push({
order_id: 62934013,
delivery_status : 80
});
let updateOrder = await Sequelize.userOrders.bulkCreate(
insertArray,
{ updateOnDuplicate: ["delivery_status"] }
)
this code is entering new data in database. Here i have to update old values only
I am new to cassandra I need your help.
After creating a collection table using cql console, I am able to create new records and read them, but Post operation using cassandra-driver in nodejs is not working, it only works when I use cql console.
I created table:
CREATE TYPE event_info (
type text,
pagePath text,
ts text,
actionName text
);
CREATE TABLE journey_info_5 (
id uuid PRIMARY KEY,
user_id text,
session_start_ts timestamp,
event FROZEN<event_info>
);
codes for post operation:
export const pushEvent = async(req,res)=>{
const pushEventQuery = 'INSERT INTO user_journey.userjourney (id, user_id, session_start_ts,events)
VALUES ( ${types.TimeUuid.now()}, ${req.body.user_id},${types.TimeUuid.now()},
{ ${req.body.type},${req.body.pagePath},${req.body.ts},${req.body.actionName}} } );'
try {
await client.execute(pushEventQuery)
res.status(201).json("new record added successfully");
} catch (error) {
res.status(404).send({ message: error });
console.log(error);
}
}
it is giving errors, How can I get data from user and post in this collection?
please help me, if any idea
The issue is that your CQL statement is invalid. The format for inserting values in a user-defined type (UDT) column is:
{ fieldname1: 'value1', fieldname2: 'value2', ... }
Note that the column names in your schema don't match up with the CQL statement in your code so I'm reposting the schema here for clarity:
CREATE TYPE community.event_info (
type text,
pagepath text,
ts text,
actionname text
)
CREATE TABLE community.journey_info_5 (
id uuid PRIMARY KEY,
event frozen<event_info>,
session_start_ts timestamp,
user_id text
)
Here's the CQL statement I used to insert a UDT into the table (formatted for readability):
INSERT INTO journey_info_5 (id, user_id, session_start_ts, event)
VALUES (
now(),
'thierry',
totimestamp(now()),
{
type: 'type1',
pagePath: 'pagePath1',
ts: 'ts1',
actionName: 'actionName1'
}
);
For reference, see Inserting or updating data into a UDT column. Cheers!
I have a many to many relationship set up with with services and service_categories. Each has a table, and there is a third table to handle to relationship (junction table) called service_service_categories. I have created them like this:
CREATE TABLE services(
service_id SERIAL,
name VARCHAR(255),
summary VARCHAR(255),
profileImage VARCHAR(255),
userAgeGroup VARCHAR(255),
userType TEXT,
additionalNeeds TEXT[],
experience TEXT,
location POINT,
price NUMERIC,
PRIMARY KEY (id),
UNIQUE (name)
);
CREATE TABLE service_categories(
service_category_id SERIAL,
name TEXT,
description VARCHAR(255),
PRIMARY KEY (id),
UNIQUE (name)
);
CREATE TABLE service_service_categories(
service_id INT NOT NULL,
service_category_id INT NOT NULL,
PRIMARY KEY (service_id, service_category_id),
FOREIGN KEY (service_id) REFERENCES services(service_id) ON UPDATE CASCADE,
FOREIGN KEY (service_category_id) REFERENCES service_categories(service_category_id) ON UPDATE CASCADE
);
Now, in my application I would like to add a service_category to a service from a select list for example, at the same time as I create or update a service. In my node js I have this post route set up:
// Create a service
router.post('/', async( req, res) => {
try {
console.log(req.body);
const { name, summary } = req.body;
const newService = await pool.query(
'INSERT INTO services(name,summary) VALUES($1,$2) RETURNING *',
[name, summary]
);
res.json(newService);
} catch (err) {
console.log(err.message);
}
})
How should I change this code to also add a row to the service_service_categories table, when the new service ahas not been created yet, so has no serial number created?
If any one could talk me through the approach for this I would be grateful.
Thanks.
You can do this in the database by adding a trigger to the services table to insert a row into the service_service_categories that fires on row insert. The "NEW" keyword in the trigger function represents the row that was just inserted, so you can access the serial ID value.
https://www.postgresqltutorial.com/postgresql-triggers/
Something like this:
CREATE TRIGGER insert_new_service_trigger
AFTER INSERT
ON services
FOR EACH ROW
EXECUTE PROCEDURE insert_new_service();
Then your trigger function looks something like this (noting that the trigger function needs to be created before the trigger itself):
CREATE OR REPLACE FUNCTION insert_new_service()
RETURNS TRIGGER
LANGUAGE PLPGSQL
AS
$$
BEGIN
-- check to see if service_id has been created
IF NEW.service_id NOT IN (SELECT service_id FROM service_service_categories) THEN
INSERT INTO service_service_categories(service_id)
VALUES(NEW.service_id);
END IF;
RETURN NEW;
END;
$$;
However in your example data structure, it doesn't seem like there's a good way to link the service_categories.service_category_id serial value to this new row - you may need to change it a bit to accommodate
I managed to get it working to a point with multiple inserts and changing the schema a bit on services table. In the service table I added a column: category_id INT:
ALTER TABLE services
ADD COLUMN category_id INT;
Then in my node query I did this and it worked:
const newService = await pool.query(
`
with ins1 AS
(
INSERT INTO services (name,summary,category_id)
VALUES ($1,$2,$3) RETURNING service_id, category_id
),
ins2 AS
(
INSERT INTO service_service_categories (service_id,service_category_id) SELECT service_id, category_id FROM ins1
)
select * from ins1
`,
[name, summary, category_id]
);
Ideally I want to have multiple categories so the category_id column on service table, would become category_ids INT[]. and it would be an array of ids.
How would I put the second insert into a foreach (interger in the array), so it creates a new service_service_categories row for each id in the array?
I would like to know how can I remove all items in table with Prisma2 and Jest ?
I read the CRUD documentation and I try with this :
user.test.js
....
import { PrismaClient } from "#prisma/client"
beforeEach(async () => {
const prisma = new PrismaClient()
await prisma.user.deleteMany({})
})
...
But I have an error :
Invalid `prisma.user.deleteMany()` invocation:
The change you are trying to make would violate the required relation 'PostToUser' between the `Post` and `User` models.
My Database
CREATE TABLE User (
id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL,
name VARCHAR(255),
email VARCHAR(255) UNIQUE NOT NULL,
password VARCHAR(255) NOT NULL
);
CREATE TABLE Post (
id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL,
title VARCHAR(255) NOT NULL,
createdAt TIMESTAMP NOT NULL DEFAULT now(),
content TEXT,
published BOOLEAN NOT NULL DEFAULT false,
fk_user_id INTEGER NOT NULL,
CONSTRAINT `fk_user_id` FOREIGN KEY (fk_user_id) REFERENCES User(id) ON DELETE CASCADE
);
schema.prisma
model Post {
content String?
createdAt DateTime #default(now())
fk_user_id Int
id Int #default(autoincrement()) #id
published Boolean #default(false)
title String
author User #relation(fields: [fk_user_id], references: [id])
##index([fk_user_id], name: "fk_user_id")
}
model User {
email String #unique
id Int #default(autoincrement()) #id
name String?
password String #default("")
Post Post[]
Profile Profile?
}
You are violating the foreign key constraint between Post and User.
You can not remove a User before deleting its Posts
beforeEach(async () => {
const prisma = new PrismaClient()
await prisma.post.deleteMany({where: {...}}) //delete posts first
await prisma.user.deleteMany({})
})
Or set CASCADE deletion on the foreign key,
this way when you delete a User its posts will be automatically deleted
This is another way to do it, this would remove all rows and its dependant rows, also would reset the ids. This way you can iterate over all the tables and order doesn't matter.
prisma.$executeRaw(`TRUNCATE TABLE ${table} RESTART IDENTITY CASCADE;`)
Actually i have this table:
ClassBookHistoric
-----------------
Id (Primary Key),
Class_Id (Unique key, foreign key of table Class),
BookUnit_Id (Unique key, foreign key of table BookUnits)
Book_Id
Status
I need to make queries to search data like this: SELECT WHERE Class_Id = (parameter), Book_Id = (parameter) and Status = 1 (active)
I'm studying about indexes and i'm thinking it is necessary to create a index using the columns that i will use to search data (Class_Id, Book_Id and Status) to increase the performance. There's a way to create a index to a group of columns: (Class_Id, Book_Id, Status)? If it's possible, how i can create a group of index in node.js/adonis?
Adonis.js uses knex.js to define columns types and other modifiers as you can see from the docs.
So as an example based on your schema (not fully working just to demonstrate):
'use strict'
const Schema = use('Schema')
class ClassBookHistoric extends Schema {
up () {
this.create('class_books', (table) => {
table.increments()
table.integer('class_id').notNullable().unique()
table.integer('book_unit_Id').notNullable().unique()
table.index(['class_id','book_unit_Id'], 'class_book_index');
table.timestamps()
})
}
down () {
this.drop('class_books')
}
}
module.exports = UsersSchema