RENAME TABLE `measure` TO `Measure` 
ALTER TABLE `Measure`  ENGINE = InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;


CREATE TABLE IF NOT EXISTS `Module` (
  `Id` int(11) NOT NULL auto_increment,
  `Name` varchar(255) NOT NULL,
  PRIMARY KEY  (`Id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;

CREATE TABLE IF NOT EXISTS `PermissionAssignment` (
  `User` int(11) default NULL,
  `Group` int(11) default NULL,
  `Operation` int(11) default NULL,
  `SubGroup` int(11) default NULL,
  KEY `Group` (`Group`),
  KEY `Action` (`Operation`),
  KEY `SubGroup` (`SubGroup`),
  KEY `User` (`User`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `PermissionGroup` (
  `Id` int(11) NOT NULL auto_increment,
  `Name` varchar(255) NOT NULL,
  PRIMARY KEY  (`Id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

CREATE TABLE IF NOT EXISTS `PermissionOperation` (
  `Id` int(11) NOT NULL auto_increment,
  `Module` int(11) NOT NULL,
  `Action` varchar(255) NOT NULL,
  `Item` int(11) NOT NULL,
  PRIMARY KEY  (`Id`),
  KEY `Module` (`Module`),
  KEY `Action` (`Action`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

ALTER TABLE `PermissionAssignment`
  ADD CONSTRAINT `PermissionAssignment_ibfk_1` FOREIGN KEY (`Group`) REFERENCES `PermissionGroup` (`Id`),
  ADD CONSTRAINT `PermissionAssignment_ibfk_3` FOREIGN KEY (`SubGroup`) REFERENCES `PermissionGroup` (`Id`),
  ADD CONSTRAINT `PermissionAssignment_ibfk_4` FOREIGN KEY (`User`) REFERENCES `User` (`Id`),
  ADD CONSTRAINT `PermissionAssignment_ibfk_5` FOREIGN KEY (`Operation`) REFERENCES `PermissionOperation` (`Id`);

ALTER TABLE `PermissionOperation`
  ADD CONSTRAINT `PermissionOperation_ibfk_1` FOREIGN KEY (`Module`) REFERENCES `Module` (`Id`);

CREATE TABLE `MeasureGroup` (
`Id` INT NOT NULL AUTO_INCREMENT ,
`Name` VARCHAR( 255 ) NOT NULL ,
`Parent` INT NOT NULL ,
PRIMARY KEY ( `Id` )
) ENGINE = InnoDB ;

ALTER TABLE `MeasureGroup` ADD INDEX ( `Parent` );
ALTER TABLE `MeasureGroup` ADD FOREIGN KEY ( `Parent` ) REFERENCES `MeasureGroup` ( `Id` ); 
ALTER TABLE `MeasureGroup` CHANGE `Parent` `Parent` INT( 11 ) NULL ;

ALTER TABLE `Measure` ADD `Group` INT NULL AFTER `Id` ;
ALTER TABLE `Measure` ADD INDEX ( `Group` ) ;
ALTER TABLE `Measure` ADD FOREIGN KEY ( `Group` ) REFERENCES `MeasureGroup` ( `Id` );
ALTER TABLE `Measure` DROP `OldName` ;
ALTER TABLE `Measure` DROP `PermissionView`,   DROP `PermissionAdd`;

ALTER TABLE `Measure` CHANGE `Name` `Name` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ,
CHANGE `Description` `Description` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ,
CHANGE `Info` `Info` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ,
CHANGE `DataTable` `DataTable` VARCHAR( 32 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT 'data',
CHANGE `DataType` `DataType` VARCHAR( 32 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL;

