This repository was archived by the owner on Dec 30, 2022. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathmodelsql.py
More file actions
2078 lines (1851 loc) · 81 KB
/
Copy pathmodelsql.py
File metadata and controls
2078 lines (1851 loc) · 81 KB
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
# This file is part of Tryton. The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.
import datetime
from collections import OrderedDict, defaultdict
from functools import wraps
from itertools import chain, groupby, islice, product, repeat
from sql import (
Asc, Column, Desc, Expression, For, Literal, Null, NullsFirst, NullsLast,
Table, Union, With)
from sql.aggregate import Count, Max
from sql.conditionals import Coalesce
from sql.functions import CurrentTimestamp, Extract, Substring
from sql.operators import And, Concat, Equal, Operator, Or
from trytond import backend
from trytond.cache import freeze
from trytond.config import config
from trytond.exceptions import ConcurrencyException
from trytond.i18n import gettext
from trytond.pool import Pool
from trytond.pyson import PYSONDecoder, PYSONEncoder
from trytond.rpc import RPC
from trytond.tools import cursor_dict, grouped_slice, reduce_ids
from trytond.transaction import Transaction, record_cache_size
from . import fields
from .descriptors import dualmethod
from .modelstorage import (
AccessError, ModelStorage, RequiredValidationError, SizeValidationError,
ValidationError, is_leaf)
from .modelview import ModelView
class ForeignKeyError(ValidationError):
pass
class SQLConstraintError(ValidationError):
pass
class Constraint(object):
__slots__ = ('_table',)
def __init__(self, table):
assert isinstance(table, Table)
self._table = table
@property
def table(self):
return self._table
def __str__(self):
raise NotImplementedError
@property
def params(self):
raise NotImplementedError
class Check(Constraint):
__slots__ = ('_expression',)
def __init__(self, table, expression):
super(Check, self).__init__(table)
assert isinstance(expression, Expression)
self._expression = expression
@property
def expression(self):
return self._expression
def __str__(self):
return 'CHECK(%s)' % self.expression
@property
def params(self):
return self.expression.params
class Unique(Constraint):
__slots__ = ('_columns',)
def __init__(self, table, *columns):
super(Unique, self).__init__(table)
assert all(isinstance(col, Column) for col in columns)
self._columns = tuple(columns)
@property
def columns(self):
return self._columns
@property
def operators(self):
return tuple(Equal for c in self._columns)
def __str__(self):
return 'UNIQUE(%s)' % (', '.join(map(str, self.columns)))
@property
def params(self):
p = []
for column in self.columns:
p.extend(column.params)
return tuple(p)
class Exclude(Constraint):
__slots__ = ('_excludes', '_where')
def __init__(self, table, *excludes, **kwargs):
super(Exclude, self).__init__(table)
assert all(isinstance(c, Expression) and issubclass(o, Operator)
for c, o in excludes), excludes
self._excludes = tuple(excludes)
where = kwargs.get('where')
if where is not None:
assert isinstance(where, Expression)
self._where = where
@property
def excludes(self):
return self._excludes
@property
def columns(self):
return tuple(c for c, _ in self._excludes)
@property
def operators(self):
return tuple(o for _, o in self._excludes)
@property
def where(self):
return self._where
def __str__(self):
exclude = ', '.join('%s WITH %s' % (column, operator._operator)
for column, operator in self.excludes)
where = ''
if self.where:
where = ' WHERE ' + str(self.where)
return 'EXCLUDE (%s)' % exclude + where
@property
def params(self):
p = []
for column, operator in self._excludes:
p.extend(column.params)
if self.where:
p.extend(self.where.params)
return tuple(p)
class Index:
__slots__ = ('table', 'expressions', 'options')
def __init__(self, table, *expressions, **options):
self.table = table
assert all(
isinstance(e, Expression) and isinstance(u, self.Usage)
for e, u in expressions)
self.expressions = expressions
self.options = options
def __hash__(self):
table_def = (
self.table._name, self.table._schema, self.table._database)
expressions = (
(str(e), e.params, hash(u)) for e, u in self.expressions)
return hash((table_def, *expressions))
def __eq__(self, other):
return (
str(self.table) == str(other.table)
and len(self.expressions) == len(other.expressions)
and all((str(c), u) == (str(oc), ou)
for (c, u), (oc, ou) in zip(
self.expressions, other.expressions))
and self.options == other.options)
class Unaccent(Expression):
"Unaccent function if database support for index"
__slots__ = ('_expression',)
def __init__(self, expression):
self._expression = expression
@property
def expression(self):
expression = self._expression
database = Transaction().database
if database.has_unaccent_indexable():
expression = database.unaccent(expression)
return expression
def __str__(self):
return str(self.expression)
@property
def params(self):
return self.expression.params
class Usage:
__slots__ = ('options',)
def __init__(self, **options):
self.options = options
def __hash__(self):
return hash((self.__class__.__name__, *self.options.items()))
def __eq__(self, other):
return (self.__class__ == other.__class__
and self.options == other.options)
class Equality(Usage):
__slots__ = ()
class Range(Usage):
__slots__ = ()
class Similarity(Usage):
__slots__ = ()
def no_table_query(func):
@wraps(func)
def wrapper(cls, *args, **kwargs):
if callable(cls.table_query):
raise NotImplementedError("On table_query")
return func(cls, *args, **kwargs)
return wrapper
class ModelSQL(ModelStorage):
"""
Define a model with storage in database.
"""
__slots__ = ()
_table = None # The name of the table in database
_order = None
_order_name = None # Use to force order field when sorting on Many2One
_history = False
table_query = None
@classmethod
def __setup__(cls):
cls._table = config.get('table', cls.__name__, default=cls._table)
if not cls._table:
cls._table = cls.__name__.replace('.', '_')
assert cls._table[-9:] != '__history', \
'Model _table %s cannot end with "__history"' % cls._table
super(ModelSQL, cls).__setup__()
cls._sql_constraints = []
cls._sql_indexes = set()
if not callable(cls.table_query):
table = cls.__table__()
cls._sql_constraints.append(
('id_positive', Check(table, table.id >= 0),
'ir.msg_id_positive'))
rec_name_field = getattr(cls, cls._rec_name, None)
if (isinstance(rec_name_field, fields.Field)
and not hasattr(rec_name_field, 'set')):
column = Column(table, cls._rec_name)
if getattr(rec_name_field, 'search_unaccented', False):
column = Index.Unaccent(column)
cls._sql_indexes.add(
Index(table, (column, Index.Similarity())))
cls._order = [('id', None)]
if issubclass(cls, ModelView):
cls.__rpc__.update({
'history_revisions': RPC(),
})
if cls._history:
history_table = cls.__table_history__()
cls._sql_indexes.add(
Index(
history_table,
(history_table.id, Index.Equality())))
@classmethod
def __post_setup__(cls):
super().__post_setup__()
# Define Range index to optimise with reduce_ids
for field in cls._fields.values():
field_names = set()
if isinstance(field, fields.One2Many):
Target = field.get_target()
if field.field:
field_names.add(field.field)
elif isinstance(field, fields.Many2Many):
Target = field.get_relation()
if field.origin:
field_names.add(field.origin)
if field.target:
field_names.add(field.target)
else:
continue
field_names.discard('id')
for field_name in field_names:
target_field = getattr(Target, field_name)
if (issubclass(Target, ModelSQL)
and not callable(Target.table_query)
and not hasattr(target_field, 'set')):
target = Target.__table__()
column = Column(target, field_name)
if not target_field.required and Target != cls:
where = column != Null
else:
where = None
if target_field._type == 'reference':
Target._sql_indexes.update({
Index(
target,
(column, Index.Equality()),
where=where),
Index(
target,
(column, Index.Similarity(begin=True)),
(target_field.sql_id(column, Target),
Index.Range()),
where=where),
})
else:
Target._sql_indexes.add(
Index(
target,
(column, Index.Range()),
where=where))
@classmethod
def __table__(cls):
if callable(cls.table_query):
return cls.table_query()
else:
return Table(cls._table)
@classmethod
def __table_history__(cls):
if not cls._history:
raise ValueError('No history table')
return Table(cls._table + '__history')
@classmethod
def __table_handler__(cls, module_name=None, history=False):
return backend.TableHandler(cls, history=history)
@classmethod
def __register__(cls, module_name):
cursor = Transaction().connection.cursor()
super(ModelSQL, cls).__register__(module_name)
if callable(cls.table_query):
return
pool = Pool()
# Initiate after the callable test to prevent calling table_query which
# may rely on other model being registered
sql_table = cls.__table__()
# create/update table in the database
table = cls.__table_handler__(module_name)
if cls._history:
history_table = cls.__table_handler__(module_name, history=True)
for field_name, field in cls._fields.items():
if field_name == 'id':
continue
sql_type = field.sql_type()
if not sql_type:
continue
default = None
if field_name in cls._defaults:
def default():
default_ = cls._clean_defaults({
field_name: cls._defaults[field_name](),
})[field_name]
return field.sql_format(default_)
table.add_column(field_name, field._sql_type, default=default)
if cls._history:
history_table.add_column(field_name, field._sql_type)
if isinstance(field, (fields.Integer, fields.Float)):
# migration from tryton 2.2
table.db_default(field_name, None)
if isinstance(field, (fields.Boolean)):
table.db_default(field_name, False)
if isinstance(field, fields.Many2One):
if field.model_name in ('res.user', 'res.group'):
# XXX need to merge ir and res
ref = field.model_name.replace('.', '_')
else:
ref_model = pool.get(field.model_name)
if (issubclass(ref_model, ModelSQL)
and not callable(ref_model.table_query)):
ref = ref_model._table
# Create foreign key table if missing
if not backend.TableHandler.table_exist(ref):
backend.TableHandler(ref_model)
else:
ref = None
if field_name in ['create_uid', 'write_uid']:
# migration from 3.6
table.drop_fk(field_name)
elif ref:
table.add_fk(field_name, ref, field.ondelete)
required = field.required
# Do not set 'NOT NULL' for Binary field as the database column
# will be left empty if stored in the filestore or filled later by
# the set method.
if isinstance(field, fields.Binary):
required = False
table.not_null_action(
field_name, action=required and 'add' or 'remove')
for field_name, field in cls._fields.items():
if (isinstance(field, fields.Many2One)
and field.model_name == cls.__name__):
if field.path:
default_path = cls._defaults.get(
field.path, lambda: None)()
cursor.execute(*sql_table.select(sql_table.id,
where=(
Column(sql_table, field.path) == default_path)
| (Column(sql_table, field.path) == Null),
limit=1))
if cursor.fetchone():
cls._rebuild_path(field_name)
if field.left and field.right:
left_default = cls._defaults.get(
field.left, lambda: None)()
right_default = cls._defaults.get(
field.right, lambda: None)()
cursor.execute(*sql_table.select(sql_table.id,
where=(
Column(sql_table, field.left) == left_default)
| (Column(sql_table, field.left) == Null)
| (Column(sql_table, field.right) == right_default)
| (Column(sql_table, field.right) == Null),
limit=1))
if cursor.fetchone():
cls._rebuild_tree(field_name, None, 0)
for ident, constraint, _ in cls._sql_constraints:
assert (
not ident.startswith('idx_') and not ident.endswith('_index'))
table.add_constraint(ident, constraint)
if cls._history:
cls._update_history_table()
history_table = cls.__table_history__()
cursor.execute(*sql_table.select(sql_table.id, limit=1))
if cursor.fetchone():
cursor.execute(
*history_table.select(history_table.id, limit=1))
if not cursor.fetchone():
columns = [n for n, f in cls._fields.items()
if f.sql_type()]
cursor.execute(*history_table.insert(
[Column(history_table, c) for c in columns],
sql_table.select(*(Column(sql_table, c)
for c in columns))))
cursor.execute(*history_table.update(
[history_table.write_date], [None]))
@classmethod
def _update_sql_indexes(cls):
if not callable(cls.table_query):
table_h = cls.__table_handler__()
# TODO: remove overlapping indexes
table_h.set_indexes(cls._sql_indexes)
@classmethod
def _update_history_table(cls):
if cls._history:
history_table = cls.__table_handler__(history=True)
for field_name, field in cls._fields.items():
if not field.sql_type():
continue
history_table.add_column(field_name, field._sql_type)
@classmethod
def __raise_integrity_error(
cls, exception, values, field_names=None, transaction=None):
pool = Pool()
if field_names is None:
field_names = list(cls._fields.keys())
if transaction is None:
transaction = Transaction()
for field_name in field_names:
if field_name not in cls._fields:
continue
field = cls._fields[field_name]
# Check required fields
if (field.required
and field.sql_type()
and field_name not in ('create_uid', 'create_date')):
if values.get(field_name) is None:
raise RequiredValidationError(
gettext('ir.msg_required_validation',
**cls.__names__(field_name)))
for name, _, error in cls._sql_constraints:
if backend.TableHandler.convert_name(name) in str(exception):
raise SQLConstraintError(gettext(error))
# Check foreign key in last because this can raise false positive
# if the target is created during the same transaction.
for field_name in field_names:
if field_name not in cls._fields:
continue
field = cls._fields[field_name]
if isinstance(field, fields.Many2One) and values.get(field_name):
Model = pool.get(field.model_name)
create_records = transaction.create_records[field.model_name]
delete_records = transaction.delete_records[field.model_name]
target_records = Model.search([
('id', '=', field.sql_format(values[field_name])),
], order=[])
if not ((
target_records
or (values[field_name] in create_records))
and (values[field_name] not in delete_records)):
error_args = cls.__names__(field_name)
error_args['value'] = values[field_name]
raise ForeignKeyError(
gettext('ir.msg_foreign_model_missing',
**error_args))
@classmethod
def __raise_data_error(
cls, exception, values, field_names=None, transaction=None):
if field_names is None:
field_names = list(cls._fields.keys())
if transaction is None:
transaction = Transaction()
for field_name in field_names:
if field_name not in cls._fields:
continue
field = cls._fields[field_name]
# Check field size
if (hasattr(field, 'size')
and isinstance(field.size, int)
and field.sql_type()):
value = values.get(field_name) or ''
size = len(value)
if size > field.size:
error_args = cls.__names__(field_name)
error_args['value'] = value
error_args['size'] = size
error_args['max_size'] = field.size
raise SizeValidationError(
gettext('ir.msg_size_validation', **error_args))
@classmethod
def history_revisions(cls, ids):
pool = Pool()
ModelAccess = pool.get('ir.model.access')
User = pool.get('res.user')
cursor = Transaction().connection.cursor()
ModelAccess.check(cls.__name__, 'read')
table = cls.__table_history__()
user = User.__table__()
revisions = []
for sub_ids in grouped_slice(ids):
where = reduce_ids(table.id, sub_ids)
cursor.execute(*table.join(user, 'LEFT',
Coalesce(table.write_uid, table.create_uid) == user.id)
.select(
Coalesce(table.write_date, table.create_date),
table.id,
user.name,
where=where))
revisions.append(cursor.fetchall())
revisions = list(chain(*revisions))
revisions.sort(reverse=True)
# SQLite uses char for COALESCE
if revisions and isinstance(revisions[0][0], str):
strptime = datetime.datetime.strptime
format_ = '%Y-%m-%d %H:%M:%S.%f'
revisions = [(strptime(timestamp, format_), id_, name)
for timestamp, id_, name in revisions]
return revisions
@classmethod
def _insert_history(cls, ids, deleted=False):
transaction = Transaction()
cursor = transaction.connection.cursor()
if not cls._history:
return
user = transaction.user
table = cls.__table__()
history = cls.__table_history__()
columns = []
hcolumns = []
if not deleted:
fields = cls._fields
else:
fields = {
'id': cls.id,
'write_uid': cls.write_uid,
'write_date': cls.write_date,
}
for fname, field in sorted(fields.items()):
if not field.sql_type():
continue
columns.append(Column(table, fname))
hcolumns.append(Column(history, fname))
for sub_ids in grouped_slice(ids):
if not deleted:
where = reduce_ids(table.id, sub_ids)
cursor.execute(*history.insert(hcolumns,
table.select(*columns, where=where)))
else:
if transaction.database.has_multirow_insert():
cursor.execute(*history.insert(hcolumns,
[[id_, CurrentTimestamp(), user]
for id_ in sub_ids]))
else:
for id_ in sub_ids:
cursor.execute(*history.insert(hcolumns,
[[id_, CurrentTimestamp(), user]]))
@classmethod
def _restore_history(cls, ids, datetime, _before=False):
if not cls._history:
return
transaction = Transaction()
cursor = transaction.connection.cursor()
table = cls.__table__()
history = cls.__table_history__()
columns = []
hcolumns = []
fnames = sorted(n for n, f in cls._fields.items()
if f.sql_type())
for fname in fnames:
columns.append(Column(table, fname))
if fname == 'write_uid':
hcolumns.append(Literal(transaction.user))
elif fname == 'write_date':
hcolumns.append(CurrentTimestamp())
else:
hcolumns.append(Column(history, fname))
def is_deleted(values):
return all(not v for n, v in zip(fnames, values)
if n not in ['id', 'write_uid', 'write_date'])
to_delete = []
to_update = []
for id_ in ids:
column_datetime = Coalesce(history.write_date, history.create_date)
if not _before:
hwhere = (column_datetime <= datetime)
else:
hwhere = (column_datetime < datetime)
hwhere &= (history.id == id_)
horder = (column_datetime.desc, Column(history, '__id').desc)
cursor.execute(*history.select(*hcolumns,
where=hwhere, order_by=horder, limit=1))
values = cursor.fetchone()
if not values or is_deleted(values):
to_delete.append(id_)
else:
to_update.append(id_)
values = list(values)
cursor.execute(*table.update(columns, values,
where=table.id == id_))
rowcount = cursor.rowcount
if rowcount == -1 or rowcount is None:
cursor.execute(*table.select(table.id,
where=table.id == id_))
rowcount = len(cursor.fetchall())
if rowcount < 1:
cursor.execute(*table.insert(columns, [values]))
if to_delete:
for sub_ids in grouped_slice(to_delete):
where = reduce_ids(table.id, sub_ids)
cursor.execute(*table.delete(where=where))
cls._insert_history(to_delete, True)
if to_update:
cls._insert_history(to_update)
@classmethod
def restore_history(cls, ids, datetime):
'Restore record ids from history at the date time'
cls._restore_history(ids, datetime)
@classmethod
def restore_history_before(cls, ids, datetime):
'Restore record ids from history before the date time'
cls._restore_history(ids, datetime, _before=True)
@classmethod
def __check_timestamp(cls, ids):
transaction = Transaction()
cursor = transaction.connection.cursor()
table = cls.__table__()
if not transaction.timestamp:
return
for sub_ids in grouped_slice(ids):
where = Or()
for id_ in sub_ids:
try:
timestamp = transaction.timestamp.pop(
'%s,%s' % (cls.__name__, id_))
except KeyError:
continue
if timestamp is None:
continue
sql_type = fields.Char('timestamp').sql_type().base
where.append((table.id == id_)
& (Extract('EPOCH',
Coalesce(table.write_date, table.create_date)
).cast(sql_type) != timestamp))
if where:
cursor.execute(*table.select(table.id, where=where, limit=1))
if cursor.fetchone():
raise ConcurrencyException(
'Records were modified in the meanwhile')
@classmethod
@no_table_query
def create(cls, vlist):
transaction = Transaction()
cursor = transaction.connection.cursor()
pool = Pool()
Translation = pool.get('ir.translation')
super(ModelSQL, cls).create(vlist)
table = cls.__table__()
modified_fields = set()
defaults_cache = {} # Store already computed default values
missing_defaults = {} # Store missing default values by schema
new_ids = []
vlist = [v.copy() for v in vlist]
for values in vlist:
# Clean values
for key in ('create_uid', 'create_date',
'write_uid', 'write_date', 'id'):
if key in values:
del values[key]
modified_fields |= values.keys()
# Get default values
values_schema = tuple(sorted(values))
if values_schema not in missing_defaults:
default = []
missing_defaults[values_schema] = default_values = {}
for fname, field in cls._fields.items():
if fname in values:
continue
if fname in [
'create_uid', 'create_date',
'write_uid', 'write_date', 'id']:
continue
if isinstance(field, fields.Function) and not field.setter:
continue
if fname in defaults_cache:
default_values[fname] = defaults_cache[fname]
else:
default.append(fname)
if default:
defaults = cls.default_get(default, with_rec_name=False)
default_values.update(cls._clean_defaults(defaults))
defaults_cache.update(default_values)
values.update(missing_defaults[values_schema])
insert_columns = [table.create_uid, table.create_date]
insert_values = [transaction.user, CurrentTimestamp()]
# Insert record
for fname, value in values.items():
field = cls._fields[fname]
if not hasattr(field, 'set'):
insert_columns.append(Column(table, fname))
insert_values.append(field.sql_format(value))
try:
if transaction.database.has_returning():
cursor.execute(*table.insert(insert_columns,
[insert_values], [table.id]))
id_new, = cursor.fetchone()
else:
id_new = transaction.database.nextid(
transaction.connection, cls._table)
if id_new:
insert_columns.append(table.id)
insert_values.append(id_new)
cursor.execute(*table.insert(insert_columns,
[insert_values]))
else:
cursor.execute(*table.insert(insert_columns,
[insert_values]))
id_new = transaction.database.lastid(cursor)
new_ids.append(id_new)
except (
backend.DatabaseIntegrityError,
backend.DatabaseDataError) as exception:
transaction = Transaction()
with Transaction().new_transaction(), \
Transaction().set_context(_check_access=False):
if isinstance(exception, backend.DatabaseIntegrityError):
cls.__raise_integrity_error(
exception, values, transaction=transaction)
elif isinstance(exception, backend.DatabaseDataError):
cls.__raise_data_error(
exception, values, transaction=transaction)
raise
transaction.create_records[cls.__name__].update(new_ids)
# Update path before fields_to_set which could create children
if cls._path_fields:
field_names = list(sorted(cls._path_fields))
cls._set_path(field_names, repeat(new_ids, len(field_names)))
# Update mptt before fields_to_set which could create children
if cls._mptt_fields:
field_names = list(sorted(cls._mptt_fields))
cls._update_mptt(field_names, repeat(new_ids, len(field_names)))
translation_values = {}
fields_to_set = {}
for values, new_id in zip(vlist, new_ids):
for fname, value in values.items():
field = cls._fields[fname]
if (getattr(field, 'translate', False)
and not hasattr(field, 'set')):
translation_values.setdefault(
'%s,%s' % (cls.__name__, fname), {})[new_id] = (
field.sql_format(value))
if hasattr(field, 'set'):
args = fields_to_set.setdefault(fname, [])
actions = iter(args)
for ids, val in zip(actions, actions):
if val == value:
ids.append(new_id)
break
else:
args.extend(([new_id], value))
if translation_values:
for name, translations in translation_values.items():
Translation.set_ids(name, 'model', Transaction().language,
list(translations.keys()), list(translations.values()))
for fname in sorted(fields_to_set, key=cls.index_set_field):
fargs = fields_to_set[fname]
field = cls._fields[fname]
field.set(cls, fname, *fargs)
cls._insert_history(new_ids)
cls.__check_domain_rule(new_ids, 'create')
records = cls.browse(new_ids)
for sub_records in grouped_slice(
records, record_cache_size(transaction)):
cls._validate(sub_records)
cls.trigger_create(records)
return records
@classmethod
def read(cls, ids, fields_names):
pool = Pool()
Rule = pool.get('ir.rule')
Translation = pool.get('ir.translation')
super(ModelSQL, cls).read(ids, fields_names=fields_names)
transaction = Transaction()
cursor = Transaction().connection.cursor()
if not ids:
return []
# construct a clause for the rules :
domain = Rule.domain_get(cls.__name__, mode='read')
fields_related = defaultdict(set)
extra_fields = set()
if 'write_date' not in fields_names:
extra_fields.add('write_date')
for field_name in fields_names:
if field_name in {'_timestamp', '_write', '_delete'}:
continue
if '.' in field_name:
field_name, field_related = field_name.split('.', 1)
fields_related[field_name].add(field_related)
field = cls._fields[field_name]
if hasattr(field, 'datetime_field') and field.datetime_field:
extra_fields.add(field.datetime_field)
if field.context:
extra_fields.update(fields.get_eval_fields(field.context))
extra_fields.discard('id')
all_fields = (
set(fields_names) | fields_related.keys() | extra_fields)
result = []
table = cls.__table__()
in_max = transaction.database.IN_MAX
history_order = None
history_clause = None
history_limit = None
if (cls._history
and transaction.context.get('_datetime')
and not callable(cls.table_query)):
in_max = 1
table = cls.__table_history__()
column = Coalesce(table.write_date, table.create_date)
history_clause = (column <= Transaction().context['_datetime'])
history_order = (column.desc, Column(table, '__id').desc)
history_limit = 1
columns = {}
for f in all_fields:
field = cls._fields.get(f)
if field and field.sql_type():
columns[f] = field.sql_column(table).as_(f)
if backend.name == 'sqlite':
columns[f].output_name += ' [%s]' % field.sql_type().base
elif f in {'_write', '_delete'}:
if not callable(cls.table_query):
rule_domain = Rule.domain_get(
cls.__name__, mode=f.lstrip('_'))
# No need to compute rule domain if it is the same as the
# read rule domain because it is already applied as where
# clause.
if rule_domain and rule_domain != domain:
rule_tables = {None: (table, None)}
rule_tables, rule_expression = cls.search_domain(
rule_domain, active_test=False, tables=rule_tables)
if len(rule_tables) > 1:
# The expression uses another table
rule_tables, rule_expression = cls.search_domain(
rule_domain, active_test=False)
rule_from = convert_from(None, rule_tables)
rule_table, _ = rule_tables[None]
rule_where = rule_table.id == table.id
rule_expression = rule_from.select(
rule_expression, where=rule_where)
columns[f] = rule_expression.as_(f)
else:
columns[f] = Literal(True).as_(f)
elif f == '_timestamp' and not callable(cls.table_query):
sql_type = fields.Char('timestamp').sql_type().base
columns[f] = Extract(
'EPOCH', Coalesce(table.write_date, table.create_date)
).cast(sql_type).as_('_timestamp')
if ('write_date' not in fields_names
and columns.keys() == {'write_date'}):
columns.pop('write_date')
extra_fields.discard('write_date')
if columns:
if 'id' not in fields_names:
columns['id'] = table.id.as_('id')
tables = {None: (table, None)}
if domain:
tables, dom_exp = cls.search_domain(
domain, active_test=False, tables=tables)
from_ = convert_from(None, tables)
for sub_ids in grouped_slice(ids, in_max):
sub_ids = list(sub_ids)
red_sql = reduce_ids(table.id, sub_ids)
where = red_sql
if history_clause:
where &= history_clause
if domain:
where &= dom_exp
cursor.execute(*from_.select(*columns.values(), where=where,
order_by=history_order, limit=history_limit))
fetchall = list(cursor_dict(cursor))
if not len(fetchall) == len({}.fromkeys(sub_ids)):
cls.__check_domain_rule(
ids, 'read', nodomain='ir.msg_read_error')
cls.__check_domain_rule(ids, 'read')
raise RuntimeError("Undetected access error")
result.extend(fetchall)
else:
result = [{'id': x} for x in ids]
cachable_fields = []
max_write_date = max(
(r['write_date'] for r in result if r.get('write_date')),
default=None)