-- MySQL Script generated by MySQL Workbench
-- Tue Apr  7 17:19:30 2026
-- Model: New Model    Version: 1.0
-- MySQL Workbench Forward Engineering


-- -----------------------------------------------------
-- Schema mydb
-- -----------------------------------------------------

-- -----------------------------------------------------
-- Schema mydb
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS `mydb` DEFAULT CHARACTER SET utf8 ;
USE `mydb` ;

-- -----------------------------------------------------
-- Table `mydb`.`sensormiguel`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`sensormiguel` (
  `idsensormiguel` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `nome` VARCHAR(35) NULL DEFAULT NULL,
  `contador` INT UNSIGNED NULL DEFAULT 0,
  PRIMARY KEY (`idsensormiguel`));


-- -----------------------------------------------------
-- Table `mydb`.`macmiguel`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`macmiguel` (
  `idmacmiguel` VARCHAR(17) NOT NULL,
  `nome` VARCHAR(35) NULL DEFAULT NULL,
  `contador` INT UNSIGNED NULL DEFAULT 0,
  `limite` INT UNSIGNED NULL DEFAULT 100,
  `ativo` TINYINT NULL DEFAULT 0,
  PRIMARY KEY (`idmacmiguel`));


-- -----------------------------------------------------
-- Table `mydb`.`leituramiguel`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`leituramiguel` (
  `idleituramiguel` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `macmiguel_idmacmiguel` VARCHAR(17) NOT NULL,
  `sensormiguel_idsensormiguel` INT UNSIGNED NOT NULL,
  `dataleitura` DATE NULL DEFAULT NULL,
  `horaleitura` TIME NULL DEFAULT NULL,
  `valor` INT UNSIGNED NULL DEFAULT NULL,
  PRIMARY KEY (`idleituramiguel`),
  INDEX `leituramiguel_FKIndex1` (`sensormiguel_idsensormiguel` ASC) VISIBLE,
  INDEX `leituramiguel_FKIndex2` (`macmiguel_idmacmiguel` ASC) VISIBLE,
  CONSTRAINT ``
    FOREIGN KEY (`sensormiguel_idsensormiguel`)
    REFERENCES `mydb`.`sensormiguel` (`idsensormiguel`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT ``
    FOREIGN KEY (`macmiguel_idmacmiguel`)
    REFERENCES `mydb`.`macmiguel` (`idmacmiguel`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION);

USE `mydb`;

DELIMITER $$
USE `mydb`$$
CREATE DEFINER = CURRENT_USER TRIGGER `mydb`.`leituramiguel_AFTER_INSERT` AFTER INSERT ON `leituramiguel` FOR EACH ROW
BEGIN
update macmiguel
set contador=contador+1
where	idmacmiguel=new.macmiguel_idmacmiguel;
update sensormiguel
set contador=contador+1
where	idsensormiguel=new.sensormiguel_idsensormiguel;
END$$

USE `mydb`$$
CREATE DEFINER = CURRENT_USER TRIGGER `mydb`.`leituramiguel_AFTER_DELETE` AFTER DELETE ON `leituramiguel` FOR EACH ROW
BEGIN
update macmiguel
set contador=contador-1
where	idmacmiguel=old.macmiguel_idmacmiguel;
update sensormiguel
set contador=contador-1
where	idsensormiguel=old.sensormiguel_idsensormiguel;
END$$


DELIMITER ;

