Why is this query forming an incorrect foreign key constraint in Knex/SQLite3? - sqlite

The Goal
I am trying to make two tables, `users` and `clients`, wherein `clients` has a foreign key called `userId` that references the `id` primary key of `users`.
Shows the desired relationship between the tables users and clients
The Migrations
Users
exports.up = function(knex) {
return knex.schema
.createTable('users', function (table) {
table.increments().primary();
table.string('username').unique().notNullable();
table.string('email').unique().notNullable();
table.string('password').notNullable();
table.boolean('admin').notNullable().defaultTo(false);
});
};
Clients
I have tried a variety of different variations of this, which I will show here along with their results:
exports.up = function(knex) {
return knex.schema
.createTable('clients', function (table) {
table.increments().primary();
table.string('name').notNullable();
table.string('secret').notNullable();
table.integer('userId').unsigned().references("id").inTable("users").onDelete("CASCADE");
});
};
This resulted the successful creation of the database, however, the SQLite Viewer indicated that clients.id was somehow referencing a users.userId, as shown in the following image.
exports.up = function(knex) {
return knex.schema
.createTable('clients', function (table) {
table.increments().primary();
table.string('name').notNullable();
table.integer('userId').unsigned();
table.string('secret').notNullable();
table.foreign('userId').references("users.id").onDelete("CASCADE");
});
};
This produced the exact same result as the previous code.
What am I doing wrong?
Edit: An Additional Complicating Factor
I have tried swapping `userId` and `id` in the first attempt at making the clients table. While this did appear to work for the clients table, when I tried to do the same for a `codes` table, I encountered an error that seemed to indicate swapping the two wasn't doing what I hoped it would do. This is consistent with what I've seen in tutorials. I'm inclined to think I was closer to the correct answer at the beginning.
exports.up = function(knex) {
return knex.schema
.createTable('codes', function (table) {
table.string('value').notNullable();
table.string('redirectUri').notNullable();
table.integer('userId').unsigned();
table.integer('clientId').notNullable();
table.foreign('id').references("userId").inTable("users").onDelete("CASCADE");
});
};
Error: create table codes (value varchar(255) not null, redirectUri varchar(255) not null, userId integer, clientId integer not null, foreign key(id) references users(userId) on delete CASCADE) - SQLITE_ERROR: unknown column "id" in foreign key definition

Related

How to write this conditional request correctly MariaDB

I need to check if a book rating for specific book from specific person exists.
If it does update it, if it doesnt create it.
I am getting a whole bunch of wrong errors for 9th 10th.... 12th parameter missing while I count only 8
My mariaDB version is 10.5.8-MariaDB.
My code:
const createBookRate = async (userId, bookId, rate) => {
const sql = `
SELECT IF(EXISTS( SELECT * from rates WHERE rates.users_id=? AND rates.books_id=? ),
UPDATE rates SET rates.rate=? WHERE rates.users_id=? AND rates.books_id=?,
INSERT INTO rates(users_id, books_id, rate))
VALUE (?,?,?,?,?,?,?,?);
`
const { insertId } = await pool.query(sql, [userId, bookId, rate, userId, bookId, userId, bookId, rate])
const rateEntry = await getBookRate(insertId)
return rateEntry
}
You cannot perform an UPDATE or an INSERT inside the IF clause of a SELECT statement, those must be performed separately.
To perform this in a safe manner, use a transaction and first lock the selected row with SELECT ... FOR UPDATE, then either UPDATE or INSERT it and finally COMMIT the transaction.
If the table has a primary key, you can use INSERT ... ON DUPLICATE KEY UPDATE to either insert the row or update it, depending on whether it exists or not. This allows everything to be done in one step without having to first select the affected rows.

sequelize alter existing table with "ON DELETE CASCADE"

I have existing tables with column 'endpointId' with "ON DELETE NO ACTION" and I want to alter column to change this to "ON DELETE CASCADE"
What I have tried is to do:
module.exports = {
up: async (queryInterface, Sequelize) => {
await queryInterface.sequelize.query("ALTER TABLE `Analyses` ALTER COLUMN `endpointId` INTEGER NOT NULL REFERENCES `Endpoints` (`id`) ON DELETE CASCADE ON UPDATE CASCADE");
},
down: async (queryInterface, Sequelize) => {
await queryInterface.sequelize.query("ALTER TABLE `Analyses` ALTER COLUMN `endpointId` INTEGER NOT NULL REFERENCES `Endpoints` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE");
}
};
but getting error:
ERROR: SQLITE_ERROR: near "ALTER": syntax error
It seems I need to remove Constraint first, but I can't find any for the table. Is there a way to check constraint?
await queryInterface.removeConstraint('Analyses', '???');

DynamoDB: Get All Sort Keys from Primary Key

I have a table with a primary key and a sort key; since this is a composite key, I have multiple primary keys mapped with different sort keys.
How can I get all of the sort keys associated with a particular primary key?
I tried using the "Get" operation, but that seems to expect the sort key as well (even though these are what I'm looking for). I also looked at the "BatchGet" operation, but this is for multiple different keys, not for a single primary key with multiple different sort keys.
I tried to do "query" as well and wasn't successful, but I understand this less, so it's possible this is the solution -- is that the case? I am also aware that I could "scan" the entire database and specifically find all items with that particular primary key, but I'm looking to avoid this if possible.
I am working with JS and using this as a reference: https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html.
Thank you!
Query() is what you want...
Basically, you just query the table (or index) with a keycondition of HashKey = :hkey and leave off any AND of sort key conditions...
In the docs you linked to, there's a section for query modifying that example...
var params = {
TableName: 'Table',
KeyConditionExpression: 'HashKey = :hkey',
ExpressionAttributeValues: {
':hkey': 'key'
}
};
var documentClient = new AWS.DynamoDB.DocumentClient();
documentClient.query(params, function(err, data) {
if (err) console.log(err);
else console.log(data);
});

Ionic3 and SQLite - create table using property as table name inside query

I'm making an app using Ionic 3 and SQLite. I tried to create a table using a property as table name inside the query but it returns this error:
'sqlite3_prepare_v2 failure: near "(": syntax error'
Here's the code that I used:
onCreateTb() {
this.database.executeSql('CREATE TABLE IF NOT EXISTS (?) (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, skill TEXT, yearsOfExperience INTEGER)', [this.tableName])
.then(() => console.log('Ok'))
.catch(error => console.log(error));
}
In various articles about SQLite I saw the (?) marker on INSERT queries but never on CREATE TABLE queries.
How can I use a property as a table name?

getting values from sqlite using group by null pointer

I have a table in that I have some duplicate record now I am getting the record without excluding duplicate records. I want to get all record excluding duplicate, and from duplicate data I want only one record. like if I have three same records i want only one record.
my query is like,this giving null pointer.
Cursor dCursor=database.rawQuery( "SELECT FROM note_image GROUP BY IDMATCHER",null,null);
and if I want to get this using query() method how can I do that. I am getting all records by using this method. but I want all records only once. without occurrence two time a record.
public Cursor fetchImage(){
String[] columns = new String[]{DatabaseHelper.NOTE_IMG_ID,DatabaseHelper.NOTE_HD_IMG_PATH,DatabaseHelper.NOTE_IMG_PATH_THUMB,DatabaseHelper.TEMP_IMG_ID};
Cursor cursor=database.query(DatabaseHelper.TABLE_NOTE_IMAGE,columns,null,null,null,null,null);
if (cursor!=null){
cursor.moveToNext();
}
return cursor;
}
I done using this query. taken help from above commented link. ` public Cursor fetchImage() {
Cursor icursor = database.query(true, DatabaseHelper.TABLE_NOTE_IMAGE, new String[]
{DatabaseHelper.TEMP_IMG_ID, DatabaseHelper.NOTE_IMG_PATH_THUMB},
null, null, DatabaseHelper.TEMP_IMG_ID, null, null, null);
if (icursor != null) {
icursor.moveToNext();
}
return icursor;
}`

Resources