select version();

create database if not exists test;
use test;

create table if not exists workstation (
  id		INT NOT NULL AUTO_INCREMENT,
  prodlineid	INT NOT NULL DEFAULT 1,
  primary key (id)
) engine=innodb;

create table if not exists process_workstation (
  processid				INT NOT NULL,
  workstationid				INT NOT NULL,
  unique index (processid, workstationid),
  index (workstationid),
  constraint foreign key (workstationid) references workstation(id) on delete cascade on update cascade
) ENGINE = InnoDB;

drop function if exists proc_on_ws;
create function proc_on_ws(process_id int, ws_id int, prodline_id int) returns int
  return
    exists(
	select * from process_workstation pw
	where pw.workstationid = ws_id and pw.processid = process_id
    )
  or (
	not isnull(prodline_id) and
	not isnull(process_id) and
	not exists(
		select * from workstation ws, process_workstation pw
		where ws.prodlineid = prodline_id and
		      pw.workstationid = ws.id and pw.processid = process_id
	)
);

insert ignore into  workstation (id) values 
	(10),(11),(12),(13),(14),(15),(16),(17),(18),(19),
	(20),(21),(22),(23),(24),(25),(26),(27),(28),(29),
	(30),(31),(32),(33),(34),(35),(36),(37),(38),(39),
	(40),(41),(42),(43),(44),(45),(46),(47),(48),(49),
	(50),(51),(52),(53),(54),(55),(56),(57),(58),(59),
	(60),(61),(62),(63),(64),(65),(66),(67),(68),(69),
	(70),(71),(72),(73),(74),(75),(76),(77),(78),(79),
	(80),(81),(82),(83),(84),(85),(86),(87),(88),(89)
	;

-- This query crash the server:

select nextws.id from workstation nextws
where nextws.prodlineid = 1 AND proc_on_ws( 7 , nextws.id, nextws.prodlineid)

