I have problems with a specific query when using the sqlite3_step function:
SELECT DISTINCT interfaces_int_id,device_dev_id FROM devInterface
INNER JOIN interfaces ON devInterface.interfaces_int_id=interfaces.intf_id
INNER JOIN nlink ON nlink.interfaces_intf_id=interfaces.intf_id
INNER JOIN neighbor ON neighbor.neighbor_id=nlink.neighbor_neighbor_id
I only posted the parts of the query which are relevant.
For querying the database, I use this code.
When debugging it, it hangs at
while(true)
{
---> result = sqlite3_step(statement);
if(result == SQLITE_ROW)
{
std::vector<std::string> values;
...
}
...
}
Depending on the database size, it sometimes takes minutes to get a result. But when using the Firefox plugin "SQLite Manager", it takes only 1-2 seconds.
In cases where the query takes several minutes, the "neighbor" and "nlink" tables have more than 150k entries.
For buliding the database, I used the Forward engineer feature of the MySQL Workbench tool, and modified the syntax to work for sqlite3:
CREATE TABLE IF NOT EXISTS device(dev_id INTEGER PRIMARY KEY AUTOINCREMENT, type INT, hwtype INT, dataSource INT, hostname TEXT, sw_version TEXT, stpBridgeID TEXT, stpProtocol TEXT);
CREATE TABLE IF NOT EXISTS interfaces(intf_id INTEGER PRIMARY KEY AUTOINCREMENT, intfName TEXT, intfType TEXT, phl INT, macAddress TEXT, ipAddress TEXT, subnetMask TEXT, duplex TEXT, speed TEXT, status TEXT, description TEXT, l2l3 TEXT, errLvl INT, loadLvl INT, channel_intf_id INT, vpc_id INT, CONSTRAINT fk_interfaces_interfaces1 FOREIGN KEY (channel_intf_id) REFERENCES interfaces (intf_id) ON DELETE CASCADE ON UPDATE CASCADE);
CREATE TABLE IF NOT EXISTS devInterface (interfaces_int_id INT, device_dev_id INT, cdp_cdp_id INT, PRIMARY KEY (interfaces_int_id, device_dev_id, cdp_cdp_id), CONSTRAINT fk_dev_interface_interfaces1 FOREIGN KEY (interfaces_int_id) REFERENCES interfaces (intf_id) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT fk_dev_interface_device1 FOREIGN KEY (device_dev_id) REFERENCES device (dev_id) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT fk_devInterface_cdp1 FOREIGN KEY (cdp_cdp_id) REFERENCES cdp (cdp_id) ON DELETE CASCADE ON UPDATE CASCADE);
CREATE TABLE IF NOT EXISTS neighbor (neighbor_id INTEGER PRIMARY KEY AUTOINCREMENT, l2_addr TEXT NULL , l3_addr TEXT NULL);
CREATE TABLE IF NOT EXISTS nlink (neighbor_neighbor_id INT, interfaces_intf_id INT, PRIMARY KEY (neighbor_neighbor_id, interfaces_intf_id), CONSTRAINT fk_table1_neighbor1 FOREIGN KEY (neighbor_neighbor_id ) REFERENCES neighbor (neighbor_id) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT fk_table1_interfaces1 FOREIGN KEY (interfaces_intf_id) REFERENCES interfaces (intf_id) ON DELETE CASCADE ON UPDATE CASCADE);
EDIT: SQLITE Version: 3.6.22
After upgrading SQLite to the latest version (3.7.6.2), performance is much better.
Related
I've created a MySQL Model with a few tables, some of them with fk's to another table. I usually export the SQL from MySQL Model to my database using the "Forward Engineer SQL CREATE Script" inside File -> Export -> Forward Engineer SQL CREATE Script. The problem here is that when I generate the creation script, all my fk's become unique. I didn't check UQ option in MySQL Model but it creates a script with unique fk's anyway, so, I need to change the SQL file generated and remove all the unwanted uniques. Anyone has a clue why this is happening?
Generated script:
CREATE TABLE IF NOT EXISTS `u514786799_detranleiloes`.`Lotes` (
`createdAt` DATE NOT NULL,
`updatedAt` DATE NOT NULL,
`id` INT UNIQUE NOT NULL AUTO_INCREMENT,
`LeiloesId` INT UNIQUE NOT NULL,
`conservado` TINYINT NULL,
`numero` INT NOT NULL,
`CRDsId` INT UNIQUE NULL,
PRIMARY KEY (`id`),
INDEX `fk_Lotes_Leiloes_idx` (`LeiloesId` ASC),
INDEX `fk_Lotes_CRDs1_idx` (`CRDsId` ASC),
CONSTRAINT `fk_Lotes_Leiloes`
FOREIGN KEY (`LeiloesId`)
REFERENCES `u514786799_detranleiloes`.`Leiloes` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_Lotes_CRDs1`
FOREIGN KEY (`CRDsId`)
REFERENCES `u514786799_detranleiloes`.`CRDs` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
AUTO_INCREMENT = 1;
I have a database in Qt.
it has four tables: maingroup, subgroup, parts, and position.this is my database:
CREATE TABLE `maingroup` (
`groupName`TEXT NOT NULL UNIQUE,
PRIMARY KEY(`groupName`)
);
CREATE TABLE `subgroup` (
`sub` TEXT NOT NULL UNIQUE,
`main` TEXT NOT NULL,
PRIMARY KEY(`sub`),
FOREIGN KEY(`main`) REFERENCES `maingroup`(`groupName`) ON DELETE CASCADE
);
CREATE TABLE `parts` (
`ID` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
`Part_Number` TEXT,
`Type` TEXT NOT NULL,
`Value` TEXT,
`Voltage` TEXT,
`Quantity` TEXT,
`Position` TEXT,
`Picture` TEXT,
FOREIGN KEY(`Position`) REFERENCES `Position`(`Poistion`) ON DELETE CASCADE,
FOREIGN KEY(`Type`) REFERENCES `subgroup`(`sub`) ON DELETE CASCADE
);
Type in table parts is foreign key refers to column sub from table subgroup.
main in table subgroup is foreign key refers to column groupname in table maingroup.
my problem is when I try (delete from maingroup WHERE groupName= 'dd';) in DB Browser it deletes both parent and children.
But in QT this command(myQuery.exec("delete from maingroup WHERE groupName= 'dd'");) just deletes the parent field in maingroup table and not the child in subgroup and part table and the main column in subgroup table refers to a field in maingroup table that does not exist.
what is wrong here?what should i do?
You need to turn on the foreign-key pragma by executing another statement before your DELETE statement.
QSqlQuery q;
q.exec("PRAGMA foreign_keys = ON");
q.exec("DELETE FROM ...");
This was able to cascade deletes, and should also be sufficient to solve other foreign-key related issues.
Credits to this forum.qt.io post.
In addition to #TrebledJ correct and very helpful answer it's worth to mention two additional characteristics about the foreign-key pragma (in connection with Qt):
1. The pragma can set via QSqlDatabase, too.
So the following code has the same effect as #TrebledJ's example:
auto database = QSqlDatabase::database();
database.exec("PRAGMA foreign_keys = ON");
QSqlQuery query(database); // query "inherits" the pragma from database
query.exec("DELETE FROM ...");
2. This behavior even applies if opening and using the database happens at different places in the program.
Still the same effect:
Somewhere in initialization code:
// this calls database.open() implicit because database was not open before.
auto database = QSqlDatabase::database();
QSqlDatabase::database();
database.exec("PRAGMA foreign_keys = ON");
// make sure database.close() is NOT called!
Somewhere else in code
// you'll get the instance of your initialization code because database is already open (so QSqlDatabase::database() implements a singleton pattern).
// so pragma foreign_keys is still set to "ON"
auto database = QSqlDatabase::database();
QSqlQuery query(database);
query.exec("DELETE FROM ...");
This might be important to know if you want to understand why the foreign_keys pragma seems to only sometimes apply in your project (and sometimes not).
What I did
So I came to the conclusion to make sure to have ONE distinct place in my code where to explicit open the database (and configure the connection):
QString dbConnectionName = "My project database";
auto database = QSqlDatabase::database(dbConnectionName, true);
// configure the pragmas here
At all other places I avoid to (accidentally) open the database:
auto database = QSqlDatabase::database(dbConnectionName, false);
// e.g. use the database via queries ...
So I am trying to create the following tables and psql will not let me create these tables unless C_Subject is given a UNIQUE constraint in the Curriculum_Subjects table.
CREATE TABLE IF NOT EXISTS Curriculum(
CID SERIAL NOT NULL,
Curriculum_Name VARCHAR(100),
Classes_Needed INTEGER,
Classes_Total INTEGER,
PRIMARY KEY(CID)
);
CREATE TABLE IF NOT EXISTS Class_Subjects(
C_Subject SERIAL NOT NULL,
Class_Subject VARCHAR(100),
PRIMARY KEY(C_Subject)
);
CREATE TABLE IF NOT EXISTS Curriculum_Subjects(
C_Subject SERIAL UNIQUE NOT NULL REFERENCES Class_Subjects(C_Subject),
CID SERIAL NOT NULL REFERENCES Curriculum(CID),
PRIMARY KEY(C_Subject, CID)
);
However the way I want my database to work is that one C_Subject can be in many curriculum. So below inserting the same C_Subject into two different curriculum should be valid. CID being the identifier for a different curriculum.
INSERT INTO Curriculum_Subjects(C_Subject, CID)
VALUES(2,1);
INSERT INTO Curriculum_Subjects(C_Subject, CID)
VALUES(2,2);
psql won't let this insert happen because C_Subject has a UNIQUE constraint. Why does C_Subject need to be UNIQUE in Curriculum_Subjects if it belongs to the composite key, PRIMARY KEY(C_Subject, CID) ? Can this insert be achievable?
Create tables
I have a database composed of two tables:
ENTITE_CANDIDATE
VARIATIONS
Tables are created by using the following queries:
CREATE TABLE IF NOT EXISTS ENTITE_CANDIDATE (ID INTEGER PRIMARY KEY NOT NULL, ID_KBP TEXT NOT NULL, wiki_title TEXT, type TEXT NOT NULL);"
CREATE TABLE IF NOT EXISTS VARIATIONS (ID INTEGER PRIMARY KEY NOT NULL, ID_ENTITE INTEGER, NAME TEXT, TYPE TEXT, LANGUAGE TEXT, FOREIGN KEY(ID_ENTITE) REFERENCES ENTITE_CANDIDATE(ID));"
Table ENTITE_CANDIDATE is composed of 818,742 records
Table VARIATIONS is composed of 154,716,653 records
Index tables
I indexed the previous tables by using the following queries:
`CREATE INDEX var_id ON VARIATIONS (ID, ID_ENTITE, NAME);`
`CREATE INDEX entity_id ON ENTITE_CANDIDATE (ID, wiki_title);`
Retrieve information
I want to retrieve from table VARIATIONS the following records:
"SELECT ID, ID_ENTITE, NAME FROM VARIATIONS WHERE NAME=foo ;"
Every select query is taking around 5.414931 seconds. I know the table contains a very large number of records. But can I make the retrieval faster? Am I indexing correctly the tables?
The documentation says:
the index might be used if the initial columns of the index … appear in WHERE clause terms.
This query uses only the NAME column to search, so the var_id index cannot be used. (That index is useful only for lookups that use ID, which is mostly useless because the ID column is already indexed as PRIMARY KEY.)
I've been trying to add a foreign key to my table using heidisql and I keep getting the error 1452.
After reading around I made sure all my tables were running on InnoDB as well as checking that they had the same datatype and the only way I can add my key is if I drop all my data which I don't intend to do since I have spent quite a few hours on this.
here is my table create code:
CREATE TABLE `data` (
`ID` INT(10) NOT NULL AUTO_INCREMENT,
#bunch of random other columns stripped out
`Ability_1` SMALLINT(5) UNSIGNED NOT NULL DEFAULT '0',
#more stripped tables
`Extra_Info` SET('1','2','3','Final','Legendary') NOT NULL DEFAULT '1' COLLATE 'utf8_unicode_ci',
PRIMARY KEY (`ID`),
UNIQUE INDEX `ID` (`ID`)
)
COLLATE='utf8_unicode_ci'
ENGINE=InnoDB
AUTO_INCREMENT=650;
here is table 2
CREATE TABLE `ability` (
`ability_ID` SMALLINT(5) UNSIGNED NOT NULL AUTO_INCREMENT,
#stripped columns
`Name_English` VARCHAR(12) NOT NULL COLLATE 'utf8_unicode_ci',
PRIMARY KEY (`ability_ID`),
UNIQUE INDEX `ability_ID` (`ability_ID`)
)
COLLATE='utf8_unicode_ci'
ENGINE=InnoDB
AUTO_INCREMENT=165;
Finally here is the create code along with the error.
ALTER TABLE `data`
ADD CONSTRAINT `Ability_1` FOREIGN KEY (`Ability_1`) REFERENCES `ability` (`ability_ID`) ON UPDATE CASCADE ON DELETE CASCADE;
/* SQL Error (1452): Cannot add or update a child row: a foreign key constraint fails (`check`.`#sql-ec0_2`, CONSTRAINT `Ability_1` FOREIGN KEY (`Ability_1`) REFERENCES `ability` (`ability_ID`) ON DELETE CASCADE ON UPDATE CASCADE) */
If there is anything else I can provide please let me know this is really bothering me. I'm also using 5.5.27 - MySQL Community Server (GPL) that came with xampp installer.
If you are using HeidiSQL it is pretty easy.
Just see the image, click on the +Add to add foreign keys.
I prefer GUI way of creating tables and its attribute because it saves time and reduces errors.
I found it. Sorry everyone. The problem was that I had 0 as a default value for my fields while my original table had no value for 0.
Here is how you can do it ;
Create your Primary keys. For me this was straight forward so I won't post how to do that here
To create your FOREIGN KEYS you need to change the table / engine type for each table from MyIASM to InnoDb. To do this Select the table on the right hand side then select the OPTIONS tab on the right hand side and change the engine from MyIASM to InnoDb for every table.