Synchronize all table fields

@Route ('GapOrm:synchronize')
18166
public function indexAction()
    {
        $models = $this->getAllModels();

        foreach($models as $model) {
            $this->checkTable(new $model['namespace']);
        }
    }
664172
public function upsert($table, $insertFieldValues, $updateFieldValues = [], $primaryKey = null)
    {
        if (!$primaryKey) {
            $primaryKey = (string)key($insertFieldValues);
        }

        if (!$updateFieldValues) {
            $updateFieldValues = $insertFieldValues;
        }

        $fields = array_keys($insertFieldValues);

        $bind = $insertFieldValues;
        $updates = [];
        foreach ($updateFieldValues as $k => $v) {
            $field = is_string($k) ? $k : $v;
            if ($primaryKey === $field) {
                continue;
            }

            if (is_int($k)) {
                $updates[] = "[$field]=:{$field}_dku";
                $bind["{$field}_dku"] = $insertFieldValues[$field];
            } elseif ($v instanceof AssignmentInterface) {
                $v->setFieldName($k);
                $updates[] = $v->getSql();
                /** @noinspection SlowArrayOperationsInLoopInspection */
                $bind = array_merge($bind, $v->getBind());
            } else {
                $updates[] = $v;
            }
        }

        $insertFieldsSql = '[' . implode('],[', $fields) . ']';
        $insertValuesSql = ':' . implode(',:', $fields);

        $updateFieldsSql = implode(',', $updates);

        $sql = 'INSERT' . " INTO {$this->_escapeIdentifier($table)}($insertFieldsSql) VALUES($insertValuesSql) ON DUPLICATE KEY UPDATE $updateFieldsSql";

        return $this->execute('insert', $sql, $bind);
    }
1230849
function synchronize() {

		$tCounter = 0;

		if ($this->changed) {
			$tFile = fopen ( $this->fileName, 'a' );

			while ( ! flock ( $tFile, LOCK_EX ) ) {
				usleep ( 5 );
				$tCounter ++;
				if ($tCounter == 100) {
					return false;
				}
			}

			$tContent = serialize ( $this->elements );

			ftruncate ( $tFile, 0 );

			if ($this->useZip) {
				$tContent = gzcompress ( $tContent );
			}

			fputs ( $tFile, $tContent );

			flock ( $tFile, LOCK_UN );
			fclose ( $tFile );
			return true;
		}
			
		return true;
	}
172309
function synchronize() {
    if (syncPointer != -1) {
        log.logMessage("verbose", "redis synchronization!");
        var syncMessage = {};
        syncMessage.data = messages.splice(syncPointer, messages.length - syncPointer);
        setTimeout(function () {
            pub.publish("message", JSON.stringify(syncMessage));
        }, 200);
        syncPointer = -1;
    }
}
14489
public function touch()
    {
        $key = $this->getRelated()->getKeyName();

        $columns = [
            $this->related->getUpdatedAtColumn() => $this->related->freshTimestampString(),
        ];

        // If we actually have IDs for the relation, we will run the query to update all
        // the related model's timestamps, to make sure these all reflect the changes
        // to the parent models. This will help us keep any caching synced up here.
        if (count($ids = $this->allRelatedIds()) > 0) {
            $this->getRelated()->newQuery()->whereIn($key, $ids)->update($columns);
        }
    }
230545
def sync(self, ids, detaching=True):
        
        changes = {"attached": [], "detached": [], "updated": []}

        if isinstance(ids, Collection):
            ids = ids.model_keys()

        current = self._new_pivot_query().lists(self._other_key).all()

        records = self._format_sync_list(ids)

        detach = [x for x in current if x not in records.keys()]

        if detaching and len(detach) > 0:
            self.detach(detach)

            changes["detached"] = detach

        changes.update(self._attach_new(records, current, False))

        if len(changes["attached"]) or len(changes["updated"]):
            self.touch_if_touching()

        return changes
75853
public void syncRecordToBase(Record recBase, Record recAlt, boolean syncSelection)
    {
        if ((recAlt != null) && (recBase != null))
        {
            recBase.moveFields(recAlt, null, true, DBConstants.READ_MOVE, false, false, true, syncSelection);
            recBase.setEditMode(recAlt.getEditMode());
        }
        if ((recBase.getEditMode() == DBConstants.EDIT_CURRENT) || (recBase.getEditMode() == DBConstants.EDIT_IN_PROGRESS))
            recBase.handleValidRecord(); // Do listeners, Display Fields
        else if (recBase.getEditMode() == DBConstants.EDIT_ADD)
            recBase.handleNewRecord(); // Do listeners, Display Fields
        //?recBase.setKeyArea(recAlt.getDefaultOrder());
    }
216
def _sync_table(self, columns):
        """"""
        if self._table is None:
            # Load an existing table from the database.
            self._reflect_table()
        if self._table is None:
            # Create the table with an initial set of columns.
            if not self._auto_create:
                raise DatasetException("Table does not exist: %s" % self.name)
            # Keep the lock scope small because this is run very often.
            with self.db.lock:
                self._threading_warn()
                self._table = SQLATable(self.name,
                                        self.db.metadata,
                                        schema=self.db.schema)
                if self._primary_id is not False:
                    # This can go wrong on DBMS like MySQL and SQLite where
                    # tables cannot have no columns.
                    primary_id = self._primary_id or self.PRIMARY_DEFAULT
                    primary_type = self._primary_type or Types.integer
                    increment = primary_type in [Types.integer, Types.bigint]
                    column = Column(primary_id, primary_type,
                                    primary_key=True,
                                    autoincrement=increment)
                    self._table.append_column(column)
                for column in columns:
                    if not column.name == self._primary_id:
                        self._table.append_column(column)
                self._table.create(self.db.executable, checkfirst=True)
        elif len(columns):
            with self.db.lock:
                self._reflect_table()
                self._threading_warn()
                for column in columns:
                    if not self.has_column(column.name):
                        self.db.op.add_column(self.name, column, self.db.schema)
                self._reflect_table()
23508
public function drupalLocalSync()
    {
        $this->executeCommandHook(__FUNCTION__, 'before');
        /** @var DrupalProjectType $instance */
        $instance = $this->getProjectInstance();

        if ($instance->getProjectVersion() >= 8) {
            $drush = new DrushCommand();

            $local_alias = $this->determineDrushLocalAlias();
            $remote_alias = $this->determineDrushRemoteAlias();

            if (isset($local_alias) && isset($remote_alias)) {
              // Drupal 8 tables to skip when syncing or dumping SQL.
                $skip_tables = implode(',', [
                    'cache_bootstrap',
                    'cache_config',
                    'cache_container',
                    'cache_data',
                    'cache_default',
                    'cache_discovery',
                    'cache_dynamic_page_cache',
                    'cache_entity',
                    'cache_menu',
                    'cache_render',
                    'history',
                    'search_index',
                    'sessions',
                    'watchdog'
                ]);

                $drush->command(
                    "sql-sync --sanitize --skip-tables-key='$skip_tables' '@$remote_alias' '@$local_alias'",
                    true
                );
            }

            $drush
                ->command('cim')
                ->command('updb --entity-updates')
                ->command('cr');

            $instance->runDrushCommand($drush);
        }
        $this->executeCommandHook(__FUNCTION__, 'after');

        return $this;
    }
564084
public function syncDatabase()
  {
    $tmpname = '/tmp/odango.php.cache';

    if (!file_exists($tmpname)) {
      $curl = new Curl();
      $curl->setOpt(CURLOPT_ENCODING, "gzip");
      $curl->download($this->titleDumpUrl, $tmpname);
      $curl->close();
    }

    $this->db->exec('START TRANSACTION');
    $this->db->exec('DELETE FROM ' . $this->table);

    $xml = simplexml_load_file($tmpname);
    foreach ($xml as $child) {
      $aid = (int)$child['aid'];
      $added = [];
      foreach($child->title as $title) {
        $type = (string)$title['type'];
        $lang = (string)$title->attributes('xml', true)['lang'];

        if ($lang == 'x-jat' || $lang == 'en') {

          if (!in_array((string)$title, $added)) {
            $added[] = (string)$title;

            $this->model->insert([
              'aniDbId'   => $aid,
              'title'     => (string)$title,
              'isDefault' => $type == 'main' ? 1 :0
            ]);
          } else if ( $type == 'main' ) {
            $this->model->update(['isDefault' => 1], 'AniDbId = '.$aid.' AND title = '.$this->db->quote((string)$title));
          }
        }
      }
    }

    $this->db->exec('COMMIT');
  }
870359
public function syncData()
    {
        if (Yii::$app->controller->interactive && $this->getRows() > self::LARGE_TABLE_PROMPT) {
            if (Console::confirm("{$this->getName()} has {$this->getRows()} entries. Do you want continue table sync?", true) === false) {
                return;
            }
        }

        $sqlMode = $this->prepare();

        try {
            Yii::$app->db->createCommand()->truncateTable($this->getName())->execute();

            $this->syncDataInternal();
        } finally {
            $this->cleanup($sqlMode);
        }
    }
1169507
@Override
    public void sync(List<Dml> dmls) {
        if (dmls == null || dmls.isEmpty()) {
            return;
        }
        try {
            rdbSyncService.sync(mappingConfigCache, dmls, envProperties);
            rdbMirrorDbSyncService.sync(dmls);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
585976
public static function syncAllGroups()
	{
		// @TODO: chunk this to 1000 groups at a time

		$db = \App::get('db');

		$query = "SELECT gidNumber FROM `#__xgroups`;";

		$db->setQuery($query);

		$result = $db->loadColumn();

		if ($result === false)
		{
			return false;
		}

		foreach ($result as $row)
		{
			self::syncGroup($row);

			if (is_array(self::$errors['fatal']) && !empty(self::$errors['fatal'][0]))
			{
				// If there's a fatal error, go ahead and stop
				return self::$errors;
			}
		}

		if (!empty(self::$errors['fatal'][0]) || !empty(self::$errors['warning'][0]))
		{
			return self::$errors;
		}
		else
		{
			return self::$success;
		}
	}
820382
public function syncRaw()
    {
        if ($model = $this->fresh()) {
            $this->setRawAttributes($model->getAttributes());

            return true;
        }

        return false;
    }
1079907
public void syncRecords(Record recAlt, Record recMain)
    {
        boolean bFieldsInSync = true;
        // Copy the language-specific fields
        m_buffer = new VectorBuffer(null);
        for (int iIndex = 0; iIndex < recMain.getFieldCount(); iIndex++)
        {
            BaseField fieldAlt = recAlt.getField(iIndex);
            BaseField fieldMain = null;
            if (bFieldsInSync)
                fieldMain = recMain.getField(iIndex);
            if ((fieldMain == null) || (!fieldMain.getFieldName().equals(fieldAlt.getFieldName())))
            {
                fieldMain = recMain.getField(fieldAlt.getFieldName());
                bFieldsInSync = false;
            }
            if (fieldMain != null) if (fieldAlt != null)
                if (this.isLanguageOverride(fieldMain))
            { // Move this field, but don't call doRecordChange (READ_MOVE)
                m_buffer.addNextField(fieldMain);   // Save these to restore later
                if (!fieldAlt.isNull())   // Don't move a null
                {
                    fieldMain.moveFieldToThis((BaseField)fieldAlt, DBConstants.DISPLAY, DBConstants.READ_MOVE);
                    fieldMain.setModified(false);
                }
            }
        }
    }
1272859
function applyModelViewRecordSynchronous (raw) {
    // get data column
    var dataColumn = this.query.model.columnName('data')
    // apply model views to data
    _.each(this.modelViews.record.synchronous, modelView => {
        // if this model view applies to meta data then pass entire db record
        var data = modelView.meta ? raw : raw[dataColumn]
        // call each function with modelView and data
        modelView.each(modelView, data)
    })
}
242116
def sync!
      events = @matrix.sync since: @since
      process_sync events
    rescue ApiError => err
      broadcast(:sync_error, err)
    end