本文整理汇总了PHP中SilverStripe\ORM\DB::get_conn方法的典型用法代码示例。如果您正苦于以下问题:PHP DB::get_conn方法的具体用法?PHP DB::get_conn怎么用?PHP DB::get_conn使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类SilverStripe\ORM\DB
的用法示例。
在下文中一共展示了DB::get_conn方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: testMultipleRowInsert
public function testMultipleRowInsert()
{
$query = SQLInsert::create('"SQLInsertTestBase"');
$query->addRow(array('"Title"' => 'First Object', '"Age"' => 10, '"Description"' => 'First the worst'));
$query->addRow(array('"Title"' => 'Second object', '"Age"' => 12));
$sql = $query->sql($parameters);
// Only test this case if using the default query builder
if (get_class(DB::get_conn()->getQueryBuilder()) === 'SilverStripe\\ORM\\Connect\\DBQueryBuilder') {
$this->assertSQLEquals('INSERT INTO "SQLInsertTestBase" ("Title", "Age", "Description") VALUES (?, ?, ?), (?, ?, ?)', $sql);
}
$this->assertEquals(array('First Object', 10, 'First the worst', 'Second object', 12, null), $parameters);
$query->execute();
$this->assertEquals(2, DB::affected_rows());
// Check inserted objects are correct
$firstObject = DataObject::get_one('SQLInsertTestBase', array('"Title"' => 'First Object'), false);
$this->assertNotEmpty($firstObject);
$this->assertEquals($firstObject->Title, 'First Object');
$this->assertEquals($firstObject->Age, 10);
$this->assertEquals($firstObject->Description, 'First the worst');
$secondObject = DataObject::get_one('SQLInsertTestBase', array('"Title"' => 'Second object'), false);
$this->assertNotEmpty($secondObject);
$this->assertEquals($secondObject->Title, 'Second object');
$this->assertEquals($secondObject->Age, 12);
$this->assertEmpty($secondObject->Description);
}
示例2: testCreateWithTransaction
public function testCreateWithTransaction()
{
if (DB::get_conn()->supportsTransactions() == true) {
DB::get_conn()->transactionStart();
$obj = new TransactionTest_Object();
$obj->Title = 'First page';
$obj->write();
$obj = new TransactionTest_Object();
$obj->Title = 'Second page';
$obj->write();
//Create a savepoint here:
DB::get_conn()->transactionSavepoint('rollback');
$obj = new TransactionTest_Object();
$obj->Title = 'Third page';
$obj->write();
$obj = new TransactionTest_Object();
$obj->Title = 'Fourth page';
$obj->write();
//Revert to a savepoint:
DB::get_conn()->transactionRollback('rollback');
DB::get_conn()->transactionEnd();
$first = DataObject::get('TransactionTest_Object', "\"Title\"='First page'");
$second = DataObject::get('TransactionTest_Object', "\"Title\"='Second page'");
$third = DataObject::get('TransactionTest_Object', "\"Title\"='Third page'");
$fourth = DataObject::get('TransactionTest_Object', "\"Title\"='Fourth page'");
//These pages should be in the system
$this->assertTrue(is_object($first) && $first->exists());
$this->assertTrue(is_object($second) && $second->exists());
//These pages should NOT exist, we reverted to a savepoint:
$this->assertFalse(is_object($third) && $third->exists());
$this->assertFalse(is_object($fourth) && $fourth->exists());
} else {
$this->markTestSkipped('Current database does not support transactions');
}
}
示例3: testFilter
public function testFilter()
{
if (DB::get_conn() instanceof MySQLDatabase) {
$baseQuery = FulltextFilterTest_DataObject::get();
$this->assertEquals(3, $baseQuery->count(), "FulltextFilterTest_DataObject count does not match.");
// First we'll text the 'SearchFields' which has been set using an array
$search = $baseQuery->filter("SearchFields:fulltext", 'SilverStripe');
$this->assertEquals(1, $search->count());
$search = $baseQuery->exclude("SearchFields:fulltext", "SilverStripe");
$this->assertEquals(2, $search->count());
// Now we'll run the same tests on 'OtherSearchFields' which should yield the same resutls
// but has been set using a string.
$search = $baseQuery->filter("OtherSearchFields:fulltext", 'SilverStripe');
$this->assertEquals(1, $search->count());
$search = $baseQuery->exclude("OtherSearchFields:fulltext", "SilverStripe");
$this->assertEquals(2, $search->count());
// Search on a single field
$search = $baseQuery->filter("ColumnE:fulltext", 'Dragons');
$this->assertEquals(1, $search->count());
$search = $baseQuery->exclude("ColumnE:fulltext", "Dragons");
$this->assertEquals(2, $search->count());
} else {
$this->markTestSkipped("FulltextFilter only supports MySQL syntax.");
}
}
示例4: testQueriedColumnsFromSubTable
public function testQueriedColumnsFromSubTable()
{
$db = DB::get_conn();
$playerList = new DataList('DataObjectTest_SubTeam');
$playerList = $playerList->setQueriedColumns(array('SubclassDatabaseField'));
$expected = 'SELECT DISTINCT "DataObjectTest_Team"."ClassName", "DataObjectTest_Team"."LastEdited", ' . '"DataObjectTest_Team"."Created", "DataObjectTest_SubTeam"."SubclassDatabaseField", ' . '"DataObjectTest_Team"."ID", CASE WHEN "DataObjectTest_Team"."ClassName" IS NOT NULL THEN ' . '"DataObjectTest_Team"."ClassName" ELSE ' . $db->quoteString('DataObjectTest_Team') . ' END ' . 'AS "RecordClassName", "DataObjectTest_Team"."Title" ' . 'FROM "DataObjectTest_Team" LEFT JOIN "DataObjectTest_SubTeam" ON "DataObjectTest_SubTeam"."ID" = ' . '"DataObjectTest_Team"."ID" WHERE ("DataObjectTest_Team"."ClassName" IN (?)) ' . 'ORDER BY "DataObjectTest_Team"."Title" ASC';
$this->assertSQLEquals($expected, $playerList->sql($parameters));
}
示例5: requireField
public function requireField()
{
// HACK: MSSQL does not support double so we're using float instead
// @todo This should go into MSSQLDatabase ideally somehow
if (DB::get_conn() instanceof MySQLDatabase) {
DB::require_field($this->tableName, $this->name, "double");
} else {
DB::require_field($this->tableName, $this->name, "float");
}
}
示例6: conditionSQL
public function conditionSQL(&$parameters)
{
$parameters = array();
// Ignore empty conditions
$where = $this->whereQuery->getWhere();
if (empty($where)) {
return null;
}
// Allow database to manage joining of conditions
$sql = DB::get_conn()->getQueryBuilder()->buildWhereFragment($this->whereQuery, $parameters);
return preg_replace('/^\\s*WHERE\\s*/i', '', $sql);
}
示例7: excludeMany
protected function excludeMany(DataQuery $query)
{
$this->model = $query->applyRelation($this->relation);
$values = $this->getValue();
$comparisonClause = DB::get_conn()->comparisonClause($this->getDbName(), null, false, true, $this->getCaseSensitive(), true);
$parameters = array();
foreach ($values as $value) {
$parameters[] = $this->getMatchPattern($value);
}
// Since query connective is ambiguous, use AND explicitly here
$count = count($values);
$predicate = implode(' AND ', array_fill(0, $count, $comparisonClause));
return $query->where(array($predicate => $parameters));
}
示例8: testTransactions
public function testTransactions()
{
$conn = DB::get_conn();
if (!$conn->supportsTransactions()) {
$this->markTestSkipped("DB Doesn't support transactions");
return;
}
// Test that successful transactions are comitted
$obj = new DatabaseTest_MyObject();
$failed = false;
$conn->withTransaction(function () use(&$obj) {
$obj->MyField = 'Save 1';
$obj->write();
}, function () use(&$failed) {
$failed = true;
});
$this->assertEquals('Save 1', DatabaseTest_MyObject::get()->first()->MyField);
$this->assertFalse($failed);
// Test failed transactions are rolled back
$ex = null;
$failed = false;
try {
$conn->withTransaction(function () use(&$obj) {
$obj->MyField = 'Save 2';
$obj->write();
throw new Exception("error");
}, function () use(&$failed) {
$failed = true;
});
} catch (Exception $ex) {
}
$this->assertTrue($failed);
$this->assertEquals('Save 1', DatabaseTest_MyObject::get()->first()->MyField);
$this->assertInstanceOf('Exception', $ex);
$this->assertEquals('error', $ex->getMessage());
}
示例9: testLeftJoinParameterised
public function testLeftJoinParameterised()
{
$db = DB::get_conn();
$list = DataObjectTest_TeamComment::get();
$list = $list->leftJoin('DataObjectTest_Team', '"DataObjectTest_Team"."ID" = "DataObjectTest_TeamComment"."TeamID" ' . 'AND "DataObjectTest_Team"."Title" LIKE ?', 'Team', 20, array('Team%'));
$expected = 'SELECT DISTINCT "DataObjectTest_TeamComment"."ClassName", ' . '"DataObjectTest_TeamComment"."LastEdited", "DataObjectTest_TeamComment"."Created", ' . '"DataObjectTest_TeamComment"."Name", "DataObjectTest_TeamComment"."Comment", ' . '"DataObjectTest_TeamComment"."TeamID", "DataObjectTest_TeamComment"."ID", ' . 'CASE WHEN "DataObjectTest_TeamComment"."ClassName" IS NOT NULL' . ' THEN "DataObjectTest_TeamComment"."ClassName" ELSE ' . $db->quoteString('DataObjectTest_TeamComment') . ' END AS "RecordClassName" FROM "DataObjectTest_TeamComment" LEFT JOIN ' . '"DataObjectTest_Team" AS "Team" ON "DataObjectTest_Team"."ID" = ' . '"DataObjectTest_TeamComment"."TeamID" ' . 'AND "DataObjectTest_Team"."Title" LIKE ?' . ' ORDER BY "DataObjectTest_TeamComment"."Name" ASC';
$this->assertSQLEquals($expected, $list->sql($parameters));
$this->assertEquals(array('Team%'), $parameters);
}
示例10: manyFilter
/**
* Applies matches for several values, either as inclusive or exclusive
*
* @param DataQuery $query
* @param bool $inclusive True if this is inclusive, or false if exclusive
* @return DataQuery
*/
protected function manyFilter(DataQuery $query, $inclusive)
{
$this->model = $query->applyRelation($this->relation);
$caseSensitive = $this->getCaseSensitive();
// Check values for null
$field = $this->getDbName();
$values = $this->getValue();
if (empty($values)) {
throw new \InvalidArgumentException("Cannot filter {$field} against an empty set");
}
$hasNull = in_array(null, $values, true);
if ($hasNull) {
$values = array_filter($values, function ($value) {
return $value !== null;
});
}
$connective = '';
if (empty($values)) {
$predicate = '';
} elseif ($caseSensitive === null) {
// For queries using the default collation (no explicit case) we can use the WHERE .. NOT IN .. syntax,
// providing simpler SQL than many WHERE .. AND .. fragments.
$column = $this->getDbName();
$placeholders = DB::placeholders($values);
if ($inclusive) {
$predicate = "{$column} IN ({$placeholders})";
} else {
$predicate = "{$column} NOT IN ({$placeholders})";
}
} else {
// Generate reusable comparison clause
$comparisonClause = DB::get_conn()->comparisonClause($this->getDbName(), null, true, !$inclusive, $this->getCaseSensitive(), true);
$count = count($values);
if ($count > 1) {
$connective = $inclusive ? ' OR ' : ' AND ';
$conditions = array_fill(0, $count, $comparisonClause);
$predicate = implode($connective, $conditions);
} else {
$predicate = $comparisonClause;
}
}
// Always check for null when doing exclusive checks (either AND IS NOT NULL / OR IS NULL)
// or when including the null value explicitly (OR IS NULL)
if ($hasNull || !$inclusive) {
// If excluding values which don't include null, or including
// values which include null, we should do an `OR IS NULL`.
// Otherwise we are excluding values that do include null, so `AND IS NOT NULL`.
// Simplified from (!$inclusive && !$hasNull) || ($inclusive && $hasNull);
$isNull = !$hasNull || $inclusive;
$nullCondition = DB::get_conn()->nullCheckClause($field, $isNull);
// Determine merge strategy
if (empty($predicate)) {
$predicate = $nullCondition;
} else {
// Merge null condition with predicate
if ($isNull) {
$nullCondition = " OR {$nullCondition}";
} else {
$nullCondition = " AND {$nullCondition}";
}
// If current predicate connective doesn't match the same as the null connective
// make sure to group the prior condition
if ($connective && ($connective === ' OR ') !== $isNull) {
$predicate = "({$predicate})";
}
$predicate .= $nullCondition;
}
}
return $query->where(array($predicate => $values));
}
示例11: create_temp_db
public static function create_temp_db()
{
// Disable PHPUnit error handling
restore_error_handler();
// Create a temporary database, and force the connection to use UTC for time
global $databaseConfig;
$databaseConfig['timezone'] = '+0:00';
DB::connect($databaseConfig);
$dbConn = DB::get_conn();
$prefix = defined('SS_DATABASE_PREFIX') ? SS_DATABASE_PREFIX : 'ss_';
$dbname = strtolower(sprintf('%stmpdb', $prefix)) . rand(1000000, 9999999);
while (!$dbname || $dbConn->databaseExists($dbname)) {
$dbname = strtolower(sprintf('%stmpdb', $prefix)) . rand(1000000, 9999999);
}
$dbConn->selectDatabase($dbname, true);
$st = Injector::inst()->create('SapphireTest');
$st->resetDBSchema();
// Reinstate PHPUnit error handling
set_error_handler(array('PHPUnit_Util_ErrorHandler', 'handleError'));
return $dbname;
}
示例12: clearAllData
/**
* Clear all data out of the database
*
* @deprecated since version 4.0
*/
public function clearAllData()
{
Deprecation::notice('4.0', 'Use DB::get_conn()->clearAllData() instead');
DB::get_conn()->clearAllData();
}
示例13: sync
/**
* Add implicit changes that should be included in this changeset
*
* When an item is created or changed, all it's owned items which have
* changes are implicitly added
*
* When an item is deleted, it's owner (even if that owner does not have changes)
* is implicitly added
*/
public function sync()
{
// Start a transaction (if we can)
DB::get_conn()->withTransaction(function () {
// Get the implicitly included items for this ChangeSet
$implicit = $this->calculateImplicit();
// Adjust the existing implicit ChangeSetItems for this ChangeSet
/** @var ChangeSetItem $item */
foreach ($this->Changes()->filter(['Added' => ChangeSetItem::IMPLICITLY]) as $item) {
$objectKey = $this->implicitKey($item);
// If a ChangeSetItem exists, but isn't in $implicit, it's no longer required, so delete it
if (!array_key_exists($objectKey, $implicit)) {
$item->delete();
} else {
$item->ReferencedBy()->setByIDList($implicit[$objectKey]['ReferencedBy']);
unset($implicit[$objectKey]);
}
}
// Now $implicit is all those items that are implicitly included, but don't currently have a ChangeSetItem.
// So create new ChangeSetItems to match
foreach ($implicit as $key => $props) {
$item = new ChangeSetItem($props);
$item->Added = ChangeSetItem::IMPLICITLY;
$item->ChangeSetID = $this->ID;
$item->ReferencedBy()->setByIDList($props['ReferencedBy']);
$item->write();
}
});
}
示例14: testPrepValueForDB
/**
* Test the prepValueForDB() method on DBField.
*/
public function testPrepValueForDB()
{
$db = DB::get_conn();
/* Float behaviour, asserting we have 0 */
$this->assertEquals(0, singleton('Float')->prepValueForDB(0));
$this->assertEquals(0, singleton('Float')->prepValueForDB(null));
$this->assertEquals(0, singleton('Float')->prepValueForDB(false));
$this->assertEquals(0, singleton('Float')->prepValueForDB(''));
$this->assertEquals('0', singleton('Float')->prepValueForDB('0'));
/* Double behaviour, asserting we have 0 */
$this->assertEquals(0, singleton('Double')->prepValueForDB(0));
$this->assertEquals(0, singleton('Double')->prepValueForDB(null));
$this->assertEquals(0, singleton('Double')->prepValueForDB(false));
$this->assertEquals(0, singleton('Double')->prepValueForDB(''));
$this->assertEquals('0', singleton('Double')->prepValueForDB('0'));
/* Integer behaviour, asserting we have 0 */
$this->assertEquals(0, singleton('Int')->prepValueForDB(0));
$this->assertEquals(0, singleton('Int')->prepValueForDB(null));
$this->assertEquals(0, singleton('Int')->prepValueForDB(false));
$this->assertEquals(0, singleton('Int')->prepValueForDB(''));
$this->assertEquals('0', singleton('Int')->prepValueForDB('0'));
/* Integer behaviour, asserting we have 1 */
$this->assertEquals(1, singleton('Int')->prepValueForDB(true));
$this->assertEquals(1, singleton('Int')->prepValueForDB(1));
$this->assertEquals('1', singleton('Int')->prepValueForDB('1'));
/* Decimal behaviour, asserting we have 0 */
$this->assertEquals(0, singleton('Decimal')->prepValueForDB(0));
$this->assertEquals(0, singleton('Decimal')->prepValueForDB(null));
$this->assertEquals(0, singleton('Decimal')->prepValueForDB(false));
$this->assertEquals(0, singleton('Decimal')->prepValueForDB(''));
$this->assertEquals('0', singleton('Decimal')->prepValueForDB('0'));
/* Decimal behaviour, asserting we have 1 */
$this->assertEquals(1, singleton('Decimal')->prepValueForDB(true));
$this->assertEquals(1, singleton('Decimal')->prepValueForDB(1));
$this->assertEquals('1', singleton('Decimal')->prepValueForDB('1'));
/* Boolean behaviour, asserting we have 0 */
$this->assertEquals(false, singleton('Boolean')->prepValueForDB(0));
$this->assertEquals(false, singleton('Boolean')->prepValueForDB(null));
$this->assertEquals(false, singleton('Boolean')->prepValueForDB(false));
$this->assertEquals(false, singleton('Boolean')->prepValueForDB('false'));
$this->assertEquals(false, singleton('Boolean')->prepValueForDB('f'));
$this->assertEquals(false, singleton('Boolean')->prepValueForDB(''));
$this->assertEquals(false, singleton('Boolean')->prepValueForDB('0'));
/* Boolean behaviour, asserting we have 1 */
$this->assertEquals(true, singleton('Boolean')->prepValueForDB(true));
$this->assertEquals(true, singleton('Boolean')->prepValueForDB('true'));
$this->assertEquals(true, singleton('Boolean')->prepValueForDB('t'));
$this->assertEquals(true, singleton('Boolean')->prepValueForDB(1));
$this->assertEquals(true, singleton('Boolean')->prepValueForDB('1'));
// @todo - Revisit Varchar to evaluate correct behaviour of nullifyEmpty
/* Varchar behaviour */
$this->assertEquals(0, singleton('Varchar')->prepValueForDB(0));
$this->assertEquals(null, singleton('Varchar')->prepValueForDB(null));
$this->assertEquals(null, singleton('Varchar')->prepValueForDB(false));
$this->assertEquals(null, singleton('Varchar')->prepValueForDB(''));
$this->assertEquals('0', singleton('Varchar')->prepValueForDB('0'));
$this->assertEquals(1, singleton('Varchar')->prepValueForDB(1));
$this->assertEquals(true, singleton('Varchar')->prepValueForDB(true));
$this->assertEquals('1', singleton('Varchar')->prepValueForDB('1'));
$this->assertEquals('00000', singleton('Varchar')->prepValueForDB('00000'));
$this->assertEquals(0, singleton('Varchar')->prepValueForDB(00));
$this->assertEquals('test', singleton('Varchar')->prepValueForDB('test'));
$this->assertEquals(123, singleton('Varchar')->prepValueForDB(123));
/* AllowEmpty Varchar behaviour */
$varcharField = new DBVarchar("testfield", 50, array("nullifyEmpty" => false));
$this->assertSame(0, $varcharField->prepValueForDB(0));
$this->assertSame(null, $varcharField->prepValueForDB(null));
$this->assertSame(null, $varcharField->prepValueForDB(false));
$this->assertSame('', $varcharField->prepValueForDB(''));
$this->assertSame('0', $varcharField->prepValueForDB('0'));
$this->assertSame(1, $varcharField->prepValueForDB(1));
$this->assertSame(true, $varcharField->prepValueForDB(true));
$this->assertSame('1', $varcharField->prepValueForDB('1'));
$this->assertSame('00000', $varcharField->prepValueForDB('00000'));
$this->assertSame(0, $varcharField->prepValueForDB(00));
$this->assertSame('test', $varcharField->prepValueForDB('test'));
$this->assertSame(123, $varcharField->prepValueForDB(123));
unset($varcharField);
/* Text behaviour */
$this->assertEquals(0, singleton('Text')->prepValueForDB(0));
$this->assertEquals(null, singleton('Text')->prepValueForDB(null));
$this->assertEquals(null, singleton('Text')->prepValueForDB(false));
$this->assertEquals(null, singleton('Text')->prepValueForDB(''));
$this->assertEquals('0', singleton('Text')->prepValueForDB('0'));
$this->assertEquals(1, singleton('Text')->prepValueForDB(1));
$this->assertEquals(true, singleton('Text')->prepValueForDB(true));
$this->assertEquals('1', singleton('Text')->prepValueForDB('1'));
$this->assertEquals('00000', singleton('Text')->prepValueForDB('00000'));
$this->assertEquals(0, singleton('Text')->prepValueForDB(00));
$this->assertEquals('test', singleton('Text')->prepValueForDB('test'));
$this->assertEquals(123, singleton('Text')->prepValueForDB(123));
/* AllowEmpty Text behaviour */
$textField = new DBText("testfield", array("nullifyEmpty" => false));
$this->assertSame(0, $textField->prepValueForDB(0));
$this->assertSame(null, $textField->prepValueForDB(null));
$this->assertSame(null, $textField->prepValueForDB(false));
$this->assertSame('', $textField->prepValueForDB(''));
//.........这里部分代码省略.........
示例15: copyVersionToStage
/**
* Move a database record from one stage to the other.
*
* @param int|string $fromStage Place to copy from. Can be either a stage name or a version number.
* @param string $toStage Place to copy to. Must be a stage name.
* @param bool $createNewVersion Set this to true to create a new version number.
* By default, the existing version number will be copied over.
*/
public function copyVersionToStage($fromStage, $toStage, $createNewVersion = false)
{
$owner = $this->owner;
$owner->invokeWithExtensions('onBeforeVersionedPublish', $fromStage, $toStage, $createNewVersion);
$baseClass = $owner->baseClass();
$baseTable = $owner->baseTable();
/** @var Versioned|DataObject $from */
if (is_numeric($fromStage)) {
$from = Versioned::get_version($baseClass, $owner->ID, $fromStage);
} else {
$owner->flushCache();
$from = Versioned::get_one_by_stage($baseClass, $fromStage, array("\"{$baseTable}\".\"ID\" = ?" => $owner->ID));
}
if (!$from) {
throw new InvalidArgumentException("Can't find {$baseClass}#{$owner->ID} in stage {$fromStage}");
}
$from->forceChange();
if ($createNewVersion) {
// Clear version to be automatically created on write
$from->Version = null;
} else {
$from->migrateVersion($from->Version);
// Mark this version as having been published at some stage
$publisherID = isset(Member::currentUser()->ID) ? Member::currentUser()->ID : 0;
$extTable = $this->extendWithSuffix($baseTable);
DB::prepared_query("UPDATE \"{$extTable}_versions\"\n\t\t\t\tSET \"WasPublished\" = ?, \"PublisherID\" = ?\n\t\t\t\tWHERE \"RecordID\" = ? AND \"Version\" = ?", array(1, $publisherID, $from->ID, $from->Version));
}
// Change to new stage, write, and revert state
$oldMode = Versioned::get_reading_mode();
Versioned::set_stage($toStage);
// Migrate stage prior to write
$from->setSourceQueryParam('Versioned.mode', 'stage');
$from->setSourceQueryParam('Versioned.stage', $toStage);
$conn = DB::get_conn();
if (method_exists($conn, 'allowPrimaryKeyEditing')) {
$conn->allowPrimaryKeyEditing($baseTable, true);
$from->write();
$conn->allowPrimaryKeyEditing($baseTable, false);
} else {
$from->write();
}
$from->destroy();
Versioned::set_reading_mode($oldMode);
$owner->invokeWithExtensions('onAfterVersionedPublish', $fromStage, $toStage, $createNewVersion);
}