-- phpMyAdmin SQL Dump
-- version 4.8.4
-- https://www.phpmyadmin.net/
--
-- Host: localhost
-- Generation Time: Feb 15, 2019 at 05:15 AM
-- Server version: 5.7.25-0ubuntu0.16.04.2
-- PHP Version: 7.0.32-0ubuntu0.16.04.1

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `powerlog`
--

-- --------------------------------------------------------

--
-- Table structure for table `energy_by_date`
--

CREATE TABLE `energy_by_date` (
  `nrg_date` date NOT NULL,
  `nrg_value` int(10) UNSIGNED NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- --------------------------------------------------------

--
-- Table structure for table `powerdata`
--

CREATE TABLE `powerdata` (
  `pwr_timestamp` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `pwr_voltage` decimal(4,1) NOT NULL,
  `pwr_power` smallint(5) UNSIGNED NOT NULL,
  `pwr_energy` int(10) UNSIGNED NOT NULL,
  `pwr_energy_orig` int(10) UNSIGNED NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Triggers `powerdata`
--
DELIMITER $$
CREATE TRIGGER `energy_by_date_rollup` AFTER INSERT ON `powerdata` FOR EACH ROW BEGIN
	DECLARE dayenergy INT DEFAULT 0;
    
	SELECT MAX(pwr_energy) - MIN(pwr_energy) 
    	FROM powerdata 
        WHERE pwr_timestamp >= DATE_FORMAT(NEW.pwr_timestamp, '%Y-%m-%d 00:00:00') 
        INTO dayenergy;

	INSERT INTO energy_by_date (nrg_date, nrg_value ) 
    	Values (DATE(NEW.pwr_timestamp), dayenergy) 
        ON DUPLICATE KEY UPDATE nrg_value = dayenergy;

END
$$
DELIMITER ;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `energy_by_date`
--
ALTER TABLE `energy_by_date`
  ADD PRIMARY KEY (`nrg_date`);

--
-- Indexes for table `powerdata`
--
ALTER TABLE `powerdata`
  ADD UNIQUE KEY `pwr_timestamp` (`pwr_timestamp`);
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
