SQLite performance when executed first time - ionic4

I am using SQLite with ionic
Ionic:
Ionic CLI : 6.6.0 (C:\Users\ADEEL\AppData\Roaming\npm\node_modules\#ionic\cli)
Ionic Framework : #ionic/angular 5.0.5
#angular-devkit/build-angular : 0.900.7
#angular-devkit/schematics : 9.0.7
#angular/cli : 9.0.7
#ionic/angular-toolkit : 2.2.0
Cordova:
Cordova CLI : 9.0.0 (cordova-lib#9.0.1)
Cordova Platforms : android 8.1.0, browser 6.0.0
Cordova Plugins : cordova-plugin-ionic-webview 4.1.3, (and 9 other plugins)
Utility:
cordova-res (update available: 0.13.0) : 0.6.0
native-run (update available: 1.0.0) : 0.2.8
System:
Android SDK Tools : 26.1.1 (C:\Users\ADEEL\AppData\Local\Android\Sdk)
NodeJS : v12.16.1 (C:\Program Files\nodejs\node.exe)
npm : 6.13.4
OS : Windows 10
I have a table with 16 records in log_book table and 1 record each in department and location. when i run the query first time it will take almost 15 to 20 seconds but after that it runs in milliseconds. Calling function as follow
getLogBooks(): Promise<LogBook[]>{
return this.storage.executeSql(`SELECT l.id, l.log_book_id, IFNULL(l.machine_no, "") machine_no , d.department_name, loc.location_name, l.section, l.area
FROM log_book l
INNER JOIN departments d ON l.department_id = d.id
INNER JOIN locations loc ON l.location_id = loc.id
WHERE l.deleted_at IS NULL`, [])
.then(res => {
const items: LogBook[] = [];
console.log('Log BOOK', res.rows.length)
if (res.rows.length > 0) {
for (let i = 0; i < res.rows.length; i++) {
items.push({
id: res.rows.item(i).id,
LogBookID: res.rows.item(i).log_book_id,
MachineNo: res.rows.item(i).machine_no,
Department: res.rows.item(i).department_name,
Location: res.rows.item(i).location_name,
Section: res.rows.item(i).section,
Area: res.rows.item(i).area
});
}
}
return items;
});
}
Table structure
CREATE TABLE IF NOT EXISTS `log_book` (
`id` integer primary key autoincrement,
`log_book_id` varchar(50) NOT NULL,
`machine_no` varchar(50) DEFAULT NULL,
`department_id` int(11) NOT NULL,
`location_id` int(11) NOT NULL,
`section` varchar(50) NOT NULL,
`area` varchar(50) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`created_by` int(11) DEFAULT NULL,
`updated_by` int(11) DEFAULT NULL,
`deleted_at` datetime DEFAULT NULL
);
CREATE TABLE IF NOT EXISTS `departments` (
`id` integer primary key autoincrement,
`department_name` varchar(50) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`created_by` int(11) DEFAULT NULL,
`updated_by` int(11) DEFAULT NULL,
`deleted_at` datetime DEFAULT NULL
);
CREATE TABLE IF NOT EXISTS `locations` (
`id` integer primary key autoincrement,
`location_name` varchar(50) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`created_by` int(11) DEFAULT NULL,
`updated_by` int(11) DEFAULT NULL,
`deleted_at` datetime DEFAULT NULL
);
What i am doing wrong.
Thanking you in anticipation

Related

The command dal:create:schema does not create foreign keys

Given the following example for an Entity-Definition, there is a foreign key defined. As a developer and database engineer i would expect that the command dal:create:schema would also create the expected foreign keys. But this is not the case.
return new FieldCollection([
(new IdField('id', 'id'))->addFlags(new PrimaryKey(), new Required()),
(new LongTextField('comment', 'name'))->addFlags(new Required()),
(new FkField('order_id', 'orderId', OrderDefinition::class))->addFlags(new Required()),
new OneToOneAssociationField('order', 'order_id', 'id', OrderDefinition::class, false),
new CreatedAtField(),
new UpdatedAtField()
]);
Instead this is the result:
CREATE TABLE `order_refund` (
`id` BINARY(16) NOT NULL,
`comment` LONGTEXT NOT NULL,
`order_id` BINARY(16) NOT NULL,
`created_at` DATETIME(3) NOT NULL,
`updated_at` DATETIME(3) NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
However, it seems like that ManyToOneAssociations will add foreign keys. Is there something missing in the entity definition?
The command you mentioned is using the SchemaGenerator which has a method to generate Foreign keys:
\Shopware\Core\Framework\DataAbstractionLayer\SchemaGenerator::generateForeignKeys
Looking at this method it seems to work only fields of the type ManyToOneAssociationField
private function generateForeignKeys(EntityDefinition $definition): string
{
$fields = $definition->getFields()->filter(
function (Field $field) {
if (!$field instanceof ManyToOneAssociationField) {
return false;
}
return true;
}
);
I also think it is a shortcoming of this function that it does not generate foreign keys for fields of the type OneToOneAssociationField. Maybe you can try to adjust this filtering and see if it works and make a pull request on GitHub for the benefit of yourself and other developers?

Using SELECT within Trigger

A customer needs a trigger for his new management tool. It works so far, but now he wants to get values from another table.
What does it mean? Take a short look at the (working) trigger:
CREATE OR REPLACE TRIGGER reldb_export_T_Import3_In
AFTER UPDATE OR INSERT OR DELETE ON infor.RELDB
FOR EACH ROW
DECLARE KST varchar(1000 BYTE);
BEGIN
IF (:new.ZUST = 4 AND :old.ZUST = 3 AND :old.SAINT = 60)
THEN
INSERT INTO infor2infoboard.T_Import3_In
(Idx, Timestamp, ObjectId, Text, RowUid, GroupName, GroupIndex, PredTimeCondition, PredGapValue, Service, ReqQuan, ReqDur,
Efficiency, BackColor, HighlightColor, Brightness, CellOffsetY, Fixed, Font, FontColor, Height, EarliestStart, LastDeliveryDate, RoleId,
StatusIds, WithReservation, LastChange, LastEditedBy, Opacity, IsProcess, CheckSymbol, Link, Priority, IconPath, Adress, CA1, CA2,
CA3, CA4, CA5, CA6, CA7, CA8, CA9, CA10, CA11, CA12, CA13, CA14, CA15,
CA16, CA17, CA18, CA19, CA20, CA21, CA22, CA23, CA24, CA25,
CA26, CA27, CA28, CA29, CA30, CA31, CA32)
VALUES
(seq_t_import3_in.nextval, sysdate, :old.RNR, NULL, CASE WHEN :NEW.KST = '3710' THEN 'Pool TB-M 1;Pool TB-M 2;Pool TB-M 3;Pool TB-M 4;Pool TB-M 5' ELSE KST END, :old.Komm, NULL, NULL, NULL, :old.KTXT, :old.TA_4, NULL,
NULL, CASE WHEN :new.MNR = '3740' THEN 'GREEN' WHEN :new.MNR != '3740' THEN 'BLUE' END, NULL, NULL, NULL, NULL, NULL, NULL, NULL, :old.TERM_2, :old.TERM_1, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, SUBSTR(:old.ANR, 1, 10), :old.KOMM, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL);
END IF;......
Now he want to replace one of the last NULLS with a selected value.
The statement should look like this:
SELECT KTXT FROM RELDB WHERE ANR = :old.ANR and SAEXT = 'H';
So, for example:
NULL, (SELECT KTXT FROM RELDB WHERE ANR = :old.ANR and SAEXT = 'H';), SUBSTR(:old.ANR, 1, 10), :old.KOMM, NULL
My problem: I'm getting an error, that the trigger couldn't notice some changes. The trigger won't get fired.
So does anyone know how I can use or how I can get selected values (from the same (!!!) table which the trigger is listening to?
I'd appreciate your help :)
Cheers,
Dom
In Oracle, you cannot select from the same table you are changing, this is the mutating table error. See https://asktom.oracle.com/pls/apex/f?p=100:11:0::::p11_question_id:9579487119866

PHP Not Executing Code To Create Database

I wrote the following code and I'm trying to make an install to create the databases and tables for the SQL but I can't figure out why it's not creating the databases or the tables.
CONFIG.PHP
<?php
// Database Details
$host = 'localhost';
$user = 'root';
$password = '';
//Install Settings
$root_username = 'root';
$root_password = 'password';
// Install Settings Advanced - Do Not Modify For Default Settings
$database = 'Sims2';
?>
INSTALL.PHP
<?php
include 'config.php';
// Remove any instance of .mysqli_connect_error() before publishing
$conn = mysqli_connect($host,$user,$password);
if (!$conn) {die("Connection failed: ".mysqli_connect_error());};
$sql = "CREATE DATABASE Sims2";
if (!$conn){die("Error creating database: ".mysqli_connect_error());};
$sql = "CREATE TABLE TEACHERS (
id INT(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
uid VARCHAR(128) NOT NULL,
pwd VARCHAR(128) NOT NULL
);";
if(!$conn){die("Error creating table: ".mysqli_connect_error());};
$sql = "CREATE TABLE STUDENTS (
id INT(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
first VARCHAR(64) NOT NULL,
last VARCHAR(64) NOT NULL,
gender VARCHAR(6) NOT NULL,
dob VARCHAR(10) NOT NULL,
semail VARCHAR(64) NOT NULL,
address VARCHAR(120) NOT NULL,
phone VARCHAR(15) NOT NULL,
tutor VARCHAR(64) NOT NULL
);";
if(!$conn){die("Error creating table: ".mysqli_connect_error());};
$sql = "INSERT INTO TEACHERS (uid, pwd) VALUES ($root_username,$root_password)";
if(!$conn){die("Error creating root account: ".mysqli_connect_error());};
echo "Done";
?>
Any help would be appreciated

PhoneGap sql checking for duplicates

I want to input a query to check the database for duplicate when inserting data into the database so it would prevent the activity Name from being entered more than once in a database
function insertQueryDB(tx) {
var myDB = window.openDatabase("test", "1.0", "Test DB", 1000000);
tx.executeSql('CREATE TABLE IF NOT EXISTS dataEntryTb (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, activityName TEXT NOT NULL, location TEXT NOT NULL, time NOT NULL, date NOT NULL, reporter NOT NULL)');
var an = document.forms["myForm"]["activityName"].value;
var l = document.forms["myForm"]["location"].value;
var t = document.forms["myForm"]["time"].value;
var d = document.forms["myForm"]["date"].value;
var r = document.forms["myForm"]["reporter"].value;
var query = 'INSERT INTO dataEntryTb ( activityName, location, time, date, reporter) VALUES ( "'+an+'", "'+l+'", "'+t+'", "'+d+'", "'+r+'")';
navigator.notification.alert("Retrieved the following: Activity Name="+an+" and Location="+l);
tx.executeSql(query,[]);
}``
Create the table with name being unique:
CREATE TABLE IF NOT EXISTS dataEntryTb (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
activityName TEXT NOT NULL UNIQUE,
location TEXT NOT NULL,
time NOT NULL, date NOT NULL,
reporter NOT NULL
);
Then the database will return an error if the name is already in the table.

Yii's updateByPk keeps returning 0

I'm trying to update my user table, which my code does. but for some reason it keeps executing the else statement.
in the documentation it states that updateByPk should return the number of rows being updated. Which should be 1. what am i missing here? and how do i check if the table has been updated successfully?
if (User::model()->updateByPk($model->id, array("last_login"=> Shared::timeNow())))
{
Yii::app()->user->login($identity, $duration);
echo json_encode(array('error' => false, 'success' => url(app()->users->getHomeUrl())));
Yii::app()->end();
}
else {
echo json_encode(array('error' => 'Could not update user info', 'code' => 'auth'));
Yii::app()->end();
}
my table schema is this
CREATE TABLE IF NOT EXISTS `user` (
`id` int(10) unsigned NOT NULL,
`username` varchar(100) DEFAULT NULL,
`email` varchar(255) NOT NULL,
`first_name` varchar(45) NOT NULL,
`last_name` varchar(45) NOT NULL,
`gender` char(1) DEFAULT NULL,
`birthday` date DEFAULT '0000-00-00',
`address` varchar(255) DEFAULT NULL,
`city` varchar(45) DEFAULT NULL,
`state` varchar(45) DEFAULT NULL,
`website` text,
`postal_code` varchar(45) DEFAULT NULL,
`phone` varchar(45) DEFAULT NULL,
`password` varchar(63) DEFAULT NULL,
`activate` varchar(63) NOT NULL DEFAULT '1',
`create_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`last_login` datetime DEFAULT NULL,
`password_reset` int(11) unsigned DEFAULT NULL,
`admin` tinyint(1) unsigned NOT NULL DEFAULT '0',
`email_verified` tinyint(1) unsigned DEFAULT NULL,
`login_disabled` tinyint(1) unsigned NOT NULL DEFAULT '0',
`oauth_id` bigint(20) DEFAULT NULL,
`oauth_username` varchar(255) DEFAULT NULL,
`oauth_provider` varchar(10) DEFAULT NULL,
`oauth_email` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
You should check $model exits first otherwise updateByPk can return 0
if ($model && User::model()->updateByPk($model->id, array("last_login"=> Shared::timeNow())))
Your table does not specify a primary key. Yet you update by primary key.
You have a few choices.
Change your table structure to include a primary key
Use another update method. For example, Update() allow you to pass a criteria object.
Know it's old, but : https://www.php.net/manual/en/pdostatement.rowcount.php
If the last SQL statement executed by the associated PDOStatement was a SELECT statement, some databases may return the number of rows returned by that statement. However, this behaviour is not guaranteed for all databases and should not be relied on for portable applications.
And Yii1 use rowCount
Model can be not updated because last_login attribute has not valid value.
Try get model errors ($model->errors()) or check model by $model->validate();
Why you not implement this as follows:
$model->last_login = Shared::timeNow();
if ($model->save())
{
Yii::app()->user->login($identity, $duration);
echo json_encode(array('error' => false, 'success' => url(app()->users->getHomeUrl())));
Yii::app()->end();
}
else {
echo json_encode(array('error' => 'Could not update user info', 'code' => 'auth'));
Yii::app()->end();
}