SQL commands not compliable by H2 - mysql

The following SQL commands are actually for MySQL. I am not a SQL expert and do not know much about H2. My Spring app throws an exception because the user_roles table can not be created. It has a problem with the fk_username_idx:
DROP TABLE IF EXISTS users;
DROP TABLE IF EXISTS user_roles;
CREATE  TABLE users (
  userid VARCHAR(5) NOT NULL,
  username VARCHAR(45) NOT NULL ,
  password VARCHAR(60) NOT NULL ,
  enabled TINYINT NOT NULL DEFAULT 1 ,
  PRIMARY KEY (userid));
   
CREATE TABLE user_roles (
  user_role_id int(11) NOT NULL AUTO_INCREMENT,
  userid varchar(5) NOT NULL,
  role varchar(45) NOT NULL,
  PRIMARY KEY (user_role_id),
  UNIQUE KEY uni_username_role (role,userid),
  KEY fk_username_idx (userid),
  CONSTRAINT fk_username FOREIGN KEY (userid) REFERENCES users (userid));
ERROR LOG:
Caused by: org.h2.jdbc.JdbcSQLException: Unbekannter Datentyp: "FK_USERNAME_IDX"
Unknown data type: "FK_USERNAME_IDX"; SQL statement:
   CREATE TABLE user_roles (   user_role_id int(11) NOT NULL AUTO_INCREMENT,   userid varchar(5) NOT NULL,   role varchar(45) NOT NULL,   PRIMARY KEY (user_role_id),   UNIQUE KEY uni_username_role (role,userid),   KEY fk_username_idx (userid),   CONSTRAINT fk_username FOREIGN KEY (userid) REFERENCES users (userid)) [50004-191]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
at org.h2.message.DbException.get(DbException.java:179)
at org.h2.message.DbException.get(DbException.java:155)
at org.h2.command.Parser.parseColumnWithType(Parser.java:4059)
at org.h2.command.Parser.parseColumnForTable(Parser.java:3922)
at org.h2.command.Parser.parseCreateTable(Parser.java:5864)
at org.h2.command.Parser.parseCreate(Parser.java:4217)
at org.h2.command.Parser.parsePrepared(Parser.java:360)
at org.h2.command.Parser.parse(Parser.java:315)
at org.h2.command.Parser.parse(Parser.java:287)
at org.h2.command.Parser.prepareCommand(Parser.java:252)
at org.h2.engine.Session.prepareLocal(Session.java:560)
at org.h2.engine.Session.prepareCommand(Session.java:501)
at org.h2.jdbc.JdbcConnection.prepareCommand(JdbcConnection.java:1188)
at org.h2.jdbc.JdbcStatement.executeInternal(JdbcStatement.java:170)
at org.h2.jdbc.JdbcStatement.execute(JdbcStatement.java:158)
at org.springframework.jdbc.datasource.init.ScriptUtils.executeSqlScript(ScriptUtils.java:472)
... 47 more

are you sure your H2 runs in MySQL compatiblity mode? Check this first. By looking at the connect string. For example like this:
final SimpleDriverDataSource ds = new SimpleDriverDataSource();
ds.setDriverClass(Driver.class);
ds.setUrl("jdbc:h2:mem:test;MODE=mysql;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE");
ds.setUsername("sa");
ds.setPassword("");
FOREIGN KEY fk_username_idx (userid), is not suppported by H2. Remove FOREIGN here.
Then it will work

Related

MySQL performance issue with simple query

I'm trying to run a more or less simple query on a MySQL table with about 100000 entries (Size: 2319.58MB; avg: 24KB pre row).
This is the query:
SELECT
n0_.id AS id0,
n0_.sentTime AS sentTime1,
n0_.deliveredTime AS deliveredTime2,
n0_.queuedTime AS queuedTime3,
n0_.message AS message4,
n0_.failReason AS failReason5,
n0_.targetNumber AS targetNumber6,
n0_.sid AS sid7,
n0_.targetNumber AS targetNumber8,
n0_.sid AS sid9,
n0_.subject AS subject10,
n0_.targetAddress AS targetAddress11,
n0_.priority AS priority12,
n0_.targetUrl AS targetUrl13,
n0_.discr AS discr14,
n0_.notification_state_id AS notification_state_id15,
n0_.user_id AS user_id16
FROM
notifications n0_
INNER JOIN notification_states n1_ ON n0_.notification_state_id = n1_.id
WHERE
n0_.discr IN (
'twilioCallNotification', 'twilioSMSNotification',
'emailNotification', 'httpNotification'
)
ORDER BY
n0_.id desc
LIMIT
25 OFFSET 0
The query between 100 and 200sec.
This is the create statement of the table:
CREATE TABLE notifications (
id INT AUTO_INCREMENT NOT NULL,
notification_state_id INT DEFAULT NULL,
user_id INT DEFAULT NULL,
sentTime DATETIME DEFAULT NULL,
deliveredTime DATETIME DEFAULT NULL,
queuedTime DATETIME NOT NULL,
message LONGTEXT NOT NULL,
failReason LONGTEXT DEFAULT NULL,
discr VARCHAR(255) NOT NULL,
targetNumber VARCHAR(1024) DEFAULT NULL,
sid VARCHAR(34) DEFAULT NULL,
subject VARCHAR(1024) DEFAULT NULL,
targetAddress VARCHAR(1024) DEFAULT NULL,
priority INT DEFAULT NULL,
targetUrl VARCHAR(1024) DEFAULT NULL,
INDEX IDX_6000B0D350C80464 (notification_state_id),
INDEX IDX_6000B0D3A76ED395 (user_id),
PRIMARY KEY (id)
) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB;
ALTER TABLE notifications ADD CONSTRAINT FK_6000B0D350C80464 FOREIGN KEY (notification_state_id) REFERENCES notification_states (id) ON DELETE CASCADE;
ALTER TABLE notifications ADD CONSTRAINT FK_6000B0D3A76ED395 FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE;
These queries are created by Doctrine2 (ORM). We are using MySQL 5.5.31 on a virtual machine (1GB ram, single core) running Debian 6.0.7. Why is the performance of the query so bad? Is it a database design fault or is the vbox just to small to handle this amount of data?
Add an index on discr column :
ALTER TABLE `notifications` ADD INDEX `idx_discr` (`discr` ASC) ;
You're filtering by notifications.discr but don't appear to have that indexed. Have you tried adding an index on it?

Error 1005: Can't create table

im trying to drop a table and before i had this problem QUESTION
and was solved succesfully but now i tried to drop the table and i got this error :
ERROR: Error 1005: Can't create table 'radiotaxi_final.#sql-108_28' (errno: 150)
the statement :
ALTER TABLE `RadioTaxi_Final`.`DireccionConductor` CHANGE COLUMN `Conductor_cedula` `Conductor_cedula` INT(11) NOT NULL ,
ADD CONSTRAINT `fk_DireccionConductor_Conductor1`
FOREIGN KEY (`Conductor_cedula` )
REFERENCES `RadioTaxi_Final`.`Conductor` (`cedula` )
ON DELETE NO ACTION
ON UPDATE NO ACTION
the results :
SQL script execution finished: statements: 11 succeeded, 1 failed
the table :
CREATE TABLE `conductor` (  `cedula` int(10) unsigned NOT NULL,  `apellidos` varchar(30) COLLATE utf8_spanish2_ci NOT NULL,  `nombres` varchar(30) COLLATE utf8_spanish2_ci NOT NULL,  `fechaNacimiento` date NOT NULL,  PRIMARY KEY (`cedula`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish2_ci
When creating a FOREIGN KEY, the data types of the referenced and referencing columns must be exactly the same. In your referenced table, conductor.cedula is of type INT(10) UNSIGNED. You have attempted to create the FK on DireccionConductor.Conductor_cedula as INT(11), implicitly SIGNED. modify your statement as follows to make the type match:
ALTER TABLE `RadioTaxi_Final`.`DireccionConductor`
/* INT(10) UNSIGNED type matches the referenced table */
CHANGE COLUMN `Conductor_cedula` `Conductor_cedula` INT(10) UNSIGNED NOT NULL ,
ADD CONSTRAINT `fk_DireccionConductor_Conductor1`
FOREIGN KEY (`Conductor_cedula` )
REFERENCES `RadioTaxi_Final`.`Conductor` (`cedula` )
ON DELETE NO ACTION
ON UPDATE NO ACTION

Inserting Foreign Key using MySQL Workbench code throwing Syntax Error

I have created several tables with MySQL Workbench and I'm having a problem with Foreign Keys. If I export code below I get an error however if I do not export with foreign keys I do not get an error could you have a look at the code for me.
SQL Code:
DROP TABLE IF EXISTS `mydb`.`users` ;
CREATE TABLE IF NOT EXISTS `mydb`.`users` (
`uuserid` INT NOT NULL AUTO_INCREMENT ,
`ufname` VARCHAR(25) NULL ,
`ulname` VARCHAR(25) NULL ,
`uuname` VARCHAR(45) NULL ,
`upass` CHAR(64) NOT NULL ,
`uemail` VARCHAR(254) NOT NULL ,
`urole` INT NULL DEFAULT 0 ,
PRIMARY KEY (`uuserid`) )
ENGINE = InnoDB;
DROP TABLE IF EXISTS `mydb`.`photos` ;
CREATE TABLE IF NOT EXISTS `mydb`.`photos` (
`pphotoid` INT NOT NULL ,
`pname` VARCHAR(4) NULL ,
`plat` FLOAT(10,6) NULL ,
`plng` FLOAT(10,6) NULL ,
`pflag` DECIMAL(10,0) NULL DEFAULT 0 ,
`pext` VARCHAR(4) NULL ,
`plike` DECIMAL(10,0) NULL DEFAULT 0 ,
PRIMARY KEY (`pphotoid`) ,
CONSTRAINT `uuserid`
FOREIGN KEY ()
REFERENCES `mydb`.`users` ()
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
Error:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') REFERENCES `mydb`.`users` () ON DELETE NO ACTION ON UPDAT' at line 21
My Database has many more tables but this code also breaks. I have tried to insert this using phpmyadmin.
Here you need to specify the column name
FOREIGN KEY (present_table_column_name)
REFERENCES mydb.users (foriegn_key_column_name)
Try running this script. I build this using your script and ran it in SQLFiddle so I know it works. In order to add a foreign key you have to have a field that will be appropriate. In this example I added a uuserid column in the photos table. This column has a foreign key constraint to the uuserid column in the users table.
DROP TABLE IF EXISTS `mydb`.`users` ;
CREATE TABLE IF NOT EXISTS `mydb`.`users` (
`uuserid` INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
`ufname` VARCHAR(25) NULL ,
`ulname` VARCHAR(25) NULL ,
`uuname` VARCHAR(45) NULL ,
`upass` CHAR(64) NOT NULL ,
`uemail` VARCHAR(254) NOT NULL ,
`urole` INT NULL DEFAULT 0
) ENGINE = InnoDB;
DROP TABLE IF EXISTS `mydb`.`photos` ;
CREATE TABLE IF NOT EXISTS `mydb`.`photos` (
`pphotoid` INT NOT NULL PRIMARY KEY,
`pname` VARCHAR(4) NULL ,
`plat` FLOAT(10,6) NULL ,
`plng` FLOAT(10,6) NULL ,
`pflag` DECIMAL(10,0) NULL DEFAULT 0 ,
`pext` VARCHAR(4) NULL ,
`plike` DECIMAL(10,0) NULL DEFAULT 0,
`uuserid`INT NOT NULL
) ENGINE = InnoDB;
Alter Table `photos` add constraint foreign key(`uuserid`) references `users`(`uuserid`);
In this example above, I moved the statement that sets the primary keys to the columns themselves rather than creating a statement at the end of the SQL.
I thought it would be a little clearer to show you how to add a foreign key constraint outside of the table creation so you can see what caused the syntax error. You had no column names in your foreign key references. Once added the above code will run perfectly.
You have a syntax error exactly where the error message tells you you have one.
The problem is you don't have you have any fields referenced in your constraint. The form of the CONSTRAINT clause should be like this:
CONSTRAINT `fkuuserid`
FOREIGN KEY `fkuuserid` (some_field_in_this_table)
REFERENCES `mydb`.`users` (uuserid)
ON DELETE NO ACTION
ON UPDATE NO ACTION
I honestly don't even see where you have a logical foreign key on the photos table, as there is no uuserid field present in this table.

MySQL workbench - self referring table and custom script

I use MySQL 5.3.28 to create my database. One of the tables is referring itself, which is a big pain. Here is the originally created code:
CREATE TABLE IF NOT EXISTS `dhbpsychiatry`.`activity` (
`ActivityId` INT(11) NOT NULL AUTO_INCREMENT ,
`NeedsRepeating` BINARY(1) NULL DEFAULT NULL ,
`Prerequisition` INT(11) NOT NULL DEFAULT 0 ,
`ActivityName` VARCHAR(45) NOT NULL ,
`ActivityDescription` VARCHAR(45) NULL ,
PRIMARY KEY (`ActivityId`) ,
INDEX `Prerequisition` (`ActivityId` ASC) ,
CONSTRAINT `Prerequisition`
FOREIGN KEY (`ActivityId` )
REFERENCES `dhbpsychiatry`.`activity` (`ActivityId` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
Problem is of course with creating first row.
INSERT INTO `dhbpsychiatry`.`activity` (`ActivityId`, `Prerequisition`,
`ActivityName`) VALUES (1, 1, 'No prerequisition');
returns
ERROR 1452: Cannot add or update a child row: a foreign key constraint fails
Same if I try even simpler
INSERT INTO `dhbpsychiatry`.`activity` (`ActivityName`)
VALUES ('No prerequisition');
I think I've tried all possibilities, making the FK nullable, not nullable, with or without default value...
After digging a bit I've found something that works:
SET FOREIGN_KEY_CHECKS = 0;
Insert into activity (ActivityID, ActivityName) VALUES (0,'No prerequisition');
SET FOREIGN_KEY_CHECKS = 1;
So I created a new SQL script in workbench with those lines.
So I have two questions here:
How I can add the first row without the script?
or if its impossible
2 How can I automatically add this script to be executed whenever I froward engineer the database?
Your indexes and Foreign key definitions are confused. Main issue is that column ActivityId is referencing itself.
Try this:
CREATE TABLE IF NOT EXISTS `dhbpsychiatry`.`activity` (
`ActivityId` INT(11) NOT NULL AUTO_INCREMENT ,
`NeedsRepeating` BINARY(1) NULL DEFAULT NULL ,
`Prerequisition` INT(11) NOT NULL DEFAULT 0 ,
`ActivityName` VARCHAR(45) NOT NULL ,
`ActivityDescription` VARCHAR(45) NULL ,
PRIMARY KEY (`ActivityId`) ,
INDEX `Prerequisition_idx` (`Prerequisition`) , --- changed the index name
--- and the indexed column
CONSTRAINT `Prerequisition_fk` --- changed the constraint name
FOREIGN KEY (`Prerequisition` ) --- main issue !! changed
--- the referencing column
REFERENCES `dhbpsychiatry`.`activity` (`ActivityId`)
ON DELETE NO ACTION
ON UPDATE NO ACTION
)

SQL Syntax Error - creating new database

Here's my code, currently got an error at line 3 on the USE statement :
CREATE DATABASE `jamestennisdbTest`;
USE jamestennisdbTest;
DROP TABLE IF EXISTS lessontbl;
CREATE TABLE lessontbl (
LessonID int(11) NOT NULL AUTO_INCREMENT,
LessonName varchar(30) NOT NULL,
LengthOfLesson int(11) NOT NULL,
NoOfPupils int(11) NOT NULL,
LocationID int(11) NOT NULL,
`Type` varchar(45) NOT NULL,
CostPerPupil float NOT NULL,
TotalCost float NOT NULL,
PRIMARY KEY (LessonID),
UNIQUE KEY LessonID_UNIQUE (LessonID),
KEY `fk_Location_lesson-location` (LocationID),
CONSTRAINT `fk_Location_lesson-location` FOREIGN KEY (LocationID) REFERENCES locationstbl (LocationID) ON DELETE NO ACTION ON UPDATE NO ACTION
)
..it goes on but thats not where the errors coming up
..And I am trying to do this through a Delphi ADOQuery (though I dont think that's where the error is)
I believe the 'use' statement is only used in the mysql command line client to switch to another database. If you want to "use" another database, you'll probably need to use some API call or just reconnect directly to the newly created database.