Need to override createQuery method because of list order & joins

{@inheritdoc}
171052
public function createQuery($context = 'list')
    {
        $query = parent::createQuery($context);
        $query->leftJoin($query->getRootAlias().'.article', 'article')->addSelect('article')
              ->leftJoin($query->getRootAlias().'.parent', 'parent')->addSelect('parent')
              ->leftJoin($query->getRootAlias().'.children', 'children')->addSelect('children')
              ->orderBy($query->getRootAlias().'.root, '.$query->getRootAlias().'.lft', 'ASC');

        return $query;
    }
675862
private boolean generateOnCreate(SQLiteDatabaseSchema schema, List<SQLiteEntity> orderedEntities) {
		boolean useForeignKey = false;
		MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("onCreate").addAnnotation(Override.class)
				.addModifiers(Modifier.PUBLIC);
		methodBuilder.addParameter(SQLiteDatabase.class, "database");
		methodBuilder.addJavadoc("onCreate\n");
		methodBuilder.addCode("// generate tables\n");
		if (schema.isLogEnabled()) {
			// generate log section - BEGIN
			methodBuilder.addComment("log section create BEGIN");
			methodBuilder.beginControlFlow("if (this.logEnabled)");

			methodBuilder.beginControlFlow("if (options.inMemory)");
			methodBuilder.addStatement("$T.info(\"Create database in memory\")", Logger.class);
			methodBuilder.nextControlFlow("else");
			methodBuilder.addStatement("$T.info(\"Create database '%s' version %s\",this.name, this.version)",
					Logger.class);
			methodBuilder.endControlFlow();

			// generate log section - END
			methodBuilder.endControlFlow();
			methodBuilder.addComment("log section create END");
		}
		for (SQLiteEntity item : orderedEntities) {
			if (schema.isLogEnabled()) {
				// generate log section - BEGIN
				methodBuilder.addComment("log section create BEGIN");
				methodBuilder.beginControlFlow("if (this.logEnabled)");

				methodBuilder.addStatement("$T.info(\"DDL: %s\",$T.CREATE_TABLE_SQL)", Logger.class,
						BindTableGenerator.tableClassName(null, item));

				// generate log section - END
				methodBuilder.endControlFlow();
				methodBuilder.addComment("log section create END");
			}
			methodBuilder.addStatement("database.execSQL($T.CREATE_TABLE_SQL)",
					BindTableGenerator.tableClassName(null, item));

			if (item.referedEntities.size() > 0) {
				useForeignKey = true;
			}
		}

		// use generated entities too
		// if we have generated entities, we use foreign key for sure
		if (schema.generatedEntities.size() > 0)
			useForeignKey = true;
		for (GeneratedTypeElement item : schema.generatedEntities) {
			if (schema.isLogEnabled()) {
				// generate log section - BEGIN
				methodBuilder.addComment("log section BEGIN");
				methodBuilder.beginControlFlow("if (this.logEnabled)");

				methodBuilder.addStatement("$T.info(\"DDL: %s\",$T.CREATE_TABLE_SQL)", Logger.class,
						TypeUtility.className(BindTableGenerator.getTableClassName(item.getQualifiedName())));

				// generate log section - END
				methodBuilder.endControlFlow();
				methodBuilder.addComment("log section END");
			}
			methodBuilder.addStatement("database.execSQL($T.CREATE_TABLE_SQL)",
					TypeUtility.className(BindTableGenerator.getTableClassName(item.getQualifiedName())));

		}

		methodBuilder.beginControlFlow("if (options.databaseLifecycleHandler != null)");
		methodBuilder.addStatement("options.databaseLifecycleHandler.onCreate(database)");
		methodBuilder.endControlFlow();

		methodBuilder.addStatement("justCreated=true");

		classBuilder.addMethod(methodBuilder.build());

		return useForeignKey;
	}
98574
private static void addOrderPossiblyNested(CriteriaQuery query,
                                               From queryRoot,
                                               CriteriaBuilder criteriaBuilder,
                                               PersistentEntity entity,
                                               String sort,
                                               String order,
                                               boolean ignoreCase) {
        int firstDotPos = sort.indexOf(".");
        if (firstDotPos == -1) {
            addOrder(entity, query, queryRoot, criteriaBuilder, sort, order, ignoreCase);
        } else { // nested property
            String sortHead = sort.substring(0, firstDotPos);
            String sortTail = sort.substring(firstDotPos + 1);
            PersistentProperty property = entity.getPropertyByName(sortHead);
            if (property instanceof Embedded) {
                // embedded objects cannot reference entities (at time of writing), so no more recursion needed
                addOrder(entity, query, queryRoot, criteriaBuilder, sort, order, ignoreCase);
            } else if (property instanceof Association) {
                Association a = (Association) property;
                final Join join = queryRoot.join(sortHead);
                PersistentEntity associatedEntity = a.getAssociatedEntity();
                Class<?> propertyTargetClass = associatedEntity.getJavaClass();
                addOrderPossiblyNested(query, join, criteriaBuilder, associatedEntity, sortTail, order, ignoreCase); // Recurse on nested sort
            }
        }
    }
1033662
protected function performJoins(Builder $query = null)
    {
        $query = $query ?: $this->query;

        foreach ($this->throughParents as $i => $model) {
            $table = $model->getTable();

            $predecessor = $i > 0 ? $this->throughParents[$i - 1] : $this->related;

            $first = $table.'.'.$this->getForeignKeyName($predecessor);

            $second = $predecessor->getQualifiedKeyName();

            $query->join($table, $first, '=', $second);

            if ($this->hasSoftDeletes($model)) {
                $this->query->whereNull($model->getQualifiedDeletedAtColumn());
            }
        }
    }
1298382
function get(tableName, fieldNames, where, orderBy) {
    if (orderBy && !checkOrderBy(orderBy)) {
      throw new Error('Invalid arg: orderBy');
    }
    if (!db) {
      throw new Error('Not connected');
    }
    let sql = `SELECT ${fieldNames.join(',')} FROM ${tableName}`;
    if (where) {
      sql += ` WHERE ${where}`;
    }
    if (orderBy) {
      sql += ` ORDER BY ${orderBy.join(',')}`;
    }
    return new Promise(((resolve, reject) => {
      db.get(sql, [], (error, row) => {
        if (error) {
          reject(error);
        } else {
          resolve(row);
        }
      });
    }));
  }
1245685
protected function createSelectQuery(array $fields = [], array $criteria = [], array $orderBy = [], $distinct = true)
	{
		if ($this->objectManager instanceof \Doctrine\ORM\EntityManager) {
			/** @var \Doctrine\ORM\QueryBuilder $builder */
			$builder = $this->objectManager->createQueryBuilder();
			$builder->select(empty($fields) ? 'p' : 'p.' . implode(', p.', $fields));
			
			if (true === $distinct) {
				$builder->distinct();
			}
			
			$builder->from($this->className, 'p')
					->setFirstResult($this->getItemOffset())
					->setMaxResults($this->itemPerPage);
			
			foreach ($orderBy as $key => $value) {
				$builder->orderBy(sprintf('p.%s', $key), $value);
			}
		} elseif ($this->objectManager instanceof \Doctrine\ODM\MongoDB\DocumentManager) {
			/** @var \Doctrine\ODM\MongoDB\Query\Builder $builder */
			$builder = $this->objectManager->createQueryBuilder($this->className);
			
			if (false === empty($fields)) {
				$builder->select($fields);
			}
			
			$builder->skip($this->getItemOffset())
					->limit($this->itemPerPage);
			
			foreach ($orderBy as $key => $value) {
				$builder->sort($key, $value);
			}
		} else {
			throw new ObjectManagerNotSupportedException(sprintf('Doctrine object manager class "%s" is not supported.', get_class($this->objectManager)));
		}
		
		$this->qbHandler->applyExprFromArray($builder, 'p', $criteria);
		
		return $builder->getQuery();
	}
878674
private function addOrders(ModelCriteria &$query)
    {
        Logger::log(static::class . ' extract orders start ', LOG_DEBUG);
        $orderAdded = FALSE;
        $tableMap = $this->getTableMap();
        foreach ($this->order->getOrders() as $field => $direction) {
            if ($column = ApiHelper::checkFieldExists($tableMap, $field)) {
                $orderAdded = TRUE;
                if ($direction === Order::ASC) {
                    $query->addAscendingOrderByColumn($column->getPhpName());
                } else {
                    $query->addDescendingOrderByColumn($column->getPhpName());
                }
            }
        }
        if (!$orderAdded) {
            $pks = $this->getPkDbName();
            foreach(array_keys($pks) as $key) {
                $query->addAscendingOrderByColumn($key);
            }
        }
        Logger::log(static::class . ' extract orders end', LOG_DEBUG);
    }
1060847
public function createQuery($context = 'list')
    {
        /** @var QueryBuilder $query */
        $query = parent::createQuery($context);

        /** @var User $user */
        $user = $this->getConfigurationPool()->getContainer()->get('security.token_storage')->getToken()->getUser();

        if ($this->isGranted('ROLE_SUPER_ADMIN')) {
            return $query;
        }

        $query->leftJoin($query->getRootAliases()[0] . '.userGroups', 'ug');

        $query->andWhere('ug.id = :group_id');
        $query->setParameter('group_id', $user->getGroups());

        return $query;
    }
851904
public function buildSortingSQL(&$joins, &$where, &$sort, $order = 'ASC')
    {
        if ($this->isRandomOrder($order)) {
            $sort = 'ORDER BY RAND()';
        } else {
            $sort = sprintf(
                'ORDER BY (
                    SELECT %s
                    FROM tbl_entries_data_%d AS `ed`
                    WHERE entry_id = e.id
                ) %s, `e`.`id` %s',
                '`ed`.date',
                $this->get('id'),
                $order,
                $order
            );
        }
    }
1116252
@Override
    public <T> TypedQuery<T> createQuery(CriteriaQuery<T> arg0) {
        try
        {
            return ivEm.createQuery(arg0);
        } finally
        {
            if (!inJTATransaction())
            {
                ivEm.clear();
            }
        }
    }
463967
@Override
	public synchronized List<T> filter(List<Predicate> predicates, Map<String, OrderType> orders, Set<String> properties, int firstResult, int maxResult) {
		
		// Criteria Builder
		CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder();
		
		// Requete de criteres
		CriteriaQuery<T>criteriaQuery = criteriaBuilder.createQuery(entityClass);
		
		// Construction de la racine
		Root<T> root = criteriaQuery.from(entityClass);
		
		// On positionne l'Alias
		root.alias(ROOT_ALIAS);
		
		// Selection de la racine
		criteriaQuery.select(root);
		
		// Ajout des Prédicats
		addPredicates(criteriaBuilder, root, criteriaQuery, predicates);
		
		// Ajout des Odres
		addOrders(criteriaBuilder, root, criteriaQuery, orders);
		
		// Ajout des Modes de chargements
		addProperties(root, criteriaQuery, properties);
		
		// Construction de la requete basée sur les critères
		TypedQuery<T> query = getEntityManager().createQuery(criteriaQuery);
		
		// Traitement de l'index du premier resultat
		
		// Si l'index du premier element est < 0
		if(firstResult < 0) query.setFirstResult(0);
		else query.setFirstResult(firstResult);
		
		// Traitement du nombre max de resultat
		
		// Si le nombre max d'element est <= 0
		if(maxResult > 0) query.setMaxResults(maxResult);
		
		// Execution
		List<T> results = query.getResultList();
		
		// On retourne le résultat
		return results;
	}
887497
public Query<S> query(Filter<S> filter, OrderingList<S> ordering, QueryHints hints)
        throws FetchException
    {
        filter = filter.bind();

        Map<OrderingList<S>, Query<S>> map;
        synchronized (mFilterToQuery) {
            map = mFilterToQuery.get(filter);
            if (map == null) {
                if (filter == null) {
                    throw new IllegalArgumentException("Query filter must not be null");
                }
                map = new SoftValuedHashMap(7);
                mFilterToQuery.put(filter, map);
            }
        }

        Query<S> query;
        synchronized (map) {
            query = map.get(ordering);
            if (query == null) {
                FilterValues<S> values = filter.initialFilterValues();
                if (values == null && filter.isClosed()) {
                    query = new EmptyQuery<S>(this, ordering);
                } else {
                    StandardQuery<S> standardQuery = createQuery(filter, values, ordering, hints);
                    if (!mLazySetExecutor) {
                        try {
                            standardQuery.setExecutor();
                        } catch (RepositoryException e) {
                            throw e.toFetchException();
                        }
                    }
                    query = standardQuery;
                }
                map.put(ordering, query);
            }
        }

        return query;
    }
289405
private void generateQuery(SQLiteDatabaseSchema schema) {
		MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("query").addModifiers(Modifier.PUBLIC).addAnnotation(Override.class).returns(Cursor.class);
		methodBuilder.addParameter(Uri.class, "uri");
		methodBuilder.addParameter(ParameterSpec.builder(TypeUtility.arrayTypeName(String.class), "projection").build());
		methodBuilder.addParameter(String.class, "selection");
		methodBuilder.addParameter(ParameterSpec.builder(TypeUtility.arrayTypeName(String.class), "selectionArgs").build());
		methodBuilder.addParameter(String.class, "sortOrder");

		boolean hasOperation = hasOperationOfType(schema, methodBuilder, JQLType.SELECT);

		if (!hasOperation) {
			methodBuilder.addStatement("throw new $T(\"Unknown URI for $L operation: \" + uri)", IllegalArgumentException.class, JQLType.SELECT);
			classBuilder.addMethod(methodBuilder.build());
			return;
		}

		methodBuilder.addStatement("$T returnCursor=null", Cursor.class);

		for (SQLiteDaoDefinition daoDefinition : schema.getCollection()) {
			for (SQLiteModelMethod daoMethod : daoDefinition.getCollection()) {
				if (daoMethod.jql.operationType != JQLType.SELECT)
					continue;
				// methodBuilder.addJavadoc("method $L.$L\n",
				// daoDefinition.getName(), daoMethod.getName());
			}
		}

		defineJavadocHeaderForContentOperation(methodBuilder, "query");

		methodBuilder.beginControlFlow("switch (sURIMatcher.match(uri))");
		for (Entry<String, ContentEntry> item : uriSet.entrySet()) {
			if (item.getValue().select == null)
				continue;

			defineJavadocForContentUri(methodBuilder, item.getValue().select);

			// methodBuilder.addJavadoc("uri $L\n", item.getKey());

			methodBuilder.beginControlFlow("case $L:", item.getValue().pathIndex);
			methodBuilder.addCode("// URI: $L\n", item.getValue().select.contentProviderUri());
			methodBuilder.addStatement("returnCursor=dataSource.get$L().$L(uri, projection, selection, selectionArgs, sortOrder)", item.getValue().select.getParent().getName(),
					item.getValue().select.contentProviderMethodName);
			methodBuilder.addStatement("break");
			methodBuilder.endControlFlow();
		}
		methodBuilder.beginControlFlow("default:");
		methodBuilder.addStatement("throw new $T(\"Unknown URI for $L operation: \" + uri)", IllegalArgumentException.class, JQLType.SELECT);
		methodBuilder.endControlFlow();

		methodBuilder.endControlFlow();

		defineJavadocFooterForContentOperation(methodBuilder);

		if (hasOperation) {
			methodBuilder.addStatement("return returnCursor");
		}

		classBuilder.addMethod(methodBuilder.build());
	}
688684
public function createQuery()
    {
        $query = \Parable\ORM\Query::createInstance();
        $query->setTableName($this->getModel()->getTableName());

        if ($this->onlyCount) {
            $query->select(['count(*)']);
        }
        if (!empty($this->orderBy)) {
            $query->orderBy($this->orderBy['key'], $this->orderBy['direction']);
        }
        if (!empty($this->limitOffset)) {
            $query->limitOffset($this->limitOffset['limit'], $this->limitOffset['offset']);
        }
        if ($this->returnOne) {
            $query->limitOffset(1);
        }

        return $query;
    }
49430
function _makeJoiner (type) {
	return function (clause, options) {
		if (isQueryizeObject(clause)) {
			if (typeof options !== 'object') throw new Error('You must define join options when joining against a queryize subquery.');

			options = Object.create(options);
			options.table = clause;
			clause = options;
		} else if (typeof clause === 'object') {
			if (isArray(clause)) throw new TypeError('Join clauses can only be strings or object definitions');
			if (!clause.table) throw new Error('You must define a table to join against');
		} else if (typeof options === 'object') {
			options = Object.create(options);
			options.table = clause;
			clause = options;
		}

		if (typeof clause === 'object') {
			clause.type = type;
		} else {
			clause = clause.search(joinTest) > -1 ? clause.replace(joinTest, type + ' JOIN ') : type + ' JOIN ' + clause;
		}

		this.join(clause);

		return this;
	};
}
1310996
protected function createQueryBuilder($joins = null)
    {
        $this->queryBuilder = $this->em->createQueryBuilder()
            ->from($this->entityName, $this->encodeAlias($this->entityName));

        $this->assignJoins($this->queryBuilder, $joins);

        if (null !== $this->ids) {
            $this->in($this->idField, !empty($this->ids) ? $this->ids : [null]);
        }

        if (null !== $this->excludedIds && !empty($this->excludedIds)) {
            $this->notIn($this->idField, $this->excludedIds);
        }

        // set expressions
        if (!empty($this->expressions)) {
            foreach ($this->expressions as $expression) {
                $this->queryBuilder->andWhere('(' . $expression->getStatement($this->queryBuilder) . ')');
            }
        }

        $this->assignGroupBy($this->queryBuilder);

        if (null !== $this->search) {
            $searchParts = [];
            foreach ($this->searchFields as $searchField) {
                $searchParts[] = $searchField->getSearch();
            }

            $this->queryBuilder->andWhere('(' . implode(' OR ', $searchParts) . ')');
            $this->queryBuilder->setParameter('search', '%' . str_replace('*', '%', $this->search) . '%');
        }

        return $this->queryBuilder;
    }
1159035
protected function createBuilderQuery(
        Request $request,
        array $columns = [],
        bool $merge = true,
        bool $defaultOrder = true
    ): Builder {
        if ($merge) {
            $availableFields = array_merge($this->getModel()::getFillableFields(), $columns);

            if (($key = array_search('*', $availableFields)) !== false) {
                unset($availableFields[$key]);
            }
        } else {
            $availableFields = $columns;
        }

        $builder = $this->getModel()::select($availableFields)
            ->where(function (Builder $query) use ($request, $availableFields) {
                // add request filtering
                $this->filterByRequestParameters($query, $request, $availableFields);
            });

        // check if soft deleted records must be shown
        $builder = $this->checkForTrashed($builder, $request);

        // search through items
        $builder = $this->search($builder, $request);

        // set order
        if ($defaultOrder) {
            $builder = $this->orderData($builder, $request, $availableFields);
        }

        return $builder;
    }