Writes the assets database in a JSON file

@param array $full_db
@return false|string
424783
public function writeJsonDatabase(array $full_db)
    {
        $assets_file = $this->assets_installer->getVendorDir() . '/' . $this->assets_installer->getAssetsDbFilename();
        $this->assets_installer->getIo()->write(
            sprintf('Writing assets json DB to <info>%s</info>',
                str_replace(dirname($this->assets_installer->getVendorDir()).'/', '', $assets_file)
            )
        );
        try {
            $json = new JsonFile($assets_file);
            if ($json->exists()) {
                unlink($assets_file);
            }
            $json->write($full_db);
            return $assets_file;
        } catch (\Exception $e) {
            if (file_put_contents($assets_file, json_encode($full_db, version_compare(PHP_VERSION, '5.4')>0 ? JSON_PRETTY_PRINT : 0))) {
                return $assets_file;
            }
        }
        return false;
    }
988490
public function write(
        /*# string */ $session_id,
        /*# string */ $session_data
    )/*# : bool */ {
        $file = $this->getSessionFile($session_id);
        return file_put_contents($file, $session_data) !== false;
    }
357639
public function getJson()
    {
      return json_encode(
        array(
          'name' => $this->name,
          'mime' => $this->mime,
          'height' => $this->height,
          'width' => $this->width,
          'size' => $this->_files['size'],
          'location' => $this->location,
          'fullpath' => $this->fullPath,
        )
      );
    }
1338407
def db_for_write(self, model, **hints):
        
        if model._meta.app_label == 'duashttp':
            if not DUAS_ENABLE_DB_WRITE:
                raise ImproperlyConfigured(
                    "Set `DUAS_ENABLE_DB_WRITE` to True in your settings to enable "
                    "write operations on unity asset server database"
                )
            return DUAS_DB_ROUTE_PREFIX
        return None
373068
def dump(self, as_json=True, commit_batch_size=100):
        
        connection = sqlite3.connect(self.destination)
        format_ = 'json' if as_json else 'xml'
        if not self._db_exists(connection):
            connection.execute(
                "CREATE TABLE grants (data text, format text)")

        # This will call the RemoteOAIRELoader.iter_grants and fetch
        # records from remote location.
        grants_iterator = self.loader.iter_grants(as_json=as_json)
        for idx, grant_data in enumerate(grants_iterator, 1):
            if as_json:
                grant_data = json.dumps(grant_data, indent=2)
            connection.execute(
                "INSERT INTO grants VALUES (?, ?)", (grant_data, format_))

            # Commit to database every N records
            if idx % commit_batch_size == 0:
                connection.commit()
        connection.commit()
        connection.close()
130102
public function init_db($db)
    {
        $engine = $db->db_provider;

        // read schema file from /SQL/*
        $fname = INSTALL_PATH . "SQL/$engine.initial.sql";
        if ($sql = @file_get_contents($fname)) {
            $db->set_option('table_prefix', $this->config['db_prefix']);
            $db->exec_script($sql);
        }
        else {
            $this->fail('DB Schema', "Cannot read the schema file: $fname");
            return false;
        }

        if ($err = $this->get_error()) {
            $this->fail('DB Schema', "Error creating database schema: $err");
            return false;
        }

        return true;
    }
1011475
public function getFullDb()
    {
        $filesystem = new Filesystem();
        $config = $this->_composer->getConfig();
        $assets_db = $this->_autoloader->getRegistry();
        $vendor_dir = $this->_autoloader->getAssetsInstaller()->getVendorDir();
        $app_base_path = $this->_autoloader->getAssetsInstaller()->getAppBasePath();
        $assets_dir = str_replace($app_base_path . '/', '', $this->_autoloader->getAssetsInstaller()->getAssetsDir());
        $assets_vendor_dir = str_replace($app_base_path . '/' . $assets_dir . '/', '', $this->_autoloader->getAssetsInstaller()->getAssetsVendorDir());
        $document_root = $this->_autoloader->getAssetsInstaller()->getDocumentRoot();
        $extra = $this->_package->getExtra();

        $root_data = $this->_autoloader->getAssetsInstaller()->parseComposerExtra($this->_package, $app_base_path, '');
        if (!empty($root_data)) {
            $root_data['relative_path'] = '../';
            $assets_db[$this->_package->getPrettyName()] = $root_data;
        }

        $vendor_path = strtr(realpath($vendor_dir), '\\', '/');
        $rel_vendor_path = $filesystem->findShortestPath(getcwd(), $vendor_path, true);

        $local_repo = $this->_composer->getRepositoryManager()->getLocalRepository();
        $package_map = $this->buildPackageMap($this->_composer->getInstallationManager(), $this->_package, $local_repo->getPackages());

        foreach ($package_map as $i=>$package) {
            if ($i===0) {
                continue;
            }
            $package_object = $package[0];
            $package_install_path = $package[1];
            if (empty($package_install_path)) {
                $package_install_path = $app_base_path;
            }
            $package_name = $package_object->getPrettyName();
            $data = $this->_autoloader->getAssetsInstaller()->parseComposerExtra(
                $package_object,
                $this->_autoloader->getAssetsInstaller()->getAssetsInstallPath($package_object),
                str_replace($app_base_path . '/', '', $vendor_path) . '/' . $package_object->getPrettyName()
            );
            if (!empty($data)) {
                $assets_db[$package_name] = $data;
            }
        }

        $full_db = array(
            'assets-dir' => $assets_dir,
            'assets-vendor-dir' => $assets_vendor_dir,
            'document-root' => $document_root,
            'packages' => $assets_db
        );
        return $full_db;
    }
387898
private synchronized void rewriteFile() throws FileNotFoundException, IOException {
        JsonArrayBuilder jsonToStore = Json.createArrayBuilder();

        // Iterate through the assets in id order
        Map<String, JsonObject> assetMap = assets == null ? Collections.<String, JsonObject> emptyMap() : assets;
        for (int i = 1; i < idCounter.get(); i++) {
            JsonObject json = assetMap.get(Integer.toString(i));
            if (json == null) {
                jsonToStore.addNull();
            } else {
                jsonToStore.add(json);
            }
        }
        // Write the assets back to the file
        Map<String, Object> config = new HashMap<String, Object>();
        config.put(JsonGenerator.PRETTY_PRINTING, true);
        JsonWriterFactory writerFactory = Json.createWriterFactory(config);
        try (FileOutputStream out = new FileOutputStream(file);
                        JsonWriter streamWriter = writerFactory.createWriter(out)) {
            streamWriter.write(jsonToStore.build());
        }
    }
807526
function write (database) {
  var deferred = q.defer();

  // Write database to file under database name
  fs.writeFile(globalConfig.db.location + database + '.db.json', JSON.stringify(databases[database]), function (err) {
    if(err) return deferred.reject(err);

    deferred.resolve();
  });

  return deferred.promise;
}
1297564
public function renderJson()
    {
        $totalCount = $this->getDatasource()->totalCount();
        $rows = $this->getDatasource()->listRows();

        $tmpData = [];
        foreach ($rows as $row) {
            $tmp = [];

            $this->currentRow = new DefaultRow();
            if ($this->rowCallback instanceof \Closure) {
                $this->rowCallback->call($this, $row);
            }

            foreach ($this->getColumns() as $key => $column) {
                $this->currentColumn = $key;
                $tmp[$column->getName()] = $column->format($row);
            }

            $tmpData[] = $tmp;
        }

        $data = [
            'draw' => $this->getRequest()->get('draw'), // @todo param names configurable
            'recordsTotal' => $totalCount,
            'recordsFiltered' => $totalCount,
            'data' => $tmpData,
        ];

        header('Content-Type: application/json');
        echo json_encode($data);die;
    }
911275
public function write($data, $lock = false) {
        if (!is_string($data) && !is_integer($data)) {
            $data = var_export($data, true);
        }
        if (is_bool($lock)) {
            $lock = $lock ? LOCK_EX : 0;
        }
        return file_put_contents($this->fullName, $data, $lock);
    }
718173
public function create ($exclude = array (), &$db = FALSE)
	{
		
		// Get columns and values
		
		$create	= $this->createColumnsAndValues ($exclude);
		
		// Get database master for write
		
		if ($db === FALSE)
		{
			$db	=& $this->getDbMaster ();
		}
		
		// Prepare query
		
		$query	= $db->prepare ('
		INSERT INTO `' . static::$dbTable . '` (' . $create['columns'] . ')
		VALUES ( ' . $create['values'] . ')
		');
		
		// Bind attributes
		
		$this->bindAttributes ($query, $exclude);
		
		// Execute
		
		if (!$this->executeCreateUpdateQuery ($query))
		{
			return FALSE;
		}
		
		// Set the pk

		if (!$this->attributeHasValue (static::$pk) || !$this->iget (static::$pk))
		{
			$this->iset (static::$pk, $db->lastInsertID ());
		}
		
		// Changelog
		
		if ($this->changelog ('create'))
		{
			$log =& $this->getResource ('changelog');
			$log->hookTransactions ($db);
			$log::_Log ('create', static::_Read ($this->iget (static::$pk), $db));
		}

		// return TRUE

		return TRUE;
		
	}
944783
protected function jsonable()
    {
        return DB::connection()->getPdo()->getAttribute(PDO::ATTR_DRIVER_NAME) === 'mysql'
               && version_compare(DB::connection()->getPdo()->getAttribute(PDO::ATTR_SERVER_VERSION), '5.7.8', 'ge')
            ? 'json' : 'text';
    }
335150
public function init($main_db, $clone_db, $table_list = null)
    {

        try {
            if (empty($main_db) && empty($clone_db)) return false;

            if (!$this->select_db((string)$main_db)) {
                throw new DatabaseException('Could not select Main Database ' . $main_db);
            }

            $this->clone_dbname = $clone_db;
            $this->main_dbname  = $main_db;

            $sql = "SHOW DATABASES";

            if (($this->database_list = $this->fetch_simple_list($this->query((string)$sql))) == false) {
                throw new DatabaseException('No Databases on the Main Server');
            }

            $this->clone_exists = (!in_array($clone_db, $this->database_list)) ? false : true;

            if (empty($table_list)) {
                $sql              = "SHOW TABLES";
                $this->table_list = $this->fetch_simple_list($this->query($sql));
            } elseif (!is_array($table_list)) {
                $this->table_list = array(
                    $table_list
                );
            } else {
                $this->table_list = $table_list;
            }

            if ($this->clone_exists === false && !$this->clone_database($main_db, $clone_db)) {
                throw new DatabaseException('Couldnt replicate database');
            }

            foreach ($this->table_list as $table_name) {
                if ($this->clone_exists) {
                    $sql = ($this->force_rebuild) ? "DROP TABLE `{$clone_db}`.`{$table_name}`" : "TRUNCATE `{$clone_db}`.`{$table_name}`";
                    $this->query($sql);
                }
                $sql = "CREATE TABLE `{$clone_db}`.`{$table_name}` LIKE `{$main_db}`.`{$table_name}`";
                if (!$this->query($sql)) continue;
                $sql = "INSERT INTO `{$clone_db}`.`{$table_name}` SELECT * FROM `{$main_db}`.`{$table_name}`";
                if (!$this->query($sql)) continue;
            }

        } catch (DatabaseException $e) {
            throw $e;
        }

        return true;
    }
302316
public function exportItem($id, $fullExport = false)
    {
        $transform = Craft::$app->assetTransforms->getTransformById($id);
        if (!$transform) {
            return false;
        }

        $this->addManifest($transform->handle);

        $newTransform = [
            'name' => $transform->name,
            'handle' => $transform->handle,
            'width' => $transform->width,
            'height' => $transform->height,
            'format' => $transform->format,
            'mode' => $transform->mode,
            'position' => $transform->position,
            'quality' => $transform->quality,
            'interlace' => $transform->interlace
        ];

        return $newTransform;
    }
313335
public function jsonCommand($services = [], $table_pattern = '')
    {
        foreach ($services ?: $this->_getDbServices() as $service) {
            /** @var \ManaPHP\DbInterface $db */
            $db = $this->_di->getShared($service);
            foreach ($this->_getTables($service, $table_pattern) as $table) {
                $fileName = "@tmp/db_json/$service/$table.json";

                $this->console->progress(['`:table` processing...', 'table' => $table], '');

                $this->filesystem->dirCreate(dirname($fileName));
                $rows = $db->fetchAll("SELECT * FROM [$table]");
                $file = fopen($this->alias->resolve($fileName), 'wb');

                $startTime = microtime(true);
                foreach ($rows as $row) {
                    fwrite($file, json_encode($row) . PHP_EOL);
                }
                fclose($file);

                $this->console->progress([
                    'write to `:file` success: :count [:time]',
                    'file' => $fileName,
                    'count' => count($rows),
                    'time' => round(microtime(true) - $startTime, 4)
                ]);
            }
        }
    }
1049797
def save
      json = MultiJson.encode(attributes)
      File.open(file, 'w') {|f| f.write(json) }
    end