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 package org.melati.poem;
46
47 import org.melati.poem.dbms.Dbms;
48 import org.melati.poem.transaction.Transactioned;
49 import org.melati.poem.transaction.TransactionedSerial;
50 import org.melati.poem.util.*;
51
52 import java.io.PrintStream;
53 import java.sql.*;
54 import java.util.*;
55
56
57
58
59
60 public class JdbcTable <P extends Persistent> implements Selectable<P>, Table<P> {
61
62
63 private static final int CACHE_LIMIT_DEFAULT = 100;
64 private static final int DISPLAY_ORDER_DEFAULT = 100;
65 private static final Procedure invalidator =
66 new Procedure() {
67 public void apply(Object arg) {
68 ((Transactioned) arg).invalidate();
69 }
70 };
71 Database database;
72 private JdbcTable<P> _this = this;
73 private String name;
74 private String quotedName;
75 private DefinitionSource definitionSource;
76 private TableInfo info = null;
77 private TableListener[] listeners = {};
78 private Column<?>[] columns = {};
79 private Hashtable<String, Column<?>> columnsByName = new Hashtable<String, Column<?>>();
80 private Column<Integer> troidColumn = null;
81 private Column<Boolean> deletedColumn = null;
82 private Column<Capability> canReadColumn = null;
83 private Column<Capability> canSelectColumn = null;
84 private Column<Capability> canWriteColumn = null;
85 private Column<Capability> canDeleteColumn = null;
86 private Column<?> displayColumn = null;
87 private Column<?> searchColumn = null;
88 private String defaultOrderByClause = null;
89 private Column<?>[][] displayColumns = new Column[DisplayLevel.count()][];
90 private Column<?>[] searchColumns = null;
91 private TransactionedSerial serial;
92 private CachedSelection<P> allTroids = null;
93 private Hashtable<String, CachedSelection<P>> cachedSelections = new Hashtable<String, CachedSelection<P>>();
94 private Hashtable<String, CachedCount> cachedCounts = new Hashtable<String, CachedCount>();
95 private Hashtable<String, CachedExists> cachedExists = new Hashtable<String, CachedExists>();
96 private int mostRecentTroid = -1;
97 private int extrasIndex = 0;
98 private CachedIndexFactory transactionStuffs = new CachedIndexFactory() {
99 public Object reallyGet(int index) {
100
101 return new TransactionStuff(
102 JdbcTable.this.database.poemTransaction(index).getConnection());
103 }
104 };
105 private TransactionStuff committedTransactionStuff = null;
106
107
108
109
110
111
112 private Cache cache = new Cache(CACHE_LIMIT_DEFAULT);
113
114
115
116
117 public JdbcTable(Database database, String name,
118 DefinitionSource definitionSource) {
119 this.database = database;
120 this.name = name;
121
122
123
124
125 this.definitionSource = definitionSource;
126 serial = new TransactionedSerial(database);
127 }
128
129
130
131
132 public void init() {
133 }
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148 public void postInitialise() {
149 clearColumnInfoCaches();
150 database.getColumnInfoTable().addListener(
151 new TableListener() {
152 public void notifyTouched(PoemTransaction transaction, Table<?> table,
153 Persistent persistent) {
154 _this.notifyColumnInfo((ColumnInfo)persistent);
155 }
156
157 public void notifyUncached(Table<?> table) {
158 _this.clearColumnInfoCaches();
159 }
160 });
161 }
162
163
164
165
166
167 public final Database getDatabase() {
168 return database;
169 }
170
171
172
173
174
175
176
177
178
179
180 public final String getName() {
181 return name;
182 }
183
184
185
186
187 public final String quotedName() {
188 if (quotedName == null) quotedName = database.quotedName(name);
189 return quotedName;
190 }
191
192
193
194
195
196
197
198 public final String getDisplayName() {
199 return info.getDisplayname();
200 }
201
202
203
204
205
206
207
208 public final String getDescription() {
209 return info.getDescription();
210 }
211
212
213
214
215
216
217
218
219 public final TableCategory getCategory() {
220 return info.getCategory();
221 }
222
223
224
225
226 public final TableInfo getInfo() {
227 return info;
228 }
229
230
231
232
233
234
235
236
237 public final Integer tableInfoID() {
238 return info == null ? null : info.troid();
239 }
240
241
242
243
244
245
246
247
248
249
250
251
252
253 public final Column<?> getColumn(String nameP) throws NoSuchColumnPoemException {
254 Column<?> column = _getColumn(nameP);
255 if (column == null)
256 throw new NoSuchColumnPoemException(this, nameP);
257 else
258 return column;
259 }
260
261 protected final Column<?> _getColumn(String nameP) {
262 Column<?> column = columnsByName.get(nameP.toLowerCase());
263 return column;
264 }
265
266
267
268
269
270
271
272 public final Enumeration<Column<?>> columns() {
273 return new ArrayEnumeration<Column<?>>(columns);
274 }
275
276 public final List<Column<?>> getColumns() {
277 return Arrays.asList(columns);
278 }
279
280
281
282
283 public final int getColumnsCount() {
284 return columns.length;
285 }
286
287
288
289
290
291 public Column<?> columnWithColumnInfoID(int columnInfoID) {
292 for (Enumeration<Column<?>> c = columns(); c.hasMoreElements();) {
293 Column<?> column = c.nextElement();
294 Integer id = column.columnInfoID();
295 if (id != null && id.intValue() == columnInfoID)
296 return column;
297 }
298 return null;
299 }
300
301
302
303
304
305
306
307
308
309
310 public final Column<Integer> troidColumn() {
311 return troidColumn;
312 }
313
314
315
316
317 public final Column<Boolean> deletedColumn() {
318 return deletedColumn;
319 }
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334 public final Column<?> displayColumn() {
335 return displayColumn == null ? troidColumn : displayColumn;
336 }
337
338
339
340
341 @SuppressWarnings("rawtypes")
342 public final void setDisplayColumn(Column column) {
343 displayColumn = column;
344 }
345
346
347
348
349
350
351
352
353
354
355
356
357
358 public final Column<?> primaryCriterionColumn() {
359 return searchColumn;
360 }
361
362
363
364
365 public void setSearchColumn(Column<?> column) {
366 searchColumn = column;
367 }
368
369
370
371
372
373
374 @SuppressWarnings({ "unchecked", "rawtypes" })
375 public String defaultOrderByClause() {
376 String clause = defaultOrderByClause;
377
378 if (clause == null) {
379 clause = EnumUtils.concatenated(
380 ", ",
381 new MappedEnumeration(new ArrayEnumeration(SortUtils.sorted(
382 new Order() {
383 public boolean lessOrEqual(Object a, Object b) {
384 return
385 ((Column)a).getDisplayOrderPriority().intValue() <=
386 ((Column)b).getDisplayOrderPriority().intValue();
387 }
388 },
389 new FilteredEnumeration<Column<?>>(columns()) {
390 public boolean isIncluded(Column<?> column) {
391 return ((Column)column).getDisplayOrderPriority() != null;
392 }
393 }))) {
394 public Object mapped(Object column) {
395 String sort = ((Column)column).fullQuotedName();
396 if (((Column)column).getSortDescending()) sort += " desc";
397 return sort;
398 }
399 });
400
401 if (clause.equals("") && displayColumn() != null)
402 clause = displayColumn().fullQuotedName();
403
404 defaultOrderByClause = clause;
405 }
406
407 return clause;
408 }
409
410
411
412
413 public void clearColumnInfoCaches() {
414 defaultOrderByClause = null;
415 for (int i = 0; i < displayColumns.length; ++i)
416 displayColumns[i] = null;
417 }
418
419
420
421
422
423
424 public void notifyColumnInfo(ColumnInfo infoP) {
425
426 if (infoP == null || infoP.getTableinfo_unsafe().equals(tableInfoID()))
427 clearColumnInfoCaches();
428 }
429
430
431
432
433
434
435
436
437
438
439 private Column<?>[] columnsWhere(String whereClause) {
440
441 Enumeration<Integer> colIDs =
442 getDatabase().getColumnInfoTable().troidSelection(
443 database.quotedName("tableinfo") + " = " + tableInfoID() +
444 " AND (" + whereClause + ")",
445 null, false, PoemThread.inSession() ? PoemThread.transaction() : null);
446
447 Vector<Column<?>> them = new Vector<Column<?>>();
448 while (colIDs.hasMoreElements()) {
449 Column<?> column =
450 columnWithColumnInfoID(((Integer)colIDs.nextElement()).intValue());
451
452 if (column != null)
453 them.addElement(column);
454 }
455
456 Column<?>[] columnsLocal = new Column<?>[them.size()];
457 them.copyInto(columnsLocal);
458 return columnsLocal;
459 }
460
461
462
463
464
465
466
467 public final Enumeration<Column<?>> displayColumns(DisplayLevel level) {
468 Column<?>[] columnsLocal = displayColumns[level.getIndex().intValue()];
469
470 if (columnsLocal == null) {
471 columnsLocal =
472 columnsWhere(database.quotedName("displaylevel") + " <= " +
473 level.getIndex());
474 displayColumns[level.getIndex().intValue()] = columnsLocal;
475 }
476 return new ArrayEnumeration<Column<?>>(columnsLocal);
477 }
478
479
480
481
482
483 public final int displayColumnsCount(DisplayLevel level) {
484 int l = level.getIndex().intValue();
485 if (displayColumns[l] == null)
486
487 displayColumns(level);
488
489 return displayColumns[l].length;
490 }
491
492
493
494
495
496
497
498
499
500 public final Enumeration<Column<?>> getDetailDisplayColumns() {
501 return displayColumns(DisplayLevel.detail);
502 }
503
504
505
506
507 public final int getDetailDisplayColumnsCount() {
508 return displayColumnsCount(DisplayLevel.detail);
509 }
510
511
512
513
514
515
516
517
518
519 public final Enumeration<Column<?>> getRecordDisplayColumns() {
520 return displayColumns(DisplayLevel.record);
521 }
522
523
524
525
526 public final int getRecordDisplayColumnsCount() {
527 return displayColumnsCount(DisplayLevel.record);
528 }
529
530
531
532
533
534
535
536
537
538
539 public final Enumeration<Column<?>> getSummaryDisplayColumns() {
540 return displayColumns(DisplayLevel.summary);
541 }
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558 public final int getSummaryDisplayColumnsCount() {
559 return displayColumnsCount(DisplayLevel.summary);
560 }
561
562
563
564
565
566
567
568
569 public final Enumeration<Column<?>> getSearchCriterionColumns() {
570 Column<?>[] columnsLocal = searchColumns;
571
572 if (columnsLocal == null) {
573 columnsLocal =
574 columnsWhere(database.quotedName("searchability") + " <= " +
575 Searchability.yes.getIndex());
576 searchColumns = columnsLocal;
577 }
578 return new ArrayEnumeration<Column<?>>(searchColumns);
579 }
580
581
582
583
584 public final int getSearchCriterionColumnsCount() {
585 if (searchColumns == null)
586
587 getSearchCriterionColumns();
588
589 return searchColumns.length;
590 }
591
592 private Dbms dbms() {
593 return getDatabase().getDbms();
594 }
595
596
597
598
599 public void dbModifyStructure(String sql)
600 throws StructuralModificationFailedPoemException {
601 database.modifyStructure(sql);
602 }
603
604 private void dbCreateTable() {
605 String createTableSql = dbms().createTableSql(this);
606 database.modifyStructure(createTableSql);
607 String tableSetup = database.getDbms().tableInitialisationSql(this);
608 if (tableSetup != null) {
609 database.modifyStructure(tableSetup);
610 }
611 }
612
613
614
615
616
617 public String getDbmsTableType() {
618 return null;
619 }
620
621
622
623
624
625
626
627
628
629
630 public void dbAddConstraints() {
631 StringBuffer sqb = new StringBuffer();
632 for (int c = 0; c < columns.length; ++c) {
633 if (columns[c].getSQLType() instanceof TroidPoemType){
634 sqb.append("ALTER TABLE " + quotedName());
635 sqb.append(dbms().getPrimaryKeyDefinition(
636 columns[c].getName()));
637 try {
638 dbModifyStructure(sqb.toString());
639 } catch (StructuralModificationFailedPoemException e) {
640
641
642 e = null;
643 }
644 }
645 }
646 for (int c = 0; c < columns.length; ++c) {
647 if (columns[c].getSQLType() instanceof ReferencePoemType){
648 IntegrityFix fix = columns[c].getIntegrityFix();
649 sqb = new StringBuffer();
650 sqb.append("ALTER TABLE " + quotedName());
651 sqb.append(dbms().getForeignKeyDefinition(
652 getName(),
653 columns[c].getName(),
654 ((PersistentReferencePoemType)columns[c].getSQLType()).
655 targetTable().getName(),
656 ((PersistentReferencePoemType)columns[c].getSQLType()).
657 targetTable().troidColumn().getName(),
658 fix.getName()));
659 try {
660 dbModifyStructure(sqb.toString());
661 } catch (StructuralModificationFailedPoemException e) {
662
663
664 e = null;
665 }
666 }
667 }
668
669
670 }
671
672 private void dbAddColumn(Column<?> column) {
673 if (column.getType().getNullable()) {
674 dbModifyStructure(
675 "ALTER TABLE " + quotedName() +
676 " ADD " + column.quotedName() +
677 " " + column.getSQLType().sqlDefinition(dbms()));
678 } else {
679 if (column.getUnique()) {
680 throw new UnificationPoemException("Cannot add new unique, non-nullable column "
681 + column.getName() + " to table " + getName());
682 } else {
683 dbModifyStructure(
684 "ALTER TABLE " + quotedName() +
685 " ADD " + column.quotedName() +
686 " " + column.getSQLType().sqlTypeDefinition(dbms()));
687 dbModifyStructure(
688 "UPDATE " + quotedName() +
689 " SET " + column.quotedName() +
690 " = " + dbms().getQuotedValue(column.getSQLType(),
691 column.getSQLType().sqlDefaultValue(dbms())));
692 }
693 dbModifyStructure(
694 dbms().alterColumnNotNullableSQL(name, column));
695
696 }
697 }
698
699 private void dbCreateIndex(Column<?> column) {
700 if (column.getIndexed()) {
701 if (!dbms().canBeIndexed(column)) {
702 database.log(new UnindexableLogEvent(column));
703 } else {
704 try {
705 dbModifyStructure(
706 "CREATE " + (column.getUnique() ? "UNIQUE " : "") + "INDEX " +
707 indexName(column) +
708 " ON " + quotedName() + " " +
709 "(" + column.quotedName() +
710 dbms().getIndexLength(column) + ")");
711 } catch (StructuralModificationFailedPoemException e) {
712 database.log(new UnindexableLogEvent(column));
713 }
714 }
715 }
716 }
717
718
719
720
721
722
723
724 private String indexName(Column<?> column) {
725 return database.quotedName(
726 dbms().unreservedName(name) + "_" +
727 dbms().unreservedName(column.getName()) + "_i");
728 }
729
730
731
732
733
734
735 private PreparedStatement simpleInsert(Connection connection) {
736 StringBuffer sql = new StringBuffer();
737 sql.append("INSERT INTO " + quotedName() + " (");
738 for (int c = 0; c < columns.length; ++c) {
739 if (c > 0) sql.append(", ");
740 sql.append(columns[c].quotedName());
741 }
742 sql.append(") VALUES (");
743 for (int c = 0; c < columns.length; ++c) {
744 if (c > 0) sql.append(", ");
745 sql.append("?");
746 }
747
748 sql.append(")");
749
750 try {
751 return connection.prepareStatement(sql.toString());
752 }
753 catch (SQLException e) {
754 throw new SimplePrepareFailedPoemException(sql.toString(), e);
755 }
756 }
757
758 private PreparedStatement simpleGet(Connection connection) {
759 StringBuffer sql = new StringBuffer();
760 sql.append("SELECT ");
761 for (int c = 0; c < columns.length; ++c) {
762 if (c > 0) sql.append(", ");
763 sql.append(columns[c].quotedName());
764 }
765 sql.append(" FROM " + quotedName() +
766 " WHERE " + troidColumn.quotedName() + " = ?");
767
768 try {
769 return connection.prepareStatement(sql.toString());
770 }
771 catch (SQLException e) {
772 throw new SimplePrepareFailedPoemException(sql.toString(), e);
773 }
774 }
775
776 private PreparedStatement simpleModify(Connection connection) {
777
778 StringBuffer sql = new StringBuffer();
779 sql.append("UPDATE " + quotedName() + " SET ");
780 for (int c = 0; c < columns.length; ++c) {
781 if (c > 0) sql.append(", ");
782 sql.append(columns[c].quotedName());
783 sql.append(" = ?");
784 }
785 sql.append(" WHERE " + troidColumn.quotedName() + " = ?");
786
787 try {
788 return connection.prepareStatement(sql.toString());
789 }
790 catch (SQLException e) {
791 throw new SimplePrepareFailedPoemException(sql.toString(), e);
792 }
793 }
794
795
796
797
798 public void invalidateTransactionStuffs() {
799 transactionStuffs.invalidate();
800 }
801
802
803
804
805
806
807
808
809
810
811
812
813 private synchronized TransactionStuff getCommittedTransactionStuff() {
814 if (committedTransactionStuff == null)
815 committedTransactionStuff =
816 new TransactionStuff(database.getCommittedConnection());
817 return committedTransactionStuff;
818 }
819
820 private void load(PreparedStatement select, Persistent p) {
821 JdbcPersistent persistent = (JdbcPersistent)p;
822 try {
823 synchronized (select) {
824 select.setInt(1, persistent.troid().intValue());
825 ResultSet rs = select.executeQuery();
826 if (database.logSQL())
827 database.log(new SQLLogEvent(select.toString()));
828 database.incrementQueryCount(select.toString());
829 try {
830 if (!rs.next())
831 persistent.setStatusNonexistent();
832 else {
833 persistent.setStatusExistent();
834 for (int c = 0; c < columns.length; ++c)
835 columns[c].load_unsafe(rs, c + 1, persistent);
836 }
837 persistent.setDirty(false);
838 persistent.markValid();
839 if (rs.next())
840 throw new DuplicateTroidPoemException(this, persistent.troid());
841 }
842 finally {
843 try { rs.close(); } catch (Exception e) {
844 database.log("Cannot close resultset after exception.");
845 }
846 }
847 }
848 }
849 catch (SQLException e) {
850 throw new SimpleRetrievalFailedPoemException(e, select.toString());
851 }
852 catch (ValidationPoemException e) {
853 throw new UnexpectedValidationPoemException(e);
854 }
855 }
856
857
858
859
860
861 @SuppressWarnings("unchecked")
862 public void load(PoemTransaction transaction, Persistent persistent) {
863 load(transaction == null ?
864 getCommittedTransactionStuff().get :
865 ((TransactionStuff)transactionStuffs.get(transaction.index)).get,
866 persistent);
867 }
868
869 private void modify(PoemTransaction transaction, Persistent persistent) {
870 @SuppressWarnings("unchecked")
871 PreparedStatement modify =
872 ((TransactionStuff)transactionStuffs.get(transaction.index)).modify;
873 synchronized (modify) {
874 for (int c = 0; c < columns.length; ++c)
875 columns[c].save_unsafe(persistent, modify, c + 1);
876
877 try {
878 modify.setInt(columns.length + 1, persistent.troid().intValue());
879 }
880 catch (SQLException e) {
881 throw new SQLSeriousPoemException(e);
882 }
883
884 try {
885 modify.executeUpdate();
886 }
887 catch (SQLException e) {
888 throw dbms().exceptionForUpdate(this, modify, false, e);
889 }
890 database.incrementQueryCount(modify.toString());
891
892 if (database.logSQL())
893 database.log(new SQLLogEvent(modify.toString()));
894 }
895 persistent.postModify();
896 }
897
898 @SuppressWarnings("unchecked")
899 private void insert(PoemTransaction transaction, Persistent persistent) {
900
901 PreparedStatement insert =
902 ((TransactionStuff)transactionStuffs.get(transaction.index)).insert;
903 synchronized (insert) {
904 for (int c = 0; c < columns.length; ++c)
905 columns[c].save_unsafe(persistent, insert, c + 1);
906 try {
907 insert.executeUpdate();
908 }
909 catch (SQLException e) {
910 throw dbms().exceptionForUpdate(this, insert, true, e);
911 }
912 database.incrementQueryCount(insert.toString());
913 if (database.logSQL())
914 database.log(new SQLLogEvent(insert.toString()));
915 }
916 persistent.postInsert();
917 }
918
919
920
921
922
923
924
925 public void delete(Integer troid, PoemTransaction transaction) {
926 String sql =
927 "DELETE FROM " + quotedName() +
928 " WHERE " + troidColumn.quotedName() + " = " +
929 troid.toString();
930 try {
931 transaction.writeDown();
932 Connection connection = transaction.getConnection();
933
934 Statement deleteStatement = connection.createStatement();
935 int deleted = deleteStatement.executeUpdate(sql);
936 if (deleted != 1) {
937 throw new RowDisappearedPoemException(this,troid);
938 }
939 deleteStatement.close();
940 database.incrementQueryCount(sql);
941 if (database.logSQL())
942 database.log(new SQLLogEvent(sql));
943
944 cache.delete(troid);
945 }
946 catch (SQLException e) {
947 throw new ExecutingSQLPoemException(sql, e);
948 }
949 }
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967 public void writeDown(PoemTransaction transaction, Persistent p) {
968 JdbcPersistent persistent = (JdbcPersistent)p;
969
970
971
972 if (persistent.isDirty()) {
973 troidColumn.setRaw_unsafe(persistent, persistent.troid());
974
975 if (persistent.statusExistent()) {
976 modify(transaction, persistent);
977 } else if (persistent.statusNonexistent()) {
978 insert(transaction, persistent);
979 persistent.setStatusExistent();
980 }
981
982 persistent.setDirty(false);
983 persistent.postWrite();
984 }
985 }
986
987
988
989
990
991
992 public void uncache() {
993 cache.iterate(invalidator);
994 serial.invalidate();
995 TableListener[] listenersLocal = this.listeners;
996 for (int l = 0; l < listenersLocal.length; ++l)
997 listenersLocal[l].notifyUncached(this);
998 }
999
1000
1001
1002
1003 public void trimCache(int maxSize) {
1004 cache.trim(maxSize);
1005 }
1006
1007
1008
1009
1010
1011
1012 public Cache.Info getCacheInfo() {
1013 return cache.getInfo();
1014 }
1015
1016
1017
1018
1019 public void addListener(TableListener listener) {
1020 listeners = (TableListener[])ArrayUtils.added(listeners, listener);
1021 }
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031 public void notifyTouched(PoemTransaction transaction, Persistent persistent) {
1032 serial.increment(transaction);
1033
1034 TableListener[] listenersLocal = this.listeners;
1035 for (int l = 0; l < listenersLocal.length; ++l)
1036 listenersLocal[l].notifyTouched(transaction, this, persistent);
1037 }
1038
1039
1040
1041
1042 public long serial(PoemTransaction transaction) {
1043 return serial.current(transaction);
1044 }
1045
1046
1047
1048
1049 public void readLock() {
1050 serial(PoemThread.transaction());
1051 }
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081 @SuppressWarnings("unchecked")
1082 public P getObject(Integer troid) throws NoSuchRowPoemException {
1083 JdbcPersistent persistent = (JdbcPersistent)cache.get(troid);
1084
1085 if (persistent == null) {
1086 persistent = (JdbcPersistent)newPersistent();
1087 claim(persistent, troid);
1088 load(PoemThread.transaction(), persistent);
1089 if (persistent.statusExistent())
1090 synchronized (cache) {
1091 JdbcPersistent tryAgain = (JdbcPersistent)cache.get(troid);
1092 if (tryAgain == null) {
1093 try {
1094 cache.put(troid, persistent);
1095 } catch (Cache.InconsistencyException e) {
1096 throw new PoemBugPoemException(
1097 "Problem putting persistent " + persistent + " into cache:", e);
1098 }
1099 } else
1100 persistent = tryAgain;
1101 }
1102 }
1103
1104 if (!persistent.statusExistent())
1105 throw new NoSuchRowPoemException(this, troid);
1106
1107 persistent.existenceLock(PoemThread.sessionToken());
1108
1109 return (P)persistent;
1110 }
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126 public Persistent getObject(int troid) throws NoSuchRowPoemException {
1127 return getObject(new Integer(troid));
1128 }
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147 public String selectionSQL(String fromClause, String whereClause,
1148 String orderByClause, boolean includeDeleted,
1149 boolean excludeUnselectable) {
1150 return selectOrCountSQL(troidColumn().fullQuotedName(),
1151 fromClause, whereClause, orderByClause,
1152 includeDeleted, excludeUnselectable);
1153 }
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176 private ResultSet selectionResultSet(String fromClause, String whereClause,
1177 String orderByClause,
1178 boolean includeDeleted,
1179 boolean excludeUnselectable,
1180 PoemTransaction transaction)
1181 throws SQLPoemException {
1182
1183 String sql = selectionSQL(fromClause, whereClause, orderByClause,
1184 includeDeleted, excludeUnselectable);
1185
1186
1187 try {
1188 Connection connection;
1189 if (transaction == null) {
1190 connection = getDatabase().getCommittedConnection();
1191 } else {
1192 transaction.writeDown();
1193 connection = transaction.getConnection();
1194 }
1195
1196 Statement selectionStatement = connection.createStatement();
1197 ResultSet rs = selectionStatement.executeQuery(sql);
1198 database.incrementQueryCount(sql);
1199
1200 SessionToken token = PoemThread._sessionToken();
1201 if (token != null) {
1202 token.toTidy().add(rs);
1203 token.toTidy().add(selectionStatement);
1204 }
1205 if (database.logSQL())
1206 database.log(new SQLLogEvent(sql));
1207 return rs;
1208 }
1209 catch (SQLException e) {
1210 throw new ExecutingSQLPoemException(sql, e);
1211 }
1212 }
1213
1214
1215
1216
1217
1218
1219
1220 public Enumeration<Integer> troidSelection(String whereClause, String orderByClause,
1221 boolean includeDeleted,
1222 PoemTransaction transaction) {
1223 return troidsFrom(selectionResultSet(null, whereClause, orderByClause,
1224 includeDeleted, true,
1225 transaction));
1226 }
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236 public Enumeration<Integer> troidSelection(Persistent criteria, String orderByClause,
1237 boolean includeDeleted,
1238 boolean excludeUnselectable,
1239 PoemTransaction transaction) {
1240 return troidsFrom(selectionResultSet(((JdbcPersistent) criteria).fromClause(),
1241 whereClause(criteria),
1242 orderByClause,
1243 includeDeleted, excludeUnselectable,
1244 transaction));
1245 }
1246
1247
1248
1249
1250
1251 private Enumeration<Integer> troidsFrom(ResultSet them) {
1252 return new ResultSetEnumeration<Integer>(them) {
1253 public Integer mapped(ResultSet rs) throws SQLException {
1254 return new Integer(rs.getInt(1));
1255 }
1256 };
1257 }
1258
1259
1260
1261
1262 public void rememberAllTroids(boolean flag) {
1263 if (flag) {
1264 if (allTroids == null &&
1265
1266 troidColumn() != null)
1267 allTroids = new CachedSelection<P>(this, null, null);
1268 }
1269 else
1270 allTroids = null;
1271 }
1272
1273
1274
1275
1276 public void setCacheLimit(Integer limit) {
1277 cache.setSize(limit == null ? CACHE_LIMIT_DEFAULT : limit.intValue());
1278 }
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302 public Enumeration<Integer> troidSelection(String whereClause, String orderByClause,
1303 boolean includeDeleted)
1304 throws SQLPoemException {
1305 if (allTroids != null &&
1306 (whereClause == null || whereClause.equals("")) &&
1307 (orderByClause == null || orderByClause.equals("") ||
1308 orderByClause == defaultOrderByClause()) &&
1309 !includeDeleted)
1310 return allTroids.troids();
1311 else
1312 return troidSelection(whereClause, orderByClause, includeDeleted,
1313 PoemThread.inSession() ? PoemThread.transaction() : null);
1314 }
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330 public Enumeration<P> selection() throws SQLPoemException {
1331 return selection((String)null, (String)null, false);
1332 }
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357 public final Enumeration<P> selection(String whereClause)
1358 throws SQLPoemException {
1359 return selection(whereClause, null, false);
1360 }
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376 public P firstSelection(String whereClause) {
1377 Enumeration<P> them = selection(whereClause);
1378 return maybeFirst(them);
1379 }
1380
1381 public P maybeFirst(Enumeration<P> them) {
1382 return them.hasMoreElements() ? them.nextElement() : null;
1383 }
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401 public Enumeration<P> selection(String whereClause, String orderByClause,
1402 boolean includeDeleted)
1403 throws SQLPoemException {
1404 return objectsFromTroids(troidSelection(whereClause, orderByClause,
1405 includeDeleted));
1406 }
1407
1408
1409
1410
1411
1412
1413
1414
1415 public Enumeration<P> selection(Persistent criteria)
1416 throws SQLPoemException {
1417 return selection(criteria,
1418 criteria.getTable().defaultOrderByClause(), false, true);
1419 }
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429 public Enumeration<P> selection(Persistent criteria, String orderByClause)
1430 throws SQLPoemException {
1431 return selection(criteria, orderByClause, false, true);
1432 }
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443 public Enumeration<P> selection(Persistent criteria, String orderByClause,
1444 boolean includeDeleted, boolean excludeUnselectable)
1445 throws SQLPoemException {
1446 return objectsFromTroids(troidSelection(criteria, orderByClause,
1447 includeDeleted, excludeUnselectable,
1448 null));
1449 }
1450
1451
1452
1453
1454 private Enumeration<P> objectsFromTroids(Enumeration<Integer> troids) {
1455 return new MappedEnumeration<P, Integer>(troids) {
1456 public P mapped(Integer troid) {
1457 return getObject(troid);
1458 }
1459 };
1460 }
1461
1462
1463
1464
1465
1466 public String countSQL(String whereClause) {
1467 return countSQL(null, whereClause, false, true);
1468 }
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479 public String countSQL(String fromClause, String whereClause,
1480 boolean includeDeleted, boolean excludeUnselectable) {
1481 return selectOrCountSQL("count(*)", fromClause, whereClause, "",
1482 includeDeleted, excludeUnselectable);
1483 }
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499 private String selectOrCountSQL(String selectClause, String fromClause,
1500 String whereClause, String orderByClause,
1501 boolean includeDeleted,
1502 boolean excludeUnselectable) {
1503
1504 if (fromClause == null) {
1505 fromClause = quotedName();
1506 }
1507
1508 String result = "SELECT " + selectClause + " FROM " + fromClause;
1509
1510 whereClause = appendWhereClauseFilters(whereClause, includeDeleted,
1511 excludeUnselectable);
1512
1513 if (whereClause.length() > 0) {
1514 result += " WHERE " + whereClause;
1515 }
1516
1517 if (orderByClause == null) {
1518 orderByClause = defaultOrderByClause();
1519 }
1520
1521 if (orderByClause.trim().length() > 0) {
1522 result += " ORDER BY " + orderByClause;
1523 }
1524 return result;
1525 }
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548 private String appendWhereClauseFilters(String whereClause,
1549 boolean includeDeleted,
1550 boolean excludeUnselectable) {
1551 if (whereClause == null || whereClause.trim().length() == 0) {
1552 whereClause = "";
1553 } else {
1554
1555
1556 whereClause = "(" + whereClause + ")";
1557 }
1558
1559 if (deletedColumn != null && !includeDeleted) {
1560 if(whereClause.length() > 0) {
1561 whereClause += " AND";
1562 }
1563 whereClause += " NOT " + dbms().booleanTrueExpression(deletedColumn);
1564 }
1565
1566 if (excludeUnselectable){
1567 String s = canSelectClause();
1568 if (s != null) {
1569 if (whereClause.length() > 0) {
1570 whereClause += " AND ";
1571 }
1572 whereClause += s;
1573 }
1574 }
1575 return whereClause;
1576 }
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589 private String canSelectClause() {
1590 Column<Capability> canSelect = canSelectColumn();
1591 AccessToken accessToken = PoemThread.inSession() ?
1592 PoemThread.sessionToken().accessToken : null;
1593 if (canSelect == null ||
1594 accessToken instanceof RootAccessToken) {
1595 return null;
1596 } else if (accessToken instanceof User) {
1597 String query = "(" +
1598 canSelect.fullQuotedName() + " IS NULL OR EXISTS( SELECT 1 FROM " +
1599 quotedName() +
1600 ", " +
1601 database.getGroupCapabilityTable().quotedName() +
1602 ", " +
1603 database.getGroupMembershipTable().quotedName() +
1604 " WHERE " +
1605 database.getGroupMembershipTable().getUserColumn().fullQuotedName() +
1606 " = " +
1607 ((User)accessToken).getId() +
1608 " AND " +
1609 database.getGroupMembershipTable().getGroupColumn().fullQuotedName() +
1610 " = " +
1611 database.getGroupCapabilityTable().getGroupColumn().fullQuotedName() +
1612 " AND " +
1613 database.getGroupCapabilityTable().getCapabilityColumn().
1614 fullQuotedName() +
1615 " = " +
1616 canSelect.fullQuotedName() +
1617 "))";
1618 return query;
1619 } else {
1620 return canSelect.fullQuotedName() + " IS NULL";
1621 }
1622 }
1623
1624
1625
1626
1627
1628
1629
1630 public int count(String whereClause,
1631 boolean includeDeleted, boolean excludeUnselectable)
1632 throws SQLPoemException {
1633 return count(appendWhereClauseFilters(whereClause,
1634 includeDeleted, excludeUnselectable));
1635 }
1636
1637
1638
1639
1640
1641
1642
1643 public int count(String whereClause, boolean includeDeleted)
1644 throws SQLPoemException {
1645 return count(whereClause, includeDeleted, true);
1646 }
1647
1648
1649
1650
1651
1652
1653
1654 public int count(String whereClause)
1655 throws SQLPoemException {
1656
1657 String sql = countSQL(whereClause);
1658
1659 try {
1660 Connection connection;
1661 if (PoemThread.inSession()) {
1662 PoemTransaction transaction = PoemThread.transaction();
1663 transaction.writeDown();
1664 connection = transaction.getConnection();
1665 } else
1666 connection = getDatabase().getCommittedConnection();
1667
1668
1669 Statement s = connection.createStatement();
1670 ResultSet rs = s.executeQuery(sql);
1671 database.incrementQueryCount(sql);
1672 if (database.logSQL())
1673 database.log(new SQLLogEvent(sql));
1674 rs.next();
1675 int count = rs.getInt(1);
1676 rs.close();
1677 s.close();
1678 return count;
1679 }
1680 catch (SQLException e) {
1681 throw new ExecutingSQLPoemException(sql, e);
1682 }
1683 }
1684
1685
1686
1687
1688 public int count()
1689 throws SQLPoemException {
1690 return count(null);
1691 }
1692
1693
1694
1695
1696
1697
1698
1699
1700 public boolean exists(String whereClause) throws SQLPoemException {
1701 return count(whereClause) > 0;
1702 }
1703
1704
1705
1706
1707
1708 public boolean exists(Persistent persistent) {
1709 return exists(whereClause(persistent));
1710 }
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729 public void appendWhereClause(StringBuffer clause, Persistent persistent) {
1730 Column<?>[] columnsLocal = this.columns;
1731 boolean hadOne = false;
1732 for (int c = 0; c < columnsLocal.length; ++c) {
1733 Column<?> column = columnsLocal[c];
1734 Object raw = column.getRaw_unsafe(persistent);
1735 if (raw != null) {
1736 if (hadOne)
1737 clause.append(" AND ");
1738 else
1739 hadOne = true;
1740
1741 String columnSQL = column.fullQuotedName();
1742 if (column.getType() instanceof StringPoemType) {
1743 clause.append(
1744 dbms().caseInsensitiveRegExpSQL(
1745 columnSQL,
1746 column.getSQLType().quotedRaw(raw)));
1747 } else if (column.getType() instanceof BooleanPoemType) {
1748 clause.append(columnSQL);
1749 clause.append(" = ");
1750 clause.append(dbms().sqlBooleanValueOfRaw(raw));
1751 } else {
1752 clause.append(columnSQL);
1753 clause.append(" = ");
1754 clause.append(column.getSQLType().quotedRaw(raw));
1755 }
1756 }
1757 }
1758 }
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770 public String whereClause(Persistent criteria) {
1771 return whereClause(criteria, true, true);
1772 }
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783 public String whereClause(Persistent criteria,
1784 boolean includeDeleted, boolean excludeUnselectable) {
1785 StringBuffer clause = new StringBuffer();
1786 appendWhereClause(clause, criteria);
1787 return appendWhereClauseFilters(clause.toString(),
1788 includeDeleted, excludeUnselectable);
1789 }
1790
1791
1792
1793
1794
1795
1796 public String cnfWhereClause(Enumeration<P> persistents) {
1797 return cnfWhereClause(persistents, false, true);
1798 }
1799
1800
1801
1802
1803
1804
1805
1806 public String cnfWhereClause(Enumeration<P> persistents,
1807 boolean includeDeleted, boolean excludeUnselectable) {
1808 StringBuffer clause = new StringBuffer();
1809
1810 boolean hadOne = false;
1811 while (persistents.hasMoreElements()) {
1812 StringBuffer pClause = new StringBuffer();
1813 appendWhereClause(pClause, (Persistent)persistents.nextElement());
1814 if (pClause.length() > 0) {
1815 if (hadOne)
1816 clause.append(" OR ");
1817 else
1818 hadOne = true;
1819 clause.append("(");
1820 clause.append(pClause);
1821 clause.append(")");
1822 }
1823 }
1824
1825 return appendWhereClauseFilters(clause.toString(),
1826 includeDeleted, excludeUnselectable);
1827 }
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839 @SuppressWarnings({ "unchecked", "rawtypes" })
1840 public Enumeration<P> referencesTo(final Persistent object) {
1841 return new FlattenedEnumeration<P>(
1842 new MappedEnumeration(columns()) {
1843 public Enumeration mapped(Object column) {
1844 return ((Column)column).referencesTo(object);
1845 }
1846 });
1847 }
1848
1849
1850
1851
1852
1853
1854
1855 public Enumeration<Column<?>> referencesTo(final Table<?> table) {
1856 return
1857 new FilteredEnumeration<Column<?>>(columns()) {
1858 public boolean isIncluded(Column<?> column) {
1859 PoemType<?> type = ((Column<?>)column).getType();
1860 return type instanceof PersistentReferencePoemType &&
1861 ((PersistentReferencePoemType)type).targetTable() == table;
1862 }
1863 };
1864 }
1865
1866 private void validate(Persistent persistent)
1867 throws FieldContentsPoemException {
1868 for (int c = 0; c < columns.length; ++c) {
1869 Column<?> column = columns[c];
1870 try {
1871 column.getType().assertValidRaw(column.getRaw_unsafe(persistent));
1872 }
1873 catch (Exception e) {
1874 throw new FieldContentsPoemException(column, e);
1875 }
1876 }
1877 }
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888 public int getMostRecentTroid() {
1889 if (mostRecentTroid == -1)
1890 throw new PoemBugPoemException("Troid still unitialised in " + name);
1891 return mostRecentTroid;
1892 }
1893
1894
1895
1896
1897
1898 public synchronized Integer troidFor(Persistent persistent) {
1899 Persistent foolEclipse = persistent;
1900 persistent = foolEclipse;
1901 if (mostRecentTroid == -1)
1902 throw new PoemBugPoemException("Troid still unitialised in " + name);
1903 return new Integer(mostRecentTroid++);
1904 }
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914 public void create(Persistent p)
1915 throws AccessPoemException, ValidationPoemException,
1916 InitialisationPoemException {
1917 JdbcPersistent persistent = (JdbcPersistent)p;
1918
1919 SessionToken sessionToken = PoemThread.sessionToken();
1920
1921 if (persistent.getTable() == null)
1922 persistent.setTable(this, null);
1923 persistent.assertCanCreate(sessionToken.accessToken);
1924
1925 claim(persistent, troidFor(persistent));
1926 persistent.setStatusNonexistent();
1927
1928
1929
1930
1931 try {
1932 validate(persistent);
1933 }
1934 catch (Exception e) {
1935 throw new InitialisationPoemException(this, e);
1936 }
1937
1938
1939
1940
1941 synchronized (cache) {
1942 persistent.setDirty(true);
1943 writeDown(sessionToken.transaction, persistent);
1944
1945
1946
1947 persistent.readLock(sessionToken.transaction);
1948 cache.put(persistent.troid(), persistent);
1949 }
1950
1951 notifyTouched(sessionToken.transaction, persistent);
1952 }
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984 public Persistent create(Initialiser initialiser)
1985 throws AccessPoemException, ValidationPoemException,
1986 InitialisationPoemException {
1987 Persistent persistent = newPersistent();
1988 initialiser.init(persistent);
1989 create(persistent);
1990 return persistent;
1991 }
1992
1993 private void claim(Persistent p, Integer troid) {
1994 JdbcPersistent persistent = (JdbcPersistent)p;
1995
1996
1997 if (cache.get(troid) != null)
1998 throw new DuplicateTroidPoemException(this, troid);
1999
2000 if (persistent.troid() != null)
2001 throw new DoubleCreatePoemException(persistent);
2002
2003 persistent.setTable(this, troid);
2004
2005 troidColumn.setRaw_unsafe(persistent, troid);
2006 if (deletedColumn != null)
2007 deletedColumn.setRaw_unsafe(persistent, Boolean.FALSE);
2008 }
2009
2010
2011
2012
2013
2014 public Persistent newPersistent() {
2015 JdbcPersistent it = _newPersistent();
2016 it.setTable(this, null);
2017 return it;
2018 }
2019
2020
2021
2022
2023
2024
2025
2026 protected JdbcPersistent _newPersistent() {
2027 return new JdbcPersistent();
2028 }
2029
2030
2031
2032
2033
2034
2035
2036 public void delete_unsafe(String whereClause) {
2037 serial.increment(PoemThread.transaction());
2038 getDatabase().sqlUpdate("DELETE FROM " + quotedName +
2039 " WHERE " + whereClause);
2040 uncache();
2041 }
2042
2043
2044
2045
2046 public int extrasCount() {
2047 return extrasIndex;
2048 }
2049
2050
2051
2052
2053
2054
2055
2056
2057 public final Capability getDefaultCanRead() {
2058 return info == null ? null : info.getDefaultcanread();
2059 }
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075 public final Capability getDefaultCanWrite() {
2076 return info == null ? null : info.getDefaultcanwrite();
2077 }
2078
2079
2080
2081
2082
2083
2084
2085
2086 public final Capability getDefaultCanDelete() {
2087 return info == null ? null : info.getDefaultcandelete();
2088 }
2089
2090
2091
2092
2093
2094
2095
2096
2097 public final Capability getCanCreate() {
2098 return info == null ? null : info.getCancreate();
2099 }
2100
2101
2102
2103
2104 public final Column<Capability> canReadColumn() {
2105 return canReadColumn == null ? canSelectColumn() : canReadColumn;
2106 }
2107
2108
2109
2110
2111
2112 public final Column<Capability> canSelectColumn() {
2113 return canSelectColumn;
2114 }
2115
2116
2117
2118
2119 public final Column<Capability> canWriteColumn() {
2120 return canWriteColumn;
2121 }
2122
2123
2124
2125
2126 public final Column<Capability> canDeleteColumn() {
2127 return canDeleteColumn;
2128 }
2129
2130
2131
2132
2133
2134
2135
2136 public Column<?> addColumnAndCommit(ColumnInfo infoP) throws PoemException {
2137
2138
2139
2140 database.log("Adding extra column from runtime " +
2141 dbms().melatiName(infoP.getName_unsafe()) +
2142 " to " + name);
2143 Column<?> column = ExtraColumn.from(this, infoP, getNextExtrasIndex(),
2144 DefinitionSource.runtime);
2145 column.setColumnInfo(infoP);
2146
2147
2148
2149
2150 defineColumn(column, false);
2151
2152
2153
2154 database.beginStructuralModification();
2155 try {
2156 dbAddColumn(column);
2157 synchronized (cache) {
2158 uncache();
2159 transactionStuffs.invalidate();
2160 defineColumn(column, true);
2161 }
2162 PoemThread.commit();
2163 }
2164 finally {
2165 database.endStructuralModification();
2166 }
2167
2168 return column;
2169 }
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180 public void deleteColumnAndCommit(ColumnInfo columnInfo) throws PoemException {
2181 database.beginStructuralModification();
2182 try {
2183 Column<?> column = columnInfo.column();
2184 columnInfo.delete();
2185 if (database.getDbms().canDropColumns())
2186 dbModifyStructure(
2187 "ALTER TABLE " + quotedName() +
2188 " DROP " + column.quotedName());
2189
2190
2191 columns = (Column[])ArrayUtils.removed(columns, column);
2192 columnsByName.remove(column.getName().toLowerCase());
2193
2194 synchronized (cache) {
2195 uncache();
2196 transactionStuffs.invalidate();
2197 }
2198 PoemThread.commit();
2199 }
2200 finally {
2201 database.endStructuralModification();
2202 }
2203
2204 }
2205
2206
2207
2208
2209
2210
2211
2212
2213 public String toString() {
2214 return getName() + " (from " + definitionSource + ")";
2215 }
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226 public void dumpCacheAnalysis() {
2227 database.log("\n-------- Analysis of " + name + "'s cache\n");
2228 cache.dumpAnalysis();
2229 }
2230
2231
2232
2233
2234 public void dump() {
2235 dump(System.out);
2236 }
2237
2238
2239
2240
2241
2242
2243 public void dump(PrintStream ps) {
2244 ps.println("=== table " + name +
2245 " (tableinfo id " + tableInfoID() + ")");
2246 for (int c = 0; c < columns.length; ++c)
2247 columns[c].dump(ps);
2248 }
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260 public CachedSelection<P> cachedSelection(String whereClause,
2261 String orderByClause) {
2262 String key = whereClause + "/" + orderByClause;
2263 CachedSelection<P> them = cachedSelections.get(key);
2264 if (them == null) {
2265 CachedSelection<P> newThem =
2266 new CachedSelection<P>(this, whereClause, orderByClause);
2267 cachedSelections.put(key, newThem);
2268 them = newThem;
2269 }
2270 return them;
2271 }
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283 public CachedCount cachedCount(String whereClause, boolean includeDeleted) {
2284 return cachedCount(whereClause, includeDeleted, true);
2285 }
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298 public CachedCount cachedCount(String whereClause, boolean includeDeleted,
2299 boolean excludeUnselectable) {
2300 return cachedCount(appendWhereClauseFilters(whereClause,
2301 includeDeleted, excludeUnselectable));
2302 }
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312 public CachedCount cachedCount(Persistent criteria, boolean includeDeleted,
2313 boolean excludeUnselectable) {
2314 return cachedCount(whereClause(criteria, includeDeleted, excludeUnselectable));
2315 }
2316
2317
2318
2319
2320
2321 public CachedCount cachedCount(Persistent criteria) {
2322 return cachedCount(whereClause(criteria, true, false));
2323 }
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334 public CachedCount cachedCount(String whereClause) {
2335 String key = "" + whereClause;
2336 CachedCount it = cachedCounts.get(key);
2337 if (it == null) {
2338 it = new CachedCount(this, whereClause);
2339 cachedCounts.put(key, it);
2340 }
2341 return it;
2342 }
2343
2344
2345
2346
2347
2348 public CachedCount cachedCount() {
2349 return cachedCount((String)null);
2350 }
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364 public CachedExists cachedExists(String whereClause) {
2365 String key = "" + whereClause;
2366 CachedExists it = null;
2367 it = cachedExists.get(key);
2368 if (it == null) {
2369 it = new CachedExists(this, whereClause);
2370 cachedExists.put(key, it);
2371 }
2372 return it;
2373 }
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386 @SuppressWarnings({ "unchecked", "rawtypes" })
2387 public RestrictedReferencePoemType<?> cachedSelectionType(String whereClause,
2388 String orderByClause, boolean nullable) {
2389 return new RestrictedReferencePoemType(
2390 cachedSelection(whereClause, orderByClause), nullable);
2391 }
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444 @SuppressWarnings({ "rawtypes", "unchecked" })
2445 public Field<?> cachedSelectionField(
2446 String whereClause, String orderByClause, boolean nullable,
2447 Integer selectedTroid, String nameP) {
2448 return new Field(
2449 selectedTroid,
2450 new BaseFieldAttributes(nameP,
2451 cachedSelectionType(whereClause,
2452 orderByClause, nullable)));
2453 }
2454
2455 @SuppressWarnings({ "rawtypes", "unchecked" })
2456 private synchronized void defineColumn(Column<?> column, boolean reallyDoIt)
2457 throws DuplicateColumnNamePoemException,
2458 DuplicateTroidColumnPoemException,
2459 DuplicateDeletedColumnPoemException {
2460 if (column.getTable() != this)
2461 throw new ColumnInUsePoemException(this, column);
2462
2463 if (_getColumn(column.getName()) != null)
2464 throw new DuplicateColumnNamePoemException(this, column);
2465
2466 if (column.isTroidColumn()) {
2467 if (troidColumn != null)
2468 throw new DuplicateTroidColumnPoemException(this, column);
2469 if (reallyDoIt)
2470 troidColumn = (Column<Integer>) column;
2471 }
2472 else if (column.isDeletedColumn()) {
2473 if (deletedColumn != null)
2474 throw new DuplicateDeletedColumnPoemException(this, column);
2475 if (reallyDoIt)
2476 deletedColumn = (Column<Boolean>)column;
2477 }
2478 else {
2479 if (reallyDoIt) {
2480 PoemType type = column.getType();
2481 if (type instanceof ReferencePoemType &&
2482 ((PersistentReferencePoemType)type).targetTable() ==
2483 database.getCapabilityTable()) {
2484 if (column.getName().equals("canRead"))
2485 canReadColumn = (Column<Capability>) column;
2486 else if (column.getName().equals("canWrite"))
2487 canWriteColumn = (Column<Capability>) column;
2488 else if (column.getName().equals("canDelete"))
2489 canDeleteColumn = (Column<Capability>) column;
2490 else if (column.getName().equals("canSelect"))
2491 canSelectColumn = (Column<Capability>) column;
2492 }
2493 }
2494 }
2495
2496 if (reallyDoIt) {
2497 column.setTable(this);
2498 columns = (Column[])ArrayUtils.added(columns, column);
2499 columnsByName.put(column.getName().toLowerCase(), column);
2500 }
2501 }
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516 public final void defineColumn(Column<?> column)
2517 throws DuplicateColumnNamePoemException,
2518 DuplicateTroidColumnPoemException,
2519 DuplicateDeletedColumnPoemException {
2520 defineColumn(column, true);
2521 }
2522
2523 private void _defineColumn(Column<?> column) {
2524 try {
2525 defineColumn(column);
2526 }
2527 catch (DuplicateColumnNamePoemException e) {
2528 throw new UnexpectedExceptionPoemException(e);
2529 }
2530 catch (DuplicateTroidColumnPoemException e) {
2531 throw new UnexpectedExceptionPoemException(e);
2532 }
2533 }
2534
2535
2536
2537
2538 public int getNextExtrasIndex() {
2539 return extrasIndex++;
2540 }
2541
2542
2543
2544
2545 public TableInfo getTableInfo() {
2546 return info;
2547 }
2548
2549
2550
2551
2552 public void setTableInfo(TableInfo tableInfo) {
2553 info = tableInfo;
2554 rememberAllTroids(tableInfo.getSeqcached().booleanValue());
2555 setCacheLimit(tableInfo.getCachelimit());
2556 }
2557
2558
2559
2560
2561
2562
2563
2564
2565 public String defaultDisplayName() {
2566 return StringUtils.capitalised(getName());
2567 }
2568
2569 public int defaultDisplayOrder() {
2570 return DISPLAY_ORDER_DEFAULT;
2571 }
2572
2573
2574
2575
2576
2577
2578
2579
2580 public String defaultDescription() {
2581 return null;
2582 }
2583
2584 public Integer defaultCacheLimit() {
2585 return new Integer(CACHE_LIMIT_DEFAULT);
2586 }
2587
2588 public boolean defaultRememberAllTroids() {
2589 return false;
2590 }
2591
2592 public String defaultCategory() {
2593 return TableCategoryTable.normalTableCategoryName;
2594 }
2595
2596
2597
2598
2599
2600
2601 public void createTableInfo() throws PoemException {
2602 if (info == null) {
2603 info = getDatabase().getTableInfoTable().defaultTableInfoFor(this);
2604 try {
2605 getDatabase().getTableInfoTable().create(info);
2606 } catch (PoemException e) {
2607 throw new UnificationPoemException(
2608 "Problem creating new tableInfo for table " + getName() + ":", e);
2609 }
2610 setTableInfo(info);
2611 }
2612 }
2613
2614
2615
2616
2617
2618 public synchronized void unifyWithColumnInfo() throws PoemException {
2619
2620 if (info == null)
2621 throw new PoemBugPoemException("Get the initialisation order right ...");
2622
2623 for (Enumeration<?> ci =
2624 database.getColumnInfoTable().getTableinfoColumn().
2625 selectionWhereEq(info.troid());
2626 ci.hasMoreElements();) {
2627 ColumnInfo columnInfo = (ColumnInfo)ci.nextElement();
2628 Column<?> column = _getColumn(columnInfo.getName());
2629 if (column == null) {
2630 database.log("Adding extra column "
2631 + dbms().melatiName(columnInfo.getName_unsafe())
2632 + " to " + name + " from definition in columninfo table.");
2633 column = ExtraColumn.from(this, columnInfo, getNextExtrasIndex(),
2634 DefinitionSource.infoTables);
2635 _defineColumn(column);
2636 }
2637 column.setColumnInfo(columnInfo);
2638 }
2639
2640 for (Enumeration<Column<?>> c = columns(); c.hasMoreElements();)
2641 c.nextElement().createColumnInfo();
2642 }
2643
2644 @Override
2645 public void unifyWithMetadata(ResultSet tableDescriptions) throws SQLException {
2646 if (info == null)
2647 return;
2648 String remarks = tableDescriptions.getString("REMARKS");
2649 if (getDescription() == null) {
2650 if (remarks != null && !remarks.trim().equals("")) {
2651 info.setDescription(remarks);
2652 getDatabase().log("Adding comment to table " + name +
2653 " from SQL metadata:" + remarks);
2654 }
2655 } else {
2656 if (!this.getDescription().equals(remarks)) {
2657 String sql = this.dbms().alterTableAddCommentSQL(this, null);
2658 if (sql != null)
2659 this.getDatabase().modifyStructure(sql);
2660 }
2661 }
2662 }
2663
2664
2665
2666
2667
2668
2669
2670
2671 @Override
2672 @SuppressWarnings({ "unchecked", "rawtypes" })
2673 public synchronized void unifyWithDB(ResultSet colDescs, String troidColumnName)
2674 throws PoemException {
2675 boolean debug = false;
2676
2677 Hashtable<Column<?>, Boolean> dbColumns = new Hashtable<Column<?>, Boolean>();
2678
2679 int colCount = 0;
2680 if (colDescs != null){
2681
2682 try {
2683 for (; colDescs.next(); ++colCount) {
2684 String colName = colDescs.getString("COLUMN_NAME");
2685 Column<?> column = _getColumn(dbms().melatiName(colName));
2686
2687 if (column == null) {
2688 SQLPoemType<?> colType =
2689 database.defaultPoemTypeOfColumnMetaData(colDescs);
2690
2691
2692 if (troidColumn == null && colName.equalsIgnoreCase(troidColumnName) &&
2693 dbms().canRepresent(colType, TroidPoemType.it) != null)
2694 colType = TroidPoemType.it;
2695
2696
2697
2698 if (deletedColumn == null && colName.equalsIgnoreCase(dbms().unreservedName("deleted")) &&
2699 dbms().canRepresent(colType, DeletedPoemType.it) != null)
2700 colType = DeletedPoemType.it;
2701
2702 database.log("Adding extra column from sql meta data "
2703 + name + "." + dbms().melatiName(colName));
2704 column = new ExtraColumn(this,
2705 dbms().melatiName(
2706 colName),
2707 colType, DefinitionSource.sqlMetaData,
2708 getNextExtrasIndex());
2709
2710 _defineColumn(column);
2711
2712
2713
2714
2715
2716
2717 if (info != null)
2718 column.createColumnInfo();
2719 }
2720 else {
2721 column.assertMatches(colDescs);
2722 }
2723 column.unifyWithMetadata(colDescs);
2724 dbColumns.put(column, Boolean.TRUE);
2725 }
2726 } catch (SQLException e) {
2727 throw new SQLSeriousPoemException(e);
2728 }
2729 } else if (debug) database.log(
2730 "Table.unifyWithDB called with null ResultsSet");
2731
2732 if (colCount == 0) {
2733
2734 dbCreateTable();
2735 } else {
2736
2737 for (int c = 0; c < columns.length; ++c) {
2738 if (dbColumns.get(columns[c]) == null) {
2739 database.log("Adding column to underlying database : " + columns[c]);
2740 dbAddColumn(columns[c]);
2741 }
2742 }
2743 }
2744
2745 if (troidColumn == null)
2746 throw new NoTroidColumnException(this);
2747
2748
2749
2750
2751
2752
2753 if (info != null) {
2754
2755
2756 Hashtable<Column<?>,Boolean> dbHasIndexForColumn = new Hashtable<Column<?>,Boolean>();
2757 String unreservedName = dbms().getJdbcMetadataName(
2758 dbms().unreservedName(getName()));
2759 if (debug) database.log("Getting indexes for " + unreservedName + "(was " + getName() + ")");
2760 ResultSet index;
2761 try {
2762 index = getDatabase().getCommittedConnection().getMetaData().
2763
2764
2765
2766 getIndexInfo(null, dbms().getSchema(),
2767 unreservedName,
2768 false, true);
2769 while (index.next()) {
2770 try {
2771 String mdIndexName = index.getString("INDEX_NAME");
2772 String mdColName = index.getString("COLUMN_NAME");
2773 if (mdColName != null) {
2774 String columnName = dbms().melatiName(mdColName);
2775 Column<?> column = getColumn(columnName);
2776
2777
2778 String expectedIndex = indexName(column).toUpperCase();
2779
2780 if (expectedIndex.indexOf(mdIndexName.toUpperCase()) == 0) {
2781 column.unifyWithIndex(mdIndexName, index);
2782 dbHasIndexForColumn.put(column, Boolean.TRUE);
2783 if (debug) database.log("Found Expected Index:" +
2784 expectedIndex + " IndexName:" + mdIndexName.toUpperCase());
2785 } else {
2786 try {
2787 column.unifyWithIndex(mdIndexName, index);
2788 dbHasIndexForColumn.put(column, Boolean.TRUE);
2789 if (debug) database.log("Not creating index because one exists with different name:" +
2790 mdIndexName.toUpperCase() + " != " + expectedIndex);
2791 } catch (IndexUniquenessPoemException e) {
2792
2793 if (debug) database.log("Creating index because existing one has different properties:" +
2794 mdIndexName.toUpperCase() + " != " + expectedIndex);
2795 }
2796 }
2797 }
2798
2799
2800 }
2801 catch (NoSuchColumnPoemException e) {
2802
2803 throw new UnexpectedExceptionPoemException(e);
2804 }
2805 }
2806 } catch (SQLException e) {
2807 throw new SQLSeriousPoemException(e);
2808 }
2809
2810
2811 for (int c = 0; c < columns.length; ++c) {
2812 if (dbHasIndexForColumn.get(columns[c]) != Boolean.TRUE)
2813 dbCreateIndex(columns[c]);
2814 }
2815 }
2816
2817
2818
2819 if (PoemThread.inSession())
2820 PoemThread.writeDown();
2821
2822 String sql =
2823 "SELECT " + troidColumn.fullQuotedName() +
2824 " FROM " + quotedName() +
2825 " ORDER BY " + troidColumn.fullQuotedName() + " DESC";
2826 try {
2827 Statement selectionStatement = getDatabase().getCommittedConnection().createStatement();
2828 ResultSet maxTroid =
2829 selectionStatement.
2830 executeQuery(sql);
2831 database.incrementQueryCount(sql);
2832 if (database.logSQL())
2833 database.log(new SQLLogEvent(sql));
2834 if (maxTroid.next()) {
2835 mostRecentTroid = maxTroid.getInt(1) + 1;
2836 } else
2837 mostRecentTroid = 0;
2838 maxTroid.close();
2839 selectionStatement.close();
2840 }
2841 catch (SQLException e) {
2842 throw new SQLSeriousPoemException(e);
2843 }
2844 }
2845
2846
2847
2848
2849
2850
2851 public final int hashCode() {
2852 return name.hashCode();
2853 }
2854
2855
2856
2857
2858
2859
2860
2861 public boolean equals(Object t) {
2862 return (t instanceof JdbcTable &&
2863 ((Table<?>)t).getName().equals(name));
2864
2865 }
2866
2867 private class TransactionStuff {
2868 PreparedStatement insert, modify, get;
2869
2870 TransactionStuff(Connection connection) {
2871 insert = _this.simpleInsert(connection);
2872 modify = _this.simpleModify(connection);
2873 get = _this.simpleGet(connection);
2874 }
2875 }
2876
2877
2878 }