-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodels.py
5690 lines (4843 loc) · 242 KB
/
models.py
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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
"""
Object Relational Mapping module:
* Hierarchical structure
* Constraints consistency and validation
* Object metadata depends on its status
* Optimised processing by complex query (multiple actions at once)
* Default field values
* Permissions optimisation
* Persistent object: DB postgresql
* Data conversion
* Multi-level caching system
* Two different inheritance mechanisms
* Rich set of field types:
- classical (varchar, integer, boolean, ...)
- relational (one2many, many2one, many2many)
- functional
"""
import datetime
import collections
import dateutil
import functools
import itertools
import io
import logging
import operator
import pytz
import re
import uuid
from collections import defaultdict, MutableMapping, OrderedDict
from contextlib import closing
from inspect import getmembers, currentframe
from operator import attrgetter, itemgetter
import babel.dates
import dateutil.relativedelta
import psycopg2
from lxml import etree
from lxml.builder import E
from psycopg2.extensions import AsIs
import odoo
from . import SUPERUSER_ID
from . import api
from . import tools
from .exceptions import AccessError, MissingError, ValidationError, UserError
from .osv.query import Query
from .tools import frozendict, lazy_classproperty, lazy_property, ormcache, \
Collector, LastOrderedSet, OrderedSet, pycompat, groupby
from .tools.config import config
from .tools.func import frame_codeinfo
from .tools.misc import CountingStream, clean_context, DEFAULT_SERVER_DATETIME_FORMAT, DEFAULT_SERVER_DATE_FORMAT
from .tools.safe_eval import safe_eval
from .tools.translate import _
from .tools import date_utils
_logger = logging.getLogger(__name__)
_schema = logging.getLogger(__name__ + '.schema')
_unlink = logging.getLogger(__name__ + '.unlink')
regex_order = re.compile('^(\s*([a-z0-9:_]+|"[a-z0-9:_]+")(\s+(desc|asc))?\s*(,|$))+(?<!,)$', re.I)
regex_object_name = re.compile(r'^[a-z0-9_.]+$')
regex_pg_name = re.compile(r'^[a-z_][a-z0-9_$]*$', re.I)
regex_field_agg = re.compile(r'(\w+)(?::(\w+)(?:\((\w+)\))?)?')
AUTOINIT_RECALCULATE_STORED_FIELDS = 1000
def check_object_name(name):
""" Check if the given name is a valid model name.
The _name attribute in osv and osv_memory object is subject to
some restrictions. This function returns True or False whether
the given name is allowed or not.
TODO: this is an approximation. The goal in this approximation
is to disallow uppercase characters (in some places, we quote
table/column names and in other not, which leads to this kind
of errors:
psycopg2.ProgrammingError: relation "xxx" does not exist).
The same restriction should apply to both osv and osv_memory
objects for consistency.
"""
if regex_object_name.match(name) is None:
return False
return True
def raise_on_invalid_object_name(name):
if not check_object_name(name):
msg = "The _name attribute %s is not valid." % name
raise ValueError(msg)
def check_pg_name(name):
""" Check whether the given name is a valid PostgreSQL identifier name. """
if not regex_pg_name.match(name):
raise ValidationError("Invalid characters in table name %r" % name)
if len(name) > 63:
raise ValidationError("Table name %r is too long" % name)
# match private methods, to prevent their remote invocation
regex_private = re.compile(r'^(_.*|init)$')
def check_method_name(name):
""" Raise an ``AccessError`` if ``name`` is a private method name. """
if regex_private.match(name):
raise AccessError(_('Private methods (such as %s) cannot be called remotely.') % (name,))
def same_name(f, g):
""" Test whether functions ``f`` and ``g`` are identical or have the same name """
return f == g or getattr(f, '__name__', 0) == getattr(g, '__name__', 1)
def fix_import_export_id_paths(fieldname):
"""
Fixes the id fields in import and exports, and splits field paths
on '/'.
:param str fieldname: name of the field to import/export
:return: split field name
:rtype: list of str
"""
fixed_db_id = re.sub(r'([^/])\.id', r'\1/.id', fieldname)
fixed_external_id = re.sub(r'([^/]):id', r'\1/id', fixed_db_id)
return fixed_external_id.split('/')
class MetaModel(api.Meta):
""" The metaclass of all model classes.
Its main purpose is to register the models per module.
"""
module_to_models = defaultdict(list)
def __init__(self, name, bases, attrs):
if not self._register:
self._register = True
super(MetaModel, self).__init__(name, bases, attrs)
return
if not hasattr(self, '_module'):
self._module = self._get_addon_name(self.__module__)
# Remember which models to instanciate for this module.
if not self._custom:
self.module_to_models[self._module].append(self)
# check for new-api conversion error: leave comma after field definition
for key, val in attrs.items():
if type(val) is tuple and len(val) == 1 and isinstance(val[0], Field):
_logger.error("Trailing comma after field definition: %s.%s", self, key)
if isinstance(val, Field):
val.args = dict(val.args, _module=self._module)
def _get_addon_name(self, full_name):
# The (OpenERP) module name can be in the ``odoo.addons`` namespace
# or not. For instance, module ``sale`` can be imported as
# ``odoo.addons.sale`` (the right way) or ``sale`` (for backward
# compatibility).
module_parts = full_name.split('.')
if len(module_parts) > 2 and module_parts[:2] == ['odoo', 'addons']:
addon_name = full_name.split('.')[2]
else:
addon_name = full_name.split('.')[0]
return addon_name
class NewId(object):
""" Pseudo-ids for new records, encapsulating an optional reference. """
__slots__ = ['ref']
def __init__(self, ref=None):
self.ref = ref
def __bool__(self):
return False
__nonzero__ = __bool__
IdType = pycompat.integer_types + pycompat.string_types + (NewId,)
# maximum number of prefetched records
PREFETCH_MAX = 1000
# special columns automatically created by the ORM
LOG_ACCESS_COLUMNS = ['create_uid', 'create_date', 'write_uid', 'write_date']
MAGIC_COLUMNS = ['id'] + LOG_ACCESS_COLUMNS
# valid SQL aggregation functions
VALID_AGGREGATE_FUNCTIONS = {
'array_agg', 'count', 'count_distinct',
'bool_and', 'bool_or', 'max', 'min', 'avg', 'sum',
}
@pycompat.implements_to_string
class BaseModel(MetaModel('DummyModel', (object,), {'_register': False})):
""" Base class for Odoo models.
Odoo models are created by inheriting:
* :class:`Model` for regular database-persisted models
* :class:`TransientModel` for temporary data, stored in the database but
automatically vacuumed every so often
* :class:`AbstractModel` for abstract super classes meant to be shared by
multiple inheriting models
The system automatically instantiates every model once per database. Those
instances represent the available models on each database, and depend on
which modules are installed on that database. The actual class of each
instance is built from the Python classes that create and inherit from the
corresponding model.
Every model instance is a "recordset", i.e., an ordered collection of
records of the model. Recordsets are returned by methods like
:meth:`~.browse`, :meth:`~.search`, or field accesses. Records have no
explicit representation: a record is represented as a recordset of one
record.
To create a class that should not be instantiated, the _register class
attribute may be set to False.
"""
_auto = False # don't create any database backend
_register = False # not visible in ORM registry
_abstract = True # whether model is abstract
_transient = False # whether model is transient
_name = None # the model name
_description = None # the model's informal name
_custom = False # should be True for custom models only
_inherit = None # Python-inherited models ('model' or ['model'])
_inherits = {} # inherited models {'parent_model': 'm2o_field'}
_constraints = [] # Python constraints (old API)
_table = None # SQL table name used by model
_sequence = None # SQL sequence to use for ID field
_sql_constraints = [] # SQL constraints [(name, sql_def, message)]
_rec_name = None # field to use for labeling records
_order = 'id' # default order for searching results
_parent_name = 'parent_id' # the many2one field used as parent field
_parent_store = False # set to True to compute parent_path field
_date_name = 'date' # field to use for default calendar view
_fold_name = 'fold' # field to determine folded groups in kanban views
_needaction = False # whether the model supports "need actions" (see mail)
_translate = True # False disables translations export for this model
_depends = {} # dependencies of models backed up by sql views
# {model_name: field_names, ...}
# default values for _transient_vacuum()
_transient_check_count = 0
_transient_max_count = lazy_classproperty(lambda _: config.get('osv_memory_count_limit'))
_transient_max_hours = lazy_classproperty(lambda _: config.get('osv_memory_age_limit'))
CONCURRENCY_CHECK_FIELD = '__last_update'
@api.model
def view_init(self, fields_list):
""" Override this method to do specific things when a form view is
opened. This method is invoked by :meth:`~default_get`.
"""
pass
@api.model_cr_context
def _reflect(self):
""" Reflect the model and its fields in the models 'ir.model' and
'ir.model.fields'. Also create entries in 'ir.model.data' if the key
'module' is passed to the context.
"""
self.env['ir.model']._reflect_model(self)
self.env['ir.model.fields']._reflect_model(self)
self.env['ir.model.constraint']._reflect_model(self)
self.invalidate_cache()
@api.model
def _add_field(self, name, field):
""" Add the given ``field`` under the given ``name`` in the class """
cls = type(self)
# add field as an attribute and in cls._fields (for reflection)
if not isinstance(getattr(cls, name, field), Field):
_logger.warning("In model %r, field %r overriding existing value", cls._name, name)
setattr(cls, name, field)
cls._fields[name] = field
# basic setup of field
field.setup_base(self, name)
@api.model
def _pop_field(self, name):
""" Remove the field with the given ``name`` from the model.
This method should only be used for manual fields.
"""
cls = type(self)
field = cls._fields.pop(name, None)
if hasattr(cls, name):
delattr(cls, name)
return field
@api.model
def _add_magic_fields(self):
""" Introduce magic fields on the current class
* id is a "normal" field (with a specific getter)
* create_uid, create_date, write_uid and write_date have become
"normal" fields
* $CONCURRENCY_CHECK_FIELD is a computed field with its computing
method defined dynamically. Uses ``str(datetime.datetime.utcnow())``
to get the same structure as the previous
``(now() at time zone 'UTC')::timestamp``::
# select (now() at time zone 'UTC')::timestamp;
timezone
----------------------------
2013-06-18 08:30:37.292809
>>> str(datetime.datetime.utcnow())
'2013-06-18 08:31:32.821177'
"""
def add(name, field):
""" add ``field`` with the given ``name`` if it does not exist yet """
if name not in self._fields:
self._add_field(name, field)
# cyclic import
from . import fields
# this field 'id' must override any other column or field
self._add_field('id', fields.Id(automatic=True))
add('display_name', fields.Char(string='Display Name', automatic=True,
compute='_compute_display_name'))
if self._log_access:
add('create_uid', fields.Many2one(
'res.users', string='Created by', automatic=True, readonly=True))
add('create_date', fields.Datetime(
string='Created on', automatic=True, readonly=True))
add('write_uid', fields.Many2one(
'res.users', string='Last Updated by', automatic=True, readonly=True))
add('write_date', fields.Datetime(
string='Last Updated on', automatic=True, readonly=True))
last_modified_name = 'compute_concurrency_field_with_access'
else:
last_modified_name = 'compute_concurrency_field'
# this field must override any other column or field
self._add_field(self.CONCURRENCY_CHECK_FIELD, fields.Datetime(
string='Last Modified on', compute=last_modified_name, automatic=True))
def compute_concurrency_field(self):
for record in self:
record[self.CONCURRENCY_CHECK_FIELD] = odoo.fields.Datetime.now()
@api.depends('create_date', 'write_date')
def compute_concurrency_field_with_access(self):
for record in self:
record[self.CONCURRENCY_CHECK_FIELD] = \
record.write_date or record.create_date or odoo.fields.Datetime.now()
#
# Goal: try to apply inheritance at the instantiation level and
# put objects in the pool var
#
@classmethod
def _build_model(cls, pool, cr):
""" Instantiate a given model in the registry.
This method creates or extends a "registry" class for the given model.
This "registry" class carries inferred model metadata, and inherits (in
the Python sense) from all classes that define the model, and possibly
other registry classes.
"""
# In the simplest case, the model's registry class inherits from cls and
# the other classes that define the model in a flat hierarchy. The
# registry contains the instance ``model`` (on the left). Its class,
# ``ModelClass``, carries inferred metadata that is shared between all
# the model's instances for this registry only.
#
# class A1(Model): Model
# _name = 'a' / | \
# A3 A2 A1
# class A2(Model): \ | /
# _inherit = 'a' ModelClass
# / \
# class A3(Model): model recordset
# _inherit = 'a'
#
# When a model is extended by '_inherit', its base classes are modified
# to include the current class and the other inherited model classes.
# Note that we actually inherit from other ``ModelClass``, so that
# extensions to an inherited model are immediately visible in the
# current model class, like in the following example:
#
# class A1(Model):
# _name = 'a' Model
# / / \ \
# class B1(Model): / A2 A1 \
# _name = 'b' / \ / \
# B2 ModelA B1
# class B2(Model): \ | /
# _name = 'b' \ | /
# _inherit = ['a', 'b'] \ | /
# ModelB
# class A2(Model):
# _inherit = 'a'
# Keep links to non-inherited constraints in cls; this is useful for
# instance when exporting translations
cls._local_constraints = cls.__dict__.get('_constraints', [])
cls._local_sql_constraints = cls.__dict__.get('_sql_constraints', [])
# determine inherited models
parents = cls._inherit
parents = [parents] if isinstance(parents, pycompat.string_types) else (parents or [])
# determine the model's name
name = cls._name or (len(parents) == 1 and parents[0]) or cls.__name__
# all models except 'base' implicitly inherit from 'base'
if name != 'base':
parents = list(parents) + ['base']
# create or retrieve the model's class
if name in parents:
if name not in pool:
raise TypeError("Model %r does not exist in registry." % name)
ModelClass = pool[name]
ModelClass._build_model_check_base(cls)
check_parent = ModelClass._build_model_check_parent
else:
ModelClass = type(name, (BaseModel,), {
'_name': name,
'_register': False,
'_original_module': cls._module,
'_inherit_children': OrderedSet(), # names of children models
'_inherits_children': set(), # names of children models
'_fields': OrderedDict(), # populated in _setup_base()
})
check_parent = cls._build_model_check_parent
# determine all the classes the model should inherit from
bases = LastOrderedSet([cls])
for parent in parents:
if parent not in pool:
raise TypeError("Model %r inherits from non-existing model %r." % (name, parent))
parent_class = pool[parent]
if parent == name:
for base in parent_class.__bases__:
bases.add(base)
else:
check_parent(cls, parent_class)
bases.add(parent_class)
parent_class._inherit_children.add(name)
ModelClass.__bases__ = tuple(bases)
# determine the attributes of the model's class
ModelClass._build_model_attributes(pool)
check_pg_name(ModelClass._table)
# Transience
if ModelClass._transient:
assert ModelClass._log_access, \
"TransientModels must have log_access turned on, " \
"in order to implement their access rights policy"
# link the class to the registry, and update the registry
ModelClass.pool = pool
pool[name] = ModelClass
# backward compatibility: instantiate the model, and initialize it
model = object.__new__(ModelClass)
model.__init__(pool, cr)
return ModelClass
@classmethod
def _build_model_check_base(model_class, cls):
""" Check whether ``model_class`` can be extended with ``cls``. """
if model_class._abstract and not cls._abstract:
msg = ("%s transforms the abstract model %r into a non-abstract model. "
"That class should either inherit from AbstractModel, or set a different '_name'.")
raise TypeError(msg % (cls, model_class._name))
if model_class._transient != cls._transient:
if model_class._transient:
msg = ("%s transforms the transient model %r into a non-transient model. "
"That class should either inherit from TransientModel, or set a different '_name'.")
else:
msg = ("%s transforms the model %r into a transient model. "
"That class should either inherit from Model, or set a different '_name'.")
raise TypeError(msg % (cls, model_class._name))
@classmethod
def _build_model_check_parent(model_class, cls, parent_class):
""" Check whether ``model_class`` can inherit from ``parent_class``. """
if model_class._abstract and not parent_class._abstract:
msg = ("In %s, the abstract model %r cannot inherit from the non-abstract model %r.")
raise TypeError(msg % (cls, model_class._name, parent_class._name))
@classmethod
def _build_model_attributes(cls, pool):
""" Initialize base model attributes. """
cls._description = cls._name
cls._table = cls._name.replace('.', '_')
cls._sequence = None
cls._log_access = cls._auto
cls._inherits = {}
cls._depends = {}
cls._constraints = {}
cls._sql_constraints = []
for base in reversed(cls.__bases__):
if not getattr(base, 'pool', None):
# the following attributes are not taken from model classes
if not base._inherit and not base._description:
_logger.warning("The model %s has no _description", cls._name)
cls._description = base._description or cls._description
cls._table = base._table or cls._table
cls._sequence = base._sequence or cls._sequence
cls._log_access = getattr(base, '_log_access', cls._log_access)
cls._inherits.update(base._inherits)
for mname, fnames in base._depends.items():
cls._depends[mname] = cls._depends.get(mname, []) + fnames
for cons in base._constraints:
# cons may override a constraint with the same function name
cls._constraints[getattr(cons[0], '__name__', id(cons[0]))] = cons
cls._sql_constraints += base._sql_constraints
cls._sequence = cls._sequence or (cls._table + '_id_seq')
cls._constraints = list(cls._constraints.values())
# update _inherits_children of parent models
for parent_name in cls._inherits:
pool[parent_name]._inherits_children.add(cls._name)
# recompute attributes of _inherit_children models
for child_name in cls._inherit_children:
child_class = pool[child_name]
child_class._build_model_attributes(pool)
@classmethod
def _init_constraints_onchanges(cls):
# store sql constraint error messages
for (key, _, msg) in cls._sql_constraints:
cls.pool._sql_error[cls._table + '_' + key] = msg
# reset properties memoized on cls
cls._constraint_methods = BaseModel._constraint_methods
cls._onchange_methods = BaseModel._onchange_methods
@property
def _constraint_methods(self):
""" Return a list of methods implementing Python constraints. """
def is_constraint(func):
return callable(func) and hasattr(func, '_constrains')
cls = type(self)
methods = []
for attr, func in getmembers(cls, is_constraint):
for name in func._constrains:
field = cls._fields.get(name)
if not field:
_logger.warning("method %s.%s: @constrains parameter %r is not a field name", cls._name, attr, name)
elif not (field.store or field.inverse or field.inherited):
_logger.warning("method %s.%s: @constrains parameter %r is not writeable", cls._name, attr, name)
methods.append(func)
# optimization: memoize result on cls, it will not be recomputed
cls._constraint_methods = methods
return methods
@property
def _onchange_methods(self):
""" Return a dictionary mapping field names to onchange methods. """
def is_onchange(func):
return callable(func) and hasattr(func, '_onchange')
# collect onchange methods on the model's class
cls = type(self)
methods = defaultdict(list)
for attr, func in getmembers(cls, is_onchange):
for name in func._onchange:
if name not in cls._fields:
_logger.warning("@onchange%r parameters must be field names", func._onchange)
methods[name].append(func)
# add onchange methods to implement "change_default" on fields
def onchange_default(field, self):
value = field.convert_to_write(self[field.name], self)
condition = "%s=%s" % (field.name, value)
defaults = self.env['ir.default'].get_model_defaults(self._name, condition)
self.update(defaults)
for name, field in cls._fields.items():
if field.change_default:
methods[name].append(functools.partial(onchange_default, field))
# optimization: memoize result on cls, it will not be recomputed
cls._onchange_methods = methods
return methods
def __new__(cls):
# In the past, this method was registering the model class in the server.
# This job is now done entirely by the metaclass MetaModel.
return None
def __init__(self, pool, cr):
""" Deprecated method to initialize the model. """
pass
@api.model
@ormcache()
def _is_an_ordinary_table(self):
return tools.table_kind(self.env.cr, self._table) == 'r'
def __ensure_xml_id(self, skip=False):
""" Create missing external ids for records in ``self``, and return an
iterator of pairs ``(record, xmlid)`` for the records in ``self``.
:rtype: Iterable[Model, str | None]
"""
if skip:
return ((record, None) for record in self)
if not self:
return iter([])
if not self._is_an_ordinary_table():
raise Exception(
"You can not export the column ID of model %s, because the "
"table %s is not an ordinary table."
% (self._name, self._table))
modname = '__export__'
cr = self.env.cr
cr.execute("""
SELECT res_id, module, name
FROM ir_model_data
WHERE model = %s AND res_id in %s
""", (self._name, tuple(self.ids)))
xids = {
res_id: (module, name)
for res_id, module, name in cr.fetchall()
}
def to_xid(record_id):
(module, name) = xids[record_id]
return ('%s.%s' % (module, name)) if module else name
# create missing xml ids
missing = self.filtered(lambda r: r.id not in xids)
if not missing:
return (
(record, to_xid(record.id))
for record in self
)
xids.update(
(r.id, (modname, '%s_%s_%s' % (
r._table,
r.id,
uuid.uuid4().hex[:8],
)))
for r in missing
)
fields = ['module', 'model', 'name', 'res_id']
cr.copy_from(io.StringIO(
u'\n'.join(
u"%s\t%s\t%s\t%d" % (
modname,
record._name,
xids[record.id][1],
record.id,
)
for record in missing
)),
table='ir_model_data',
columns=fields,
)
self.env['ir.model.data'].invalidate_cache(fnames=fields)
return (
(record, to_xid(record.id))
for record in self
)
@api.multi
def _export_rows(self, fields, *, _is_toplevel_call=True):
""" Export fields of the records in ``self``.
:param fields: list of lists of fields to traverse
:param bool _is_toplevel_call:
used when recursing, avoid using when calling from outside
:return: list of lists of corresponding values
"""
import_compatible = self.env.context.get('import_compat', True)
lines = []
def splittor(rs):
""" Splits the self recordset in batches of 1000 (to avoid
entire-recordset-prefetch-effects) & removes the previous batch
from the cache after it's been iterated in full
"""
for idx in range(0, len(rs), 1000):
sub = rs[idx:idx+1000]
for rec in sub:
yield rec
rs.invalidate_cache(ids=sub.ids)
if not _is_toplevel_call:
splittor = lambda rs: rs
# memory stable but ends up prefetching 275 fields (???)
for record in splittor(self):
# main line of record, initially empty
current = [''] * len(fields)
lines.append(current)
# list of primary fields followed by secondary field(s)
primary_done = []
# process column by column
for i, path in enumerate(fields):
if not path:
continue
name = path[0]
if name in primary_done:
continue
if name == '.id':
current[i] = str(record.id)
elif name == 'id':
current[i] = (record._name, record.id)
else:
field = record._fields[name]
value = record[name]
# this part could be simpler, but it has to be done this way
# in order to reproduce the former behavior
if not isinstance(value, BaseModel):
current[i] = field.convert_to_export(value, record)
else:
primary_done.append(name)
# in import_compat mode, m2m should always be exported as
# a comma-separated list of xids in a single cell
if import_compatible and field.type == 'many2many' and len(path) > 1 and path[1] == 'id':
xml_ids = [xid for _, xid in value.__ensure_xml_id()]
current[i] = ','.join(xml_ids) or False
continue
# recursively export the fields that follow name; use
# 'display_name' where no subfield is exported
fields2 = [(p[1:] or ['display_name'] if p and p[0] == name else [])
for p in fields]
lines2 = value._export_rows(fields2, _is_toplevel_call=False)
if lines2:
# merge first line with record's main line
for j, val in enumerate(lines2[0]):
if val or isinstance(val, bool):
current[j] = val
# append the other lines at the end
lines += lines2[1:]
else:
current[i] = False
# if any xid should be exported, only do so at toplevel
if _is_toplevel_call and any(f[-1] == 'id' for f in fields):
bymodels = collections.defaultdict(set)
xidmap = collections.defaultdict(list)
# collect all the tuples in "lines" (along with their coordinates)
for i, line in enumerate(lines):
for j, cell in enumerate(line):
if type(cell) is tuple:
bymodels[cell[0]].add(cell[1])
xidmap[cell].append((i, j))
# for each model, xid-export everything and inject in matrix
for model, ids in bymodels.items():
for record, xid in self.env[model].browse(ids).__ensure_xml_id():
for i, j in xidmap.pop((record._name, record.id)):
lines[i][j] = xid
assert not xidmap, "failed to export xids for %s" % ', '.join('{}:{}' % it for it in xidmap.items())
return lines
# backward compatibility
__export_rows = _export_rows
@api.multi
def export_data(self, fields_to_export, raw_data=False):
""" Export fields for selected objects
:param fields_to_export: list of fields
:param raw_data: True to return value in native Python type
:rtype: dictionary with a *datas* matrix
This method is used when exporting data via client menu
"""
fields_to_export = [fix_import_export_id_paths(f) for f in fields_to_export]
if raw_data:
self = self.with_context(export_raw_data=True)
return {'datas': self._export_rows(fields_to_export)}
@api.model
def load(self, fields, data):
"""
Attempts to load the data matrix, and returns a list of ids (or
``False`` if there was an error and no id could be generated) and a
list of messages.
The ids are those of the records created and saved (in database), in
the same order they were extracted from the file. They can be passed
directly to :meth:`~read`
:param fields: list of fields to import, at the same index as the corresponding data
:type fields: list(str)
:param data: row-major matrix of data to import
:type data: list(list(str))
:returns: {ids: list(int)|False, messages: [Message]}
"""
# determine values of mode, current_module and noupdate
mode = self._context.get('mode', 'init')
current_module = self._context.get('module', '__import__')
noupdate = self._context.get('noupdate', False)
# add current module in context for the conversion of xml ids
self = self.with_context(_import_current_module=current_module)
cr = self._cr
cr.execute('SAVEPOINT model_load')
fields = [fix_import_export_id_paths(f) for f in fields]
fg = self.fields_get()
ids = []
messages = []
ModelData = self.env['ir.model.data']
# list of (xid, vals, info) for records to be created in batch
batch = []
batch_xml_ids = set()
def flush(xml_id=None):
if not batch:
return
if xml_id and xml_id not in batch_xml_ids:
return
data_list = [
dict(xml_id=xid, values=vals, info=info, noupdate=noupdate)
for xid, vals, info in batch
]
batch.clear()
batch_xml_ids.clear()
try:
cr.execute('SAVEPOINT model_load_save')
except psycopg2.InternalError as e:
# broken transaction, exit and hope the source error was
# already logged
if not any(message['type'] == 'error' for message in messages):
info = data_list[0]['info']
messages.append(dict(info, type='error', message=u"Unknown database error: '%s'" % e))
return
# try to create in batch
try:
recs = self._load_records(data_list, mode == 'update')
ids.extend(recs.ids)
cr.execute('RELEASE SAVEPOINT model_load_save')
return
except Exception:
cr.execute('ROLLBACK TO SAVEPOINT model_load_save')
# try again, this time record by record
for rec_data in data_list:
try:
cr.execute('SAVEPOINT model_load_save')
rec = self._load_records([rec_data], mode == 'update')
ids.append(rec.id)
cr.execute('RELEASE SAVEPOINT model_load_save')
except psycopg2.Warning as e:
info = rec_data['info']
messages.append(dict(info, type='warning', message=str(e)))
cr.execute('ROLLBACK TO SAVEPOINT model_load_save')
except psycopg2.Error as e:
info = rec_data['info']
messages.append(dict(info, type='error', **PGERROR_TO_OE[e.pgcode](self, fg, info, e)))
# Failed to write, log to messages, rollback savepoint (to
# avoid broken transaction) and keep going
cr.execute('ROLLBACK TO SAVEPOINT model_load_save')
except Exception as e:
_logger.exception("Error while loading record")
info = rec_data['info']
message = (_(u'Unknown error during import:') + u' %s: %s' % (type(e), e))
moreinfo = _('Resolve other errors first')
messages.append(dict(info, type='error', message=message, moreinfo=moreinfo))
# Failed for some reason, perhaps due to invalid data supplied,
# rollback savepoint and keep going
cr.execute('ROLLBACK TO SAVEPOINT model_load_save')
# make 'flush' available to the methods below, in the case where XMLID
# resolution fails, for instance
flush_self = self.with_context(import_flush=flush)
extracted = flush_self._extract_records(fields, data, log=messages.append)
converted = flush_self._convert_records(extracted, log=messages.append)
for id, xid, record, info in converted:
if xid:
xid = xid if '.' in xid else "%s.%s" % (current_module, xid)
batch_xml_ids.update(ModelData._generate_xmlids(xid, self))
elif id:
record['id'] = id
batch.append((xid, record, info))
flush()
if any(message['type'] == 'error' for message in messages):
cr.execute('ROLLBACK TO SAVEPOINT model_load')
ids = False
# cancel all changes done to the registry/ormcache
self.pool.reset_changes()
return {'ids': ids, 'messages': messages}
def _add_fake_fields(self, fields):
from odoo.fields import Char, Integer
fields[None] = Char('rec_name')
fields['id'] = Char('External ID')
fields['.id'] = Integer('Database ID')
return fields
@api.model
def _extract_records(self, fields_, data, log=lambda a: None):
""" Generates record dicts from the data sequence.
The result is a generator of dicts mapping field names to raw
(unconverted, unvalidated) values.
For relational fields, if sub-fields were provided the value will be
a list of sub-records
The following sub-fields may be set on the record (by key):
* None is the name_get for the record (to use with name_create/name_search)
* "id" is the External ID for the record
* ".id" is the Database ID for the record
"""
fields = dict(self._fields)
# Fake fields to avoid special cases in extractor
fields = self._add_fake_fields(fields)
# m2o fields can't be on multiple lines so exclude them from the
# is_relational field rows filter, but special-case it later on to
# be handled with relational fields (as it can have subfields)
is_relational = lambda field: fields[field].relational
get_o2m_values = itemgetter_tuple([
index
for index, fnames in enumerate(fields_)
if fields[fnames[0]].type == 'one2many'
])
get_nono2m_values = itemgetter_tuple([
index
for index, fnames in enumerate(fields_)
if fields[fnames[0]].type != 'one2many'
])
# Checks if the provided row has any non-empty one2many fields
def only_o2m_values(row):
return any(get_o2m_values(row)) and not any(get_nono2m_values(row))
index = 0
while index < len(data):
row = data[index]
# copy non-relational fields to record dict
record = {fnames[0]: value
for fnames, value in pycompat.izip(fields_, row)
if not is_relational(fnames[0])}
# Get all following rows which have relational values attached to
# the current record (no non-relational values)
record_span = itertools.takewhile(
only_o2m_values, itertools.islice(data, index + 1, None))
# stitch record row back on for relational fields
record_span = list(itertools.chain([row], record_span))
for relfield in set(fnames[0] for fnames in fields_ if is_relational(fnames[0])):