if (select top 1 0 from sys.databases where name = 'NucelarMonitor') is null create database NucelarMonitor collate Latin1_General_100_CI_AS_SC_UTF8
go
use NucelarMonitor

if object_id(N'dbo.tables_drop', N'P') is not null drop procedure dbo.tables_drop
go
create procedure dbo.tables_drop as begin 

    set nocount on

    -- Level Plains.

    -- Level 2.
    if object_id(N'dbo.MachineInterfacesData', N'U') is not null drop table dbo.MachineInterfacesData
    if object_id(N'dbo.MachineInterfacesTraffic', N'U') is not null drop table dbo.MachineInterfacesTraffic
    if object_id(N'dbo.MachineDisksSpace', N'U') is not null drop table dbo.MachineDisksSpace
    if object_id(N'dbo.Exceptions', N'U') is not null drop table dbo.Exceptions

    -- Level 1.
    if object_id(N'dbo.MachineInterfaces', N'U') is not null drop table dbo.MachineInterfaces
    if object_id(N'dbo.MachineDisks', N'U') is not null drop table dbo.MachineDisks
    if object_id(N'dbo.MachineRAM', N'U') is not null drop table dbo.MachineRAM
    if object_id(N'dbo.MachineCPU', N'U') is not null drop table dbo.MachineCPU
    if object_id(N'dbo.Procedures', N'U') is not null drop table dbo.Procedures

    -- Level 0.
    if object_id(N'dbo.CandlesTimes', N'U') is not null drop table dbo.CandlesTimes
    if object_id(N'dbo.Interfaces', N'U') is not null drop table dbo.Interfaces
    if object_id(N'dbo.Disks', N'U') is not null drop table dbo.Disks
    if object_id(N'dbo.Hostnames', N'U') is not null drop table dbo.Hostnames
    if object_id(N'dbo.Domains', N'U') is not null drop table dbo.Domains
    if object_id(N'dbo.Machines', N'U') is not null drop table dbo.Machines
    if object_id(N'dbo.Databases', N'U') is not null drop table dbo.Databases
    if object_id(N'dbo.Messages', N'U') is not null drop table dbo.Messages
    if object_id(N'dbo.BigData', N'U') is not null drop table dbo.BigData

end
go

if object_id(N'dbo.tables_create', N'P') is not null drop procedure dbo.tables_create
go
create procedure dbo.tables_create as begin 

    set nocount on

    -- Level 0.
    if object_id(N'dbo.Machines', N'U') is null create table dbo.Machines(
        id integer not null identity(1, 1),
        [key] varchar(32) not null,
        [description] varchar(512), 
        date_in datetime not null constraint machines_df_date_in default getdate(),
        date_out datetime, 
        constraint machines_pk primary key clustered (id), 
        constraint machines_uk_key unique ([key]), 
        constraint machines_ck_key check ([key] like '[a-zA-Z0-9][a-zA-Z0-9_]{0,31}') with (fillfactor = 90)
    )

    if object_id(N'dbo.Domains', N'U') is null create table dbo.Domains(
        id integer not null identity(1, 1), 
        domain varchar(64) not null, 
        [description] varchar(512), 
        date_in datetime not null constraint domains_df_date_in default getdate(),
        date_out datetime, 
        constraint domains_pk primary key clustered (id), 
        constraint domains_uk_domain unique nonclustered (domain asc) with (fillfactor = 90), 
        constraint domains_ck_domain check ([domain] like '[a-zA-Z0-9_-.]{1,64}') with (fillfactor = 90)
    )
    

    if object_id(N'dbo.Hostnames', N'U') is null create table dbo.Hostnames(
        id integer not null identity(1, 1), 
        [name] varchar(32) not null, 
        [description] varchar(512), 
        date_in datetime not null constraint hostnames_df_date_in default getdate(),
        date_out datetime, 
        constraint hostnames_pk primary key clustered (id), 
        constraint hostnames_uk_name unique nonclustered ([name] asc) with (fillfactor = 90), 
        constraint hostnames_ck_name check ([name] like '[a-zA-Z0-9_-]{1,32}') with (fillfactor = 90)
    )

    if object_id(N'dbo.Disks', N'U') is null create table dbo.Disks(
        id integer not null identity(1, 1), 
        [name] varchar(32) not null, 
        [size] bigint not null,
        mountpoint varchar(128) not null,
        [description] varchar(512), 
        date_in datetime not null constraint disks_df_date_in default getdate(),
        date_out datetime, 
        constraint disks_pk primary key clustered (id), 
        constraint disks_uk_name unique nonclustered ([name] asc, mountpoint asc) with (fillfactor = 90), 
        constraint disks_ck_name check (
            [name] like '[a-zA-Z0-9_-]{1,32}' or 
            mountpoint like '[A-Z]:'
        ) with (fillfactor = 90), 
        constraint disks_ck_size check (size >= 0 and size < power(2, 53)) with (fillfactor = 90),
        constraint disks_ck_mountpoint check (
            mountpoint like '/%' or 
            mountpoint like '[a-zA-Z]:\%' or 
            mountpoint like '\\%'
        ) with (fillfactor = 90)
    )

    if object_id(N'dbo.Interfaces', N'U') is null create table dbo.Interfaces(
        id integer not null identity(1, 1), 
        [name] varchar(32) not null, 
        [description] varchar(512), 
        date_in datetime not null constraint interfaces_df_date_in default getdate(),
        date_out datetime, 
        constraint interfaces_pk primary key clustered (id), 
        constraint interfaces_uk_machine_name unique nonclustered (machine asc, [name] asc) with (fillfactor = 90), 
        constraint interfaces_ck_name check ([name] like '[a-zA-Z0-9_-]{1,32}') with (fillfactor = 90)
    )

    if object_id(N'dbo.CandlesTimes', N'U') is null create table dbo.CandlesTimes(
        id integer not null identity(1, 1), 
        [from] datetime not null, 
        [to] datetime not null, 
        date_in datetime not null constraint candles_times_df_date_in default getdate(),
        date_out datetime, 
        constraint candles_times_pk primary key clustered (id), 
        constraint candles_times_uk_from_to unique nonclustered ([from] asc, [to] asc) with (fillfactor = 90),
        constraint candles_times_ck_from_to check ([from] < [to]) with (fillfactor = 90)
    )

    if object_id(N'dbo.BigData', N'U') is null create table dbo.BigData(
        id integer not null identity(1, 1),
        [hash] binary(64) not null,
        [value] varchar(max) not null,
        date_in datetime not null constraint big_data_df_date_in default getdate(),
        date_out datetime, 
        constraint big_data_pk primary key clustered (id), 
        constraint big_data_uk_hash unique nonclustered ([hash] asc) with (fillfactor = 90)
    )

    if object_id(N'dbo.Messages', N'U') is null create table dbo.Messages(
        id integer not null identity(1, 1),
        [key] varchar(128) not null,
        date_in datetime not null constraint messages_df_date_in default getdate(),
        date_out datetime, 
        constraint messages_pk primary key clustered (id), 
        constraint messages_ck_key check ([key] like '[a-zA-Z_][a-zA-Z0-9_]{0,127}') with (fillfactor = 90)
    )

    if object_id(N'dbo.Databases', N'U') is null create table dbo.Databases(
        id integer not null identity(1, 1),
        [name] varchar(64) not null,
        date_in datetime not null constraint databases_df_date_in default getdate(),
        date_out datetime, 
        constraint databases_pk primary key clustered (id), 
        constraint databases_uk_name unique nonclustered ([name] asc) with (fillfactor = 90), 
        constraint databases_ck_name check ([name] like '[a-zA-Z_][a-zA-Z0-9_]{0,63}') with (fillfactor = 90)
    )

    -- Level 1.
    if object_id(N'dbo.MachineCPU', N'U') is null create table dbo.MachineCPU(
        id integer not null identity(1, 1), 
        machine integer not null, 
        candle_time integer not null, 
        [in] float not null, 
        [out] float not null, 
        minimum float not null, 
        maximum float not null, 
        average float not null, 
        date_in datetime not null constraint machine_cpu_df_date_in default getdate(),
        date_out datetime, 
        constraint machine_cpu_pk primary key clustered (id), 
        constraint machine_cpu_fk_machine foreign key (machine) references dbo.Machines(id)
            on update no action 
            on delete no action,
        constraint machine_cpu_fk_candle_time foreign key (candle_time) references dbo.CandlesTimes(id)
            on update no action 
            on delete no action, 
        constraint machine_cpu_ck_cpu_in check (
            [in] between 0 and 100 and 
            [in] between minimum and maximum
        ) with (fillfactor = 90),
        constraint machine_cpu_ck_cpu_out check (
            [out] between 0 and 100 and 
            [out] between minimum and maximum
        ) with (fillfactor = 90),
        constraint machine_cpu_ck_cpu_minimum check (
            minimum between 0 and 100 and
            minimum <= maximum
        ) with (fillfactor = 90),
        constraint machine_cpu_ck_cpu_maximum check (
            maximum between 0 and 100 and
            maximum >= minimum
        ) with (fillfactor = 90),
        constraint machine_cpu_ck_cpu_average check (
            average between 0 and 100 and
            average between minimum and maximum
        ) with (fillfactor = 90)
    )

    if object_id(N'dbo.MachineRAM', N'U') is null create table dbo.MachineRAM(
        id integer not null identity(1, 1), 
        machine integer not null, 
        candle_time integer not null, 
        total bigint not null,
        [in] bigint not null, 
        [out] bigint not null, 
        minimum bigint not null, 
        maximum bigint not null, 
        average bigint not null, 
        date_in datetime not null constraint machine_ram_df_date_in default getdate(),
        date_out datetime, 
        constraint machine_ram_pk primary key clustered (id), 
        constraint machine_ram_fk_machine foreign key (machine) references dbo.Machines(id)
            on update no action 
            on delete no action,
        constraint machine_ram_fk_candle_time foreign key (candle_time) references dbo.CandlesTimes(id)
            on update no action 
            on delete no action, 
        constraint machine_ram_ck_memory_total check (
            total between 0 and power(2, 53) - 1
        ) with (fillfactor = 90),
        constraint machine_ram_ck_memory_in check (
            [in] between 0 and power(2, 53) - 1 and 
            [in] between minimum and maximum and 
            [in] <= total
        ) with (fillfactor = 90),
        constraint machine_ram_ck_memory_out check (
            [out] between 0 and power(2, 53) - 1 and 
            [out] between minimum and maximum and 
            [out] <= total
        ) with (fillfactor = 90),
        constraint machine_ram_ck_memory_minimum check (
            minimum between 0 and power(2, 53) - 1 and 
            minimum <= total and 
            minimum <= maximum
        ) with (fillfactor = 90),
        constraint machine_ram_ck_memory_maximum check (
            maximum between 0 and power(2, 53) - 1 and 
            maximum between total and minimum
        ) with (fillfactor = 90),
        constraint machine_ram_ck_memory_average check (
            average between 0 and power(2, 53) - 1 and 
            average between minimum and maximum and 
            average <= total
        ) with (fillfactor = 90)
    )

    if object_id(N'dbo.MachineDisks', N'U') is null create table dbo.MachineDisks(
        id integer not null identity(1, 1), 
        machine integer not null, 
        [disk] integer not null, 
        belongs bit not null constraint machine_disks_df_belongs default 1, 
        mounted bit not null constraint machine_disks_df_mounted default 1,
        date_in datetime not null constraint machine_disks_df_date_in default getdate(),
        date_out datetime, 
        constraint machine_disks_pk primary key clustered (id), 
        constraint machine_disks_fk_machine foreign key (machine) references dbo.Machines(id)
            on update no action 
            on delete no action,
        constraint machine_disks_fk_disk foreign key ([disk]) references dbo.Disks(id)
            on update no action 
            on delete no action
    )

    if object_id(N'dbo.MachineInterfaces', N'U') is null create table dbo.MachineInterfaces(
        id integer not null identity(1, 1), 
        machine integer not null, 
        [interface] integer not null, 
        belongs bit not null constraint machine_interfaces_df_belongs default 1, 
        mounted bit not null constraint machine_interfaces_df_mounted default 1,
        date_in datetime not null constraint machine_interfaces_df_date_in default getdate(),
        date_out datetime, 
        constraint machine_interfaces_pk primary key clustered (id), 
        constraint machine_interfaces_fk_machine foreign key (machine) references dbo.Machines(id)
            on update no action 
            on delete no action,
        constraint machine_interfaces_fk_interface foreign key ([interface]) references dbo.Interfaces(id)
            on update no action 
            on delete no action
    )

    if object_id(N'dbo.Procedures', N'U') is null create table dbo.Procedures(
        id integer not null identity(1, 1),
        [database] integer not null,
        [name] varchar(64) not null,
        date_in datetime not null constraint procedures_df_date_in default getdate(),
        date_out datetime, 
        constraint procedures_pk primary key clustered (id), 
        constraint procedures_fk_database foreign key ([database]) references dbo.Databases(id)
            on update no action 
            on delete no action,
        constraint procedures_uk_name unique nonclustered ([database] asc, [name] asc) with (fillfactor = 90), 
        constraint procedures_ck_name check ([name] like '[a-zA-Z_][a-zA-Z0-9_]{0,63}') with (fillfactor = 90)
    )

    -- Level 2.
    if object_id(N'dbo.MachineDisksSpace', N'U') is null create table dbo.MachineDisksSpace(
        id integer not null identity(1, 1), 
        machine_disk integer not null, 
        candle_time integer not null, 
        free bigint not null, 
        date_in datetime not null constraint machine_disks_space_df_date_in default getdate(),
        date_out datetime, 
        constraint machine_disks_space_pk primary key clustered (id), 
        constraint machine_disks_space_fk_machine_disk foreign key (machine_disk) references dbo.MachineDisks(id)
            on update no action 
            on delete no action,
        constraint machine_disks_space_fk_candle_time foreign key (candle_time) references dbo.CandlesTimes(id)
            on update no action 
            on delete no action,
        constraint machine_disks_space_ck_free check (
            free between 0 and power(2, 53) - 1 and 
            free <= isnull((
                select top 1 disks.[size] 
                from dbo.Disks disks 
                join dbo.MachineDisks machine_disks on machine_disks.[disk] = disks.id 
                where 
                    disks.date_out is null and 
                    machine_disks.date_out is null and 
                    machine_disks.belongs = 1 and 
                    machine_disks.id = machine_disk
            ), 0)
        ) with (fillfactor = 90)
    )

    if object_id(N'dbo.MachineInterfacesTraffic', N'U') is null create table dbo.MachineInterfacesTraffic(
        id integer not null identity(1, 1), 
        machine_interface integer not null, 
        candle_time integer not null, 
        bytes bigint not null, 
        packages integer not null, 
        errors integer not null, 
        date_in datetime not null constraint machine_interfaces_traffic_df_date_in default getdate(),
        date_out datetime, 
        constraint machine_interfaces_traffic_pk primary key clustered (id), 
        constraint machine_interfaces_traffic_fk_machine_interface foreign key (machine_interface) references dbo.MachineInterfaces(id)
            on update no action 
            on delete no action,
        constraint machine_interfaces_traffic_fk_candle_time foreign key (candle_time) references dbo.CandlesTimes(id)
            on update no action 
            on delete no action,
        constraint machine_interfaces_traffic_ck_bytes check (
            bytes between 0 and power(2, 53) - 1
        ) with (fillfactor = 90),
        constraint machine_interfaces_traffic_ck_packages check (
            packages between 0 and power(2, 31) - 1
        ) with (fillfactor = 90),
        constraint machine_interfaces_traffic_ck_errors check (
            errors between 0 and power(2, 31) - 1
        ) with (fillfactor = 90)
    )

    if object_id(N'dbo.MachineInterfacesData', N'U') is null create table dbo.MachineInterfacesData(
        id integer not null identity(1, 1), 
        machine_interface integer not null, 
        is_ipv6 bit not null constraint machine_interfaces_data_df_is_ipv6 default 0,
        [address] varchar(45) not null,
        mask tinyint not null,
        date_in datetime not null constraint machine_interfaces_data_df_date_in default getdate(),
        date_out datetime, 
        constraint machine_interfaces_data_pk primary key clustered (id), 
        constraint machine_interfaces_data_fk_machine_interface foreign key (machine_interface) references dbo.MachineInterfaces(id)
            on update no action 
            on delete no action, 
        constraint machine_interfaces_data_ck_is_ipv6 check (
            (is_ipv6 = 0 and [address] like '[0-9]%.%.%.%') or 
            (is_ipv6 = 1 and [address] like '%:%')
        ) with (fillfactor = 90), 
        constraint machine_interfaces_data_ck_address check (
            ([address] like '[0-9]%.%.%.%' and mask between 0 and 32) or 
            ([address] like '%:%' and mask between 0 and 128)
        ) with (fillfactor = 90), 
        constraint machine_interfaces_data_ck_mask check (
            (mask between 0 and (case when is_ipv6 = 1 then 128 else 32 end))
        ) with (fillfactor = 90)
    )

    if object_id(N'dbo.Exceptions', N'U') is null create table dbo.Exceptions(
        id integer not null identity(1, 1), 
        [procedure] integer not null, 
        [message] integer not null, 
        parameters integer, 
        exception integer not null, 
        [status] varchar(16), 
        code integer,
        date_in datetime not null constraint exceptions_df_date_in default getdate(),
        date_out datetime, 
        constraint exceptions_pk primary key clustered (id), 
        constraint exceptions_fk_procedure foreign key ([procedure]) references dbo.Procedures(id)
            on update no action 
            on delete no action,
        constraint exceptions_fk_message foreign key ([message]) references dbo.Messages(id)
            on update no action 
            on delete no action,
        constraint exceptions_fk_parameters foreign key (parameters) references dbo.BigData(id)
            on update no action 
            on delete no action,
        constraint exceptions_fk_exception foreign key (exception) references dbo.BigData(id)
            on update no action 
            on delete no action
    )

    -- Level Plains.
    if object_id(N'dbo.MachineInterfacesPlain', N'U') is null create table dbo.MachineInterfacesPlain(
        id integer not null identity(1, 1), 
        machine integer not null, 
        interface integer not null, 
        machine_interface integer not null,
        candle_time integer not null, 
        bytes bigint not null, 
        packages integer not null, 
        errors integer not null, 
        is_ipv6 bit not null constraint machine_interfaces_data_df_is_ipv6 default 0,
        [address] varchar(45) not null,
        mask tinyint not null,
        belongs bit not null constraint machine_interfaces_plain_df_belongs default 1, 
        date_in datetime not null constraint machine_interfaces_plain_df_date_in default getdate(),
        date_out datetime, 
        constraint machine_interfaces_plain_pk primary key clustered (id), 
        constraint machine_interfaces_plain_fk_machine foreign key (machine) references dbo.Machines(id)
            on update no action 
            on delete no action,
        constraint machine_interfaces_plain_uk_machine_interface unique nonclustered (machine asc, [interface] asc) with (fillfactor = 90), 
        constraint machine_interfaces_plain_ck_interface check ([interface] like '[a-zA-Z0-9_-]{1,32}') with (fillfactor = 90)
    )

end
go

if object_id(N'dbo.tables_update', N'P') is not null drop procedure dbo.tables_update
go
create procedure dbo.tables_update as begin 

    set nocount on

end
go

if object_id(N'dbo.tables_fill', N'P') is not null drop procedure dbo.tables_fill
go
create procedure dbo.tables_fill as begin 

    set nocount on

end
go

execute dbo.tables_drop
go
execute dbo.tables_create
go
execute dbo.tables_update
go
execute dbo.tables_fill
go

if object_id(N'dbo.hash_big_data', N'FN') is not null drop function dbo.hash_big_data
go
create function dbo.hash_big_data (@value varchar(max)) returns binary(64) as begin 
    return select top 1 convert(binary(64), hashbytes('SHA2_256', convert(nvarchar(max), @value)))
end
go

if object_id(N'dbo.get_procedure', N'P') is not null drop procedure dbo.get_procedure
go
create procedure dbo.get_procedure 
    @database varchar(64), 
    @procedure varchar(64),
    @id integer output
as begin

    declare @database_id integer = (
        select top 1 id from dbo.Databases where 
            date_out is null and 
            [name] = @database
    )

    set nocount on

    if @database_id is null begin
        insert into dbo.Databases([name]) values (@database)
        set @database_id = scope_identity()
    end

    set @id = (
        select top 1 id from dbo.Procedures where 
            date_out is null and 
            [database] = @database_id and 
            [name] = @procedure
    )

    if @id is null begin
        insert into dbo.Procedures([database], [name]) values (@database_id, @procedure)
        set @id = scope_identity()
    end

end
go

if object_id(N'dbo.get_big_data', N'P') is not null drop procedure dbo.get_big_data
go
create procedure dbo.get_big_data 
    @value varchar(max),
    @id integer output
as begin

    declare @hash binary(64) = dbo.hash_big_data(@value)

    set nocount on

    set @id = (
        select top 1 id from dbo.BigData where 
            date_out is null and 
            [hash] = @hash
    )

    if @id is null begin
        insert into dbo.BigData([hash], [value]) values (@hash, @value)
        set @id = scope_identity()
    end

end
go

if object_id(N'dbo.get_message', N'P') is not null drop procedure dbo.get_message
go
create procedure dbo.get_message 
    @message varchar(128),
    @id integer output
as begin

    set nocount on

    set @id = (
        select top 1 id from dbo.Messages where 
            date_out is null and 
            [key] = @message
    )

    if @id is null begin
        insert into dbo.Messages([key]) values (@message)
        set @id = scope_identity()
    end

end
go

if object_id(N'dbo.set_exception', N'P') is not null drop procedure dbo.set_exception
go
create procedure dbo.set_exception 
    @database varchar(64), 
    @procedure varchar(64),
    @message varchar(128), 
    @parameters varchar(max) = null 
as begin 

    declare @procedure_id integer
    declare @message_id integer
    declare @exception_message varchar(max) = error_message()
    declare @exception_message_id integer
    declare @parameters_id integer

    set nocount on

    execute dbo.get_procedure @database, @procedure, @procedure_id output
    execute dbo.get_big_data @exception_message, @exception_message_id output
    execute dbo.get_big_data @parameters, @parameters_id output
    execute dbo.get_message @message, @message_id output

    insert into dbo.Exceptions([procedure], [message], [parameters], exception, [status], code) values
        (@procedure_id, @message_id, @parameters_id, @exception_message_id, error_severity(), error_number())

end
go

if object_id(N'dbo.ProceduresView', N'V') is not null drop view dbo.ProceduresView
go
create view dbo.ProceduresView as select 
    procedures.id, 
    databases.[name] as [database], 
    procedures.[name] as [procedure], 
    procedures.date_in, 
    procedures.date_out
from dbo.Procedures procedures
join dbo.Databases databases on databases.id = procedures.[database]
where 
    procedures.date_out is null and 
    databases.date_out is null
go

if object_id(N'dbo.ExceptionsView', N'V') is not null drop view dbo.ExceptionsView
go
create view dbo.ExceptionsView as select 
    exceptions.id, 
    procedures.[database] as [database], 
    procedures.[procedure] as [procedure], 
    messages.[key] as [message], 
    parameters.[value] as [parameters], 
    exception.[value] as [exception], 
    exceptions.[status], 
    exceptions.code, 
    exceptions.date_in
from dbo.Exceptions exceptions
join dbo.ProceduresView procedures on procedures.id = exceptions.[procedure]
join dbo.Messages messages on messages.id = exceptions.[message]
join dbo.BigData parameters on parameters.id = exceptions.parameters
join dbo.BigData exception on exception.id = exceptions.exception
where 
    exceptions.date_out is null and 
    procedures.date_out is null and 
    messages.date_out is null and 
    parameters.date_out is null and 
    exception.date_out is null
go