summaryrefslogtreecommitdiff
path: root/lib/mysql.php
blob: c6d7fdf03baed59e736d3354b659bd5623ed0dc9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
<?php

# do not include twice
if (isset($mysql))
  return;

include_once BASE . "/lib/http.php";
include_once BASE . "/lib/mysql-joins.php";

$mysql = new mysqli("localhost", "webserver", "empty", "buildmaster");
if ( $mysql -> connect_error ) {
  die_500( "Connection failed: " . $mysql -> connect_error );
}

function print_important_trace_components($call) {
  return substr($call['file'], strlen(BASE)+1) . '(' . $call['line'] . ')';
}

function mysql_log_duration_and_trace($start) {
  $start = round((microtime(true) - $start) * 1000000);
  $trace = debug_backtrace();
  array_shift($trace);
  // silently fail if logfile is unavailable
  if (($fp = fopen(BASE . '/log', 'a')) !== false) {
    flock($fp, LOCK_EX);
    fwrite($fp,
      date('Y-m-d H:i:s') . " " .
      $start . " " .
      implode(' ', array_map('print_important_trace_components', $trace)) . " - " .
      $trace[0]['args'][0] . "\n"
    );
    flock($fp, LOCK_UN);
    fclose($fp);
  }
}

function mysql_run_query($query) {
  global $mysql;
  $start = microtime(true);
  if ( ! $result = $mysql -> query($query) )
    die_500( "Query failed: " .  $mysql -> error );
  mysql_log_duration_and_trace($start);
  return $result;
}

function mysql_prepare_query($query) {
  global $mysql;
  $start = microtime(true);
  if ( ! $result = $mysql -> prepare($query) )
    die_500( "Prepare failed: " . $mysql -> error );
  mysql_log_duration_and_trace($start);
  return $result;
}

function show_warning_on_offline_slave() {
  $result = mysql_run_query("SHOW STATUS LIKE \"Slave_running\"");
  if (($result -> num_rows == 0) ||
    ($result -> fetch_assoc() ["Value"] != "ON")) {
    print "<div><font color=\"ff0000\">The replication slave is currently not running. The database might be outdated.</font></div>\n";
  }
}

function mysql_url_encode($input) {
  return
    "REPLACE(" . $input . ",\"+\",\"%2B\")";
}

function mysql_query_package_version($table) {
  return
    "CONCAT(" .
      "IF(" .
        "`" .$table . "`.`epoch`=\"0\"," .
        "\"\"," .
        "CONCAT(" .
          "`" . $table . "`.`epoch`," .
          "\":\"" .
        ")" .
      ")," .
      "`" . $table . "`.`pkgver`,\"-\"," .
      "`" . $table . "`.`pkgrel`," .
      "IF(`" . $table . "`.`sub_pkgrel_omitted`," .
        "\"\"," .
        "CONCAT(" .
          "\".\"," .
          "`" . $table . "`.`sub_pkgrel`" .
        ")" .
      ")" .
    ")";
}