+ def _apply_valid_types(self, name, valid_types):
+ """Combines the enforced `valid_types` with any from the search string
+ itself and updates the query.
+
+ For example, a name of 'a,b:foo' and valid_types of b,c will search for
+ only `b`s named "foo".
+
+ Returns `(name, merged_valid_types, term)`, where `name` has had any type
+ prefix stripped, `merged_valid_types` combines the original
+ `valid_types` with the type prefix, and `term` is a query term for
+ limited to just the allowed types. If there are no type restrictions
+ at all, `term` will be None.
+ """
+
+ # Remove any type prefix (pokemon:133) first
+ user_valid_types = []
+ if ':' in name:
+ prefix_chunk, name = name.split(':', 1)
+ name = name.strip()
+
+ prefixes = prefix_chunk.split(',')
+ user_valid_types = [_.strip() for _ in prefixes]
+
+ # Merge the valid types together. Only types that appear in BOTH lists
+ # may be used.
+ # As a special case, if the user asked for types that are explicitly
+ # forbidden, completely ignore what the user requested.
+ # And, just to complicate matters: "type" and language need to be
+ # considered separately.
+ def merge_requirements(func):
+ user = filter(func, user_valid_types)
+ system = filter(func, valid_types)
+
+ if user and system:
+ merged = list(set(user) & set(system))
+ if merged:
+ return merged
+ else:
+ # No overlap; use the system restrictions
+ return system
+ else:
+ # One or the other is blank; use the one that's not
+ return user or system
+
+ # @foo means language must be foo; otherwise it's a table name
+ lang_requirements = merge_requirements(lambda req: req[0] == u'@')
+ type_requirements = merge_requirements(lambda req: req[0] != u'@')
+ all_requirements = lang_requirements + type_requirements
+
+ # Construct the term
+ lang_terms = []
+ for lang in lang_requirements:
+ # Allow for either country or language codes
+ lang_code = lang[1:]
+ lang_terms.append(whoosh.query.Term(u'iso639', lang_code))
+ lang_terms.append(whoosh.query.Term(u'iso3166', lang_code))
+
+ type_terms = []
+ for type in type_requirements:
+ table_name = self._parse_table_name(type)
+
+ # Quietly ignore bogus valid_types; more likely to DTRT
+ if table_name:
+ type_terms.append(whoosh.query.Term(u'table', table_name))
+
+ # Combine both kinds of restriction
+ all_terms = []
+ if type_terms:
+ all_terms.append(whoosh.query.Or(type_terms))
+ if lang_terms:
+ all_terms.append(whoosh.query.Or(lang_terms))
+
+ return name, all_requirements, whoosh.query.And(all_terms)
+
+