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

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?

Related

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

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

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);
});

ASP Core 1 with PostgreSql. Authorizatioin and authentication

I have a web application based on ASP Core 1 with PostgreSql data storage. And now i want to add auth functionality. I have created base example mvc project with authorization and it works fine with MsSql server. But what about PostgreSql?
At first i create database with same schema (sql was generated via dnx ef migrations script and code was updated with pg-style). Then i have configured EF with Postgres
services.AddEntityFramework()
.AddNpgsql()
.AddDbContext<ApplicationDbContext>(options =>
options.UseNpgsql(Configuration["Data:DefaultConnection:ConnectionString"]));
When i try to register as new user, i get an error 42P01: relation \"AspNetUsers\" does not exist. I have already surrounded table name with doublequotes, but it does not helps. I have no access to default auth models and can't add name atribute to table name and name of fields.
So, my questions are:
What wrong with my sample project and why i can't get access to db?
More globally. What is the best way to organize authorization and authentication with ASP Core 1 + PostgreSql? I no needed in all ASP auth features, i just neede in roles, i want to have bigint-based id and i want to extend users model (table).
Note: I use EF7.
So the answer for my first question is in the wrong database schema. For someone interested in schema i get the full pg sql code, but my second question is still opened.
CREATE TABLE public."AspNetRoles" (
"Id" character varying(450) NOT NULL,
"ConcurrencyStamp" text,
"Name" character varying(256),
"NormalizedName" character varying(256),
CONSTRAINT pk_identityrole PRIMARY KEY ("Id")
);
CREATE TABLE public."AspNetUsers" (
"Id" character varying(450) NOT NULL,
"AccessFailedCount" integer NOT NULL,
"ConcurrencyStamp" text,
"Email" character varying(256),
"EmailConfirmed" boolean NOT NULL,
"LockoutEnabled" boolean NOT NULL,
"LockoutEnd" timestamp without time zone,
"NormalizedEmail" character varying(256),
"NormalizedUserName" character varying(256),
"PasswordHash" text,
"PhoneNumber" text,
"PhoneNumberConfirmed" boolean NOT NULL,
"SecurityStamp" text,
"TwoFactorEnabled" boolean NOT NULL,
"UserName" character varying(256),
CONSTRAINT pk_applicationuser PRIMARY KEY ("Id")
);
CREATE TABLE public."AspNetRoleClaims" (
"Id" serial NOT NULL,
"ClaimType" text,
"ClaimValue" text,
"RoleId" character varying(450),
CONSTRAINT pk_identityroleclaim PRIMARY KEY ("Id"),
CONSTRAINT fk_identityroleclaim_identityrole_roleid FOREIGN KEY ("RoleId")
REFERENCES public."AspNetRoles" ("Id") MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
);
CREATE TABLE public."AspNetUserClaims" (
"Id" serial NOT NULL,
"ClaimType" text,
"ClaimValue" text,
"UserId" character varying(450),
CONSTRAINT pk_identityuserclaim PRIMARY KEY ("Id"),
CONSTRAINT fk_identityuserclaim_applicationuser_userid FOREIGN KEY ("UserId")
REFERENCES public."AspNetUsers" ("Id") MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
);
CREATE TABLE public."AspNetUserLogins" (
"LoginProvider" character varying(450) NOT NULL,
"ProviderKey" character varying(450) NOT NULL,
"ProviderDisplayName" text,
"UserId" character varying(450),
CONSTRAINT pk_identityuserlogin PRIMARY KEY ("LoginProvider", "ProviderKey"),
CONSTRAINT fk_identityuserlogin_applicationuser_userid FOREIGN KEY ("UserId")
REFERENCES public."AspNetUsers" ("Id") MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
);
CREATE TABLE public."AspNetUserRoles" (
"UserId" character varying(450) NOT NULL,
"RoleId" character varying(450) NOT NULL,
CONSTRAINT pk_identityuserrole PRIMARY KEY ("UserId", "RoleId"),
CONSTRAINT fk_identityuserrole_applicationuser_userid FOREIGN KEY ("UserId")
REFERENCES public."AspNetUsers" ("Id") MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION,
CONSTRAINT fk_identityuserrole_identityrole_roleid FOREIGN KEY ("RoleId")
REFERENCES public."AspNetRoles" ("Id") MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
);
I transfer my database from SQL SERVER to postgreSQL, after transfer, I found this error. when I checked my database, the table was in lowercase. I changed all AspTables and columns to default name and solved my problem.

How to use QML to import a CSV to s SQLite database?

I've been programming an app that uses two databases, one of which contains contacts that I've exported from outlook.
I would like to import these into a sqlite database using QML/javascript only.
I have created the table and I'm trying to execute the below commands:
function createTable(database)
{
database.transaction(
function(tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS staff(id INTEGER PRIMARY KEY AUTOINCREMENT, "First Name" TEXT, "Last Name" TEXT)');
tx.executeSql('.mode csv');
tx.executeSql('".import" "./contacts.csv"');
}
)
}
I haven't got to the .import yet so that is secondary. I'm guessing I must be missing some method that I'm not familiar with.
Any help is appreciated.

Resources