From: tjhunt Date: Fri, 18 Aug 2006 11:28:30 +0000 (+0000) Subject: New function record_exists_select with unit tests for all the record_exists_* functions. X-Git-Url: http://git.mjollnir.org/gw?a=commitdiff_plain;h=5553c2ec47982e16322595efe3dc83c90761ff98;p=moodle.git New function record_exists_select with unit tests for all the record_exists_* functions. --- diff --git a/lib/datalib.php b/lib/datalib.php index ae3de5228a..f83d9c0c20 100644 --- a/lib/datalib.php +++ b/lib/datalib.php @@ -436,6 +436,24 @@ function record_exists($table, $field1='', $value1='', $field2='', $value2='', $ return record_exists_sql('SELECT * FROM '. $CFG->prefix . $table .' '. $select .' LIMIT 1'); } +/** + * Test whether any records exists in a table which match a particular WHERE clause. + * + * @uses $CFG + * @param string $table The database table to be checked against. + * @param string $select A fragment of SQL to be used in a WHERE clause in the SQL call. + * @return bool true if a matching record exists, else false. + */ +function record_exists_select($table, $select='') { + + global $CFG; + + if ($select) { + $select = 'WHERE '.$select; + } + + return record_exists_sql('SELECT * FROM '. $CFG->prefix . $table . ' ' . $select); +} /** * Test whether a SQL SELECT statement returns any records. diff --git a/lib/simpletest/testdatalib.php b/lib/simpletest/testdatalib.php index f7fcec230c..38bceed0b5 100644 --- a/lib/simpletest/testdatalib.php +++ b/lib/simpletest/testdatalib.php @@ -51,6 +51,23 @@ class datalib_test extends prefix_changing_test_case { $this->assertEqual(where_clause('f1', 'v1', 'f2', 2), "WHERE f1 = 'v1' AND f2 = '2'"); $this->assertEqual(where_clause('f1', 'v1', 'f2', 1.75, 'f3', 'v3'), "WHERE f1 = 'v1' AND f2 = '1.75' AND f3 = 'v3'"); } + + function test_record_exists() { + $this->assertTrue(record_exists($this->table, 'number', 101, 'id', 1)); + $this->assertFalse(record_exists($this->table, 'number', 102, 'id', 1)); + } + + function test_record_exists_select() { + $this->assertTrue(record_exists_select($this->table, 'number = 101 AND id = 1')); + $this->assertFalse(record_exists_select($this->table, 'number = 102 AND id = 1')); + } + + function test_record_exists_sql() { + global $CFG; + $this->assertTrue(record_exists_sql("SELECT * FROM {$CFG->prefix}$this->table WHERE number = 101 AND id = 1")); + $this->assertFalse(record_exists_sql("SELECT * FROM {$CFG->prefix}$this->table WHERE number = 102 AND id = 1")); + } + function test_get_record() { // Get particular records.