private Query inferTableForQuery(Class<? extends AbstractModel> modelClass, Query query) { if (!query.hasTable() && modelClass != null) { SqlTable<?> table = getSqlTable(modelClass); if (table == null) { throw new IllegalArgumentException("Query has no FROM clause and model class " + modelClass.getSimpleName() + " has no associated table"); } query = query.from(table); // If argument was frozen, we may get a new object } return query; }
/** * Construct a new Select statement that queries all the {@link Field Fields} of the given {@link View} * * @param view the View to select from * @return a new Query object */ public static Query fromView(View view) { return Query.select(view.qualifiedFields()).from(view); }
/** * Set the {@link SqlTable table} this query selects from * * @param table the table to select from * @return this Query object, to allow chaining method calls */ public Query from(SqlTable<?> table) { if (immutable) { return fork().from(table); } if (this.table != table) { this.table = table; if (selectAllCache != null) { selectAllCache.clear(); } invalidateCompileCache(); } return this; }
/** * Construct a new Select statement that queries all the {@link Field}s of the given subquery * * @param subquery the inner Query object * @param subqueryAlias the name to alias the subquery * @return a new Query object */ public static Query fromSubquery(Query subquery, String subqueryAlias) { SubqueryTable table = subquery.as(subqueryAlias); return Query.select(table.qualifiedFields()).from(table); }
protected <TYPE extends AbstractModel> SquidCursor<TYPE> fetchFirstItem(Class<TYPE> modelClass, Query query) { boolean immutableQuery = query.isImmutable(); Field<Integer> beforeLimit = query.getLimit(); SqlTable<?> beforeTable = query.getTable(); query = query.limit(1); // If argument was frozen, we may get a new object SquidCursor<TYPE> cursor = query(modelClass, query); if (!immutableQuery) { query.from(beforeTable).limit(beforeLimit); // Reset for user } cursor.moveToFirst(); return cursor; }
/** * Build a {@link Query} combining this object's internal state with the arguments passed. If a * {@link ProjectionMap} is set, the projection elements will be evaluated and transformed accordingly. If the * sortOrder is null or empty, the default order will be used (if one was set). * * @param projection the raw column names to be selected * @param selection a raw selection string * @param selectionArgs array of strings which substitute replaceable arguments in the selection string * @param sortOrder a raw ordering clause * @return a {@link Query} using the projection, selection, selection args, and sort order */ public Query build(String[] projection, String selection, String[] selectionArgs, String sortOrder) { Query query = Query.select(computeProjection(projection)).from(dataSource); boolean hasUserSelection = !SqlUtils.isEmpty(selection); if (hasUserSelection) { query.where(Criterion.fromRawSelection(selection, selectionArgs)); } if (!SqlUtils.isEmpty(sortOrder)) { query.orderBy(Order.fromExpression(sortOrder)); } else if (defaultOrder != null && defaultOrder.length > 0) { query.orderBy(defaultOrder); } if (strictMode && hasUserSelection) { query.requestValidation(); } return query; }
public void testObservableEmitsCustomObject() { final AtomicBoolean objectsMatch = new AtomicBoolean(false); final Query originalQuery = Query.select().from(TestModel.TABLE); Observable<Query> observable = database.observeTableAndEmit(TestModel.TABLE, originalQuery, true); observable.subscribe(new Action1<Query>() { @Override public void call(Query query) { objectsMatch.set(originalQuery == query); } }); assertTrue(objectsMatch.get()); }
@Override public void run() { database.query(TestViewModel.class, Query.select().from(TestViewModel.VIEW)); } });
@Override public void run() { database.query(TestModel.class, Query.select().from(TestModel.TABLE)); } });
public void testAllFields() { Query query = Query.select().from(TestViewModel.VIEW) .leftJoin(Thing.TABLE, TestViewModel.TEST_MODEL_ID.eq(Thing.ID)); List<Field<?>> fields = query.getFields(); for (Property<?> p : TestViewModel.PROPERTIES) { assertTrue(fields.contains(p)); } for (Property<?> p : Thing.PROPERTIES) { assertTrue(fields.contains(p)); } assertEquals(TestViewModel.PROPERTIES.length + Thing.PROPERTIES.length, fields.size()); }
public void testValidationPropagatesToSubqueryJoinAndCompoundSelect() { Query subquery = Query.select(Thing.FOO).from(Thing.TABLE).where(Thing.BAR.gt(0)); Query joinSubquery = Query.select(Thing.BAR).from(Thing.TABLE).where(Thing.FOO.isNotEmpty()); Query compoundSubquery = Query.select(Thing.BAZ).from(Thing.TABLE).where(Thing.IS_ALIVE.isTrue()); SubqueryTable subqueryTable = subquery.as("t1"); SubqueryTable joinTable = joinSubquery.as("t2"); Query query = Query.select().from(subqueryTable).innerJoin(joinTable, (Criterion[]) null) .union(compoundSubquery); final int queryLength = query.compile(database.getCompileContext()).sql.length(); String withValidation = query.sqlForValidation(database.getCompileContext()); assertEquals(queryLength + 6, withValidation.length()); }
public void testEnumResolvedUsingName() { Query query = Query.select(TestModel.SOME_ENUM).from(TestModel.TABLE) .where(TestModel.SOME_ENUM.eq(TestEnum.APPLE)); CompiledStatement compiledStatement = query.compile(database.getCompileContext()); verifyCompiledSqlArgs(compiledStatement, 1, "APPLE"); }
public void testDatabaseProvidedArgumentResolver() { database.useCustomArgumentBinder = true; Query query = Query.select(TestModel.SOME_ENUM).from(TestModel.TABLE) .where(TestModel.SOME_ENUM.eq(TestEnum.APPLE)); CompiledStatement compiledStatement = query.compile(database.getCompileContext()); verifyCompiledSqlArgs(compiledStatement, 1, 0); }
@Override public void run() { // insert into testModels select luckyNumber from testModels where luckyNumber = 9; Query query = Query.select(TestModel.FIRST_NAME, TestModel.LAST_NAME, TestModel.BIRTHDAY) .from(TestModel.TABLE) .where(TestModel.LUCKY_NUMBER.eq(9)); Insert insert = Insert.into(TestModel.TABLE).select(query); insert.compile(database.getCompileContext()); } }, IllegalStateException.class);
public void testNeedsValidationUpdatedByQueryFunction() { Query subquery = Query.select(Function.max(Thing.ID)).from(Thing.TABLE).where(Criterion.literal(123)); subquery.requestValidation(); assertTrue(subquery.compile(database.getCompileContext()).sql.contains("WHERE (?)")); Query baseTestQuery = Query.select().from(Thing.TABLE).where(Thing.FOO.isNotEmpty()).freeze(); assertFalse(baseTestQuery.needsValidation()); Query testQuery = baseTestQuery.selectMore(subquery.asFunction()); assertTrue(testQuery.compile(database.getCompileContext()).needsValidation); assertTrue(testQuery.sqlForValidation(database.getCompileContext()).contains("WHERE ((?))")); }
@Override public void run() { // insert into testModels (firstName, lastName) select (firstName, lastName, creationDate) from // testModels where luckyNumber = 9; Query query = Query.select(TestModel.FIRST_NAME, TestModel.LAST_NAME, TestModel.BIRTHDAY) .from(TestModel.TABLE) .where(TestModel.LUCKY_NUMBER.eq(9)); Insert insert = Insert.into(TestModel.TABLE).columns(TestModel.FIRST_NAME, TestModel.LAST_NAME) .select(query); insert.compile(database.getCompileContext()); } }, IllegalStateException.class);
public void testIntersect() { Query query = Query.select().from(Employee.TABLE).where(Employee.MANAGER_ID.eq(1)) .intersect(Query.select().from(Employee.TABLE).where(Employee.ID.eq(2))) .orderBy(Employee.ID.asc()); SquidCursor<Employee> cursor = database.query(Employee.class, query); try { assertEquals(1, cursor.getCount()); cursor.moveToFirst(); assertEquals(cookieMonster, new Employee(cursor)); } finally { cursor.close(); } }
public void testQueryFreeze() { Query base = Query.select().from(Employee.TABLE).limit(1).freeze(); Query fork = base.limit(2); assertFalse(base == fork); assertEquals(Field.field("1"), base.getLimit()); assertEquals(Field.field("2"), fork.getLimit()); assertEquals(base.getTable(), fork.getTable()); }
public void testFork() { Query base = Query.select().from(Employee.TABLE).limit(1); Query fork = base.fork().limit(2); base.limit(3); assertFalse(base == fork); assertEquals(Field.field("3"), base.getLimit()); assertEquals(Field.field("2"), fork.getLimit()); assertEquals(base.getTable(), fork.getTable()); }
public void testInsertWithQuery() { double pi = Math.PI; Criterion criterion = Thing.QUX.gt(pi); int numThingsMatching = database.count(Thing.class, criterion); // insert into testModels select foo, bar, isAlive from things where qux > 3.1415...; Query query = Query.select(Thing.FOO, Thing.BAR, Thing.IS_ALIVE).from(Thing.TABLE).where(criterion); Insert insert = Insert.into(TestModel.TABLE).columns(TestModel.LAST_NAME, TestModel.LUCKY_NUMBER, TestModel.IS_HAPPY).select(query); CompiledStatement compiled = insert.compile(database.getCompileContext()); verifyCompiledSqlArgs(compiled, 1, pi); int testModelsBeforeInsert = database.countAll(TestModel.class); assertEquals(3, database.insert(insert)); int testModelsAfterInsert = database.countAll(TestModel.class); assertEquals(testModelsBeforeInsert + numThingsMatching, testModelsAfterInsert); }