async def check(data, records): for column, fkvalues_lst in data.items(): for fkvalues in fkvalues_lst: # got nothing, skip if not records: continue pks = [] all_ni = True for i in records: val = i.get(column, NotImplemented) if val != NotImplemented: all_ni = False pks.append(val) if all_ni: logger.debug( "load foreign key failed, do you have read permission to the column %r?" % column) continue # 3. query foreign keys vcls = self.app.tables[fkvalues['table']] v = vcls(self.app, self._request) # fake view await v._prepare() info2 = SQLQueryInfo() info2.set_select(ALL_COLUMNS) info2.add_condition(PRIMARY_KEY, SQL_OP.IN, pks) info2.bind(v) # ability = vcls.permission.request_role(self.current_user, fkvalues['role']) # info2.check_query_permission_full(self.current_user, fktable, ability) try: fk_records, count = await v._sql.select_page(info2, size=-1) except RecordNotFound: # 外键没有找到值,也许全部都是null,这很常见 continue if not fk_records: continue fk_records = list(fk_records) await v.check_records_permission(info2, fk_records) fk_dict = {} for i in fk_records: # 主键: 数据 fk_dict[i[vcls.primary_key]] = i column_to_set = fkvalues.get('as', column) or column for _, record in enumerate(records): k = record.get(column, NotImplemented) if k in fk_dict: record[column_to_set] = fk_dict[k] if fkvalues['loadfk']: await check(fkvalues['loadfk'], fk_records)
async def test_condition_bind_error_column_not_found(): sqi = SQLQueryInfo() sqi.parse_then_add_condition('name1', '=', '1') view: PeeweeView = await make_mocked_view_instance(app, ATestView, 'GET', '/api/test1') with pytest.raises(ColumnNotFound) as e: sqi.bind(view) assert 'name1' in e.value.args[0]
async def test_condition_bind_error_convert_failed(): sqi = SQLQueryInfo() sqi.parse_then_add_condition('name', '=', {}) view: PeeweeView = await make_mocked_view_instance(app, ATestView, 'GET', '/api/test1') with pytest.raises(InvalidParams) as e: sqi.bind(view) assert 'name' in e.value.args[0] assert "Couldn't interpret" in str(e.value)
async def test_pg_array_contains_ok2(): view = ATestView(app) sqi = SQLQueryInfo() sqi.add_condition('name', SQL_OP.CONTAINS, [b'aa', b'bb']) sqi.bind(view)
async def test_pg_array_contains_bad_type3(): view = ATestView(app) sqi = SQLQueryInfo() with pytest.raises(InvalidParams): sqi.add_condition('name', SQL_OP.CONTAINS, [b'aa', 11]) sqi.bind(view)
async def test_condition_bind(): sqi = SQLQueryInfo() sqi.parse_then_add_condition('name', '=', '1') view: PeeweeView = await make_mocked_view_instance(app, ATestView, 'GET', '/api/test1') sqi.bind(view)