I am currently writing this manually using a line read from a file and am trying to read all table ddls where the table begins a_
An input of this:
Other stuff:
Other stuff:
create table a_table1 (
id number(10,0) not null,
timestamp number(19,0) not null,
primary key (id)
)
stuff
create table a_table2 (
id number(10,0) not null,
primary key (id)
)
Other stuff:
create table b_table1 (
id number(10,0) not null,
timestamp number(19,0) not null,
primary key (id)
)
other stuff
other stuff
should output only this
create table a_table1 (
id number(10,0) not null,
timestamp number(19,0) not null,
primary key (id)
)
create table a_table2 (
id number(10,0) not null,
primary key (id)
)
Currently I am using LineReaders and remembering when I see create table and then reading everything until I see )
Is this the most efficient way? Is there some fancy reg ex I could use?
I tried the following reg ex but this didnt work as it just returns the whole string again. Perhaps the new lines are breaking it
"^.*create.*a_(.*?)\\).*$", "$1")
Any advice would be appreciated
Thanks
Try something like this:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
IOUtils.copyLarge(getClass().getClassLoader().getResourceAsStream("input.txt"), baos);
String org = baos.toString();
final Pattern compile = Pattern.compile("(?s)(create table a_.*?\n\\)\n)");
final Matcher matcher = compile.matcher(org);
while (matcher.find()) {
System.out.println(matcher.group());
}
input.txt
Other stuff:
Other stuff:
create table a_table1 (
id number(10,0) not null,
timestamp number(19,0) not null,
primary key (id)
)
stuff
create table a_table2 (
id number(10,0) not null,
primary key (id)
)
Other stuff:
create table b_table1 (
id number(10,0) not null,
timestamp number(19,0) not null,
primary key (id)
)
other stuff
output
create table a_table1 (
id number(10,0) not null,
timestamp number(19,0) not null,
primary key (id)
)
create table a_table2 (
id number(10,0) not null,
primary key (id)
)
Following regex based code will work as long as there is only 2 level nesting of parenthesis in the create table sql statements:
String sql = "Other stuff: \n\nOther stuff: \ncreate table a_table1 (\nid number(10,0) not null,\ntimestamp number(19,0) not null,\nprimary key (id)\n)\nstuff\ncreate table a_table2 (\nid number(10,0) not null,\nprimary key (id)\n)\n\nOther stuff: \ncreate table b_table1 (\nid number(10,0) not null,\ntimestamp number(19,0) not null,\nprimary key (id)\n)\nother stuff \n\nother stuff\n\n";
Pattern p = Pattern.compile(
"(?i)create\\s+table\\s+a_\\w+\\s+\\((?:[^()]+|\\([^()]+\\))*\\)"
);
Matcher m = p.matcher(sql);
while (m.find()) {
System.out.println(m.group());
}
OUTPUT
create table a_table1 (
id number(10,0) not null,
timestamp number(19,0) not null,
primary key (id)
)
create table a_table2 (
id number(10,0) not null,
primary key (id)
)
Related
I have a problem with that.
I was working with the perfume project
https://github.com/merikbest/OnlineShop
and wanted to convert it to wine, but I got this error
I do not understand what my mistake is, I have reviewed many articles and found nothing.
org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "alter table orders_wine_list add constraint FKas0ewroa6urvffgjnu25f5jv0 foreign key (order_id) references orders (id)" via JDBC Statement
org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "alter table usr_wine_list add constraint FK3sqekriy3xfd3ctdfcsumx3v1 foreign key (user_id) references usr (id)" via JDBC Statement
This is SQL code:
table orders
CREATE TABLE `wine`.`orders` (
`id` INT NOT NULL AUTO_INCREMENT,
`address` VARCHAR(255) NULL,
`city` VARCHAR(255) NULL,
`date` DATETIME NULL,
`email` VARCHAR(255) NULL,
`first_name` VARCHAR(255) NULL,
`last_name` VARCHAR(255) NULL,
`phone_number` VARCHAR(255) NULL,
`post_index` VARCHAR(45) NOT NULL,
`total_price` FLOAT NULL,
`user_id` INT NULL,
PRIMARY KEY (`id`));
table wine
CREATE TABLE `wine`.`wine` (
`id` INT NOT NULL AUTO_INCREMENT,
`country` VARCHAR(255) NULL,
`description` VARCHAR(255) NULL,
`filename` VARCHAR(255) NULL,
`decantation` VARCHAR(255) NULL,
`combination` VARCHAR(255) NULL,
`grape` VARCHAR(255) NULL,
`color` VARCHAR(255) NULL,
`wine_title` VARCHAR(255) NULL,
`brand` VARCHAR(255) NULL,
`price` INT NOT NULL,
`type` VARCHAR(255) NULL,
`volume` VARCHAR(255) NULL,
`year` VARCHAR(255) NOT NULL,
PRIMARY KEY (`id`));
table user
CREATE TABLE `wine`.`usr` (
`id` INT NOT NULL AUTO_INCREMENT,
`activation_code` VARCHAR(255) NULL,
`active` TINYINT NOT NULL,
`email` VARCHAR(255) NULL,
`password` VARCHAR(255) NOT NULL,
`username` VARCHAR(255) NOT NULL,
PRIMARY KEY (`id`));
table user role
CREATE TABLE `wine`.`user_role` (
`user_id` INT NOT NULL,
`roles` VARCHAR(255) NULL);
table orders_wine_list
CREATE TABLE `wine`.`orders_wine_list` (
`order_id` INT NOT NULL,
`wine_list_id` INT NOT NULL,
`wine_list_order` INT NOT NULL,
PRIMARY KEY (`order_id`, `wine_list_order`));
table usr_wine_list
CREATE TABLE `wine`.`usr_wine_list` (
`user_id` INT NOT NULL,
`wine_list_id` INT NOT NULL);
and ALTER TABLE
ALTER TABLE `wine`.`orders`
ADD CONSTRAINT `FK7ncuqw9n77odylknbo8aikc9w`
FOREIGN KEY (`user_id`)
REFERENCES `wine`.`usr` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION;
ALTER TABLE `wine`.`orders_wine_list`
ADD CONSTRAINT `FKi6hpa14qaenek8pc9pf3vmlei`
FOREIGN KEY (`wine_list_id`)
REFERENCES `wine`.`wine` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION;
ALTER TABLE `wine`.`orders_wine_list`
ADD CONSTRAINT `FK8jft4d30d5dgvauht7ssndwau`
FOREIGN KEY (`order_id`)
REFERENCES `wine`.`orders` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION;
ALTER TABLE `wine`.`user_role`
ADD CONSTRAINT `FKfpm8swft53ulq2hl11yplpr5`
FOREIGN KEY (`user_id`)
REFERENCES `wine`.`usr` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION;
ALTER TABLE `wine`.`usr_wine_list`
ADD CONSTRAINT `FK1n7n8prjoexkp1twc9f6kgbtm`
FOREIGN KEY (`wine_list_id`)
REFERENCES `wine`.`wine` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION;
ALTER TABLE `wine`.`usr_wine_list`
ADD CONSTRAINT `FKc5b4lo20noteewtlrq1kd8nhs`
FOREIGN KEY (`user_id`)
REFERENCES `wine`.`usr` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION;
just verified all the scripts under mysql env. Seems no issue.
see: DB Fiddle
I have a table of Orders, and a table of Order Status Updates that points to order.id. I need to get a list of Orders, but I need to join in order status updates because I don't want orders which last status is 'Cancelled'
CREATE TABLE `orders` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`end_customer_id` bigint(20) NOT NULL,
`created_at` datetime NOT NULL,
`updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `FK_end_customer` (`end_customer_id`),
CONSTRAINT `orders_ibfk_3` FOREIGN KEY (`end_customer_id`) REFERENCES `end_customers` (`id`) ON UPDATE CASCADE,
) ENGINE=InnoDB AUTO_INCREMENT=100333 DEFAULT CHARSET=utf8;
CREATE TABLE `order_status_updates` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`status` varchar(255) NOT NULL,
`date` datetime NOT NULL,
`order_id` bigint(20) NOT NULL,
PRIMARY KEY (`id`),
KEY `FK_order` (`order_id`),
CONSTRAINT `order_status_updates_ibfk_3` FOREIGN KEY (`order_id`) REFERENCES `orders` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
) ENGINE=InnoDB AUTO_INCREMENT=344180 DEFAULT CHARSET=utf8;
Current Criteria is:
final Criteria c = criteria("o")
.add(eq("o.endCustomer.id", endCustomerId));
return list(c.addOrder(desc("createdAt")));
I need to filter out Orders which latest status (sorted by Date) is Cancelled
Assuming a class called MyOrder and an ORDER_STATUS enum as well as id, status and createdAt field definitions:
final Criteria c = sessionFactory.getCurrentSession().createCriteria(MyOrder.class);
c.add(Restrictions.eq("id", yourId))
.add(Restrictions.ne("status", ORDER_STATUS.CANCELLED)
.addOrder(Order.desc("createdAt"));
I've got tables Artist, Concert, and Artist_Concert, which contains many-to many connections between Artist and Concert.
The problem is: after adding a Concert with few Artists, when trying to delete rows from Artist_Concert, it only deletes only one row and nothing happens when trying to delete any others.
This is how I'm trying to delete rows in Java:
stat = connect.createStatement();
res = stat.executeQuery ("SELECT idConcert FROM concerthall.concert where ConcertName = '"+conc+"';");
res.first();
int idconc = res.getInt(1);
stat.execute ("DELETE FROM concerthall.artist_concert WHERE idConc="+idconc+"");
Artist
CREATE TABLE IF NOT EXISTS `concerthall`.`Artist` (
`idArtist` INT NOT NULL AUTO_INCREMENT,
`ArtName` VARCHAR(45) NOT NULL,
`ArtFee` INT NULL,
PRIMARY KEY (`idArtist`))
ENGINE = InnoDB
Artist-Concert
CREATE TABLE IF NOT EXISTS `concerthall`.`Artist_Concert` (
`idCA` INT NOT NULL AUTO_INCREMENT,
`idArt` INT NOT NULL,
`IdConc` INT NOT NULL,
INDEX `idart_idx` (`idArt` ASC),
INDEX `idconc_idx` (`IdConc` ASC),
PRIMARY KEY (`idCA`),
CONSTRAINT `idart2`
FOREIGN KEY (`idArt`)
REFERENCES `concerthall`.`Artist` (`idArtist`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `idconct4`
FOREIGN KEY (`IdConc`)
REFERENCES `concerthall`.`Concert` (`idConcert`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
Concert
CREATE TABLE IF NOT EXISTS `concerthall`.`Concert` (
`idConcert` INT NOT NULL AUTO_INCREMENT,
`ConcertName` VARCHAR(45) NOT NULL,
`ConcertDateTime` DATETIME NOT NULL,
`Organizator` INT NOT NULL,
PRIMARY KEY (`idConcert`),
INDEX `concertorg_idx` (`Organizator` ASC),
CONSTRAINT `concertorg`
FOREIGN KEY (`Organizator`)
REFERENCES `concerthall`.`Organizator` (`idOrganizator`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
The easiest way to drop duplicates is:
ALTER IGNORE TABLE table ADD UNIQUE INDEX( a, b );
In the INDEX() part, enter the name(s) of the column(s) you only want unique entries for. I think you want:
ALTER IGNORE TABLE concerthall.artist_concert ADD UNIQUE INDEX( idConc );
Then drop the index.
I have two tables whereby the primary key(foreign key on the other table) is auto incremented at run time (using TOAD for mysql).
How can I insert data into the two tables at the same time using a transaction.
This is the ddl for the first table:
CREATE TABLE `suspendedsales` (
`SID` int(11) NOT NULL AUTO_INCREMENT,
`SequenceNo` int(11) NOT NULL DEFAULT '0',
`ProductCode` varchar(100) DEFAULT NULL,
`ItemName` varchar(100) DEFAULT NULL,
`Quantity` int(11) DEFAULT NULL,
`Discount` double DEFAULT NULL,
`ItemCost` double DEFAULT NULL,
PRIMARY KEY (`SID`,`SequenceNo`),
CONSTRAINT `SIDFKey` FOREIGN KEY (`SID`) REFERENCES `suspendedsalesdetails` (`SID`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
The ddl for the second table:
CREATE TABLE `suspendedsalesdetails` (
`SID` int(11) NOT NULL DEFAULT '0',
`Date` date DEFAULT NULL,
`Total` double DEFAULT NULL,
PRIMARY KEY (`SID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
N.B: The major challenge would be to get the auto-incremented key value from on the primary key to be inserted into the other table at run time.
Thanks in anticipation.
If your database is a MySql database you can insert a record in the first table use the following function
SELECT LAST_INSERT_ID();
to get the last inserted id and you can use it in the second insert. Commit all only after the second insert
How about this:
private void insert() {
OraclePreparedStatement statement = null;
try {
Connection dbConnection = getConnection();
statement = dbConnection.createStatement();
String insertToSuspendedsales = "insert into suspendedsales (SequenceNo, ProductCode,ItemName,Quantity,Discount,ItemCost) "
+ "values(:segNo, :prodNo, :itmeName, :quantity, :discount, :itemCost) returning SID into ?";
statement.setIntAtName("segNo", intValue);
....
int id = statement.registerReturnParameter(1, OracleTypes.INTEGER)
statement.executeUpdate(insertToSuspendedsales);
String insertToSuspendedsalesdetails = "insert into suspendedsalesdetails (SID, Date, Total) "
+ "values(:sid, :date, :total) returning SID into ?";
statement.setIntAtName("sid", id);
....
statement.executeUpdate(insertToSuspendedsalesdetails);
} catch (SQLException ex) {
ex.printStackTrace();
//rollback
} finally {
//close Connection
}
}
Hi I'm trying to get the foreig key for a given table, I'm using this code :
ResultSet rs = meta.getImportedKeys(_con.getCatalog(), null, _tableName);
while (rs.next())
{
//get the foreignKeys
}
ResultSet rs2 = meta.getExportedKeys(_con.getCatalog(), null, _tableName);
while (rs2.next())
{
//get the foreignKeys
}
The resultSet is empty, although the table contains a foreign key and is a foreign key to another table,
the getImportedKeys works fine.
Thanks for any suggestions.
Tables :
CREATE TABLE `COMMANDE` (
`COMMANDE_ID` int(11) NOT NULL,
`CLIENT_ID` int(100) DEFAULT NULL,
`TOURNEE_ID` int(100) DEFAULT NULL,
PRIMARY KEY (`COMMANDE_ID`),
KEY `CLIENT_ID` (`CLIENT_ID`),
KEY `TOURNEE_ID` (`TOURNEE_ID`),
CONSTRAINT `commande_ibfk_1` FOREIGN KEY (`CLIENT_ID`) REFERENCES `CLIENT` (`CLIENT_ID`),
CONSTRAINT `commande_ibfk_2` FOREIGN KEY (`TOURNEE_ID`) REFERENCES `TOURNEE` (`TOURNEE_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `CLIENT` (
`CLIENT_ID` int(100) NOT NULL,
`LIBELLE` varchar(100) DEFAULT NULL,
PRIMARY KEY (`CLIENT_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
I tried the code with both tables.
I think the problem is from the rather curious naming of the methods in JDBC, and the hard to grok description.
To get primary keys of a table, you should use getPrimaryKeys(), to get the foreign key of a table (and the primary key they reference), use getImportedKeys()
There are additional methods
- getExportedKeys() exposes the foreign keys that reference the specified table (so the table parameter specifies the table with the primary key)
- getCrossReference() is a combination of all of the above: you need to specify the tables on both sides of the constraint