/
SchemaBootstrap.java
2477 lines (2253 loc) · 90.6 KB
/
SchemaBootstrap.java
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
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2023 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.domain.schema;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.sql.Array;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.NClob;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLClientInfoException;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.SQLXML;
import java.sql.Savepoint;
import java.sql.Statement;
import java.sql.Struct;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Executor;
import javax.sql.DataSource;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngineConfiguration;
import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.ibatis.SerializableTypeHandler;
import org.alfresco.repo.admin.patch.AppliedPatch;
import org.alfresco.repo.admin.patch.Patch;
import org.alfresco.repo.admin.patch.impl.SchemaUpgradeScriptPatch;
import org.alfresco.repo.content.filestore.FileContentWriter;
import org.alfresco.repo.domain.dialect.MySQLClusterNDBDialect;
import org.alfresco.repo.domain.dialect.Oracle9Dialect;
import org.alfresco.repo.domain.dialect.SQLServerDialect;
import org.alfresco.repo.domain.dialect.Dialect;
import org.alfresco.repo.domain.dialect.MySQLInnoDBDialect;
import org.alfresco.repo.domain.dialect.PostgreSQLDialect;
import org.alfresco.repo.domain.patch.AppliedPatchDAO;
import org.alfresco.service.cmr.repository.ContentWriter;
import org.alfresco.service.descriptor.DescriptorService;
import org.alfresco.util.DatabaseMetaDataHelper;
import org.alfresco.util.DialectUtil;
import org.alfresco.util.LogUtil;
import org.alfresco.util.PropertyCheck;
import org.alfresco.util.TempFileProvider;
import org.alfresco.util.schemacomp.ExportDb;
import org.alfresco.util.schemacomp.MultiFileDumper;
import org.alfresco.util.schemacomp.MultiFileDumper.DbToXMLFactory;
import org.alfresco.util.schemacomp.Result;
import org.alfresco.util.schemacomp.Results;
import org.alfresco.util.schemacomp.SchemaComparator;
import org.alfresco.util.schemacomp.SchemaDifferenceHelper;
import org.alfresco.util.schemacomp.XMLToSchema;
import org.alfresco.util.schemacomp.model.Schema;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.extensions.surf.util.AbstractLifecycleBean;
import org.springframework.extensions.surf.util.I18NUtil;
/**
* Bootstraps the schema and schema update. The schema is considered missing if the applied patch table
* is not present, and the schema is considered empty if the applied patch table is empty.
*
* @author Derek Hulley
*/
public class SchemaBootstrap extends AbstractLifecycleBean
{
/** The global property containing the default batch size used by --FOREACH */
private static final String PROPERTY_DEFAULT_BATCH_SIZE = "system.upgrade.default.batchsize";
private static final String MSG_DIALECT_USED = "schema.update.msg.dialect_used";
private static final String MSG_DATABASE_USED = "schema.update.msg.database_used";
private static final String MSG_BYPASSING_SCHEMA_UPDATE = "schema.update.msg.bypassing";
private static final String MSG_NORMALIZED_SCHEMA = "schema.update.msg.normalized_schema";
private static final String MSG_NO_CHANGES = "schema.update.msg.no_changes";
private static final String MSG_ALL_STATEMENTS = "schema.update.msg.all_statements";
private static final String MSG_EXECUTING_GENERATED_SCRIPT = "schema.update.msg.executing_generated_script";
private static final String MSG_EXECUTING_COPIED_SCRIPT = "schema.update.msg.executing_copied_script";
private static final String MSG_EXECUTING_STATEMENT = "schema.update.msg.executing_statement";
private static final String MSG_OPTIONAL_STATEMENT_FAILED = "schema.update.msg.optional_statement_failed";
private static final String MSG_OPTIONAL_PATCH_RUN_SUGGESTION = "system.schema_comp.patch_run_suggestion";
private static final String ERR_FORCED_STOP = "schema.update.err.forced_stop";
private static final String ERR_MULTIPLE_SCHEMAS = "schema.update.err.found_multiple";
private static final String ERR_PREVIOUS_FAILED_BOOTSTRAP = "schema.update.err.previous_failed";
private static final String ERR_UPDATE_IN_PROGRESS_ON_ANOTHER_NODE = "schema.update.err.upgrade_in_progress_on_another_node";
private static final String ERR_STATEMENT_FAILED = "schema.update.err.statement_failed";
private static final String ERR_UPDATE_FAILED = "schema.update.err.update_failed";
private static final String ERR_VALIDATION_FAILED = "schema.update.err.validation_failed";
private static final String ERR_SCRIPT_NOT_RUN = "schema.update.err.update_script_not_run";
private static final String ERR_SCRIPT_NOT_FOUND = "schema.update.err.script_not_found";
private static final String ERR_STATEMENT_INCLUDE_BEFORE_SQL = "schema.update.err.statement_include_before_sql";
private static final String ERR_STATEMENT_VAR_ASSIGNMENT_BEFORE_SQL = "schema.update.err.statement_var_assignment_before_sql";
private static final String ERR_STATEMENT_VAR_ASSIGNMENT_FORMAT = "schema.update.err.statement_var_assignment_format";
private static final String ERR_STATEMENT_TERMINATOR = "schema.update.err.statement_terminator";
private static final String ERR_DELIMITER_SET_BEFORE_SQL = "schema.update.err.delimiter_set_before_sql";
private static final String ERR_DELIMITER_INVALID = "schema.update.err.delimiter_invalid";
private static final String DEBUG_SCHEMA_COMP_NO_REF_FILE = "system.schema_comp.debug.no_ref_file";
private static final String INFO_SCHEMA_COMP_ALL_OK = "system.schema_comp.info.all_ok";
private static final String WARN_SCHEMA_COMP_PROBLEMS_FOUND = "system.schema_comp.warn.problems_found";
private static final String WARN_SCHEMA_COMP_PROBLEMS_FOUND_NO_FILE = "system.schema_comp.warn.problems_found_no_file";
private static final String DEBUG_SCHEMA_COMP_TIME_TAKEN = "system.schema_comp.debug.time_taken";
public static final int DEFAULT_LOCK_RETRY_COUNT = 24;
public static final int DEFAULT_LOCK_RETRY_WAIT_SECONDS = 5;
public static final int DEFAULT_MAX_STRING_LENGTH = 1024;
public static final int DEFAULT_MAX_STRING_LENGTH_NDB = 400;
private static volatile int maxStringLength = DEFAULT_MAX_STRING_LENGTH;
private Dialect dialect;
private SchemaDifferenceHelper differenceHelper;
private ResourcePatternResolver rpr = new PathMatchingResourcePatternResolver(this.getClass().getClassLoader());
/**
* @see #DEFAULT_MAX_STRING_LENGTH
*/
public static final void setMaxStringLength(int length, Dialect dialect)
{
int max = (dialect instanceof MySQLClusterNDBDialect ? DEFAULT_MAX_STRING_LENGTH_NDB : DEFAULT_MAX_STRING_LENGTH);
if (length < max)
{
throw new AlfrescoRuntimeException("The maximum string length must >= "+max+" characters.");
}
SchemaBootstrap.maxStringLength = length;
}
/**
* @return Returns the maximum number of characters that a string field can be
*/
public static final int getMaxStringLength()
{
return SchemaBootstrap.maxStringLength;
}
/**
* Truncates or returns a string that will fit into the string columns in the schema. Text fields can
* either cope with arbitrarily long text fields or have the default limit, {@link #DEFAULT_MAX_STRING_LENGTH}.
*
* @param value the string to check
* @return Returns a string that is short enough for {@link SchemaBootstrap#getMaxStringLength()}
*
* @since 3.2
*/
public static final String trimStringForTextFields(String value)
{
if (value != null && value.length() > maxStringLength)
{
return value.substring(0, maxStringLength);
}
else
{
return value;
}
}
/**
* Provide a reference to the DescriptorService, used to provide information
* about the repository such as the database schema version number.
*
* @param descriptorService the descriptorService to set
*/
public void setDescriptorService(DescriptorService descriptorService)
{
this.descriptorService = descriptorService;
}
/**
* Defines the DatabaseMetaDataHelper to be used
*
* @param databaseMetaDataHelper DatabaseMetaDataHelper
*/
public void setDatabaseMetaDataHelper(DatabaseMetaDataHelper databaseMetaDataHelper)
{
this.databaseMetaDataHelper = databaseMetaDataHelper;
}
/**
* Sets the previously auto-detected Hibernate dialect.
*
* @param dialect
* the dialect
*/
public void setDialect(Dialect dialect)
{
this.dialect = dialect;
}
public void setDifferenceHelper(SchemaDifferenceHelper differenceHelper)
{
this.differenceHelper = differenceHelper;
}
private static Log logger = LogFactory.getLog(SchemaBootstrap.class);
private DescriptorService descriptorService;
private DataSource dataSource;
private AppliedPatchDAO appliedPatchDAO;
private String schemaOuputFilename;
private boolean updateSchema;
private boolean stopAfterSchemaBootstrap;
private List<String> preCreateScriptUrls;
private List<String> postCreateScriptUrls;
private List<String> schemaReferenceUrls;
private List<SchemaUpgradeScriptPatch> preUpdateScriptPatches;
private List<SchemaUpgradeScriptPatch> postUpdateScriptPatches;
private List<SchemaUpgradeScriptPatch> updateActivitiScriptPatches;
private int schemaUpdateLockRetryCount = DEFAULT_LOCK_RETRY_COUNT;
private int schemaUpdateLockRetryWaitSeconds = DEFAULT_LOCK_RETRY_WAIT_SECONDS;
private int maximumStringLength;
private Properties globalProperties;
private String dbSchemaName;
private DatabaseMetaDataHelper databaseMetaDataHelper;
private ThreadLocal<StringBuilder> executedStatementsThreadLocal = new ThreadLocal<StringBuilder>();
public SchemaBootstrap()
{
preCreateScriptUrls = new ArrayList<String>(1);
postCreateScriptUrls = new ArrayList<String>(1);
preUpdateScriptPatches = new ArrayList<SchemaUpgradeScriptPatch>(4);
postUpdateScriptPatches = new ArrayList<SchemaUpgradeScriptPatch>(4);
updateActivitiScriptPatches = new ArrayList<SchemaUpgradeScriptPatch>(4);
maximumStringLength = -1;
globalProperties = new Properties();
}
public void setDataSource(DataSource dataSource)
{
this.dataSource = dataSource;
}
public void setAppliedPatchDAO(AppliedPatchDAO appliedPatchDAO)
{
this.appliedPatchDAO = appliedPatchDAO;
}
/**
* Set this to output the full database creation script
*
* @param schemaOuputFilename the name of a file to dump the schema to, or null to ignore
*/
public void setSchemaOuputFilename(String schemaOuputFilename)
{
this.schemaOuputFilename = schemaOuputFilename;
}
/**
* Set whether to modify the schema or not. Either way, the schema will be validated.
*
* @param updateSchema true to update and validate the schema, otherwise false to just
* validate the schema. Default is <b>true</b>.
*/
public void setUpdateSchema(boolean updateSchema)
{
this.updateSchema = updateSchema;
}
/**
* Set whether this component should terminate the bootstrap process after running all the
* usual checks and scripts. This has the additional effect of dumping a final schema
* structure file just before exiting.
* <p>
* <b>WARNING: </b>USE FOR DEBUG AND UPGRADE TESTING ONLY
*
* @param stopAfterSchemaBootstrap <tt>true</tt> to terminate (with exception) after
* running all the usual schema updates and checks.
*/
public void setStopAfterSchemaBootstrap(boolean stopAfterSchemaBootstrap)
{
this.stopAfterSchemaBootstrap = stopAfterSchemaBootstrap;
}
/**
* Specifies the schema reference files that will be used to validate the repository
* schema whenever changes have been made. The database dialect placeholder will be
* resolved so that the correct reference files are loaded for the current database
* type (e.g. PostgreSQL)
*
* @param schemaReferenceUrls the schemaReferenceUrls to set
*/
public void setSchemaReferenceUrls(List<String> schemaReferenceUrls)
{
this.schemaReferenceUrls = schemaReferenceUrls;
}
/**
* Set the number times that the DB must be checked for the presence of the table
* indicating that a schema change is in progress.
*
* @param schemaUpdateLockRetryCount the number of times to retry (default 24)
*/
public void setSchemaUpdateLockRetryCount(int schemaUpdateLockRetryCount)
{
this.schemaUpdateLockRetryCount = schemaUpdateLockRetryCount;
}
/**
* Set the wait time (seconds) between checks for the schema update lock.
*
* @param schemaUpdateLockRetryWaitSeconds the number of seconds between checks (default 5 seconds)
*/
public void setSchemaUpdateLockRetryWaitSeconds(int schemaUpdateLockRetryWaitSeconds)
{
this.schemaUpdateLockRetryWaitSeconds = schemaUpdateLockRetryWaitSeconds;
}
/**
* Optionally override the system's default maximum string length. Some databases have
* limitations on how long the <b>string_value</b> columns can be while other do not.
* Some parts of the persistence have alternatives when the string values exceed this
* length while others do not. Either way, it is possible to adjust the text column sizes
* and adjust this value manually to override the default associated with the database
* being used.
* <p>
* The system - as of V2.1.2 - will attempt to adjust the maximum string length size
* automatically and therefore this method is not normally required. But it is possible
* to manually override the value if, for example, the system doesn't guess the correct
* maximum length or if the dialect is not explicitly catered for.
* <p>
* All negative or zero values are ignored and the system defaults to its best guess based
* on the dialect being used.
*
* @param maximumStringLength the maximum length of the <b>string_value</b> columns
*/
public void setMaximumStringLength(int maximumStringLength)
{
if (maximumStringLength > 0)
{
this.maximumStringLength = maximumStringLength;
}
}
/**
* Set db.schema.name to be used
*/
public void setDbSchemaName(String dbSchemaName)
{
if (PropertyCheck.isValidPropertyString(dbSchemaName))
{
this.dbSchemaName = dbSchemaName;
}
}
/**
* Sets the properties map from which we look up some configuration settings.
*
* @param globalProperties
* the global properties
*/
public void setGlobalProperties(Properties globalProperties)
{
this.globalProperties = globalProperties;
}
/**
* Register a new script for execution when creating a clean schema. The order of registration
* determines the order of execution.
*
* @param preCreateScriptUrl the script URL, possibly containing the <b>${db.script.dialect}</b> placeholder
*/
public void addPreCreateScriptUrl(String preCreateScriptUrl)
{
if (logger.isDebugEnabled())
{
logger.debug("Registered create script URL (pre-Hibernate): " + preCreateScriptUrl);
}
this.preCreateScriptUrls.add(preCreateScriptUrl);
}
/**
* Register a new script for execution after the Hibernate schema creation phase. The order of registration
* determines the order of execution.
*
* @param postUpdateScriptUrl the script URL, possibly containing the <b>${db.script.dialect}</b> placeholder
*/
public void addPostCreateScriptUrl(String postUpdateScriptUrl)
{
if (logger.isDebugEnabled())
{
logger.debug("Registered create script URL (post-Hibernate): " + postUpdateScriptUrl);
}
this.postCreateScriptUrls.add(postUpdateScriptUrl);
}
/**
* Register a new SQL-based patch for consideration against the instance (before Hibernate execution)
*
* @param scriptPatch the patch that will be examined for execution
*/
public void addPreUpdateScriptPatch(SchemaUpgradeScriptPatch scriptPatch)
{
if(false == scriptPatch.isIgnored())
{
if (logger.isDebugEnabled())
{
logger.debug("Registered script patch (pre-Hibernate): " + scriptPatch.getId());
}
this.preUpdateScriptPatches.add(scriptPatch);
}
else
{
logger.info("Ignoring script patch (pre-Hibernate): " + scriptPatch.getId());
}
}
/**
* Register a new SQL-based patch for consideration against the instance (after Hibernate execution)
*
* @param scriptPatch the patch that will be examined for execution
*/
public void addPostUpdateScriptPatch(SchemaUpgradeScriptPatch scriptPatch)
{
if(false == scriptPatch.isIgnored())
{
if (logger.isDebugEnabled())
{
logger.debug("Registered script patch (post-Hibernate): " + scriptPatch.getId());
}
this.postUpdateScriptPatches.add(scriptPatch);
}
else
{
logger.info("Ignoring script patch (post-Hibernate): " + scriptPatch.getId());
}
}
/**
* Register a new SQL-based patch for consideration against the Activiti instance
*
* @param scriptPatch the patch that will be examined for execution
*/
public void addUpdateActivitiScriptPatch(SchemaUpgradeScriptPatch scriptPatch)
{
if(false == scriptPatch.isIgnored())
{
if (logger.isDebugEnabled())
{
logger.debug("Registered Activiti script patch: " + scriptPatch.getId());
}
this.updateActivitiScriptPatches.add(scriptPatch);
}
else
{
logger.info("Ignoring Activiti script patch: " + scriptPatch.getId());
}
}
private static class NoSchemaException extends Exception
{
private static final long serialVersionUID = 5574280159910824660L;
}
/**
* Used to indicate a forced stop of the bootstrap.
*
* @see SchemaBootstrap#setStopAfterSchemaBootstrap(boolean)
*
* @author Derek Hulley
* @since 3.1.1
*/
private static class BootstrapStopException extends RuntimeException
{
private static final long serialVersionUID = 4250016675538442181L;
private BootstrapStopException()
{
super(I18NUtil.getMessage(ERR_FORCED_STOP));
}
}
/**
* Count applied patches. This fails if multiple applied patch tables are found,
* which normally indicates that the schema view needs to be limited.
*
* @param connection a valid database connection
* @return Returns the number of applied patches
* @throws NoSchemaException if the table of applied patches can't be found
*/
private int countAppliedPatches(Connection connection) throws Exception
{
String defaultSchema = dbSchemaName != null ? dbSchemaName : databaseMetaDataHelper.getSchema(connection);
if (defaultSchema != null && defaultSchema.length() == 0)
{
defaultSchema = null;
}
String defaultCatalog = connection.getCatalog();
if (defaultCatalog != null && defaultCatalog.length() == 0)
{
defaultCatalog = null;
}
DatabaseMetaData dbMetadata = connection.getMetaData();
ResultSet tableRs = dbMetadata.getTables(defaultCatalog, defaultSchema, "%", null);
boolean newPatchTable = false;
boolean oldPatchTable = false;
try
{
boolean multipleSchemas = false;
while (tableRs.next())
{
String tableName = tableRs.getString("TABLE_NAME");
if (tableName.equalsIgnoreCase("applied_patch"))
{
if (oldPatchTable || newPatchTable)
{
// Found earlier
multipleSchemas = true;
}
oldPatchTable = true;
}
else if (tableName.equalsIgnoreCase("alf_applied_patch"))
{
if (oldPatchTable || newPatchTable)
{
// Found earlier
multipleSchemas = true;
}
newPatchTable = true;
}
}
// We go through all the tables so that multiple visible schemas are detected
if (multipleSchemas)
{
throw new AlfrescoRuntimeException(ERR_MULTIPLE_SCHEMAS);
}
}
finally
{
try { tableRs.close(); } catch (Throwable e) {e.printStackTrace(); }
}
if (newPatchTable)
{
Statement stmt = connection.createStatement();
try
{
ResultSet rs = stmt.executeQuery("select count(id) from alf_applied_patch");
rs.next();
int count = rs.getInt(1);
return count;
}
catch (SQLException e)
{
// This should work at least and is probably an indication of the user viewing multiple schemas
throw new AlfrescoRuntimeException(ERR_MULTIPLE_SCHEMAS);
}
finally
{
try { stmt.close(); } catch (Throwable e) {}
}
}
else if (oldPatchTable)
{
// found the old style table name
Statement stmt = connection.createStatement();
try
{
ResultSet rs = stmt.executeQuery("select count(id) from applied_patch");
rs.next();
int count = rs.getInt(1);
return count;
}
finally
{
try { stmt.close(); } catch (Throwable e) {}
}
}
else
{
// The applied patches table is not present
throw new NoSchemaException();
}
}
/**
* Check whether Activiti tables already created in db.
*
* @param connection a valid database connection
* @return <code>true</code> if Activiti tables already created in schema, otherwise <code>false</code>
*/
private boolean checkActivitiTablesExist(Connection connection)
{
Statement stmt = null;
try
{
stmt = connection.createStatement();
stmt.executeQuery("select min(id_) from ACT_RU_TASK");
return true;
}
catch (SQLException e)
{
logger.debug("Did not find ACT_RU_TASK table.");
return false;
}
finally
{
try
{
if (stmt != null)
{
stmt.close();
}
}
catch (Throwable e) {}
}
}
/**
* @return Returns the name of the applied patch table, or <tt>null</tt> if the table doesn't exist
*/
private String getAppliedPatchTableName(Connection connection) throws Exception
{
Statement stmt = connection.createStatement();
try
{
stmt.executeQuery("select * from alf_applied_patch");
return "alf_applied_patch";
}
catch (Throwable e)
{
// we'll try another table name
}
finally
{
try { stmt.close(); } catch (Throwable e) {}
}
// for pre-1.4 databases, the table was named differently
stmt = connection.createStatement();
try
{
stmt.executeQuery("select * from applied_patch");
return "applied_patch";
}
catch (Throwable e)
{
// It is not there
return null;
}
finally
{
try { stmt.close(); } catch (Throwable e) {}
}
}
/**
* @return Returns the number of applied patches
*/
private boolean didPatchSucceed(Connection connection, String patchId, boolean alternative) throws Exception
{
String patchTableName = getAppliedPatchTableName(connection);
if (patchTableName == null)
{
// Table doesn't exist, yet
return false;
}
Statement stmt = connection.createStatement();
try
{
ResultSet rs = stmt.executeQuery("select succeeded, was_executed from " + patchTableName + " where id = '" + patchId + "'");
if (!rs.next())
{
return false;
}
boolean succeeded = rs.getBoolean(1);
boolean wasExecuted = rs.getBoolean(2);
if (alternative)
{
return succeeded && wasExecuted;
}
else
{
return succeeded;
}
}
finally
{
try { stmt.close(); } catch (Throwable e) {}
}
}
/**
* Finds the <b>version.properties</b> file and determines the installed <b>version.schema</b>.<br>
* The only way to determine the original installed schema number is by quering the for the minimum value in
* <b>alf_applied_patch.applied_to_schema</b>. This might not work if an upgrade is attempted straight from
* Alfresco v1.0!
*
* @return the installed schema number or <tt>-1</tt> if the installation is new.
*/
private int getInstalledSchemaNumber(Connection connection) throws Exception
{
Statement stmt = connection.createStatement();
try
{
ResultSet rs = stmt.executeQuery(
"select min(applied_to_schema) from alf_applied_patch where applied_to_schema > -1");
if (!rs.next())
{
// Nothing in the table
return -1;
}
if (rs.getObject(1) == null)
{
// Nothing in the table
return -1;
}
int installedSchema = rs.getInt(1);
return installedSchema;
}
finally
{
try { stmt.close(); } catch (Throwable e) {}
}
}
private static class LockFailedException extends Exception
{
private static final long serialVersionUID = -6676398230191205456L;
}
/**
* Records that the bootstrap process has started
*/
private synchronized void setBootstrapStarted(Connection connection) throws Exception
{
// Create the marker table
Statement stmt = connection.createStatement();
try
{
stmt.executeUpdate("create table alf_bootstrap_lock (charval CHAR(1) NOT NULL)");
// Success
if (logger.isInfoEnabled())
{
logger.info("Bootstrap started.");
}
return;
}
catch (Throwable e)
{
// We throw a well-known exception to be handled by retrying code if required
throw new LockFailedException();
}
finally
{
try { stmt.close(); } catch (Throwable e) {}
}
}
/**
* Used to identify the case where one of the nodes (!maybe even this one!)
* has created the alf_bootstrap_lock table - This table indicates that a schema initialization
* or schema DB update is in progress.
*
* @return true if the alf_bootstrap_lock marker table exists in the DB; false otherwise
*
*/
private synchronized boolean isBootstrapInProgress(Connection connection) throws Exception
{
Statement stmt = connection.createStatement();
try
{
stmt.executeQuery("select * from alf_bootstrap_lock");
// Success
if (logger.isInfoEnabled())
{
logger.info("Bootstrap marker still present in the DB.");
}
return true;
}
catch (Throwable e)
{
// The exception will be thrown if the table does not exist.
return false;
}
finally
{
try { stmt.close(); } catch (Throwable e) {}
}
}
/**
* Records that the bootstrap process has finished
*/
private void setBootstrapCompleted(Connection connection) throws Exception
{
// Create the marker table
Statement stmt = connection.createStatement();
try
{
stmt.executeUpdate("drop table alf_bootstrap_lock");
// from Thor
executedStatementsThreadLocal.set(null);
if (logger.isInfoEnabled())
{
logger.info("Bootstrap completed.");
}
}
catch (Throwable e)
{
if (logger.isDebugEnabled())
{
logger.debug("Exception in deleting the alf_bootstrap_lock table: " + e.getMessage(), e);
}
throw AlfrescoRuntimeException.create(ERR_PREVIOUS_FAILED_BOOTSTRAP);
}
finally
{
try { stmt.close(); } catch (Throwable e) {}
}
}
/**
* Builds the schema from scratch or applies the necessary patches to the schema.
*/
private boolean updateSchema(Connection connection) throws Exception
{
boolean create = false;
try
{
final int numberOfPatchesApplied = countAppliedPatches(connection);
if (logger.isInfoEnabled())
{
logger.info("Applied patches detected: " + numberOfPatchesApplied);
}
}
catch (NoSchemaException e)
{
create = true;
}
// Get the dialect
final Dialect dialect = this.dialect;
String dialectStr = dialect.getClass().getSimpleName();
if (create)
{
long start = System.currentTimeMillis();
// execute pre-create scripts (not patches)
for (String scriptUrl : this.preCreateScriptUrls)
{
executeScriptUrl(connection, scriptUrl);
}
// execute post-create scripts (not patches)
for (String scriptUrl : this.postCreateScriptUrls)
{
executeScriptUrl(connection, scriptUrl);
}
if (logger.isInfoEnabled())
{
logger.info("Creating Alfresco tables took " + (System.currentTimeMillis() - start) + " ms");
}
}
else
{
long start = System.currentTimeMillis();
// Execute any pre-auto-update scripts
checkSchemaPatchScripts(connection, preUpdateScriptPatches, true);
// Execute any post-auto-update scripts
checkSchemaPatchScripts(connection, postUpdateScriptPatches, true);
if (logger.isInfoEnabled())
{
logger.info(
"Checking and patching Alfresco tables took " + (System.currentTimeMillis() - start) + " ms");
}
}
ensureCurrentClusterMemberIsBootstrapping(connection);
// Initialise Activiti DB, using an unclosable connection
boolean activitiTablesExist = checkActivitiTablesExist(connection);
if (logger.isInfoEnabled())
{
logger.info("Activiti tables need to be " + (activitiTablesExist ? "checked for patches" : " created"));
}
if(!activitiTablesExist)
{
long start = System.currentTimeMillis();
ensureCurrentClusterMemberIsBootstrapping(connection);
// Activiti DB updates are performed as patches in alfresco, only give
// control to activiti when creating new one.
initialiseActivitiDBSchema(new UnclosableConnection(connection));
// ALF-18996: Upgrade from 3.4.12 to 4.2.0 fails: Activiti tables have not been bootstrapped
// The Activiti bootstrap is effectively doing the work of all the other patches,
// which should be considered complete.
int installedSchemaNumber = getInstalledSchemaNumber(connection);
for (Patch activitiScriptPatch : updateActivitiScriptPatches)
{
AppliedPatch appliedPatch = new AppliedPatch();
appliedPatch.setId(activitiScriptPatch.getId());
appliedPatch.setDescription(activitiScriptPatch.getDescription());
appliedPatch.setFixesFromSchema(activitiScriptPatch.getFixesFromSchema());
appliedPatch.setFixesToSchema(activitiScriptPatch.getFixesToSchema());
appliedPatch.setTargetSchema(activitiScriptPatch.getTargetSchema());
appliedPatch.setAppliedToSchema(installedSchemaNumber);
appliedPatch.setAppliedToServer("UNKNOWN");
appliedPatch.setAppliedOnDate(new Date()); // the date applied
appliedPatch.setSucceeded(true);
appliedPatch.setWasExecuted(false);
appliedPatch.setReport("Placeholder for Activiti bootstrap at schema " + installedSchemaNumber);
appliedPatchDAO.createAppliedPatch(appliedPatch);
}
if (logger.isInfoEnabled())
{
logger.info("Creating Activiti tables took " + (System.currentTimeMillis() - start) + " ms");
}
}
else
{
long start = System.currentTimeMillis();
// Execute any auto-update scripts for Activiti tables
checkSchemaPatchScripts(connection, updateActivitiScriptPatches, true);
// verify that all Activiti patches have been applied correctly
checkSchemaPatchScripts(connection, updateActivitiScriptPatches, false);
if (logger.isInfoEnabled())
{
logger.info("Checking and patching Activiti tables took " + (System.currentTimeMillis() - start) + " ms");
}
}
if (!create)
{
long start = System.currentTimeMillis();
// verify that all patches have been applied correctly
checkSchemaPatchScripts(connection, preUpdateScriptPatches, false); // check scripts
checkSchemaPatchScripts(connection, postUpdateScriptPatches, false); // check scripts
if (logger.isInfoEnabled())
{
logger.info("Checking that all patches have been applied took " + (System.currentTimeMillis() - start) + " ms");
}
}