Issue with MySQL to H2 DDL - mysql

I have a table created in MySQL that is initiated and it works fine. But I have defined an in memory database with H2 for testing purposes that uses the same DDL to clone the table that I can test my app with.
CREATE TABLE `foo` (
`fieldA` BIGINT(20) NOT NULL AUTO_INCREMENT,
`fieldB` BIGINT(20) NOT NULL,
`fieldC` TIMESTAMP NOT NULL,
`fieldD` TIMESTAMP NOT NULL,
`fieldE` VARCHAR(40) NOT NULL,
`fieldF` VARCHAR(40) NOT NULL,
`fieldG` CHAR(3) NOT NULL,
PRIMARY KEY (`id`),
KEY `fieldF` (`fieldF`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
But when i try to initialise the table for my tests it spits back this error:
Caused by: org.h2.jdbc.JdbcSQLException: Unknown data type: "fieldF";
That's about as helpful as the error gets. I've explicitly set field F to VARCHAR(40), so what have do i need to do more?
if it helps, I'm creating the table in Spring Boot configuration here:
#Configuration
#EnableAutoConfiguration
#Import(ImportDataJobConfig.class)
public class TestJobConfiguration {
#Bean
public DataSource tlDataSource() {
return new EmbeddedDatabaseBuilder()
.generateUniqueName(true)
.setType(H2)
.setScriptEncoding("UTF-8")
.ignoreFailedDrops(true)
.addScript("sql/ve/init.sql")
.build();
}
}
Thanks!

Using h2-1.4.196 MySQL mode, your code snippet gives the following error:
Column "ID" not found (...)
Your DDL is wrong around id and needs to be fixed.
In order to fix the error you're facing, I would suggest:
Use the MySQL mode in your JDBC URL like jdbc:h2:mem:;mode=mysql
It seems your real primary key is fieldA, not id. Please change your SQL DDL accordingly:
CREATE TABLE `foo` (
`fieldA` BIGINT(20) NOT NULL AUTO_INCREMENT,
`fieldB` BIGINT(20) NOT NULL,
`fieldC` TIMESTAMP NOT NULL,
`fieldD` TIMESTAMP NOT NULL,
`fieldE` VARCHAR(40) NOT NULL,
`fieldF` VARCHAR(40) NOT NULL,
`fieldG` CHAR(3) NOT NULL,
PRIMARY KEY (`fieldA`),
KEY `fieldF` (`fieldF`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Related

MySQL - SQLite - Converting is spitting out SET error

I am trying to convert the following sql into sqlite via sqlite3.exe but it keeps giving me this error:
Error: near line 1: near "SET": syntax error
I'm not entirely sure what this means or why. Here is my sql script:
SET SQL_MODE = 'NO_AUTO_VALUE_ON_ZERO',
time_zone = '+00:00';
CREATE TABLE `px` (
`x` int(11) NOT NULL,
`y` int(11) NOT NULL,
`colour` varchar(30) NOT NULL,
`time` varchar(30) NOT NULL,
`id` int(10) UNSIGNED NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `px`
ADD PRIMARY KEY (`id`);
ALTER TABLE `px`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT;
I'm sure i'm overlooking a simple syntax error. Any help would be much appreciated!
You can 't just run a MySQL script in SQLite. These are two different databases, whose syntax differ.
In SQLite, a relatively close syntax to the MySQL script would be:
CREATE TABLE `px` (
`x` integer NOT NULL,
`y` integer NOT NULL,
`colour` varchar(30) NOT NULL,
`time` varchar(30) NOT NULL,
`id` integer NOT NULL PRIMARY KEY AUTOINCREMENT
);

Foreign key constraint fails but referenced row exists

I'm running MySQL 5.7.21 on Amazon RDS.
I know this question has been asked a thousand times, but I'm getting the issue on a scenario I wouldn't expect, so please read through before downvoting or marking as duplicate.
I'm not restoring the database, just running single INSERT queries, so is not a matter of ordering.
The referenced row does exist on the table; me and my colleagues had it triple checked.
As one might expect, disabling the FK checks with SET foreign_key_checks = 0 does make the query work.
I've seen this happening because of different table charsets, but in this case, both use utf8mb4. Also both have collation set to utf8mb4_general_ci.
This is happening in a production environment, so dropping the tables and recreating them is something I would like to avoid.
Some additional information:
The FK constraint was created AFTER the original tables were already populated.
Here is the relevant portion of the current DDL:
CREATE TABLE `VehicleTickets` (
`id` varchar(50) NOT NULL,
`vehiclePlate` char(7) NOT NULL,
`organizationId` varchar(50) NOT NULL,
`createdAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updatedAt` timestamp NULL DEFAULT NULL,
`status` varchar(15) NOT NULL DEFAULT 'OPEN',
`description` text NULL DEFAULT NULL,
`ticketInfo` json DEFAULT NULL,
`externalId` varchar(100) GENERATED ALWAYS AS (json_unquote(json_extract(`ticketInfo`,'$.externalId'))) VIRTUAL,
`value` decimal(10,2) GENERATED ALWAYS AS (json_unquote(json_extract(`ticketInfo`,'$.value'))) VIRTUAL,
`issuedAt` timestamp GENERATED ALWAYS AS (json_unquote(json_extract(`ticketInfo`,'$.issuedAt'))) VIRTUAL NOT NULL,
`expiresAt` timestamp GENERATED ALWAYS AS (json_unquote(json_extract(`ticketInfo`,'$.expiresAt'))) VIRTUAL NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `VehicleTickets_externalId_unq_idx` (`externalId`,`organizationId`),
KEY `VehicleTickets_vehiclePlate_idx` (`vehiclePlate`),
KEY `VehicleTickets_organizationId_idx` (`organizationId`),
KEY `VehicleTickets_issuedAt_idx` (`createdAt`),
KEY `VehicleTickets_expiresAt_idx` (`expiresAt`),
CONSTRAINT `VehicleTickets_Organizations_fk`
FOREIGN KEY (`organizationId`) REFERENCES `Organizations` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE `Organizations` (
`id` varchar(50) NOT NULL,
`name` varchar(100) NOT NULL,
`taxPayerId` varchar(50) DEFAULT NULL,
`businessName` varchar(100) DEFAULT NULL,
`status` varchar(15) NOT NULL DEFAULT 'TESTING',
`createdAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updatedAt` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`activatedAt` timestamp NULL DEFAULT NULL,
`assetConfiguration` json DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
When I run:
select * from VehicleTickets where organizationId not in (
select id from Organizations
);
I get an empty result set.
However, if I run a query like this:
insert into `VehicleTickets` (
`id`,
`createdAt`,
`organizationId`,
`ticketInfo`,
`vehiclePlate`
)
values (
'... application generated id',
'... current date ',
'cjlchoksi01r8nfks3f51kht8', -- DOES EXIST on Organizations
'{ ... some JSON payload }',
'... vehicle plate'
)
This produces the following error:
Cannot add or update a child row: a foreign key constraint fails
(VehicleTickets, CONSTRAINT VehicleTickets_Organizations_fk
FOREIGN KEY (organizationId) REFERENCES Organizations (id))
Additionally, it gives me:
"errno": 1452,
"sqlState": "23000",
I've read through several threads regarding this issue, but couldn't find a similar case.

MySQL Workbench wont make constraint when parent table has Generated Virtual columns

SETUP
MySQL Workbench (ver 6.3.9)
MySQL 5.7.21
My setup is simple.. I have 2 tables:
CREATE TABLE `UserDevices` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`UserID` int(11) DEFAULT NULL,
`UUID` binary(16) DEFAULT NULL,
`DeviceName` varchar(45) DEFAULT NULL,
`DeviceType` tinyint(3) NOT NULL DEFAULT '1',
`CreatedDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`TimeStamp` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
CREATE TABLE `UserInfo` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`UUID` binary(16) DEFAULT NULL,
`UUIDText` varchar(40) GENERATED ALWAYS AS (insert(insert(insert(insert(hex(`UUID`),9,0,'-'),14,0,'-'),19,0,'-'),24,0,'-')) VIRTUAL,
`FirstName` varchar(45) DEFAULT NULL,
`LastName` varchar(45) DEFAULT NULL,
`FullName` varchar(90) GENERATED ALWAYS AS (concat(`FirstName`,' ',`LastName`)) VIRTUAL,
`Email` varchar(120) DEFAULT NULL,
`Status` tinyint(3) DEFAULT '0',
`AccountType` tinyint(3) DEFAULT '1',
`CreatedDate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`TimeStamp` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
PROBLEM
When working inside Workbench I'm simply trying to Make a Foreign key constraint in table "UserDevices" on Column "UserID" Pointed at Table "UserInfo" Column "ID". When selecting "UserInfo" as the Referenced Table. I can not put a check next to UserID.. Also no columns show up in the drop down list under Referenced Column..
QUESTION
I understand there are a number of reasons this scenario would happen. But I'm not seeing Any data type mismatch or such that would explain this. What is making it so I can't select UserID.ID?
P.S. Setting up another table named "DeviceMeasurements" with a Column "DeviceID" I'm completely successful at setting up the constraint exactly as expected.
UPDATE
On a hunch since this is my first time playing around with Generated Virtual Columns. I went into the table and removed columns "UUIDText" and "FullName". NOW I can build my constraints as desired. But my question stands. Why can't I build constraint with the tables built as above!?
UPDATE 2
This has been confirmed as a bug in WorkBench. Manually adding the constraint via SQL code is a valid work around currently. Please see accepted answer.
Can confirm, this is a bug in WB. Have raised it with MySQL dev team.
Bug link

Error when importing schema.sql

I'm new to sql, currently I am using phpMyAdmin via XAMP, I think that uses mysql so correct me if I'm wrong by saying that. Anywhos, I'm trying to import a schema.sql data file into my database I created called "test" but I got an error upon importing it:
It says
Import has been successfully finished, 1 queries executed.
(schema.sql)
But then it also gives me an error message:
CREATE TABLE `population` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`location` varchar(150) NOT NULL,
`slug` varchar(150) NOT NULL,
`population` int(10) unsigned NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8
MySQL said: Documentation
1075 - Incorrect table definition; there can be only one auto column and it must be defined as a key
and :
Notice in .\import.php#704 Undefined variable: import_text Backtrace
I'm not sure what the issue is. The database I created is completely and has nothing in it.
Column id is the auto-column in question; auto-columns need to be defined as a key, for example as a unique key or a primary key. In your case, a primary key is a good idea because - well, it's your id-column.
CREATE TABLE `population` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`location` varchar(150) NOT NULL,
`slug` varchar(150) NOT NULL,
`population` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

Mysql DDL works on local wamp but does not import on online server

I am using this schema on localhost wamp MySQL server and it works fine:
CREATE TABLE `tblcustomers` (
`customerid` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`customername` varchar(50) NOT NULL,
`customerphone` varchar(11) DEFAULT NULL,
`customeraddress` varchar(255) DEFAULT NULL,
`registrationdate` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
UNIQUE KEY `credid` (`customerid`),
UNIQUE KEY `credname` (`customername`),
UNIQUE KEY `customerid` (`customerid`)
) ENGINE=InnoDB AUTO_INCREMENT=110 DEFAULT CHARSET=latin1;
MySQL said: Documentation
#1067 - Invalid default value for 'registrationdate'
When I import the dump file on online server I get the message above. How to deal with it?
change datatype for registrationdate FROM DATETIME to TIMESTAMP and you should be through