WARNING: Don't use QuerySet inside QuerySet in this
method because recursion...

@throws \Exception
325002
protected function findAndFixCorruptedTree()
    {
        $table = $this->getModel()->tableName();

        $this
            ->deleteBranchWithoutRoot($table)
            ->deleteBranchWithoutParent($table)
            ->rebuildLftRgt($table);
    }
136553
protected function _next()
    {
        try {
            $this->_setIteration($this->_loop());
        } catch (RootException $exception) {
            $this->_throwIteratorException(
                $this->__('An error occurred while iterating'),
                null,
                $exception
            );
        }
    }
1354420
protected function extractResult()
    {
        if (!$this->getQuery()) {
            throw new \Exception(sprintf(
                'No defined query from %s. Did you forget to call method %s ?',
                Query::class,
                '"setQuery()"'
            ));
            exit;
        }

        $arrayResult = $this->getArrayResult();

        if (isset($arrayResult['error']) && isset($arrayResult['message']) && $arrayResult['error'] === true) {
            $this->getQuery()->getError()->setMessage($arrayResult['message']);
        } elseif (isset($arrayResult['response']) && $arrayResult['response']) {
            $response = $arrayResult['response'];
            $resultDataType = $this->getQuery()->getResultDataType();

            foreach ($response as $index => $result) {
                $sql = $this->getQuery()->addOrReplace($index, $result['string']);
                $sqlResult = $sql->getResult();

                if ($resultDataType instanceof DataInterface) {
                    $sqlResult->setDataType($resultDataType);
                }

                $sql->execute($result['executed']);
                $insertId = $result['result']['insertId'];

                $sqlResult->setColumnTypes($result['result']['types']);
                $sqlResult->setStart($result['result']['start']);
                $sqlResult->setEnd($result['result']['end']);
                $sqlResult->setAffected($result['result']['affected']);
                $sqlResult->setStartRow($result['result']['startRow']);
                $sqlResult->setTotalRows($result['result']['totalRows']);
                $sqlResult->setTotalShows($result['result']['totalShows']);
                $sqlResult->setInsertId(is_numeric($insertId) ? floatval($insertId) : $insertId);

                foreach ($result['result']['data'] as $data) {
                    if (!is_array($sqlResult->getDataType())) {
                        $item = $sqlResult->getDataType();
                        foreach ($data as $key => $value) {
                            $item->set($key, $value);
                        }
                        $data = $item;
                    }
                    $sqlResult->add($data);
                }
            }

            $this->getQuery()->removeFromIndex(count($response));
        }

        return $this->getQuery();
    }
1354790
public function close(): void
    {
        if ($this->stmt === null) {
            throw new \Exception('Statement has already been closed');
        }

        if (!$this->stmt->close()) {
            throw new SqlException('Failed to close statement', $this->stmt->error_list, $this->query, $this->params);
        }

        $this->stmt = null;
        $this->meta = null;
    }
11612
private function query()
    {
        foreach ($this->search_models as $model_name => $filters) {
            // Apply search against the original model.
            if ($model_name === 'self') {
                self::applySearch($this->query, $filters);
                continue;
            }

            // Apply search against the related model.
            $this->query->whereHas($model_name, function ($query) use ($filters) {
                self::applySearch($query, $filters);
            });
        }

        return $this->query;
    }
751195
public function update()
    {
        //translate model data to sql data
        if (is_null($this->schema)) {
            throw Exception::forNoSchema();
        }

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

        //queries to run
        $queries = [];
        //this is used to determine whether to add/alter/remove columns
        $exists = [];

        //if there's no system
        if (!$this->exists($data['name'])) {
            //go to create mode
            return $this->create($data, true);
        }

        $primary = $this->resource->getPrimaryKey($data['name']);
        $columns = $this->resource->getColumns($data['name']);
        $query = $this->resource->getAlterQuery($data['name']);

        //remove or change fields
        foreach ($columns as $current) {
            //don't do primary
            if ($primary === $current['Field']) {
                continue;
            }

            $exists[] = $name = $current['Field'];

            //if there is no field in the data
            if (!isset($data['columns'][$name])) {
                $query->removeField($name);
                continue;
            }

            $column = $data['columns'][$name];

            $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'];
            }

            $default = null;
            if (isset($attributes['default'])) {
                $default = $attributes['default'];
            }

            //if all matches
            if ($attributes['type'] === $current['Type']
                && $attributes['null'] == ($current['Null'] === 'YES')
                && $default === $current['Default']
            ) {
                continue;
            }

            //do the alter
            $query->changeField($name, $attributes);
        }

        //add fields
        foreach ($data['columns'] as $name => $column) {
            if (in_array($name, $exists)) {
                continue;
            }

            $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);
            }
        }

        $query = (string) $query;
        if ($query !== 'ALTER TABLE `' . $data['name'] . '` ;') {
            $queries[] = $query;
        }

        $installed = $this->resource->getTables($data['name'] . '_%');
        $relations = array_keys($data['relations']);

        //determine the relation tables that need to be removed
        foreach ($installed as $relation) {
            //uninstall if it's not in the schema
            if (!in_array($relation, $relations)) {
                $queries[] = 'DROP TABLE IF EXISTS `' . $relation . '`;';
            }
        }

        //determine the relation tables that need to be added
        foreach ($data['relations'] as $table => $relation) {
            //install if it's installed
            if (in_array($table, $installed)) {
                continue;
            }

            $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;
    }
771192
public function rewind()
    {
        if (!$this->rewindable && !$this->firstCross) {
            throw new \Exception('Unable to traverse not rewindable iterator multiple time');
        }
        $this->firstCross = false;
        $this->position = 0;
    }
392497
private function checkProperties()
    {
        if (!isset($this->listId)) {
            throw new \Exception('[listId] is not set', 1);
        }

        if (!isset($this->installationUrl)) {
            throw new \Exception('[installationUrl] is not set', 1);
        }

        if (!isset($this->apiKey)) {
            throw new \Exception('[apiKey] is not set', 1);
        }
    }
428540
public function batchUpdate()
    {
        if ($this->_entityName === null) {
            throw new \Exception('Please call « handleEntity(ClassMetadata $class) » before using this handler');
        }
        if (!$this->truncateTable()) {
            throw new \Exception('Could not truncate table ' . $this->getSearchIndexTable());
        }
        $em = $this->_em;
        $indexClass = $this->getSearchIndexClass();

        $batchSize = 100;
        $offset = 0;
        $query = $this->_em->createQueryBuilder()
            ->select('o')
            ->from($this->_entityName, 'o')
            ->setMaxResults($batchSize);

        do {
            $query->setFirstResult($offset);
            $entities = $query->getQuery()->execute();
            foreach ($entities as $entity) {
                $fields = $this->searchIndexes[$this->_class->getName()]['fields'];
                foreach ($fields as $field) {
                    $keywords = $entity->analyseField($field);
                    foreach ($keywords as $keyword) {
                        $index = new $indexClass();
                        $index->setObject($entity);
                        $index->setField($field);
                        $index->setKeyword($keyword);
                        $em->persist($index);
                    }
                }
            }

            $em->flush();
            $offset += $batchSize;
        } while (count($entities) > 0);
    }
1292896
def queryset(self, request, queryset):
        
        if self.value():
            try:
                section = SectionPage.objects.get(id=self.value())
                return queryset.child_of(section).all()
            except (ObjectDoesNotExist, MultipleObjectsReturned):
                return None
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;
    }
31623
public function categories()
    {
        $findPostType = PostType::findBySlug($this->getTable());
        if(!$findPostType) {
            throw new \Exception("Categories  relations could not be made because the post type of the post #".$this->postID." could ont be found!");
        }
        return $this->customHasManyThrough(
            'App\Models\Category', 'App\Models\CategoryRelation',
            'postID', 'categoryID', 'postID', 'categoryID', $this->getTable()."_categories"
        )
            ->where('postTypeID', $findPostType->postTypeID);
    }
761097
private function playQueries($executeQueries = false)
    {
        foreach ($this->migration->getQueries() as $idx => $query) {
            try {
                $this->runQuery($query, $executeQueries);
            } catch (\Exception $e) {
                // Only throw if more than one query is played
                if ($idx >= 1) {
                    throw new Exception($e->getMessage());
                }

                throw $e;
            }
        }
    }
1055361
public function clean()
    {
        if (null === $this->primaryModel->pk) {
            throw new Exception('Unable to clean models: the primary key of '.get_class($this->primaryModel).' is null.');
        }
        $db = $this->primaryModel->getConnection();
        $builder = QueryBuilderFactory::getQueryBuilder($db);

        return $db->delete($builder->getQuotedName(TableNameResolver::getTableName($this->relatedTable)), [$this->primaryModelColumn => $this->primaryModel->pk]);
    }
65829
public static function find($collection, $query = null, $fields = array())
  {
    static::checkConnexion();
    $collection = self::$db->$collection;
    if (is_string($query)) {
      $query = json_decode($query, true);
      if (!$query) {
        throw new \Exception('Requête JSON formulée incorrectement');
      }
    }
    if ($query) {
      return $collection->find($query, $fields);
    } else {
      return $collection->find(array(), $fields);
    }
  }
358418
public function read(Model $model, $queryData = array(), $recursive = null) {
		if (!isset($model->records) || !is_array($model->records) || empty($model->records)) {
			$this->_requestsLog[] = array(
				'query' => 'Model ' . $model->alias,
				'error' => __('No records found in model.'),
				'affected' => 0,
				'numRows' => 0,
				'took' => 0
			);
			return array($model->alias => array());
		}
		$startTime = microtime(true);
		$data = array();
		$i = 0;
		$limit = false;
		if ($recursive === null && isset($queryData['recursive'])) {
			$recursive = $queryData['recursive'];
		}

		if (!is_null($recursive)) {
			$_recursive = $model->recursive;
			$model->recursive = $recursive;
		}
		if (is_integer($queryData['limit']) && $queryData['limit'] > 0) {
			$limit = $queryData['page'] * $queryData['limit'];
		}
		foreach ($model->records as $pos => $record) {
			// Tests whether the record will be chosen
			if (!empty($queryData['conditions'])) {
				$queryData['conditions'] = (array)$queryData['conditions'];
				if (!$this->conditionsFilter($model, $record, $queryData['conditions'])) {
					continue;
				}
			}
			$data[$i][$model->alias] = $record;
			$i++;
			// Test limit
			if ($limit !== false && $i == $limit && empty($queryData['order'])) {
				break;
			}
		}
		if ($queryData['fields'] === 'COUNT') {
			$this->_registerLog($model, $queryData, microtime(true) - $startTime, 1);
			if ($limit !== false) {
				$data = array_slice($data, ($queryData['page'] - 1) * $queryData['limit'], $queryData['limit'], false);
			}
			return array(array(array('count' => count($data))));
		}
		// Order
		if (!empty($queryData['order'])) {
			if (is_string($queryData['order'][0])) {
				$field = $queryData['order'][0];
				$alias = $model->alias;
				if (strpos($field, '.') !== false) {
					list($alias, $field) = explode('.', $field, 2);
				}
				if ($alias === $model->alias) {
					$sort = 'ASC';
					if (strpos($field, ' ') !== false) {
						list($field, $sort) = explode(' ', $field, 2);
					}
					if ($data) {
						$data = Hash::sort($data, '{n}.' . $model->alias . '.' . $field, $sort);
					}
				}
			}
		}
		// Limit
		if ($limit !== false) {
			$data = array_slice($data, ($queryData['page'] - 1) * $queryData['limit'], $queryData['limit'], false);
		}
		// Filter fields
		if (!empty($queryData['fields'])) {
			$listOfFields = array();
			foreach ((array)$queryData['fields'] as $field) {
				if (strpos($field, '.') !== false) {
					list($alias, $field) = explode('.', $field, 2);
					if ($alias !== $model->alias) {
						continue;
					}
				}
				$listOfFields[] = $field;
			}
			foreach ($data as $id => $record) {
				foreach ($record[$model->alias] as $field => $value) {
					if (!in_array($field, $listOfFields)) {
						unset($data[$id][$model->alias][$field]);
					}
				}
			}
		}
		$this->_registerLog($model, $queryData, microtime(true) - $startTime, count($data));
		$_associations = $model->_associations;
		if ($model->recursive > -1) {
			foreach ($_associations as $type) {
				foreach ($model->{$type} as $assoc => $assocData) {
					$linkModel = $model->{$assoc};

					if ($model->useDbConfig == $linkModel->useDbConfig) {
						$db = $this;
					} else {
						$db = ConnectionManager::getDataSource($linkModel->useDbConfig);
					}

					if (isset($db)) {
						if (method_exists($db, 'queryAssociation')) {
							$stack = array($assoc);
							$db->queryAssociation($model, $linkModel, $type, $assoc, $assocData, $queryData, true, $data, $model->recursive - 1, $stack);
						}
						unset($db);
					}
				}
			}
		}
		if ($model->findQueryType === 'first') {
			if (!isset($data[0])) {
				$data = array();
			} else {
				$data = array($data[0]);
			}
		}

		if (!is_null($recursive)) {
			$model->recursive = $_recursive;
		}
		return $data;
	}
100701
def none(self):
        
        return EmptyQuerySet(model=self.model, using=self._using, connection=self._connection)