This file is indexed.

/usr/lib/python3/dist-packages/trytond/model/fields/many2one.py is in tryton-server 4.6.3-2.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
# This file is part of Tryton.  The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.
from sql import Literal, Column
from sql.aggregate import Max
from sql.conditionals import Coalesce
from sql.operators import Or

from .field import Field
from ...pool import Pool
from ...tools import reduce_ids
from ...transaction import Transaction


class Many2One(Field):
    '''
    Define many2one field (``int``).
    '''
    _type = 'many2one'
    _sql_type = 'INTEGER'

    def __init__(self, model_name, string='', left=None, right=None,
            ondelete='SET NULL', datetime_field=None, target_search='join',
            help='', required=False, readonly=False, domain=None, states=None,
            select=False, on_change=None, on_change_with=None, depends=None,
            context=None, loading='eager'):
        '''
        :param model_name: The name of the target model.
        :param left: The name of the field to store the left value for
            Modified Preorder Tree Traversal.
            See http://en.wikipedia.org/wiki/Tree_traversal
        :param right: The name of the field to store the right value. See left
        :param ondelete: Define the behavior of the record when the target
            record is deleted. (``CASCADE``, ``RESTRICT``, ``SET NULL``)
            ``SET NULL`` will be changed into ``RESTRICT`` if required is set.
        :param datetime_field: The name of the field that contains the datetime
            value to read the target record.
        :param target_search: The kind of target search 'subquery' or 'join'
        '''
        self.__required = required
        if ondelete not in ('CASCADE', 'RESTRICT', 'SET NULL'):
            raise Exception('Bad arguments')
        self.ondelete = ondelete
        if datetime_field:
            if depends:
                depends.append(datetime_field)
            else:
                depends = [datetime_field]
        super(Many2One, self).__init__(string=string, help=help,
            required=required, readonly=readonly, domain=domain, states=states,
            select=select, on_change=on_change, on_change_with=on_change_with,
            depends=depends, context=context, loading=loading)
        self.model_name = model_name
        self.left = left
        self.right = right
        self.datetime_field = datetime_field
        assert target_search in ['subquery', 'join']
        self.target_search = target_search
    __init__.__doc__ += Field.__init__.__doc__

    def __get_required(self):
        return self.__required

    def __set_required(self, value):
        self.__required = value
        if value and self.ondelete == 'SET NULL':
            self.ondelete = 'RESTRICT'

    required = property(__get_required, __set_required)

    def get_target(self):
        'Return the target Model'
        return Pool().get(self.model_name)

    def __set__(self, inst, value):
        Target = self.get_target()
        if isinstance(value, dict):
            value = Target(**value)
        elif isinstance(value, int):
            value = Target(value)
        assert isinstance(value, (Target, type(None)))
        super(Many2One, self).__set__(inst, value)

    def sql_format(self, value):
        if value is None:
            return None
        assert value is not False
        return int(value)

    def convert_domain_mptt(self, domain, tables):
        cursor = Transaction().connection.cursor()
        table, _ = tables[None]
        name, operator, ids = domain
        red_sql = reduce_ids(table.id, ids)
        Target = self.get_target()
        left = getattr(Target, self.left).sql_column(table)
        right = getattr(Target, self.right).sql_column(table)
        cursor.execute(*table.select(left, right, where=red_sql))
        where = Or()
        for l, r in cursor.fetchall():
            if operator.endswith('child_of'):
                where.append((left >= l) & (right <= r))
            else:
                where.append((left <= l) & (right >= r))
        if not where:
            where = Literal(False)
        if operator.startswith('not'):
            return ~where
        return where

    def convert_domain_tree(self, domain, tables):
        Target = self.get_target()
        table, _ = tables[None]
        name, operator, ids = domain
        ids = set(ids)  # Ensure it is a set for concatenation

        def get_child(ids):
            if not ids:
                return set()
            children = Target.search([
                    (name, 'in', ids),
                    (name, '!=', None),
                    ], order=[])
            child_ids = get_child(set(c.id for c in children))
            return ids | child_ids

        def get_parent(ids):
            if not ids:
                return set()
            parent_ids = set(getattr(p, name).id
                for p in Target.browse(ids) if getattr(p, name))
            return ids | get_parent(parent_ids)

        if operator.endswith('child_of'):
            ids = list(get_child(ids))
        else:
            ids = list(get_parent(ids))
        if not ids:
            expression = Literal(False)
        else:
            expression = table.id.in_(ids)
        if operator.startswith('not'):
            return ~expression
        return expression

    def convert_domain(self, domain, tables, Model):
        pool = Pool()
        Rule = pool.get('ir.rule')
        Target = self.get_target()

        table, _ = tables[None]
        name, operator, value = domain[:3]
        column = self.sql_column(table)
        if '.' not in name:
            if operator.endswith('child_of') or operator.endswith('parent_of'):
                if Target != Model:
                    if operator.endswith('child_of'):
                        target_operator = 'child_of'
                    else:
                        target_operator = 'parent_of'
                    query = Target.search([
                            (domain[3], target_operator, value),
                            ], order=[], query=True)
                    expression = column.in_(query)
                    if operator.startswith('not'):
                        return ~expression
                    return expression

                if isinstance(value, str):
                    targets = Target.search([('rec_name', 'ilike', value)],
                        order=[])
                    ids = [t.id for t in targets]
                elif not isinstance(value, (list, tuple)):
                    ids = [value]
                else:
                    ids = value
                if not ids:
                    expression = Literal(False)
                    if operator.startswith('not'):
                        return ~expression
                    return expression
                elif self.left and self.right:
                    return self.convert_domain_mptt(
                        (name, operator, ids), tables)
                else:
                    return self.convert_domain_tree(
                        (name, operator, ids), tables)

            # Used for Many2Many where clause
            if operator.endswith('where'):
                query = Target.search(value, order=[], query=True)
                expression = column.in_(query)
                if operator.startswith('not'):
                    return ~expression
                return expression

            if not isinstance(value, str):
                return super(Many2One, self).convert_domain(domain, tables,
                    Model)
            else:
                target_name = 'rec_name'
        else:
            _, target_name = name.split('.', 1)
        target_domain = [(target_name,) + tuple(domain[1:])]
        if 'active' in Target._fields:
            target_domain.append(('active', 'in', [True, False]))
        if self.target_search == 'subquery':
            query = Target.search(target_domain, order=[], query=True)
            return column.in_(query)
        else:
            target_tables = self._get_target_tables(tables)
            target_table, _ = target_tables[None]
            rule_domain = Rule.domain_get(Target.__name__, mode='read')
            if rule_domain:
                target_domain = [target_domain, rule_domain]
            _, expression = Target.search_domain(
                target_domain, tables=target_tables)
            return expression

    def convert_order(self, name, tables, Model):
        fname, _, oexpr = name.partition('.')
        if not oexpr and getattr(Model, 'order_%s' % fname, None):
            return super(Many2One, self).convert_order(fname, tables, Model)
        assert fname == self.name

        Target = self.get_target()

        if oexpr:
            oname, _, _ = oexpr.partition('.')
        else:
            oname = 'id'
            if Target._rec_name in Target._fields:
                oname = Target._rec_name
            if Target._order_name in Target._fields:
                oname = Target._order_name
            oexpr = oname

        table, _ = tables[None]
        if oname == 'id':
            return [self.sql_column(table)]

        ofield = Target._fields[oname]
        target_tables = self._get_target_tables(tables)
        return ofield.convert_order(oexpr, target_tables, Target)

    def _get_target_tables(self, tables):
        Target = self.get_target()
        table, _ = tables[None]
        target_tables = tables.get(self.name)
        context = Transaction().context
        if target_tables is None:
            if Target._history and context.get('_datetime'):
                target = Target.__table_history__()
                target_history = Target.__table_history__()
                history_condition = Column(target, '__id').in_(
                    target_history.select(
                        Max(Column(target_history, '__id')),
                        where=Coalesce(
                            target_history.write_date,
                            target_history.create_date)
                        <= context['_datetime'],
                        group_by=target_history.id))
            else:
                target = Target.__table__()
                history_condition = None
            condition = target.id == self.sql_column(table)
            if history_condition:
                condition &= history_condition
            target_tables = {
                None: (target, condition),
                }
            tables[self.name] = target_tables
        return target_tables