-
Notifications
You must be signed in to change notification settings - Fork 34
/
Versioned.php
3017 lines (2683 loc) · 98.6 KB
/
Versioned.php
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
<?php
namespace SilverStripe\Versioned;
use InvalidArgumentException;
use LogicException;
use SilverStripe\Control\Controller;
use SilverStripe\Control\Cookie;
use SilverStripe\Control\Director;
use SilverStripe\Control\HTTPRequest;
use SilverStripe\Core\ClassInfo;
use SilverStripe\Core\Config\Config;
use SilverStripe\Core\Extension;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\Core\Resettable;
use SilverStripe\Dev\Deprecation;
use SilverStripe\Forms\FieldList;
use SilverStripe\ORM\ArrayList;
use SilverStripe\ORM\DataExtension;
use SilverStripe\ORM\DataList;
use SilverStripe\ORM\DataObject;
use SilverStripe\ORM\DataQuery;
use SilverStripe\ORM\DB;
use SilverStripe\ORM\FieldType\DBDatetime;
use SilverStripe\ORM\Queries\SQLSelect;
use SilverStripe\Security\Member;
use SilverStripe\Security\Permission;
use SilverStripe\Security\Security;
use SilverStripe\View\TemplateGlobalProvider;
/**
* The Versioned extension allows your DataObjects to have several versions,
* allowing you to rollback changes and view history. An example of this is
* the pages used in the CMS.
*
* Note: This extension relies on the object also having the {@see Ownership} extension applied.
*
* @property int $Version
* @mixin RecursivePublishable
*
* @extends DataExtension<DataObject&RecursivePublishable&static>
*/
class Versioned extends DataExtension implements TemplateGlobalProvider, Resettable
{
/**
* Versioning mode for this object.
* Note: Not related to the current versioning mode in the state / session
* Will be one of 'StagedVersioned' or 'Versioned';
*
* @var string
*/
protected $mode;
/**
* The default reading mode
*/
const DEFAULT_MODE = 'Stage.Live';
/**
* Constructor arg to specify that staging is active on this record.
* 'Staging' implies that 'Versioning' is also enabled.
*/
const STAGEDVERSIONED = 'StagedVersioned';
/**
* Constructor arg to specify that versioning only is active on this record.
*/
const VERSIONED = 'Versioned';
/**
* The Public stage.
*/
const LIVE = 'Live';
/**
* The draft (default) stage
*/
const DRAFT = 'Stage';
/**
* A cache used by get_versionnumber_by_stage().
* Clear through {@link flushCache()}.
* version (int)0 means not on this stage.
*
* @var array
*/
protected static $cache_versionnumber;
/**
* Set if draft site is secured or not. Fails over to
* $draft_site_secured if unset
*
* @var bool|null
*/
protected static $is_draft_site_secured = null;
/**
* Default config for $is_draft_site_secured
*
* @config
* @var bool
*/
private static $draft_site_secured = true;
/**
* Cache of version to modified dates for this object
*
* @var array
*/
protected $versionModifiedCache = [];
/**
* Current reading mode. Supports stage / archive modes.
*
* @var string
*/
protected static $reading_mode = null;
/**
* Default reading mode, if none set.
* Any modes which differ to this value should be assigned via querystring / session (if enabled)
*
* @var null
*/
protected static $default_reading_mode = Versioned::DEFAULT_MODE;
/**
* Field used to hold the migrating version
*/
const MIGRATING_VERSION = 'MigratingVersion';
/**
* Field used to hold flag indicating the next write should be without a new version
*/
const NEXT_WRITE_WITHOUT_VERSIONED = 'NextWriteWithoutVersioned';
/**
* Prevents delete() from creating a _Versions record (in case this must be deferred)
* Best used with suppressDeleteVersion()
*/
const DELETE_WRITES_VERSION_DISABLED = 'DeleteWritesVersionDisabled';
/**
* Ensure versioned page doesn't attempt to virtualise these non-db fields
*
* @config
* @var array
*/
private static $non_virtual_fields = [
Versioned::MIGRATING_VERSION,
Versioned::NEXT_WRITE_WITHOUT_VERSIONED,
Versioned::DELETE_WRITES_VERSION_DISABLED,
];
/**
* Additional database columns for the new
* "_Versions" table. Used in {@link augmentDatabase()}
* and all Versioned calls extending or creating
* SELECT statements.
*
* @var array $db_for_versions_table
*/
private static $db_for_versions_table = [
"RecordID" => "Int",
"Version" => "Int",
"WasPublished" => "Boolean",
"WasDeleted" => "Boolean",
"WasDraft" => "Boolean(1)",
"AuthorID" => "Int",
"PublisherID" => "Int"
];
/**
* Ensure versioned records cast extra fields properly
*
* @config
* @var array
*/
private static $casting = [
"RecordID" => "Int",
"WasPublished" => "Boolean",
"WasDeleted" => "Boolean",
"WasDraft" => "Boolean",
"AuthorID" => "Int",
"PublisherID" => "Int"
];
/**
* @var array
* @config
*/
private static $db = [
'Version' => 'Int'
];
/**
* Used to enable or disable the prepopulation of the version number cache.
* Defaults to true.
*
* @config
* @var boolean
*/
private static $prepopulate_versionnumber_cache = true;
/**
* Indicates whether augmentSQL operations should add subselects as WHERE conditions instead of INNER JOIN
* intersections. Performance of the INNER JOIN scales on the size of _Versions tables where as the condition scales
* on the number of records being returned from the base query.
*
* @config
* @var bool
*/
private static $use_conditions_over_inner_joins = false;
/**
* Additional database indexes for the new
* "_Versions" table. Used in {@link augmentDatabase()}.
*
* @var array $indexes_for_versions_table
*/
private static $indexes_for_versions_table = [
'RecordID_Version' => [
'type' => 'index',
'columns' => ['RecordID', 'Version'],
],
'RecordID' => [
'type' => 'index',
'columns' => ['RecordID'],
],
'Version' => [
'type' => 'index',
'columns' => ['Version'],
],
'AuthorID' => [
'type' => 'index',
'columns' => ['AuthorID'],
],
'PublisherID' => [
'type' => 'index',
'columns' => ['PublisherID'],
],
];
/**
* An array of DataObject extensions that may require versioning for extra tables
* The array value is a set of suffixes to form these table names, assuming a preceding '_'.
* E.g. if Extension1 creates a new table 'Class_suffix1'
* and Extension2 the tables 'Class_suffix2' and 'Class_suffix3':
*
* $versionableExtensions = array(
* 'Extension1' => 'suffix1',
* 'Extension2' => array('suffix2', 'suffix3'),
* );
*
* This can also be manipulated by updating the current loaded config
*
* SiteTree:
* versionableExtensions:
* - Extension1:
* - suffix1
* - suffix2
* - Extension2:
* - suffix1
* - suffix2
*
* or programatically:
*
* Config::modify()->merge($this->owner->class, 'versionableExtensions',
* array('Extension1' => 'suffix1', 'Extension2' => array('suffix2', 'suffix3')));
*
*
* Your extension must implement VersionableExtension interface in order to
* apply custom tables for versioned.
*
* @config
* @var array
*/
private static $versionableExtensions = [];
/**
* Permissions necessary to view records outside of the live stage (e.g. archive / draft stage).
*
* @config
* @var array
*/
private static $non_live_permissions = ['CMS_ACCESS_LeftAndMain', 'CMS_ACCESS_CMSMain', 'VIEW_DRAFT_CONTENT', 'CAN_DEV_BUILD'];
/**
* Use PHP's session storage for the "reading mode" and "unsecuredDraftSite",
* instead of explicitly relying on the "stage" query parameter.
* This is considered bad practice, since it can cause draft content
* to leak under live URLs to unauthorised users, depending on HTTP cache settings.
*
* @config
* @var bool
*/
private static $use_session = false;
/**
* Reset static configuration variables to their default values.
*/
public static function reset()
{
Versioned::$reading_mode = '';
Controller::curr()->getRequest()->getSession()->clear('readingMode');
}
/**
* Amend freshly created DataQuery objects with versioned-specific
* information.
*
* @param SQLSelect $query
* @param DataQuery $dataQuery
*/
public function augmentDataQueryCreation(SQLSelect &$query, DataQuery &$dataQuery)
{
// Convert reading mode to dataquery params and assign
$args = ReadingMode::toDataQueryParams(Versioned::get_reading_mode());
if ($args) {
foreach ($args as $key => $value) {
$dataQuery->setQueryParam($key, $value);
}
}
}
/**
* Construct a new Versioned object.
*
* @var string $mode One of "StagedVersioned" or "Versioned".
*/
public function __construct($mode = Versioned::STAGEDVERSIONED)
{
if (!in_array($mode, [static::STAGEDVERSIONED, static::VERSIONED])) {
throw new InvalidArgumentException("Invalid mode: {$mode}");
}
$this->mode = $mode;
}
/**
* Get this record at a specific version
*
* @param int|string|null $from Version or stage to get at. Null mean returns self object
* @return Versioned|DataObject
*/
public function getAtVersion($from)
{
// Null implies return current version
if (is_null($from)) {
return $this->owner;
}
$baseClass = $this->owner->baseClass();
$id = $this->owner->ID ?: $this->owner->OldID;
// By version number
if (is_numeric($from)) {
return Versioned::get_version($baseClass, $id, $from);
}
// By stage
return Versioned::get_by_stage($baseClass, $from)->byID($id);
}
/**
* Get modified date and stage for the given version
*
* @param int $version
* @return array A list containing 0 => LastEdited, 1 => Stage
*/
protected function getLastEditedAndStageForVersion($version)
{
// Cache key
$baseTable = $this->baseTable();
$id = $this->owner->ID;
$key = "{$baseTable}#{$id}/{$version}";
// Check cache
if (isset($this->versionModifiedCache[$key])) {
return $this->versionModifiedCache[$key];
}
// Build query
$table = "\"{$baseTable}_Versions\"";
$query = SQLSelect::create(['"LastEdited"', '"WasPublished"'], $table)
->addWhere([
"{$table}.\"RecordID\"" => $id,
"{$table}.\"Version\"" => $version
]);
$result = $query->execute()->record();
if (!$result) {
return null;
}
$list = [
$result['LastEdited'],
$result['WasPublished'] ? static::LIVE : static::DRAFT,
];
$this->versionModifiedCache[$key] = $list;
return $list;
}
/**
* Updates query parameters of relations attached to versioned dataobjects
*
* @param array $params
*/
public function updateInheritableQueryParams(&$params)
{
// Skip if versioned isn't set
if (!isset($params['Versioned.mode'])) {
return;
}
// Adjust query based on original selection criterea
switch ($params['Versioned.mode']) {
case 'all_versions':
{
// Versioned.mode === all_versions doesn't inherit very well, so default to stage
$params['Versioned.mode'] = 'stage';
$params['Versioned.stage'] = static::DRAFT;
break;
}
case 'version':
{
// If we selected this object from a specific version, we need
// to find the date this version was published, and ensure
// inherited queries select from that date.
$version = $params['Versioned.version'];
$dateAndStage = $this->getLastEditedAndStageForVersion($version);
// Filter related objects at the same date as this version
unset($params['Versioned.version']);
if ($dateAndStage) {
list($date, $stage) = $dateAndStage;
$params['Versioned.mode'] = 'archive';
$params['Versioned.date'] = $date;
$params['Versioned.stage'] = $stage;
} else {
// Fallback to default
$params['Versioned.mode'] = 'stage';
$params['Versioned.stage'] = static::DRAFT;
}
break;
}
}
}
/**
* Augment the the SQLSelect that is created by the DataQuery
*
* See {@see augmentLazyLoadFields} for lazy-loading applied prior to this.
*
* @param SQLSelect $query
* @param DataQuery|null $dataQuery
* @throws InvalidArgumentException
*/
public function augmentSQL(SQLSelect $query, DataQuery $dataQuery = null)
{
if (!$dataQuery) {
return;
}
// Ensure query mode exists
$versionedMode = $dataQuery->getQueryParam('Versioned.mode');
if (!$versionedMode) {
return;
}
switch ($versionedMode) {
case 'stage':
$this->augmentSQLStage($query, $dataQuery);
break;
case 'stage_unique':
$this->augmentSQLStageUnique($query, $dataQuery);
break;
case 'archive':
$this->augmentSQLVersionedArchive($query, $dataQuery);
break;
case 'latest_version_single':
$this->augmentSQLVersionedLatestSingle($query, $dataQuery);
break;
case 'latest_versions':
$this->augmentSQLVersionedLatest($query, $dataQuery);
break;
case 'version':
$this->augmentSQLVersionedVersion($query, $dataQuery);
break;
case 'all_versions':
$this->augmentSQLVersionedAll($query);
break;
default:
throw new InvalidArgumentException("Bad value for query parameter Versioned.mode: {$versionedMode}");
}
}
/**
* Reading a specific stage (Stage or Live)
*
* @param SQLSelect $query
* @param DataQuery $dataQuery
*/
protected function augmentSQLStage(SQLSelect $query, DataQuery $dataQuery)
{
if (!$this->hasStages()) {
return;
}
$stage = $dataQuery->getQueryParam('Versioned.stage');
ReadingMode::validateStage($stage);
if ($stage === static::DRAFT) {
return;
}
// Rewrite all tables to select from the live version
foreach ($query->getFrom() as $table => $dummy) {
if (!$this->isTableVersioned($table)) {
continue;
}
$stageTable = $this->stageTable($table, $stage);
$query->renameTable($table, $stageTable);
}
}
/**
* Reading a specific stage, but only return items that aren't in any other stage
*
* @param SQLSelect $query
* @param DataQuery $dataQuery
*/
protected function augmentSQLStageUnique(SQLSelect $query, DataQuery $dataQuery)
{
if (!$this->hasStages()) {
return;
}
// Set stage first
$this->augmentSQLStage($query, $dataQuery);
// Now exclude any ID from any other stage.
$stage = $dataQuery->getQueryParam('Versioned.stage');
$excludingStage = $stage === static::DRAFT ? static::LIVE : static::DRAFT;
// Note that we double rename to avoid the regular stage rename
// renaming all subquery references to be Versioned.stage
$tempName = 'ExclusionarySource_' . $excludingStage;
$excludingTable = $this->baseTable($excludingStage);
$baseTable = $this->baseTable($stage);
$query->addWhere("\"{$baseTable}\".\"ID\" NOT IN (SELECT \"ID\" FROM \"{$tempName}\")");
$query->renameTable($tempName, $excludingTable);
}
/**
* Augment SQL to select from `_Versions` table instead.
*
* @param SQLSelect $query
* @param bool $filterDeleted Whether to exclude deleted entries or not
*/
protected function augmentSQLVersioned(SQLSelect $query, bool $filterDeleted = true)
{
$baseTable = $this->baseTable();
foreach ($query->getFrom() as $alias => $join) {
if (!$this->isTableVersioned($alias)) {
continue;
}
if ($alias != $baseTable) {
// Make sure join includes version as well
$query->setJoinFilter(
$alias,
"\"{$alias}_Versions\".\"RecordID\" = \"{$baseTable}_Versions\".\"RecordID\""
. " AND \"{$alias}_Versions\".\"Version\" = \"{$baseTable}_Versions\".\"Version\""
);
}
// Rewrite all usages of `Table` to `Table_Versions`
$query->renameTable($alias, $alias . '_Versions');
// However, add an alias back to the base table in case this must later be joined.
// See ApplyVersionFilters for example which joins _Versions back onto draft table.
$query->renameTable($alias . '_Draft', $alias);
}
// Add all <basetable>_Versions columns
foreach (Config::inst()->get(static::class, 'db_for_versions_table') as $name => $type) {
$query->selectField(sprintf('"%s_Versions"."%s"', $baseTable, $name), $name);
}
// Alias the record ID as the row ID, and ensure ID filters are aliased correctly
$query->selectField("\"{$baseTable}_Versions\".\"RecordID\"", "ID");
$query->replaceText("\"{$baseTable}_Versions\".\"ID\"", "\"{$baseTable}_Versions\".\"RecordID\"");
// However, if doing count, undo rewrite of "ID" column
$query->replaceText(
"count(DISTINCT \"{$baseTable}_Versions\".\"RecordID\")",
"count(DISTINCT \"{$baseTable}_Versions\".\"ID\")"
);
// Filter deleted versions, which are all unqueryable
if ($filterDeleted) {
$query->addWhere(["\"{$baseTable}_Versions\".\"WasDeleted\"" => 0]);
}
}
/**
* Prepare a sub-select for determining latest versions of records on the base table. This is used as either an
* inner join or sub-select on the base query
*
* @param SQLSelect $baseQuery
* @param DataQuery $dataQuery
* @return SQLSelect
*/
protected function prepareMaxVersionSubSelect(SQLSelect $baseQuery, DataQuery $dataQuery)
{
$baseTable = $this->baseTable();
// Create a sub-select that we determine latest versions
$subSelect = SQLSelect::create(
['LatestVersion' => "MAX(\"{$baseTable}_Versions_Latest\".\"Version\")"],
[$baseTable . '_Versions_Latest' => "\"{$baseTable}_Versions\""]
);
$subSelect->renameTable($baseTable, "{$baseTable}_Versions");
// Determine the base table of the existing query
$baseFrom = $baseQuery->getFrom();
$baseTable = trim(reset($baseFrom) ?? '', '"');
// And then the name of the base table in the new query
$newFrom = $subSelect->getFrom();
$newTable = trim(key($newFrom ?? []) ?? '', '"');
// Parse "where" conditions to find those appropriate to be "promoted" into an inner join
// We can ONLY promote a filter on the primary key of the base table. Any other conditions will make the
// version returned incorrect, as we are filtering out version that may be the latest (and correct) version
foreach ($baseQuery->getWhere() as $condition) {
if (is_object($condition)) {
continue;
}
$conditionClause = key($condition ?? []);
// Pull out the table and field for this condition. We'll skip anything we can't parse
if (preg_match('/^"([^"]+)"\."([^"]+)"/', $conditionClause ?? '', $matches) !== 1) {
continue;
}
$table = $matches[1];
$field = $matches[2];
if ($table !== $baseTable || $field !== 'RecordID') {
continue;
}
// Rename conditions on the base table to the new alias
$conditionClause = preg_replace(
'/^"([^"]+)"\./',
"\"{$newTable}\".",
$conditionClause ?? ''
);
$subSelect->addWhere([$conditionClause => reset($condition)]);
}
$shouldApplySubSelectAsCondition = $this->shouldApplySubSelectAsCondition($baseQuery);
$this->owner->extend(
'augmentMaxVersionSubSelect',
$subSelect,
$dataQuery,
$shouldApplySubSelectAsCondition
);
return $subSelect;
}
/**
* Indicates if a subquery filtering versioned records should apply as a condition instead of an inner join
*
* @param SQLSelect $baseQuery
*/
protected function shouldApplySubSelectAsCondition(SQLSelect $baseQuery)
{
$baseTable = $this->baseTable();
$shouldApply =
$baseQuery->getLimit() === 1 || Config::inst()->get(static::class, 'use_conditions_over_inner_joins');
$this->owner->extend('updateApplyVersionedFiltersAsConditions', $shouldApply, $baseQuery, $baseTable);
return $shouldApply;
}
/**
* Filter the versioned history by a specific date and archive stage
*
* @param SQLSelect $query
* @param DataQuery $dataQuery
*/
protected function augmentSQLVersionedArchive(SQLSelect $query, DataQuery $dataQuery)
{
$baseTable = $this->baseTable();
$date = $dataQuery->getQueryParam('Versioned.date');
if (!$date) {
throw new InvalidArgumentException("Invalid archive date");
}
// Query against _Versions table first
$this->augmentSQLVersioned($query);
// Validate stage
$stage = $dataQuery->getQueryParam('Versioned.stage');
ReadingMode::validateStage($stage);
$subSelect = $this->prepareMaxVersionSubSelect($query, $dataQuery);
$subSelect->addWhere(["\"{$baseTable}_Versions_Latest\".\"LastEdited\" <= ?" => $date]);
// Filter on appropriate stage column in addition to date
if ($this->hasStages()) {
$stageColumn = $stage === static::LIVE
? 'WasPublished'
: 'WasDraft';
$subSelect->addWhere("\"{$baseTable}_Versions_Latest\".\"{$stageColumn}\" = 1");
}
if ($this->shouldApplySubSelectAsCondition($query)) {
$subSelect->addWhere(
"\"{$baseTable}_Versions_Latest\".\"RecordID\" = \"{$baseTable}_Versions\".\"RecordID\""
);
$query->addWhere([
"\"{$baseTable}_Versions\".\"Version\" = ({$subSelect->sql($params)})" => $params,
]);
return;
}
$subSelect->addSelect("\"{$baseTable}_Versions_Latest\".\"RecordID\"");
$subSelect->addGroupBy("\"{$baseTable}_Versions_Latest\".\"RecordID\"");
// Join on latest version filtered by date
$query->addInnerJoin(
'(' . $subSelect->sql($params) . ')',
<<<SQL
"{$baseTable}_Versions_Latest"."RecordID" = "{$baseTable}_Versions"."RecordID"
AND "{$baseTable}_Versions_Latest"."LatestVersion" = "{$baseTable}_Versions"."Version"
SQL
,
"{$baseTable}_Versions_Latest",
20,
$params
);
}
/**
* Return latest version instance, regardless of whether it is on a particular stage.
* This is similar to augmentSQLVersionedLatest() below, except it only returns a single value
* selected by Versioned.id
*
* @param SQLSelect $query
* @param DataQuery $dataQuery
*/
protected function augmentSQLVersionedLatestSingle(SQLSelect $query, DataQuery $dataQuery)
{
$id = $dataQuery->getQueryParam('Versioned.id');
if (!$id) {
throw new InvalidArgumentException("Invalid id");
}
// Query against _Versions table first
$this->augmentSQLVersioned($query);
$baseTable = $this->baseTable();
$query->addWhere(["\"$baseTable\".\"RecordID\"" => $id]);
$query->setOrderBy("Version DESC");
$query->setLimit(1);
}
/**
* Return latest version instances, regardless of whether they are on a particular stage.
* This provides "show all, including deleted" functionality.
*
* Note: latest_version ignores deleted versions, and will select the latest non-deleted
* version.
*
* @param SQLSelect $query
* @param DataQuery $dataQuery
*/
protected function augmentSQLVersionedLatest(SQLSelect $query, DataQuery $dataQuery)
{
// Query against _Versions table first
$this->augmentSQLVersioned($query);
// Join and select only latest version
$baseTable = $this->baseTable();
$subSelect = $this->prepareMaxVersionSubSelect($query, $dataQuery);
$subSelect->addWhere("\"{$baseTable}_Versions_Latest\".\"WasDeleted\" = 0");
if ($this->shouldApplySubSelectAsCondition($query)) {
$subSelect->addWhere(
"\"{$baseTable}_Versions_Latest\".\"RecordID\" = \"{$baseTable}_Versions\".\"RecordID\""
);
$query->addWhere([
"\"{$baseTable}_Versions\".\"Version\" = ({$subSelect->sql($params)})" => $params,
]);
return;
}
$subSelect->addSelect("\"{$baseTable}_Versions_Latest\".\"RecordID\"");
$subSelect->addGroupBy("\"{$baseTable}_Versions_Latest\".\"RecordID\"");
// Join on latest version filtered by date
$query->addInnerJoin(
'(' . $subSelect->sql($params) . ')',
<<<SQL
"{$baseTable}_Versions_Latest"."RecordID" = "{$baseTable}_Versions"."RecordID"
AND "{$baseTable}_Versions_Latest"."LatestVersion" = "{$baseTable}_Versions"."Version"
SQL
,
"{$baseTable}_Versions_Latest",
20,
$params
);
}
/**
* If selecting a specific version, filter it here
*
* @param SQLSelect $query
* @param DataQuery $dataQuery
*/
protected function augmentSQLVersionedVersion(SQLSelect $query, DataQuery $dataQuery)
{
$version = $dataQuery->getQueryParam('Versioned.version');
if (!$version) {
throw new InvalidArgumentException("Invalid version");
}
// Query against _Versions table first
$this->augmentSQLVersioned($query);
// Add filter on version field
$baseTable = $this->baseTable();
$query->addWhere([
"\"{$baseTable}_Versions\".\"Version\"" => $version,
]);
}
/**
* If all versions are requested, ensure that records are sorted by this field
*
* @param SQLSelect $query
*/
protected function augmentSQLVersionedAll(SQLSelect $query)
{
// Query against _Versions table first
$this->augmentSQLVersioned($query, false);
$baseTable = $this->baseTable();
$query->addOrderBy("\"{$baseTable}_Versions\".\"Version\"");
}
/**
* Determine if the given versioned table is a part of the sub-tree of the current dataobject
* This helps prevent rewriting of other tables that get joined in, in particular, many_many tables
*
* @param string $table
* @return bool True if this table should be versioned
*/
protected function isTableVersioned($table)
{
$schema = DataObject::getSchema();
$tableClass = $schema->tableClass($table);
if (empty($tableClass)) {
return false;
}
// Check that this class belongs to the same tree
$baseClass = $schema->baseDataClass($this->owner);
if (!is_a($tableClass, $baseClass ?? '', true)) {
return false;
}
// Check that this isn't a derived table
// (e.g. _Live, or a many_many table)
$mainTable = $schema->tableName($tableClass);
if ($mainTable !== $table) {
return false;
}
return true;
}
/**
* For lazy loaded fields requiring extra sql manipulation, ie versioning.
*
* @param SQLSelect $query
* @param DataQuery $dataQuery
* @param DataObject $dataObject
*/
public function augmentLoadLazyFields(SQLSelect &$query, DataQuery &$dataQuery = null, $dataObject)
{
// The VersionedMode local variable ensures that this decorator only applies to
// queries that have originated from the Versioned object, and have the Versioned
// metadata set on the query object. This prevents regular queries from
// accidentally querying the *_Versions tables.
$versionedMode = $dataObject->getSourceQueryParam('Versioned.mode');
$modesToAllowVersioning = ['all_versions', 'latest_versions', 'archive', 'version'];
if (!empty($dataObject->Version) &&
(!empty($versionedMode) && in_array($versionedMode, $modesToAllowVersioning ?? []))
) {
// This will ensure that augmentSQL will select only the same version as the owner,
// regardless of how this object was initially selected
$versionColumn = $this->owner->getSchema()->sqlColumnForField($this->owner, 'Version');
$dataQuery->where([
$versionColumn => $dataObject->Version
]);
$dataQuery->setQueryParam('Versioned.mode', 'all_versions');
}
}
public function augmentDatabase()
{
$owner = $this->owner;
$class = get_class($owner);
$schema = $owner->getSchema();
$baseTable = $this->baseTable();
$classTable = $schema->tableName($owner);
$isRootClass = $class === $owner->baseClass();
// Build a list of suffixes whose tables need versioning
$allSuffixes = [];
$versionableExtensions = (array)$owner->config()->get('versionableExtensions');
if (count($versionableExtensions ?? [])) {
foreach ($versionableExtensions as $versionableExtension => $suffixes) {
if ($owner->hasExtension($versionableExtension)) {
foreach ((array)$suffixes as $suffix) {
$allSuffixes[$suffix] = $versionableExtension;
}
}
}
}
// Add the default table with an empty suffix to the list (table name = class name)
$allSuffixes[''] = null;
foreach ($allSuffixes as $suffix => $extension) {
// Check tables for this build
if ($suffix) {
$suffixBaseTable = "{$baseTable}_{$suffix}";
$suffixTable = "{$classTable}_{$suffix}";
} else {
$suffixBaseTable = $baseTable;
$suffixTable = $classTable;
}
$fields = $schema->databaseFields($class, false);
unset($fields['ID']);
if ($fields) {
$options = Config::inst()->get($class, 'create_table_options');
$indexes = $schema->databaseIndexes($class, false);
$extensionClass = $allSuffixes[$suffix];
if ($suffix && ($extension = $owner->getExtensionInstance($extensionClass))) {
if (!$extension instanceof VersionableExtension) {
throw new LogicException(
"Extension {$extensionClass} must implement VersionableExtension"
);
}
// Allow versionable extension to customise table fields and indexes
try {
$extension->setOwner($owner);
if ($extension->isVersionedTable($suffixTable)) {
$extension->updateVersionableFields($suffix, $fields, $indexes);
}
} finally {
$extension->clearOwner();
}
}
// Build _Live table
if ($this->hasStages()) {
$liveTable = $this->stageTable($suffixTable, static::LIVE);
DB::require_table($liveTable, $fields, $indexes, false, $options);
}
// Build _Versions table
//Unique indexes will not work on versioned tables, so we'll convert them to standard indexes:
$nonUniqueIndexes = $this->uniqueToIndex($indexes);
if ($isRootClass) {
// Create table for all versions
$versionFields = array_merge(
Config::inst()->get(static::class, 'db_for_versions_table'),
(array)$fields
);
$versionIndexes = array_merge(
Config::inst()->get(static::class, 'indexes_for_versions_table'),
(array)$nonUniqueIndexes
);
} else {
// Create fields for any tables of subclasses
$versionFields = array_merge(