Returns whether or not this form is for a create operation.

For this method to return true, both the primary key constraint
must be defined in the 'schema' data, and the 'defaults' data must
contain a value for all fields in the key.

@return bool
321276
public function isCreate()
    {
        $primary = $this->primaryKey();
        foreach ($primary as $column) {
            if (!empty($this->_context['defaults'][$column])) {
                return false;
            }
        }

        return true;
    }
579377
public function create()
    {
        //queries to run
        $queries = [];

        //translate model data to sql data
        if (is_null($this->schema)) {
            throw Exception::forNoSchema();
        }

        $data = $this->schema->toSql();

        //determine the create schema
        $query = $this
            ->resource
            ->getCreateQuery($data['name'])
            ->addPrimaryKey($data['primary'])
            ->addField($data['primary'], [
                'type' => 'int(10)',
                'null' => false,
                'attribute' => 'UNSIGNED',
                'auto_increment' => true,
            ]);

        foreach ($data['columns'] as $name => $column) {
            $attributes = ['type' => $column['type']];

            if (isset($column['length'])) {
                $attributes['type'] .= '(' . $column['length'] . ')';
            }

            if (isset($column['default']) && strlen($column['default'])) {
                $attributes['default'] = $column['default'];
            } else if (!isset($column['required']) || !$column['required']) {
                $attributes['null'] = true;
            }

            if (isset($column['required']) && $column['required']) {
                $attributes['null'] = false;
            }

            if (isset($column['attribute']) && $column['attribute']) {
                $attributes['attribute'] = $column['attribute'];
            }

            $query->addField($name, $attributes);

            if (isset($column['index']) && $column['index']) {
                $query->addKey($name, [$name]);
            }

            if (isset($column['unique']) && $column['unique']) {
                $query->addUniqueKey($name, [$name]);
            }

            if (isset($column['primary']) && $column['primary']) {
                $query->addPrimaryKey($name);
            }
        }

        $queries[] = 'DROP TABLE IF EXISTS `' . $data['name'] . '`;';
        $queries[] = (string) $query;

        //determine the relation schema
        foreach ($data['relations'] as $table => $relation) {
            $query = $this->resource->getCreateQuery($table);

            $query->addPrimaryKey($relation['primary1']);
            $query->addField($relation['primary1'], [
                'type' => 'int(10)',
                'null' => false,
                'attribute' => 'UNSIGNED'
            ]);

            $query->addPrimaryKey($relation['primary2']);
            $query->addField($relation['primary2'], [
                'type' => 'int(10)',
                'null' => false,
                'attribute' => 'UNSIGNED'
            ]);

            $queries[] = 'DROP TABLE IF EXISTS `'. $table . '`;';
            $queries[] = (string) $query;
        }

        //execute queries
        $results = [];
        foreach ($queries as $query) {
            $results[] = [
                'query' => $query,
                'results' => $this->resource->query($query)
            ];
        }

        return $results;
    }
169462
public function save() : bool
    {
        if (!$this->isTableNameSet()) {
            return false;
        }
        $pkName = $this->primaryKey;
        if ((int) $this->$pkName > 0) {
            $this->updateEntry();
        } else {
            $this->createEntry();
        }
        return true;
    }
59180
protected function _Create() {
      $PrimaryKey = array();
      $UniqueKey = array();
      $FullTextKey = array();
      $AllowFullText = TRUE;
      $Indexes = array();
      $Keys = '';
      $Sql = '';
      
      $ForceDatabaseEngine = C('Database.ForceStorageEngine');
      if ($ForceDatabaseEngine && !$this->_TableStorageEngine) {
         $this->_TableStorageEngine = $ForceDatabaseEngine;
         $AllowFullText = $this->_SupportsFulltext();
      }

      foreach ($this->_Columns as $ColumnName => $Column) {
         if ($Sql != '')
            $Sql .= ',';

         $Sql .= "\n".$this->_DefineColumn($Column);

         $ColumnKeyTypes = (array)$Column->KeyType;

         foreach ($ColumnKeyTypes as $ColumnKeyType) {
            $KeyTypeParts = explode('.', $ColumnKeyType, 2);
            $ColumnKeyType = $KeyTypeParts[0];
            $IndexGroup = GetValue(1, $KeyTypeParts, '');
            
            if ($ColumnKeyType == 'primary')
               $PrimaryKey[] = $ColumnName;
            elseif ($ColumnKeyType == 'key')
               $Indexes['FK'][$IndexGroup][] = $ColumnName;
            elseif ($ColumnKeyType == 'index')
               $Indexes['IX'][$IndexGroup][] = $ColumnName;
            elseif ($ColumnKeyType == 'unique')
               $UniqueKey[] = $ColumnName;
            elseif ($ColumnKeyType == 'fulltext' && $AllowFullText)
               $FullTextKey[] = $ColumnName;
         }
      }
      // Build primary keys
      if (count($PrimaryKey) > 0)
         $Keys .= ",\nprimary key (`".implode('`, `', $PrimaryKey)."`)";
      // Build unique keys.
      if (count($UniqueKey) > 0)
         $Keys .= ",\nunique index `".Gdn_Format::AlphaNumeric('UX_'.$this->_TableName).'` (`'.implode('`, `', $UniqueKey)."`)";
      // Build full text index.
      if (count($FullTextKey) > 0)
         $Keys .= ",\nfulltext index `".Gdn_Format::AlphaNumeric('TX_'.$this->_TableName).'` (`'.implode('`, `', $FullTextKey)."`)";
      // Build the rest of the keys.
      foreach ($Indexes as $IndexType => $IndexGroups) {
         $CreateString = ArrayValue($IndexType, array('FK' => 'key', 'IX' => 'index'));
         foreach ($IndexGroups as $IndexGroup => $ColumnNames) {
            if (!$IndexGroup) {
               foreach ($ColumnNames as $ColumnName) {
                  $Keys .= ",\n{$CreateString} `{$IndexType}_{$this->_TableName}_{$ColumnName}` (`{$ColumnName}`)";
               }
            } else {
               $Keys .= ",\n{$CreateString} `{$IndexType}_{$this->_TableName}_{$IndexGroup}` (`".implode('`, `', $ColumnNames).'`)';
            }
         }
      }

      $Sql = 'create table `'.$this->_DatabasePrefix.$this->_TableName.'` ('
         .$Sql
         .$Keys
      ."\n)";

      // Check to see if there are any fulltext columns, otherwise use innodb.
      if (!$this->_TableStorageEngine) {
         $HasFulltext = FALSE;
         foreach ($this->_Columns as $Column) {
            $ColumnKeyTypes = (array)$Column->KeyType;
            array_map('strtolower', $ColumnKeyTypes);
            if (in_array('fulltext', $ColumnKeyTypes)) {
               $HasFulltext = TRUE;
               break;
            }
         }
         if ($HasFulltext)
            $this->_TableStorageEngine = 'myisam';
         else
            $this->_TableStorageEngine = C('Database.DefaultStorageEngine', 'innodb');
         
         if (!$this->HasEngine($this->_TableStorageEngine)) {
            $this->_TableStorageEngine = 'myisam';
         }
      }
      
      if ($this->_TableStorageEngine)
         $Sql .= ' engine='.$this->_TableStorageEngine;

      if ($this->_CharacterEncoding !== FALSE && $this->_CharacterEncoding != '')
         $Sql .= ' default character set '.$this->_CharacterEncoding;
         
      if (array_key_exists('Collate', $this->Database->ExtendedProperties)) {
         $Sql .= ' collate ' . $this->Database->ExtendedProperties['Collate'];
      }
      
      $Sql .= ';';

      $Result = $this->Query($Sql);
      $this->Reset();
      
      return $Result;
   }
54255
public function exists()
    {
        if (! array_key_exists($this->primaryKey, $this->attributes)) {
            return false;
        }

        return ! empty($this->attributes[$this->primaryKey]);
    }
724292
public function isLockedOut()
    {
        /** @var DBDatetime $lockedOutUntilObj */
        $lockedOutUntilObj = $this->dbObject('LockedOutUntil');
        if ($lockedOutUntilObj->InFuture()) {
            return true;
        }

        $maxAttempts = $this->config()->get('lock_out_after_incorrect_logins');
        if ($maxAttempts <= 0) {
            return false;
        }

        $idField = static::config()->get('unique_identifier_field');
        $attempts = LoginAttempt::getByEmail($this->{$idField})
            ->sort('Created', 'DESC')
            ->limit($maxAttempts);

        if ($attempts->count() < $maxAttempts) {
            return false;
        }

        foreach ($attempts as $attempt) {
            if ($attempt->Status === 'Success') {
                return false;
            }
        }

        // Calculate effective LockedOutUntil
        /** @var DBDatetime $firstFailureDate */
        $firstFailureDate = $attempts->first()->dbObject('Created');
        $maxAgeSeconds = $this->config()->get('lock_out_delay_mins') * 60;
        $lockedOutUntil = $firstFailureDate->getTimestamp() + $maxAgeSeconds;
        $now = DBDatetime::now()->getTimestamp();
        if ($now < $lockedOutUntil) {
            return true;
        }

        return false;
    }
1216341
public function validate() : bool
    {
        $table = $this->getConfig()->getTable();
        foreach ([$this->config->getField(), $this->config->getDisplayField()] as $field) {
            if ($table->getSchema()->hasColumn($field)) {
                continue;
            }

            $this->errors[] = sprintf('Unknown column "%s" for table "%s"', $field, $table->getAlias());
        }

        return empty($this->errors);
    }
169083
public function insert()
	{
		$res = \DB::insert(call_user_func($this->model.'::table'), array_keys($this->values))
			->values(array_values($this->values))
			->execute($this->write_connection);

		// Failed to save the new record
		if ($res[1] === 0)
		{
			return false;
		}

		return $res[0];
	}
18228
public function save()
    {
        // Validate
        if (!$this->validates()) {
            return false;
        }

        // Run filter
        $this->runFilters('before', $this->_isNew ? 'create' : 'save');

        // Get data
        $data = static::data();

        // Create
        if ($this->_isNew) {
            $result = static::connection()
                ->insert($data)
                ->into(static::table())
                ->exec();

            $this->id = static::connection()->lastInsertId();
        }
        // Update
        else {
            $result = static::connection()
                ->update(static::table())
                ->set($data)
                ->where(static::$_primaryKey . ' = ?', $data[static::$_primaryKey])
                ->exec();
        }

        // Run filters
        $this->runFilters('after', $this->_isNew ? 'create' : 'save');

        return $result;
    }
1260297
public function isVersioningService()
    {
        $schema = $this->utils->getCurrentSchema();
        if (isset($schema->{'x-versioning'}) && $schema->{'x-versioning'} === true) {
            return true;
        }
        return false;
    }
595551
function hasPrimaryKeyValues() {
		$pks = static::$_primaryKeys;
		if (!$pks)
			return false;

		foreach ($pks as &$pk)
			if ($this->$pk === null)
				return false;
		return true;
	}
489150
public function dbInsert() {
		BLog::addToLog('[Items.Item.' . $this->tableName . ']: Inserting data...');
		if (!$db = \Brilliant\BFactory::getDBO()) {
			return false;
		}
		//Forming query...
		$this->modified = new \Brilliant\BDateTime();
		//For import we need ability to set `created`
		if (empty($this->created)) {
			$this->created = new \Brilliant\BDateTime();
		}
		$qr = $this->dbInsertQuery();
		//Running query...
		$q = $db->query($qr);
		if (empty($q)) {
			return false;
		}
		$this->{$this->primaryKeyName} = $db->insertId();
		$this->isNew = false;
		//Updating cache...
		$this->updateCache();
		//Return result
		return true;
	}
438717
protected static function databaseIsReady()
    {
        $object = DataObject::singleton(static::class);

        // if any of the tables aren't created in the database
        $table = $object->baseTable();
        if (!ClassInfo::hasTable($table)) {
            return false;
        }

        // if any of the tables don't have all fields mapped as table columns
        $dbFields = DB::field_list($table);
        if (!$dbFields) {
            return false;
        }

        $objFields = $object->getSchema()->databaseFields($object, false);
        $missingFields = array_diff_key($objFields, $dbFields);

        if ($missingFields) {
            return false;
        }

        return true;
    }
27868
private function createIfNotExists()
    {
        $table = new Table('schema_migration');
        if ($this->info->isTableExists($table)) {
            return;
        }
        $primaryKey = new PrimaryKey(array('version'));
        $primaryKey->disableAutoIncrement();

        $table->addConstraint($primaryKey);
        $table
            ->addColumn(new BigIntegerColumn('version'))
            ->addColumn(new DateTimeColumn('created_at', array('nullable' => false, 'default' => 'now()')));
        $this->manipulation->create($table);
    }
527215
public function checkPrimaryKey()
    {
        if (($retval = $this->checkPrimaryConstraint())) {
            if ($this->is_translation) {
                $this->table_field_id = NABU_LANG_FIELD_ID;
            } else {
                $keys = $this->getStorageDescriptor()->getPrimaryConstraintFieldNames();
                $size = count($keys);
                if ($size > 0) {
                    $this->table_field_id = $keys[$size - 1];
                } else {
                    $this->table_field_id = null;
                    $this->is_translation = false;
                }
            }
        } else {
            $this->table_field_id = null;
            $this->is_translation = false;
        }

        return $retval;
    }
1026552
final public function create() {

		$app = Application::getInstance();
		$class = get_called_class();
		
		if (!$this->areKeysPopulated() and !$this->db->isAutoIncrement(static::TABLE_NAME)) {
			$app->logEvent('The object’s ' . implode(', ', $this->keyProperties) . ' properties must be populated in order to create a ' . $class . ' record');
			return FALSE;
		}
		
		// hook for tasks to be executed before creation
		$this->beforeCreate();
		
		// get list of class property names
		$props = array_keys(static::getBinds());
		
		// insert the object as db record
		$dbObj = $this->prepareData($props);
		$res = $this->db->insertObject(static::TABLE_NAME, $dbObj);

		// get last insert id if not compound key
		if (!static::hasCompoundKey()) {

			$lastInsertId = $this->db->getLastInsertId();
		
			$key = $this->keyProperties[0];
			
			if ('int' == $this->getPropertyType($key)) {
				$this->{$key} = (int)$lastInsertId;
			} else {
				$this->{$key} = $lastInsertId;
			}
			
		}

		// set logs
		$keyParts = array();
			
		foreach ($this->keyProperties as $prop) {
			$keyParts[] = $prop . '=' . $this->{$prop};
		}
		
		// log as application event
		$app->logEvent('Created a new ' . $class . ' object with ' . implode(', ' , $keyParts));
		
		// hook for tasks to be executed after creation
		$this->afterCreate();
		
		return (bool)$res;
	
	}
917571
public function postCreate()
    {

        // Check if we should store creations in our revision history
        // Set this value to true in your model if you want to
        if(empty($this->revisionCreationsEnabled))
        {
            // We should not store creations.
            return false;
        }

        if ((!isset($this->revisionEnabled) || $this->revisionEnabled))
        {
            $revisions[] = array(
                'revisionable_type' => $this->getMorphClass(),
                'revisionable_id' => $this->getKey(),
                'key' => self::CREATED_AT,
                'old_value' => null,
                'new_value' => $this->{self::CREATED_AT},
                'user_id' => $this->getSystemUserId(),
                'created_at' => new \DateTime(),
                'updated_at' => new \DateTime(),
            );

            $revision = static::newModel();
            \DB::table($revision->getTable())->insert($revisions);
        }
    }