/inc/sql.inc.php (93f801589bf6cf0dde6655647ecb3cfc29558d13) (9577 bytes) (mode 100644) (type blob)

<?php
require_once(__DIR__ . '/log.inc.php');
require_once(__DIR__ . '/prof.inc.php');


$_sql_add = @file_get_contents('/home/rocketgit/sql_add');
if ($_sql_add !== FALSE)
	$rg_sql .= ' ' . trim($_sql_add);


// Some constants for sql error codes
define('RG_SQL_UNIQUE_VIOLATION', '23505');
define('RG_SQL_UNDEFINED_TABLE', '42P01');

if (!function_exists("pg_connect"))
	die("FATAL: php PostgreSQL is not installed!");

if (!isset($rg_sql_debug))
	$rg_sql_debug = 0;

$rg_sql_conn = array();

$rg_sql_error = "";


/*
 * Set error string
 */
function rg_sql_set_error($str)
{
	global $rg_sql_error;
	$rg_sql_error = $str;
	rg_log('sql_set_error: ' . $str);
}

function rg_sql_error()
{
	global $rg_sql_error;
	return $rg_sql_error;
}

/*
 * Set application name to be able to identify the scripts
 */
$rg_sql_app = "rg-unk";
function rg_sql_app($name)
{
	global $rg_sql_app;

	$rg_sql_app = $name;
}

/*
 * Connect to database
 */
function rg_sql_open_nodelay($h)
{
	global $rg_sql_debug;
	global $rg_sql_conn;

	if ($rg_sql_debug > 20)
		rg_log_enter('sql_open_nodelay');

	$ret = FALSE;
	while (1) {
		if (!isset($rg_sql_conn[$h])) {
			rg_internal_error('Handler [' . $h . '] not present!');
			break;
		}

		if ($rg_sql_debug > 40) {
			rg_log('My pid: ' . getmypid());
			rg_log_debug('rg_sql_conn: ' . print_r($rg_sql_conn, TRUE));
		}

		if (isset($rg_sql_conn[$h]['db'])) {
			if (getmypid() == $rg_sql_conn[$h]['pid']) {
				if ($rg_sql_debug > 30)
					rg_log('DB: Same pid, reuse connection');
				$ret = $rg_sql_conn[$h]['db'];
				break;
			}

			if ($rg_sql_debug > 25)
				rg_log('DB: pid is different, reconnecting...');
			unset($rg_sql_conn[$h]['db']);
		}

		putenv('PGAPPNAME=' . $rg_sql_conn[$h]['app']);

		$str = $rg_sql_conn[$h]['str'];
		if ($rg_sql_debug > 0)
			rg_log("DB: openning [$str]...");

		rg_prof_set(array('db_conn' => 1));

		// This is used to test if we forked
		$rg_sql_conn[$h]['pid'] = getmypid();

		$_s = microtime(TRUE);

		$tries = 0;
		while (1) {
			$db = @pg_pconnect($str);
			if ($db !== FALSE) {
				// reconnect if needed
				$x = @pg_ping($db);
				if ($x === TRUE)
					break;
			}

			if ($tries == 0)
				rg_log('Cannot connect to db. Keep trying...');

			$tries++;
			if ($tries > 30) {
				$db = FALSE;
				break;
			}
			sleep(1);
		}
		$diff = intval((microtime(TRUE) - $_s) * 1000);
		rg_prof_set(array('db_c_ms' => $diff));
		if ($db === FALSE) {
			$err = 'cannot connect to database';
			rg_sql_set_error($err);
			rg_internal_error($err);
			rg_prof_set(array('db_conn_errors' => 1));
			break;
		}

		$rg_sql_conn[$h]['db'] = $db;
		$ret = $db;
		break;
	}

	if ($rg_sql_debug > 20)
		rg_log_exit();
	return $ret;
}

/*
 * Prepare to connect to database (delayed connection).
 * Returns a special handler.
 */
function rg_sql_open($str)
{
	global $rg_sql_conn;
	global $rg_sql_app;

	$free_index = count($rg_sql_conn);
	$rg_sql_conn[$free_index] = array(
		'str' => $str,
		'app' => $rg_sql_app
	);

	//rg_log("Delay connection to [$str], index $free_index.");
	return $free_index;
}

/*
 * Escaping [obsolete - do not use]
 */
function rg_sql_escape($h, $str)
{
	$db = rg_sql_open_nodelay($h);
	if ($db === FALSE)
		return FALSE;

	return pg_escape_string($db, $str);
}

/*
 * Returns the last error codes
 */
function rg_sql_last_error_code($res)
{
	return @pg_result_error_field($res, PGSQL_DIAG_SQLSTATE);
}

/*
 * Helper for sql_query and sql_query_params
 */
function rg_sql_query0($db, $sql, $r, $start_ts, $ignore, &$ignore_kicked)
{
	global $rg_sql_debug;

	$ignore_kicked = FALSE;
	while (1) {
		if ($r !== TRUE) {
			$err = "$sql: send: " . @pg_last_error($db);
			$res = FALSE;
			break;
		}

		$res = @pg_get_result($db);
		if ($res === FALSE) {
			$err = $sql . ': get: no pending query';
			break;
		}

		$state = rg_sql_last_error_code($res);
		if ($state === FALSE) {
			$err = $sql . ': pg_result_error_field error';
			break;
		}
		if (($state !== NULL) && (strcmp($state, '00000') !== 0)) {
			if ($rg_sql_debug > 0)
				rg_log('DB: error_code=' . $state);

			foreach ($ignore as $code) {
				if (strcmp($code, $state) == 0) {
					$ignore_kicked = TRUE;
					break;
				}
			}

			if ($ignore_kicked)
				if ($rg_sql_debug > 50)
					rg_log('DB: We should ignore the error!');

			$err = $sql . ': ' . @pg_last_error($db) . ' (' . $state . ')';
			@pg_free_result($res);
			$res = FALSE;
			break;
		}

		$diff = sprintf("%u", (microtime(TRUE) - $start_ts) * 1000);
		$rows = rg_sql_num_rows($res);
		$arows = rg_sql_affected_rows($res);

		if ($rg_sql_debug > 0)
			rg_log("DB: Took " . $diff . "ms, $rows row(s), $arows affected");

		rg_prof_set(array("q" => 1,
			"rows" => $rows,
			"arows" => $arows,
			"q_ms" => $diff));
		break;
	}

	if ($res === FALSE) {
		rg_sql_set_error($err);
		if (!$ignore_kicked) {
			rg_internal_error($err);
			rg_prof_set(array('qerrors' => 1));
		}
		// reconnect if needed
		@pg_ping($db);
	}

	return $res;

}

/*
 * Do a query
 */
function rg_sql_query($h, $sql)
{
	global $rg_sql_debug;

	if ($rg_sql_debug > 0)
		rg_log_enter("sql_query: sql=$sql");

	$ret = FALSE;
	while (1) {
		$db = rg_sql_open_nodelay($h);
		if ($db === FALSE)
			break;

		$ignore = array();
		$start_ts = microtime(TRUE);
		$r = @pg_send_query($db, $sql);
		$ret = rg_sql_query0($db, $sql, $r, $start_ts,
			$ignore, $ignore_kicked);
		break;
	}

	if ($rg_sql_debug > 0)
		rg_log_exit();
	return $ret;
}

/*
 * Queries using params
 * @params - array of fields -> values
 * @ignore - array of strings with errors we should not log as internal errors
 *	See https://www.postgresql.org/docs/current/static/errcodes-appendix.html
 * @ignore_kicked will be set to true if the error is in @ignore array
 * Examples: $params = array("id" => "1", "name" = "bau")
 *	$sql = "UPDATE x SET name = @@name@@ WHERE id = @@id@@ AND @@name@@ = @@name@@"
 *	=> $sql2 = "UPDATE x SET name = $1 WHERE id = $2 AND name = $1"
 */
function rg_sql_query_params_ignore($h, $sql, $params, $ignore, &$ignore_kicked)
{
	global $rg_sql_debug;

	if ($rg_sql_debug > 0)
		rg_log_enter('sql_query_params: sql=[' . $sql . ']'
			. ' params=[' . rg_array2string_short($params) . ']'
			. (empty($ignore) ? '' : ' ignore=' . implode(',', $ignore)));

	$ret = FALSE;
	while (1) {
		$db = rg_sql_open_nodelay($h);
		if ($db === FALSE)
			break;

		// Transforms @params into $x system
		$params2 = array();
		$i = 1;
		foreach ($params as $k => $v) {
			$what = '@@' . $k . '@@';
			$value = '$' . $i;
			$sql = str_replace($what, $value, $sql, $count);

			//rg_log("rg_sql_query_params: k=[$k] value=$value count=$count");
			if ($count > 0) {
				$params2[] = $v;
				$i++;
			}
		}
		//rg_log("new sql: $sql");
		//rg_log("params2: " . rg_array2string_short($params2));

		$start_ts = microtime(TRUE);
		$r = @pg_send_query_params($db, $sql, $params2);
		$ret = rg_sql_query0($db, $sql, $r, $start_ts, $ignore, $ignore_kicked);
		break;
	}

	if ($rg_sql_debug > 0)
		rg_log_exit();
	return $ret;
}

function rg_sql_query_params($h, $sql, $params)
{
	$ignore = array();
	return rg_sql_query_params_ignore($h, $sql, $params,
		$ignore, $ignore_kicked);
}

/*
 * Close database
 */
function rg_sql_close($h)
{
	global $rg_sql_conn;

	if (!isset($rg_sql_conn[$h])) {
		rg_internal_error('Handler ' . $h . ' was not allocated!');
		return FALSE;
	}

	if (!isset($rg_sql_conn[$h]['db'])) {
		// was not opened
		return TRUE;
	}

	$r = pg_close($rg_sql_conn[$h]['db']);
	if ($r === FALSE)
		return FALSE;

	unset($rg_sql_conn[$h]['db']);

	return TRUE;
}

/*
 * Free results
 */
function rg_sql_free_result($res)
{
	pg_free_result($res);
}

/*
 * Returns a row as an associated array
 */
function rg_sql_fetch_array($res)
{
	return pg_fetch_assoc($res);
}

function rg_sql_last_id($h)
{
	$sql = "SELECT lastval() AS id";
	$res = rg_sql_query($h, $sql);
	if ($res === FALSE)
		return FALSE;

	$row = rg_sql_fetch_array($res);
	rg_sql_free_result($res);
	return $row['id'];
}

function rg_sql_num_rows($res)
{
	return pg_num_rows($res);
}

function rg_sql_affected_rows($res)
{
	return pg_affected_rows($res);
}

function rg_sql_begin($h)
{
	$res = rg_sql_query($h, "BEGIN");
	if ($res === FALSE)
		return FALSE;

	rg_sql_free_result($res);
	return TRUE;
}

function rg_sql_commit($h)
{
	$res = rg_sql_query($h, "COMMIT");
	if ($res === FALSE)
		return FALSE;

	rg_sql_free_result($res);
	return TRUE;
}

function rg_sql_rollback($h)
{
	$res = rg_sql_query($h, "ROLLBACK");
	if ($res === FALSE)
		return FALSE;

	rg_sql_free_result($res);
	return TRUE;
}

/*
 * Test if a table exists
 * Returns FALSE on error, 0 if does not exists, 1 if exists
 */
function rg_sql_rel_exists($h, $rel)
{
	$sql = "SELECT 1 FROM pg_class"
		. " WHERE relname = '" . $rel . "'";
	$res = rg_sql_query($h, $sql);
	if ($res === FALSE)
		return FALSE;

	$rows = rg_sql_num_rows($res);
	rg_sql_free_result($res);

	return $rows;
}

/*
 * Returns the fileds names of a table
 */
function rg_sql_fields($h, $table)
{
	$params = array('table' => $table);
	$sql = 'SELECT column_name FROM information_schema.columns'
		. ' WHERE table_name = @@table@@';
	$res = rg_sql_query_params($h, $sql, $params);
	if ($res === FALSE)
		return FALSE;

	$ret = array();
	while (($row = rg_sql_fetch_array($res))) {
		$f = $row['column_name'];
		$ret[$f] = 1;
	}
	rg_sql_free_result($res);

	return $ret;
}

function rg_sql_dbname($h)
{
	global $rg_sql_conn;

	return pg_dbname($rg_sql_conn[$h]['db']);
}

function rg_sql_escape_identifier($h, string $data)
{
	global $rg_sql_conn;

	return pg_escape_identifier($rg_sql_conn[$h]['db'], $data);
}



Mode Type Size Ref File
100644 blob 9 f3c7a7c5da68804a1bdf391127ba34aed33c3cca .exclude
100644 blob 108 acc2186b1d357966e09df32afcea14933f5f0c78 .gitignore
100644 blob 375 1f425bcd2049c526744d449511094fc045ceac74 AUTHORS
100644 blob 2375 07d4a2277dd1c385e2562a9ac7c636bcdd084c18 History.txt
100644 blob 34520 dba13ed2ddf783ee8118c6a581dbf75305f816a3 LICENSE
100644 blob 3632 f216d8f6ca7180c095ee4fcbe96d8fc2ca2b0dee Makefile.in
100644 blob 5325 96c40d868ce10b715299085ccffb30f96a730cf3 README
100644 blob 192509 58df4c67a312c3a7dc7d0f102b55e90b9127bc87 TODO
100644 blob 1294 f22911eb777f0695fcf81ad686eac133eb11fcc4 TODO-plans
100644 blob 203 a2863c67c3da44126b61a15a6f09738c25e0fbe0 TODO.perf
100644 blob 967 56bbaa7c937381fb10a2907b6bbe056ef8cc824a TODO.vm
040000 tree - 21928e906ad2907a55c2e81c2a8b0502b586b8a0 artwork
100644 blob 5328 d5be4cc3f15d059ad8d267d800c602e9774816a8 compare.csv
100755 blob 30 92c4bc48245c00408cd7e1fd89bc1a03058f4ce4 configure
040000 tree - 0a74883db0753f35db9a227ed8f0f46e3c8b1746 debian
040000 tree - fa4b417ddd8b9684c764ea6f1c96065c4d9427b1 docker
040000 tree - f67d3605efbd6422a8acdd953578991139266391 docs
100755 blob 18252 e2438615edba7066a730ed6a796a5302263f1f37 duilder
100644 blob 536 4d35fc700881fc03e043a4c22d8770baa298d093 duilder.conf
040000 tree - 73914e7faf49474a12b29e936ae77006254cc1a1 hooks
040000 tree - 343af578d66f98094554d1c45d863a21f2dfbf2f inc
040000 tree - e255ce234c3993998edc12bc7e93fff555376eda misc
100644 blob 6307 67d5e75076766ad844969abaff446face8ca9eff rocketgit.spec
040000 tree - 459cf6e889bc65568b4fe8d99774380bd2844b39 root
040000 tree - b6db32295abaf3229561581e7577da53af8caf47 samples
040000 tree - 3e6d3d08c1a0baea952bada0f36e29ad9f82d778 scripts
040000 tree - 454044f7e286fe13ec18598fce6b613190f52e5e selinux
100755 blob 256 462ccd108c431f54e380cdac2329129875a318b5 spell_check.sh
040000 tree - d9260d3cf0d6490be720312893600a8041bf991b techdocs
040000 tree - fae18775ac52de4a170fcd1baa733433f31b9559 tests
040000 tree - e810d7397575886ef495708d571eb3675f6928ba tools
Hints:
Before first commit, do not forget to setup your git environment:
git config --global user.name "your_name_here"
git config --global user.email "your@email_here"

Clone this repository using HTTP(S):
git clone https://rocketgit.com/user/catalinux/rocketgit

Clone this repository using ssh (do not forget to upload a key first):
git clone ssh://rocketgit@ssh.rocketgit.com/user/catalinux/rocketgit

Clone this repository using git:
git clone git://git.rocketgit.com/user/catalinux/rocketgit

You are allowed to anonymously push to this repository.
This means that your pushed commits will automatically be transformed into a merge request:
... clone the repository ...
... make some changes and some commits ...
git push origin main