Add backticks for mysql 8

This commit is contained in:
Isaac Connor 2019-08-25 12:30:06 -04:00
parent 3e84597900
commit 5f5d5f691a
4 changed files with 170 additions and 176 deletions

View File

@ -95,27 +95,26 @@ sub new {
sub load {
my ( $self, $data ) = @_;
my $type = ref $self;
if ( ! $data ) {
if ( !$data ) {
no strict 'refs';
my $table = ${$type.'::table'};
if ( ! $table ) {
Error( 'NO table for type ' . $type );
Error('No table for type '.$type);
return;
} # end if
my $primary_key = ${$type.'::primary_key'};
if ( ! $primary_key ) {
Error( 'NO primary_key for type ' . $type );
if ( !$primary_key ) {
Error('No primary_key for type '.$type);
return;
} # end if
if ( ! $$self{$primary_key} ) {
my ( $caller, undef, $line ) = caller;
Error( (ref $self) . "::load called without $primary_key from $caller:$line");
Error("$type ::load called without $primary_key from $caller:$line");
} else {
#$log->debug("Object::load Loading from db $type");
Debug("Loading $type from $table WHERE $primary_key = $$self{$primary_key}");
$data = $ZoneMinder::Database::dbh->selectrow_hashref( "SELECT * FROM $table WHERE $primary_key=?", {}, $$self{$primary_key} );
if ( ! $data ) {
$data = $ZoneMinder::Database::dbh->selectrow_hashref("SELECT * FROM `$table` WHERE `$primary_key`=?", {}, $$self{$primary_key});
if ( !$data ) {
if ( $ZoneMinder::Database::dbh->errstr ) {
Error( "Failure to load Object record for $$self{$primary_key}: Reason: " . $ZoneMinder::Database::dbh->errstr );
} else {
@ -137,26 +136,26 @@ sub lock_and_load {
no strict 'refs';
my $table = ${$type.'::table'};
if ( ! $table ) {
Error('NO table for type ' . $type);
Error('NO table for type '.$type);
return;
} # end if
my $primary_key = ${$type.'::primary_key'};
if ( ! $primary_key ) {
Error('NO primary_key for type ' . $type);
if ( !$primary_key ) {
Error('No primary_key for type ' . $type);
return;
} # end if
if ( ! $$self{$primary_key} ) {
if ( !$$self{$primary_key} ) {
my ( $caller, undef, $line ) = caller;
Error("$type ::lock_and_load called without $primary_key from $caller:$line");
return;
}
Debug("Lock and Load $type from $table WHERE $primary_key = $$self{$primary_key}");
my $data = $ZoneMinder::Database::dbh->selectrow_hashref("SELECT * FROM $table WHERE $primary_key=? FOR UPDATE", {}, $$self{$primary_key});
my $data = $ZoneMinder::Database::dbh->selectrow_hashref("SELECT * FROM `$table` WHERE `$primary_key`=? FOR UPDATE", {}, $$self{$primary_key});
if ( ! $data ) {
if ( $ZoneMinder::Database::dbh->errstr ) {
Error("Failure to load Object record for $$self{$primary_key}: Reason: " . $ZoneMinder::Database::dbh->errstr);
Error("Failure to load Object record for $$self{$primary_key}: Reason: ".$ZoneMinder::Database::dbh->errstr);
} else {
Debug("No Results Lock and Loading $type from $table WHERE $primary_key = $$self{$primary_key}");
} # end if
@ -216,12 +215,12 @@ sub save {
$log->debug("No serial") if $debug;
# No serial columns defined, which means that we will do saving by delete/insert instead of insert/update
if ( @identified_by ) {
my $where = join(' AND ', map { $$fields{$_}.'=?' } @identified_by );
my $where = join(' AND ', map { '`'.$$fields{$_}.'`=?' } @identified_by );
if ( $debug ) {
$log->debug("DELETE FROM $table WHERE $where");
$log->debug("DELETE FROM `$table` WHERE $where");
} # end if
if ( ! ( ( $_ = $local_dbh->prepare("DELETE FROM $table WHERE $where") ) and $_->execute( @$self{@identified_by} ) ) ) {
if ( ! ( ( $_ = $local_dbh->prepare("DELETE FROM `$table` WHERE $where") ) and $_->execute( @$self{@identified_by} ) ) ) {
$where =~ s/\?/\%s/g;
$log->error("Error deleting: DELETE FROM $table WHERE " . sprintf($where, map { defined $_ ? $_ : 'undef' } ( @$self{@identified_by}) ).'):' . $local_dbh->errstr);
$local_dbh->rollback();
@ -240,7 +239,7 @@ $log->debug("No serial") if $debug;
next;
}
if ( ! $$self{$id} ) {
my $s = qq{SELECT `auto_increment` FROM INFORMATION_SCHEMA.TABLES WHERE table_name = '$table'};
my $s = qq{SELECT `auto_increment` FROM INFORMATION_SCHEMA.TABLES WHERE `table_name` = '$table'};
($$self{$id}) = ($sql{$$fields{$id}}) = $local_dbh->selectrow_array( $s );
#($$self{$id}) = ($sql{$$fields{$id}}) = $local_dbh->selectrow_array( q{SELECT nextval('} . $serial{$id} . q{')} );
@ -252,7 +251,7 @@ $log->debug("No serial") if $debug;
if ( $insert ) {
my @keys = keys %sql;
my $command = "INSERT INTO $table (" . join(',', @keys ) . ') VALUES (' . join(',', map { '?' } @sql{@keys} ) . ')';
my $command = "INSERT INTO `$table` (" . join(',', @keys ) . ') VALUES (' . join(',', map { '?' } @sql{@keys} ) . ')';
if ( ! ( ( $_ = $local_dbh->prepare($command) ) and $_->execute( @sql{@keys} ) ) ) {
my $error = $local_dbh->errstr;
$command =~ s/\?/\%s/g;
@ -267,7 +266,7 @@ $log->debug("No serial") if $debug;
} # end if
} else {
my @keys = keys %sql;
my $command = "UPDATE $table SET " . join(',', map { $_ . ' = ?' } @keys ) . ' WHERE ' . join(' AND ', map { $_ . ' = ?' } @$fields{@identified_by} );
my $command = "UPDATE `$table` SET " . join(',', map { '`'.$_ . '` = ?' } @keys ) . ' WHERE ' . join(' AND ', map { '`'.$_ . '` = ?' } @$fields{@identified_by} );
if ( ! ( $_ = $local_dbh->prepare($command) and $_->execute( @sql{@keys,@$fields{@identified_by}} ) ) ) {
my $error = $local_dbh->errstr;
$command =~ s/\?/\%s/g;
@ -293,12 +292,12 @@ $log->debug("No serial") if $debug;
if ( $need_serial ) {
if ( $serial ) {
$log->debug("Getting auto_increments");
my $s = qq{SELECT `auto_increment` FROM INFORMATION_SCHEMA.TABLES WHERE table_name = '$table'};
my $s = qq{SELECT `auto_increment` FROM INFORMATION_SCHEMA.TABLES WHERE `table_name` = '$table'};
@$self{@identified_by} = @sql{@$fields{@identified_by}} = $local_dbh->selectrow_array( $s );
#@$self{@identified_by} = @sql{@$fields{@identified_by}} = $local_dbh->selectrow_array( q{SELECT nextval('} . $serial . q{')} );
if ( $local_dbh->errstr() ) {
$log->error("Error getting next id. " . $local_dbh->errstr() );
$log->error("SQL statement execution $s returned ".join(',',@$self{@identified_by}));
$log->error("Error getting next id. " . $local_dbh->errstr() ."\n".
"SQL statement execution $s returned ".join(',',@$self{@identified_by}));
} elsif ( $debug or DEBUG_ALL ) {
$log->debug("SQL statement execution $s returned ".join(',',@$self{@identified_by}));
} # end if
@ -306,7 +305,7 @@ $log->debug("No serial") if $debug;
} # end if
my @keys = keys %sql;
my $command = "INSERT INTO $table (" . join(',', @keys ) . ') VALUES (' . join(',', map { '?' } @sql{@keys} ) . ')';
my $command = "INSERT INTO `$table` (" . join(',', map { '`'.$_.'`' } @keys ) . ') VALUES (' . join(',', map { '?' } @sql{@keys} ) . ')';
if ( ! ( $_ = $local_dbh->prepare($command) and $_->execute( @sql{@keys} ) ) ) {
$command =~ s/\?/\%s/g;
my $error = $local_dbh->errstr;
@ -325,7 +324,7 @@ $log->debug("No serial") if $debug;
my %identified_by = map { $_, $_ } @identified_by;
@keys = map { $identified_by{$_} ? () : $$fields{$_} } @keys;
my $command = "UPDATE $table SET " . join(',', map { $_ . ' = ?' } @keys ) . ' WHERE ' . join(' AND ', map { $$fields{$_} .'= ?' } @identified_by );
my $command = "UPDATE `$table` SET " . join(',', map { '`'.$_ . '` = ?' } @keys ) . ' WHERE ' . join(' AND ', map { '`'.$$fields{$_} .'`= ?' } @identified_by );
if ( ! ( $_ = $local_dbh->prepare($command) and $_->execute( @sql{@keys}, @sql{@$fields{@identified_by}} ) ) ) {
my $error = $local_dbh->errstr;
$command =~ s/\?/\%s/g;

View File

@ -201,12 +201,12 @@ MAIN: while( $loop ) {
my %Monitors;
my $db_monitors;
my $monitorSelectSql = $monitor_id ? 'SELECT * FROM Monitors WHERE Id=?' : 'SELECT * FROM Monitors ORDER BY Id';
my $monitorSelectSql = $monitor_id ? 'SELECT * FROM `Monitors` WHERE `Id`=?' : 'SELECT * FROM `Monitors` ORDER BY `Id`';
my $monitorSelectSth = $dbh->prepare_cached( $monitorSelectSql )
or Fatal( "Can't prepare '$monitorSelectSql': ".$dbh->errstr() );
my $eventSelectSql = 'SELECT Id, (unix_timestamp() - unix_timestamp(StartTime)) AS Age
FROM Events WHERE MonitorId = ?'.(@Storage_Areas ? ' AND StorageId IN ('.join(',',map { '?'} @Storage_Areas).')' : '' ). ' ORDER BY Id';
my $eventSelectSql = 'SELECT `Id`, (unix_timestamp() - unix_timestamp(`StartTime`)) AS Age
FROM `Events` WHERE `MonitorId` = ?'.(@Storage_Areas ? ' AND `StorageId` IN ('.join(',',map { '?'} @Storage_Areas).')' : '' ). ' ORDER BY `Id`';
my $eventSelectSth = $dbh->prepare_cached( $eventSelectSql )
or Fatal( "Can't prepare '$eventSelectSql': ".$dbh->errstr() );
@ -373,8 +373,7 @@ MAIN: while( $loop ) {
}
aud_print("Deleting event directories with no event id information at $day_dir/$event_dir");
if ( confirm() ) {
my $command = "rm -rf $event_dir";
executeShellCommand( $command );
executeShellCommand("rm -rf $event_dir");
$cleaned = 1;
}
} # end if able to find id
@ -476,11 +475,10 @@ MAIN: while( $loop ) {
} # end if ! in db events
} # end foreach fs event
} else {
aud_print( "Filesystem monitor '$monitor_id' in $$Storage{Path} does not exist in database" );
aud_print("Filesystem monitor '$monitor_id' in $$Storage{Path} does not exist in database");
if ( confirm() ) {
my $command = "rm -rf $monitor_id";
executeShellCommand( $command );
executeShellCommand("rm -rf $monitor_id");
$cleaned = 1;
}
}
@ -494,8 +492,7 @@ MAIN: while( $loop ) {
aud_print("Filesystem monitor link '$link' does not point to valid monitor directory");
if ( confirm() ) {
( $link ) = ( $link =~ /^(.*)$/ ); # De-taint
my $command = qq`rm "$link"`;
executeShellCommand($command);
executeShellCommand(qq`rm "$link"`);
$cleaned = 1;
}
} # end foreach monitor link
@ -508,17 +505,17 @@ MAIN: while( $loop ) {
$cleaned = 0;
my $deleteMonitorSql = 'DELETE LOW_PRIORITY FROM Monitors WHERE Id = ?';
my $deleteMonitorSth = $dbh->prepare_cached( $deleteMonitorSql )
or Fatal( "Can't prepare '$deleteMonitorSql': ".$dbh->errstr() );
my $deleteMonitorSth = $dbh->prepare_cached($deleteMonitorSql)
or Fatal("Can't prepare '$deleteMonitorSql': ".$dbh->errstr());
my $deleteEventSql = 'DELETE LOW_PRIORITY FROM Events WHERE Id = ?';
my $deleteEventSth = $dbh->prepare_cached( $deleteEventSql )
or Fatal( "Can't prepare '$deleteEventSql': ".$dbh->errstr() );
or Fatal("Can't prepare '$deleteEventSql': ".$dbh->errstr());
my $deleteFramesSql = 'DELETE LOW_PRIORITY FROM Frames WHERE EventId = ?';
my $deleteFramesSth = $dbh->prepare_cached( $deleteFramesSql )
or Fatal( "Can't prepare '$deleteFramesSql': ".$dbh->errstr() );
or Fatal("Can't prepare '$deleteFramesSql': ".$dbh->errstr());
my $deleteStatsSql = 'DELETE LOW_PRIORITY FROM Stats WHERE EventId = ?';
my $deleteStatsSth = $dbh->prepare_cached( $deleteStatsSql )
or Fatal( "Can't prepare '$deleteStatsSql': ".$dbh->errstr() );
or Fatal("Can't prepare '$deleteStatsSql': ".$dbh->errstr());
# Foreach database monitor and it's list of events.
while ( my ( $db_monitor, $db_events ) = each(%$db_monitors) ) {
@ -631,21 +628,21 @@ if ( $level > 1 ) {
# Shouldn't be possible anymore with FOREIGN KEYS in place
$cleaned = 0;
Debug("Checking for Orphaned Events");
my $selectOrphanedEventsSql = 'SELECT Events.Id, Events.Name
FROM Events LEFT JOIN Monitors ON (Events.MonitorId = Monitors.Id)
WHERE isnull(Monitors.Id)';
my $selectOrphanedEventsSql = 'SELECT `Events`.`Id`, `Events`.`Name`
FROM `Events` LEFT JOIN `Monitors` ON (`Events`.`MonitorId` = `Monitors`.`Id`)
WHERE isnull(`Monitors`.`Id`)';
my $selectOrphanedEventsSth = $dbh->prepare_cached( $selectOrphanedEventsSql )
or Error( "Can't prepare '$selectOrphanedEventsSql': ".$dbh->errstr() );
or Error("Can't prepare '$selectOrphanedEventsSql': ".$dbh->errstr());
$res = $selectOrphanedEventsSth->execute()
or Error( "Can't execute: ".$selectOrphanedEventsSth->errstr() );
or Error("Can't execute: ".$selectOrphanedEventsSth->errstr());
while( my $event = $selectOrphanedEventsSth->fetchrow_hashref() ) {
aud_print( "Found orphaned event with no monitor '$event->{Id}'" );
aud_print("Found orphaned event with no monitor '$event->{Id}'");
if ( confirm() ) {
if ( $res = $deleteEventSth->execute( $event->{Id} ) ) {
if ( $res = $deleteEventSth->execute($event->{Id}) ) {
$cleaned = 1;
} else {
Error( "Can't execute: ".$deleteEventSth->errstr() );
Error("Can't execute: ".$deleteEventSth->errstr());
}
}
}
@ -655,42 +652,42 @@ if ( $level > 1 ) {
# Remove empty events (with no frames)
$cleaned = 0;
Debug("Checking for Events with no Frames");
my $selectEmptyEventsSql = 'SELECT E.Id AS Id, E.StartTime, F.EventId FROM Events as E LEFT JOIN Frames as F ON (E.Id = F.EventId)
WHERE isnull(F.EventId) AND now() - interval '.$Config{ZM_AUDIT_MIN_AGE}.' second > E.StartTime';
my $selectEmptyEventsSql = 'SELECT `E`.`Id` AS `Id`, `E`.`StartTime`, `F`.`EventId` FROM `Events` AS E LEFT JOIN `Frames` AS F ON (`E`.`Id` = `F`.`EventId`)
WHERE isnull(`F`.`EventId`) AND now() - interval '.$Config{ZM_AUDIT_MIN_AGE}.' second > `E`.`StartTime`';
if ( my $selectEmptyEventsSth = $dbh->prepare_cached( $selectEmptyEventsSql ) ) {
if ( $res = $selectEmptyEventsSth->execute() ) {
while( my $event = $selectEmptyEventsSth->fetchrow_hashref() ) {
aud_print( "Found empty event with no frame records '$event->{Id}' at $$event{StartTime}" );
aud_print("Found empty event with no frame records '$event->{Id}' at $$event{StartTime}");
if ( confirm() ) {
if ( $res = $deleteEventSth->execute( $event->{Id} ) ) {
if ( $res = $deleteEventSth->execute($event->{Id}) ) {
$cleaned = 1;
} else {
Error( "Can't execute: ".$deleteEventSth->errstr() );
Error("Can't execute: ".$deleteEventSth->errstr());
}
}
} # end foreach row
} else {
Error( "Can't execute: ".$selectEmptyEventsSth->errstr() );
Error("Can't execute: ".$selectEmptyEventsSth->errstr());
}
} else {
Error( "Can't prepare '$selectEmptyEventsSql': ".$dbh->errstr() );
Error("Can't prepare '$selectEmptyEventsSql': ".$dbh->errstr());
}
redo MAIN if $cleaned;
# Remove orphaned frame records
$cleaned = 0;
Debug("Checking for Orphaned Frames");
my $selectOrphanedFramesSql = 'SELECT DISTINCT EventId FROM Frames
WHERE (SELECT COUNT(*) FROM Events WHERE Events.Id=EventId)=0';
Debug('Checking for Orphaned Frames');
my $selectOrphanedFramesSql = 'SELECT DISTINCT `EventId` FROM `Frames`
WHERE (SELECT COUNT(*) FROM `Events` WHERE `Events`.`Id`=`EventId`)=0';
my $selectOrphanedFramesSth = $dbh->prepare_cached( $selectOrphanedFramesSql )
or Fatal( "Can't prepare '$selectOrphanedFramesSql': ".$dbh->errstr() );
or Fatal("Can't prepare '$selectOrphanedFramesSql': ".$dbh->errstr());
$res = $selectOrphanedFramesSth->execute()
or Fatal( "Can't execute: ".$selectOrphanedFramesSth->errstr() );
or Fatal("Can't execute: ".$selectOrphanedFramesSth->errstr());
while( my $frame = $selectOrphanedFramesSth->fetchrow_hashref() ) {
aud_print( "Found orphaned frame records for event '$frame->{EventId}'" );
aud_print("Found orphaned frame records for event '$frame->{EventId}'");
if ( confirm() ) {
$res = $deleteFramesSth->execute( $frame->{EventId} )
or Fatal( "Can't execute: ".$deleteFramesSth->errstr() );
$res = $deleteFramesSth->execute($frame->{EventId})
or Fatal("Can't execute: ".$deleteFramesSth->errstr());
$cleaned = 1;
}
}
@ -699,18 +696,18 @@ if ( $level > 1 ) {
if ( $level > 1 ) {
# Remove orphaned stats records
$cleaned = 0;
Debug("Checking for Orphaned Stats");
my $selectOrphanedStatsSql = 'SELECT DISTINCT EventId FROM Stats
WHERE EventId NOT IN (SELECT Id FROM Events)';
Debug('Checking for Orphaned Stats');
my $selectOrphanedStatsSql = 'SELECT DISTINCT `EventId` FROM `Stats`
WHERE `EventId` NOT IN (SELECT `Id` FROM `Events`)';
my $selectOrphanedStatsSth = $dbh->prepare_cached( $selectOrphanedStatsSql )
or Fatal( "Can't prepare '$selectOrphanedStatsSql': ".$dbh->errstr() );
or Fatal("Can't prepare '$selectOrphanedStatsSql': ".$dbh->errstr());
$res = $selectOrphanedStatsSth->execute()
or Fatal( "Can't execute: ".$selectOrphanedStatsSth->errstr() );
or Fatal("Can't execute: ".$selectOrphanedStatsSth->errstr());
while( my $stat = $selectOrphanedStatsSth->fetchrow_hashref() ) {
aud_print( "Found orphaned statistic records for event '$stat->{EventId}'" );
aud_print("Found orphaned statistic records for event '$stat->{EventId}'");
if ( confirm() ) {
$res = $deleteStatsSth->execute( $stat->{EventId} )
or Fatal( "Can't execute: ".$deleteStatsSth->errstr() );
or Fatal("Can't execute: ".$deleteStatsSth->errstr());
$cleaned = 1;
}
}
@ -732,44 +729,44 @@ if ( $level > 1 ) {
#WHERE isnull(E.Frames) or isnull(E.EndTime)
#GROUP BY E.Id HAVING EndTime < (now() - interval ".$Config{ZM_AUDIT_MIN_AGE}.' second)'
#;
'SELECT *, unix_timestamp(StartTime) AS TimeStamp FROM Events WHERE EndTime IS NULL AND StartTime < (now() - interval '.$Config{ZM_AUDIT_MIN_AGE}.' second)';
'SELECT *, unix_timestamp(`StartTime`) AS `TimeStamp` FROM `Events` WHERE `EndTime` IS NULL AND `StartTime` < (now() - interval '.$Config{ZM_AUDIT_MIN_AGE}.' second)';
my $selectFrameDataSql = '
SELECT
max(TimeStamp) as EndTime,
unix_timestamp(max(TimeStamp)) AS EndTimeStamp,
max(FrameId) as Frames,
count(if(Score>0,1,NULL)) as AlarmFrames,
sum(Score) as TotScore,
max(Score) as MaxScore
FROM Frames WHERE EventId=?';
max(`TimeStamp`) AS `EndTime`,
unix_timestamp(max(`TimeStamp`)) AS `EndTimeStamp`,
max(`FrameId`) AS `Frames`,
count(if(`Score`>0,1,NULL)) AS `AlarmFrames`,
sum(`Score`) AS `TotScore`,
max(`Score`) AS `MaxScore`
FROM `Frames` WHERE `EventId`=?';
my $selectFrameDataSth = $dbh->prepare_cached($selectFrameDataSql)
or Fatal( "Can't prepare '$selectFrameDataSql': ".$dbh->errstr() );
my $selectUnclosedEventsSth = $dbh->prepare_cached( $selectUnclosedEventsSql )
or Fatal( "Can't prepare '$selectUnclosedEventsSql': ".$dbh->errstr() );
or Fatal("Can't prepare '$selectUnclosedEventsSql': ".$dbh->errstr());
my $updateUnclosedEventsSql =
"UPDATE low_priority Events
SET Name = ?,
EndTime = ?,
Length = ?,
Frames = ?,
AlarmFrames = ?,
TotScore = ?,
AvgScore = ?,
MaxScore = ?,
Notes = concat_ws( ' ', Notes, ? )
WHERE Id = ?"
"UPDATE low_priority `Events`
SET `Name` = ?,
`EndTime` = ?,
`Length` = ?,
`Frames` = ?,
`AlarmFrames` = ?,
`TotScore` = ?,
`AvgScore` = ?,
`MaxScore` = ?,
`Notes` = concat_ws( ' ', `Notes`, ? )
WHERE `Id` = ?"
;
my $updateUnclosedEventsSth = $dbh->prepare_cached( $updateUnclosedEventsSql )
or Fatal( "Can't prepare '$updateUnclosedEventsSql': ".$dbh->errstr() );
or Fatal("Can't prepare '$updateUnclosedEventsSql': ".$dbh->errstr());
$res = $selectUnclosedEventsSth->execute()
or Fatal( "Can't execute: ".$selectUnclosedEventsSth->errstr() );
or Fatal("Can't execute: ".$selectUnclosedEventsSth->errstr());
while( my $event = $selectUnclosedEventsSth->fetchrow_hashref() ) {
aud_print( "Found open event '$event->{Id}' on Monitor $event->{MonitorId} at $$event{StartTime}" );
if ( confirm( 'close', 'closing' ) ) {
aud_print("Found open event '$event->{Id}' on Monitor $event->{MonitorId} at $$event{StartTime}");
if ( confirm('close', 'closing') ) {
if ( ! ( $res = $selectFrameDataSth->execute($event->{Id}) ) ) {
Error( "Can't execute: $selectFrameDataSql:".$selectFrameDataSth->errstr() );
Error("Can't execute: $selectFrameDataSql:".$selectFrameDataSth->errstr());
next;
}
my $frame = $selectFrameDataSth->fetchrow_hashref();
@ -802,7 +799,7 @@ FROM Frames WHERE EventId=?';
# Now delete any old image files
if ( my @old_files = grep { -M > $max_image_age } <$image_path/*.{jpg,gif,wbmp}> ) {
aud_print( 'Deleting '.int(@old_files)." old images\n" );
aud_print('Deleting '.int(@old_files)." old images\n");
my $untainted_old_files = join( ';', @old_files );
( $untainted_old_files ) = ( $untainted_old_files =~ /^(.*)$/ );
unlink( split( /;/, $untainted_old_files ) );
@ -816,21 +813,21 @@ FROM Frames WHERE EventId=?';
if ( $Config{ZM_LOG_DATABASE_LIMIT} ) {
if ( $Config{ZM_LOG_DATABASE_LIMIT} =~ /^\d+$/ ) {
# Number of rows
my $selectLogRowCountSql = 'SELECT count(*) AS Rows FROM Logs';
my $selectLogRowCountSql = 'SELECT count(*) AS `Rows` FROM `Logs`';
my $selectLogRowCountSth = $dbh->prepare_cached( $selectLogRowCountSql )
or Fatal( "Can't prepare '$selectLogRowCountSql': ".$dbh->errstr() );
or Fatal("Can't prepare '$selectLogRowCountSql': ".$dbh->errstr());
$res = $selectLogRowCountSth->execute()
or Fatal( "Can't execute: ".$selectLogRowCountSth->errstr() );
or Fatal("Can't execute: ".$selectLogRowCountSth->errstr());
my $row = $selectLogRowCountSth->fetchrow_hashref();
my $logRows = $row->{Rows};
if ( $logRows > $Config{ZM_LOG_DATABASE_LIMIT} ) {
my $deleteLogByRowsSql = 'DELETE low_priority FROM Logs ORDER BY TimeKey ASC LIMIT ?';
my $deleteLogByRowsSql = 'DELETE low_priority FROM `Logs` ORDER BY `TimeKey` ASC LIMIT ?';
my $deleteLogByRowsSth = $dbh->prepare_cached( $deleteLogByRowsSql )
or Fatal( "Can't prepare '$deleteLogByRowsSql': ".$dbh->errstr() );
or Fatal("Can't prepare '$deleteLogByRowsSql': ".$dbh->errstr());
$res = $deleteLogByRowsSth->execute( $logRows - $Config{ZM_LOG_DATABASE_LIMIT} )
or Fatal( "Can't execute: ".$deleteLogByRowsSth->errstr() );
or Fatal("Can't execute: ".$deleteLogByRowsSth->errstr());
if ( $deleteLogByRowsSth->rows() ) {
aud_print( 'Deleted '.$deleteLogByRowsSth->rows() ." log table entries by count\n" );
aud_print('Deleted '.$deleteLogByRowsSth->rows() ." log table entries by count\n");
}
}
} else {
@ -843,67 +840,67 @@ FROM Frames WHERE EventId=?';
my $deleted_rows;
do {
my $deleteLogByTimeSql =
'DELETE FROM Logs
WHERE TimeKey < unix_timestamp(now() - interval '.$Config{ZM_LOG_DATABASE_LIMIT}.') LIMIT 10';
'DELETE FROM `Logs`
WHERE `TimeKey` < unix_timestamp(now() - interval '.$Config{ZM_LOG_DATABASE_LIMIT}.') LIMIT 10';
my $deleteLogByTimeSth = $dbh->prepare_cached( $deleteLogByTimeSql )
or Fatal( "Can't prepare '$deleteLogByTimeSql': ".$dbh->errstr() );
or Fatal("Can't prepare '$deleteLogByTimeSql': ".$dbh->errstr());
$res = $deleteLogByTimeSth->execute()
or Fatal( "Can't execute: ".$deleteLogByTimeSth->errstr() );
or Fatal("Can't execute: ".$deleteLogByTimeSth->errstr());
$deleted_rows = $deleteLogByTimeSth->rows();
aud_print( "Deleted $deleted_rows log table entries by time\n" );
aud_print("Deleted $deleted_rows log table entries by time\n");
} while ( $deleted_rows );
}
} # end if ZM_LOG_DATABASE_LIMIT
$loop = $continuous;
my $eventcounts_sql = q`
UPDATE Monitors SET
TotalEvents=(SELECT COUNT(Id) FROM Events WHERE MonitorId=Monitors.Id),
TotalEventDiskSpace=(SELECT SUM(DiskSpace) FROM Events WHERE MonitorId=Monitors.Id AND DiskSpace IS NOT NULL),
ArchivedEvents=(SELECT COUNT(Id) FROM Events WHERE MonitorId=Monitors.Id AND Archived=1),
ArchivedEventDiskSpace=(SELECT SUM(DiskSpace) FROM Events WHERE MonitorId=Monitors.Id AND Archived=1 AND DiskSpace IS NOT NULL)
`;
my $eventcounts_sql = '
UPDATE `Monitors` SET
`TotalEvents`=(SELECT COUNT(`Id`) FROM `Events` WHERE `MonitorId`=`Monitors.Id`),
`TotalEventDiskSpace`=(SELECT SUM(`DiskSpace`) FROM `Events` WHERE `MonitorId`=`Monitors`.`Id` AND `DiskSpace` IS NOT NULL),
`ArchivedEvents`=(SELECT COUNT(`Id`) FROM `Events` WHERE `MonitorId`=`Monitors`.`Id` AND `Archived`=1),
`ArchivedEventDiskSpace`=(SELECT SUM(`DiskSpace`) FROM `Events` WHERE `MonitorId`=`Monitors`.`Id` AND `Archived`=1 AND `DiskSpace` IS NOT NULL)
';
my $eventcounts_sth = $dbh->prepare_cached( $eventcounts_sql );
$eventcounts_sth->execute();
$eventcounts_sth->finish();
my $eventcounts_hour_sql = q`
UPDATE Monitors INNER JOIN (
SELECT MonitorId, COUNT(*) AS HourEvents, SUM(COALESCE(DiskSpace,0)) AS HourEventDiskSpace
FROM Events_Hour GROUP BY MonitorId
) AS E ON E.MonitorId=Monitors.Id SET
Monitors.HourEvents = E.HourEvents,
Monitors.HourEventDiskSpace = E.HourEventDiskSpace
`;
my $eventcounts_hour_sql = '
UPDATE `Monitors` INNER JOIN (
SELECT `MonitorId`, COUNT(*) AS `HourEvents`, SUM(COALESCE(`DiskSpace`,0)) AS `HourEventDiskSpace`
FROM `Events_Hour` GROUP BY `MonitorId`
) AS `E` ON `E`.`MonitorId`=`Monitors`.`Id` SET
`Monitors`.`HourEvents` = `E`.`HourEvents`,
`Monitors`.`HourEventDiskSpace` = `E`.`HourEventDiskSpace`
';
my $eventcounts_day_sql = q`
UPDATE Monitors INNER JOIN (
SELECT MonitorId, COUNT(*) AS DayEvents, SUM(COALESCE(DiskSpace,0)) AS DayEventDiskSpace
FROM Events_Day GROUP BY MonitorId
) AS E ON E.MonitorId=Monitors.Id SET
Monitors.DayEvents = E.DayEvents,
Monitors.DayEventDiskSpace = E.DayEventDiskSpace
`;
my $eventcounts_day_sql = '
UPDATE `Monitors` INNER JOIN (
SELECT `MonitorId`, COUNT(*) AS `DayEvents`, SUM(COALESCE(`DiskSpace`,0)) AS `DayEventDiskSpace`
FROM `Events_Day` GROUP BY `MonitorId`
) AS `E` ON `E`.`MonitorId`=`Monitors`.`Id` SET
`Monitors`.`DayEvents` = `E`.`DayEvents`,
`Monitors`.`DayEventDiskSpace` = `E`.`DayEventDiskSpace`
';
my $eventcounts_week_sql = q`
UPDATE Monitors INNER JOIN (
SELECT MonitorId, COUNT(*) AS WeekEvents, SUM(COALESCE(DiskSpace,0)) AS WeekEventDiskSpace
FROM Events_Week GROUP BY MonitorId
) AS E ON E.MonitorId=Monitors.Id SET
Monitors.WeekEvents = E.WeekEvents,
Monitors.WeekEventDiskSpace = E.WeekEventDiskSpace
`;
my $eventcounts_week_sql = '
UPDATE `Monitors` INNER JOIN (
SELECT `MonitorId`, COUNT(*) AS `WeekEvents`, SUM(COALESCE(`DiskSpace`,0)) AS `WeekEventDiskSpace`
FROM `Events_Week` GROUP BY `MonitorId`
) AS `E` ON `E`.`MonitorId`=`Monitors`.`Id` SET
`Monitors`.`WeekEvents` = `E`.`WeekEvents`,
`Monitors`.`WeekEventDiskSpace` = `E`.`WeekEventDiskSpace`
';
my $eventcounts_month_sql = q`
UPDATE Monitors INNER JOIN (
SELECT MonitorId, COUNT(*) AS MonthEvents, SUM(COALESCE(DiskSpace,0)) AS MonthEventDiskSpace
FROM Events_Month GROUP BY MonitorId
) AS E ON E.MonitorId=Monitors.Id SET
Monitors.MonthEvents = E.MonthEvents,
Monitors.MonthEventDiskSpace = E.MonthEventDiskSpace
`;
my $eventcounts_month_sql = '
UPDATE `Monitors` INNER JOIN (
SELECT `MonitorId`, COUNT(*) AS `MonthEvents`, SUM(COALESCE(`DiskSpace`,0)) AS `MonthEventDiskSpace`
FROM `Events_Month` GROUP BY `MonitorId`
) AS `E` ON `E`.`MonitorId`=`Monitors`.`Id` SET
`Monitors`.`MonthEvents` = `E`.`MonthEvents`,
`Monitors`.`MonthEventDiskSpace` = `E`.`MonthEventDiskSpace`
';
my $eventcounts_hour_sth = $dbh->prepare_cached($eventcounts_hour_sql);
my $eventcounts_day_sth = $dbh->prepare_cached($eventcounts_day_sql);
my $eventcounts_week_sth = $dbh->prepare_cached($eventcounts_week_sql);

View File

@ -221,27 +221,27 @@ sub getFilters {
my @sql_values;
my @filters;
my $sql = 'SELECT * FROM Filters WHERE';
my $sql = 'SELECT * FROM `Filters` WHERE';
if ( $$sql_filters{Name} ) {
$sql .= ' Name = ? AND';
$sql .= ' `Name` = ? AND';
push @sql_values, $$sql_filters{Name};
} elsif ( $$sql_filters{Id} ) {
$sql .= ' Id = ? AND';
$sql .= ' `Id` = ? AND';
push @sql_values, $$sql_filters{Id};
} else {
$sql .= ' Background = 1 AND';
$sql .= ' `Background` = 1 AND';
}
$sql .= '( AutoArchive = 1
or AutoVideo = 1
or AutoUpload = 1
or AutoEmail = 1
or AutoMessage = 1
or AutoExecute = 1
or AutoDelete = 1
or UpdateDiskSpace = 1
or AutoMove = 1
or AutoCopy = 1
) ORDER BY Name';
$sql .= '( `AutoArchive` = 1
or `AutoVideo` = 1
or `AutoUpload` = 1
or `AutoEmail` = 1
or `AutoMessage` = 1
or `AutoExecute` = 1
or `AutoDelete` = 1
or `UpdateDiskSpace` = 1
or `AutoMove` = 1
or `AutoCopy` = 1
) ORDER BY `Name`';
my $sth = $dbh->prepare_cached($sql)
or Fatal("Unable to prepare '$sql': ".$dbh->errstr());
my $res = $sth->execute(@sql_values)
@ -301,7 +301,7 @@ sub checkFilter {
if ( $filter->{AutoArchive} ) {
Info("Archiving event $Event->{Id}");
# Do it individually to avoid locking up the table for new events
my $sql = 'UPDATE Events SET Archived = 1 WHERE Id = ?';
my $sql = 'UPDATE `Events` SET `Archived` = 1 WHERE `Id` = ?';
my $sth = $dbh->prepare_cached($sql)
or Fatal("Unable to prepare '$sql': ".$dbh->errstr());
my $res = $sth->execute($Event->{Id})
@ -434,7 +434,7 @@ sub generateVideo {
}
return 0;
} else {
my $sql = 'UPDATE Events SET Videoed = 1 WHERE Id = ?';
my $sql = 'UPDATE `Events` SET `Videoed` = 1 WHERE `Id` = ?';
my $sth = $dbh->prepare_cached($sql)
or Fatal("Unable to prepare '$sql': ".$dbh->errstr());
my $res = $sth->execute($Event->{Id})
@ -619,7 +619,7 @@ sub uploadArchFile {
or Error("SFTP - Unable to upload '$archLocPath': ".$sftp->error);
}
unlink($archLocPath);
my $sql = 'UPDATE Events SET Uploaded = 1 WHERE Id = ?';
my $sql = 'UPDATE `Events` SET `Uploaded` = 1 WHERE `Id` = ?';
my $sth = $dbh->prepare_cached($sql)
or Fatal("Unable to prepare '$sql': ".$dbh->errstr());
my $res = $sth->execute($Event->{Id})
@ -647,12 +647,10 @@ sub substituteTags {
my $max_alarm_frame;
my $max_alarm_score = 0;
if ( $need_images ) {
my $sql = q`SELECT * FROM Frames
WHERE EventId = ? AND Type = 'Alarm'
ORDER BY FrameId`;
my $sql = 'SELECT * FROM `Frames` WHERE `EventId`=? AND `Type`=? ORDER BY `FrameId`';
my $sth = $dbh->prepare_cached($sql)
or Fatal("Unable to prepare '$sql': ".$dbh->errstr());
my $res = $sth->execute($Event->{Id})
my $res = $sth->execute($Event->{Id},'Alarm')
or Fatal("Unable to execute '$sql': ".$dbh->errstr());
my $rows = 0;
while( my $frame = $sth->fetchrow_hashref() ) {
@ -879,7 +877,7 @@ sub sendEmail {
} else {
Info('Notification email sent');
}
my $sql = 'UPDATE Events SET Emailed = 1 WHERE Id = ?';
my $sql = 'UPDATE `Events` SET `Emailed` = 1 WHERE `Id` = ?';
my $sth = $dbh->prepare_cached($sql)
or Fatal("Unable to prepare '$sql': ".$dbh->errstr());
my $res = $sth->execute($Event->{Id})
@ -984,7 +982,7 @@ sub sendMessage {
} else {
Info('Notification message sent');
}
my $sql = 'UPDATE Events SET Messaged = 1 WHERE Id = ?';
my $sql = 'UPDATE `Events` SET `Messaged` = 1 WHERE `Id` = ?';
my $sth = $dbh->prepare_cached($sql)
or Fatal("Unable to prepare '$sql': ".$dbh->errstr());
my $res = $sth->execute($Event->{Id})
@ -1014,7 +1012,7 @@ sub executeCommand {
Error("Command '$command' exited with status: $status");
return 0;
} else {
my $sql = 'UPDATE Events SET Executed = 1 WHERE Id = ?';
my $sql = 'UPDATE `Events` SET `Executed` = 1 WHERE `Id` = ?';
my $sth = $dbh->prepare_cached($sql)
or Fatal("Unable to prepare '$sql': ".$dbh->errstr());
my $res = $sth->execute( $Event->{Id} )

View File

@ -301,7 +301,7 @@ if ( $migrateEvents ) {
$sth->finish();
print( "Updating configuration.\n" );
$sql = "update Config set Value = ? where Name = 'ZM_USE_DEEP_STORAGE'";
$sql = "UPDATE `Config` SET `Value` = ? WHERE `Name` = 'ZM_USE_DEEP_STORAGE'";
$sth = $dbh->prepare_cached( $sql ) or die( "Can't prepare '$sql': ".$dbh->errstr() );
$res = $sth->execute( 1 ) or die( "Can't execute: ".$sth->errstr() );
$sth->finish();
@ -323,7 +323,7 @@ if ( $freshen ) {
if ( $interactive ) {
# Now check for MyISAM Tables
my @MyISAM_Tables;
my $sql = "SELECT table_name FROM INFORMATION_SCHEMA.TABLES WHERE table_schema='zm' AND engine = 'MyISAM'";
my $sql = "SELECT `table_name` FROM INFORMATION_SCHEMA.TABLES WHERE `table_schema`='zm' AND `engine` = 'MyISAM'";
my $sth = $dbh->prepare_cached( $sql ) or die( "Can't prepare '$sql': ".$dbh->errstr() );
my $res = $sth->execute() or die( "Can't execute: ".$sth->errstr() );
@ -341,7 +341,7 @@ if ( $interactive ) {
$dbh->do(q|SET sql_mode='traditional'|); # Elevate warnings to errors
print "\nConverting MyISAM tables to InnoDB. Please wait.\n";
foreach (@MyISAM_Tables) {
my $sql = "ALTER TABLE $_ ENGINE = InnoDB";
my $sql = "ALTER TABLE `$_` ENGINE = InnoDB";
my $sth = $dbh->prepare_cached( $sql ) or die( "Can't prepare '$sql': ".$dbh->errstr() );
my $res = $sth->execute() or die( "Can't execute: ".$sth->errstr() );
$sth->finish();
@ -447,7 +447,7 @@ if ( $version ) {
# Rename the event directories and create a new symlink for the names
chdir( EVENT_PATH );
my $sql = "select * from Monitors order by Id";
my $sql = "SELECT * FROM `Monitors` ORDER BY `Id`";
my $sth = $dbh->prepare_cached( $sql ) or die( "Can't prepare '$sql': ".$dbh->errstr() );
my $res = $sth->execute() or die( "Can't execute: ".$sth->errstr() );
while( my $monitor = $sth->fetchrow_hashref() ) {