<commit_before># -*- coding: utf-8 -*-
# Copyright 2014 OpenMarket Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import collections

from ._base import SQLBaseStore, Table
from twisted.internet import defer

import logging
import copy
import json

logger = logging.getLogger(__name__)


class PushRuleStore(SQLBaseStore):
    @defer.inlineCallbacks
    def get_push_rules_for_user_name(self, user_name):
        sql = (
            "SELECT "+",".join(PushRuleTable.fields)+" "
            "FROM "+PushRuleTable.table_name+" "
            "WHERE user_name = ? "
            "ORDER BY priority_class DESC, priority DESC"
        )
        rows = yield self._execute(None, sql, user_name)

        dicts = []
        for r in rows:
            d = {}
            for i, f in enumerate(PushRuleTable.fields):
                d[f] = r[i]
            dicts.append(d)

        defer.returnValue(dicts)

    @defer.inlineCallbacks
    def add_push_rule(self, before, after, **kwargs):
        vals = copy.copy(kwargs)
        if 'conditions' in vals:
            vals['conditions'] = json.dumps(vals['conditions'])
        if 'actions' in vals:
            vals['actions'] = json.dumps(vals['actions'])
        # we could check the rest of the keys are valid column names
        # but sqlite will do that anyway so I think it's just pointless.
        if 'id' in vals:
            del vals['id']

        if before or after:
            ret = yield self.runInteraction(
                "_add_push_rule_relative_txn",
                self._add_push_rule_relative_txn,
                before=before,
                after=after,
                **vals
            )
            defer.returnValue(ret)
        else:
            ret = yield self.runInteraction(
                "_add_push_rule_highest_priority_txn",
                self._add_push_rule_highest_priority_txn,
                **vals
            )
            defer.returnValue(ret)

    def _add_push_rule_relative_txn(self, txn, user_name, **kwargs):
        after = None
        relative_to_rule = None
        if 'after' in kwargs and kwargs['after']:
            after = kwargs['after']
            relative_to_rule = after
        if 'before' in kwargs and kwargs['before']:
            relative_to_rule = kwargs['before']

        # get the priority of the rule we're inserting after/before
        sql = (
            "SELECT priority_class, priority FROM "+PushRuleTable.table_name+
            " WHERE user_name = ? and rule_id = ?"
        )
        txn.execute(sql, (user_name, relative_to_rule))
        res = txn.fetchall()
        if not res:
            raise RuleNotFoundException("before/after rule not found: %s" % (relative_to_rule))
        priority_class, base_rule_priority = res[0]

        if 'priority_class' in kwargs and kwargs['priority_class'] != priority_class:
            raise InconsistentRuleException(<commit_msg>Use %s instead of +<commit_after># -*- coding: utf-8 -*-
# Copyright 2014 OpenMarket Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import collections

from ._base import SQLBaseStore, Table
from twisted.internet import defer

import logging
import copy
import json

logger = logging.getLogger(__name__)


class PushRuleStore(SQLBaseStore):
    @defer.inlineCallbacks
    def get_push_rules_for_user_name(self, user_name):
        sql = (
            "SELECT "+",".join(PushRuleTable.fields)+" "
            "FROM "+PushRuleTable.table_name+" "
            "WHERE user_name = ? "
            "ORDER BY priority_class DESC, priority DESC"
        )
        rows = yield self._execute(None, sql, user_name)

        dicts = []
        for r in rows:
            d = {}
            for i, f in enumerate(PushRuleTable.fields):
                d[f] = r[i]
            dicts.append(d)

        defer.returnValue(dicts)

    @defer.inlineCallbacks
    def add_push_rule(self, before, after, **kwargs):
        vals = copy.copy(kwargs)
        if 'conditions' in vals:
            vals['conditions'] = json.dumps(vals['conditions'])
        if 'actions' in vals:
            vals['actions'] = json.dumps(vals['actions'])
        # we could check the rest of the keys are valid column names
        # but sqlite will do that anyway so I think it's just pointless.
        if 'id' in vals:
            del vals['id']

        if before or after:
            ret = yield self.runInteraction(
                "_add_push_rule_relative_txn",
                self._add_push_rule_relative_txn,
                before=before,
                after=after,
                **vals
            )
            defer.returnValue(ret)
        else:
            ret = yield self.runInteraction(
                "_add_push_rule_highest_priority_txn",
                self._add_push_rule_highest_priority_txn,
                **vals
            )
            defer.returnValue(ret)

    def _add_push_rule_relative_txn(self, txn, user_name, **kwargs):
        after = None
        relative_to_rule = None
        if 'after' in kwargs and kwargs['after']:
            after = kwargs['after']
            relative_to_rule = after
        if 'before' in kwargs and kwargs['before']:
            relative_to_rule = kwargs['before']

        # get the priority of the rule we're inserting after/before
        sql = (
            "SELECT priority_class, priority FROM ? "
            "WHERE user_name = ? and rule_id = ?" % (PushRuleTable.table_name,)
        )
        txn.execute(sql, (user_name, relative_to_rule))
        res = txn.fetchall()
        if not res:
            raise RuleNotFoundException("before/after rule not found: %s" % (relative_to_rule))
        priority_class, base_rule_priority = res[0]

        if 'priority_class' in kwargs and kwargs['priority_class'] != priority_class:
            raise InconsistentRuleException(
{'fraction_non_alphanumeric': 0.08923076923076922, 'fraction_numerical': 0.0029304029304029304, 'mean_word_length': 2.2335386072951207, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1050284', 'n_tokens_mistral': 1943, 'n_tokens_neox': 1867, 'n_words': 577}