Repository navigation
Expand file tree
/
Copy pathTable.java
More file actions
1961 lines (1677 loc) · 75.4 KB
/
Copy pathTable.java
File metadata and controls
1961 lines (1677 loc) · 75.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2004-2026 Fred Hutchinson Cancer Research Center
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.labkey.api.data;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Strings;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.Logger;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.junit.Assert;
import org.junit.Test;
import org.labkey.api.collections.BoundMap;
import org.labkey.api.collections.CaseInsensitiveHashMap;
import org.labkey.api.collections.CaseInsensitiveHashSet;
import org.labkey.api.data.dialect.SqlDialect;
import org.labkey.api.data.validator.ColumnValidator;
import org.labkey.api.data.validator.ColumnValidators;
import org.labkey.api.dataiterator.AbstractDataIterator;
import org.labkey.api.dataiterator.DataIteratorBuilder;
import org.labkey.api.dataiterator.DataIteratorContext;
import org.labkey.api.dataiterator.Pump;
import org.labkey.api.dataiterator.SimpleTranslator;
import org.labkey.api.dataiterator.SimpleTranslator.SpecialColumn;
import org.labkey.api.dataiterator.TableInsertDataIteratorBuilder;
import org.labkey.api.di.DataIntegrationService;
import org.labkey.api.exceptions.OptimisticConflictException;
import org.labkey.api.exp.api.ExperimentService;
import org.labkey.api.exp.property.Domain;
import org.labkey.api.exp.property.DomainKind;
import org.labkey.api.miniprofiler.MiniProfiler;
import org.labkey.api.query.AliasedColumn;
import org.labkey.api.query.FieldKey;
import org.labkey.api.query.QueryService;
import org.labkey.api.query.RuntimeValidationException;
import org.labkey.api.security.User;
import org.labkey.api.util.BaseScanner;
import org.labkey.api.util.ExceptionUtil;
import org.labkey.api.util.GUID;
import org.labkey.api.util.JunitUtil;
import org.labkey.api.util.MemTracker;
import org.labkey.api.util.TestContext;
import org.labkey.api.util.logging.LogHelper;
import java.io.EOFException;
import java.sql.BatchUpdateException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.sql.Types;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
/**
* Table manipulation methods
* <p/>
* select/insert/update/delete
*/
public class Table
{
public static final String SQLSTATE_TRANSACTION_STATE = "25000";
public static final int ERROR_ROWVERSION = 10001;
public static final int ERROR_DELETED = 10002;
public static final int ERROR_TABLEDELETED = 10003;
private static final Logger _log = LogHelper.getLogger(Table.class, "SQL generation and execution, some TableInfo-scoped DB operations");
// Don't limit the rows returned to a specific count (filters and offsets can still eliminate rows)
public static final int ALL_ROWS = -1;
// Return no rows -- useful for query validation or when you need just metadata
public static final int NO_ROWS = 0;
// Makes long parameter lists easier to read
public static final int NO_OFFSET = 0;
private static final String ENTITY_ID_COLUMN_NAME = SpecialColumn.EntityId.name();
private static final String OWNER_COLUMN_NAME = "Owner";
private static final String CREATED_BY_COLUMN_NAME = SpecialColumn.CreatedBy.name();
private static final String CREATED_COLUMN_NAME = SpecialColumn.Created.name();
private static final String MODIFIED_BY_COLUMN_NAME = SpecialColumn.ModifiedBy.name();
private static final String MODIFIED_COLUMN_NAME = SpecialColumn.Modified.name();
/** Columns that are magically populated as part of an insert or update operation */
public static final Set<String> AUTOPOPULATED_COLUMN_NAMES = CaseInsensitiveHashSet.of(
ENTITY_ID_COLUMN_NAME,
OWNER_COLUMN_NAME,
CREATED_BY_COLUMN_NAME,
CREATED_COLUMN_NAME,
MODIFIED_BY_COLUMN_NAME,
MODIFIED_COLUMN_NAME
);
private Table()
{
}
public static boolean validMaxRows(int maxRows)
{
return NO_ROWS == maxRows | ALL_ROWS == maxRows | maxRows > 0;
}
// ================== These methods have not been converted to Selector/Executor ==================
// Careful: caller must track and clean up parameters (e.g., close InputStreams) after execution is complete
public static PreparedStatement prepareStatement(Connection conn, String sql, Collection<?> parameters, List<Parameter> jdbcParameters) throws SQLException
{
PreparedStatement stmt = conn.prepareStatement(sql);
setParameters(stmt, parameters, jdbcParameters);
MemTracker.getInstance().put(stmt);
return stmt;
}
public static void setParameters(PreparedStatement stmt, Collection<?> parameters, List<Parameter> jdbcParameters)
{
if (null == parameters)
return;
int i = 1;
for (Object value : parameters)
{
//Parameter validation
//Bug 1996 - rossb: Generally, we let JDBC validate the
//parameters and throw exceptions, however, it doesn't recognize NaN
//properly which can lead to database corruption.
// [This is now handled by making a special value (in ResultSetUtil) to hand to the DB]
Parameter p = new Parameter(stmt, i);
p.setValue(value);
jdbcParameters.add(p);
i++;
}
}
/**
* @return if this is a SELECT statement that contains FROM, possibly proceeded by one or more CTEs (WITH clause).
* Comments and quoted strings are ignored.
*/
public static boolean isSelect(String sql)
{
// Remove comments and quoted strings, then trim
String noComments = new SqlScanner(sql).stripComments().toString();
String strippedSql = new SqlScanner(noComments).stripQuotedStrings().toString().trim();
// If present, remove WITH statement, which should leave behind a SELECT
if (strippedSql.matches("^(?ims)WITH\\s.*$")) // flags: case-insensitive, multiline, dot-all
{
int fromIndex = "WITH ".length();
// WITH clause contains one or more CTEs; skip them all
do
{
SqlScanner scanner = new SqlScanner(strippedSql);
SkipCteHandler handler = new SkipCteHandler();
scanner.scan(fromIndex, handler);
String error = handler.getError();
if (null != error)
{
_log.warn("{}!\n{}", error, strippedSql);
return false;
}
strippedSql = strippedSql.substring(handler.getSelectIdx()).trim();
fromIndex = 1;
}
while (strippedSql.startsWith(","));
}
// We must see a FROM clause, so we don't flag stored procedure invocations, #22648
return strippedSql.matches("^(?ims)SELECT\\s.*\\sFROM\\s.*$"); // flags: case-insensitive, multiline, dot-all
}
private static class SkipCteHandler implements BaseScanner.Handler
{
private boolean _parenSeen = false;
private int _parens = -1;
private int _selectIdx = -1;
@Override
public boolean character(char c, int index)
{
if (!_parenSeen)
{
if (c == '(')
{
_parenSeen = true;
_parens = 1;
}
}
else
{
switch (c)
{
case '(' -> _parens++;
case ')' -> _parens--;
}
if (_parens == 0)
{
_selectIdx = index + 1;
return false;
}
}
return true;
}
private @Nullable String getError()
{
if (!_parenSeen)
return "Parentheses expected after WITH statement";
else if (_parens != 0)
return "Mismatched parentheses";
else
return null;
}
private int getSelectIdx()
{
return _selectIdx;
}
}
public static class IsSelectTestCase extends Assert
{
@Test
public void test()
{
assertTrue(isSelect("SELECT * FROM foo.bar"));
assertTrue(isSelect("WITH Blue AS (SELECT * FROM foo.bar) SELECT * FROM Blue"));
assertTrue(isSelect("WITH cte AS (SELECT CAST('1' AS INTEGER) AS i) SELECT * FROM cte"));
assertTrue(isSelect("with lowercase as (select cast('1' as integer) as i) select * from lowercase"));
assertTrue(isSelect("WITH\nMultiLine AS (SELECT * FROM foo.bar)\nSELECT *\nFROM Blue"));
assertTrue(isSelect("""
WITH RECURSIVE
/*CTE*/
org_lk_exp_CHILDREN_INNER AS (SELECT
0 AS depth)
,/*CTE*/
org_lk_exp_CHILDREN AS (SELECT
I.depth,
I.self),
/*CTE*/
org_lk_exp_CHILDREN_OUTER AS (SELECT 2 AS depth)
SELECT *
FROM (
SELECT
SourceSamples.SampleState AS SampleState
FROM org_lk_exp_CHILDREN
WHERE depth != 0
AND objectid <> self
AND depth <= 10
GROUP BY self, objectid) AS X))
ORDER BY rowid ASC
LIMIT 21"""));
assertFalse(isSelect("WITH Nothing SELECT * FROM foo.bar"));
assertFalse(isSelect("WITH Mismatched AS (SELECT * FROM (SELECT * FROM foo.bar) SELECT * FROM Mismatched"));
assertFalse(isSelect("WITH Incomplete AS (SELECT * FROM foo.bar)"));
assertFalse(isSelect("WITH NonSelect AS (SELECT * FROM foo.bar) UPDATE foo.bar SET bam = 1"));
assertFalse(isSelect("WITH NonSelect AS (SELECT * FROM foo.bar) DELETE FROM foo.bar WHERE 1=1"));
assertFalse(isSelect("WITHOUT NonCTE AS (SELECT * FROM foo.bar) SELECT NonCTE WHERE 1=1"));
assertFalse(isSelect("SELECT \" FROM \" /* FROM */ ' FROM ' foo.bar WHERE 1=1"));
}
}
// Careful: Caller must track and clean up parameters (e.g., close InputStreams) after execution is complete
public static void batchExecute(DbSchema schema, String sql, Iterable<? extends Collection<?>> paramList) throws SQLException
{
Connection conn = schema.getScope().getConnection();
PreparedStatement stmt = null;
try (Parameter.ParameterList jdbcParameters = new Parameter.ParameterList())
{
stmt = conn.prepareStatement(sql);
int paramCounter = 0;
for (Collection<?> params : paramList)
{
setParameters(stmt, params, jdbcParameters);
stmt.addBatch();
paramCounter += params.size();
if (paramCounter > 1000)
{
paramCounter = 0;
stmt.executeBatch();
jdbcParameters.close();
}
}
stmt.executeBatch();
}
catch (SQLException|RuntimeSQLException e)
{
SQLException sqlx = e instanceof RuntimeSQLException ? ((RuntimeSQLException)e).getSQLException() : (SQLException)e;
if (sqlx instanceof BatchUpdateException)
{
if (null != sqlx.getNextException())
sqlx = sqlx.getNextException();
}
logException(new SQLFragment(sql), conn, sqlx, Level.WARN);
throw sqlx;
}
finally
{
doClose(null, stmt, conn, schema.getScope());
}
}
static void batchExecute1String(DbSchema schema, String sql, Iterable<String> paramList) throws SQLException
{
Connection conn = schema.getScope().getConnection();
PreparedStatement stmt = null;
try
{
stmt = conn.prepareStatement(sql);
int paramCounter = 0;
for (String s : paramList)
{
stmt.setString(1, s);
stmt.addBatch();
paramCounter++;
if (paramCounter > 2000)
{
paramCounter = 0;
stmt.executeBatch();
}
}
stmt.executeBatch();
}
catch (SQLException e)
{
if (e instanceof BatchUpdateException)
{
if (null != e.getNextException())
e = e.getNextException();
}
logException(new SQLFragment(sql), conn, e, Level.WARN);
throw(e);
}
finally
{
doClose(null, stmt, conn, schema.getScope());
}
}
public static void batchExecute1Integer(DbSchema schema, @NotNull String sql1, @Nullable String sql100, List<Integer> paramList) throws SQLException
{
_batchExecute1Integer(Integer.class, schema, sql1, sql100, paramList);
}
public static void batchExecute1Long(DbSchema schema, @NotNull String sql1, @Nullable String sql100, List<Long> paramList) throws SQLException
{
_batchExecute1Integer(Long.class, schema, sql1, sql100, paramList);
}
public static <T> void _batchExecute1Integer(Class<T> clazz, DbSchema schema, @NotNull String sql1, @Nullable String sql100, List<T> paramList) throws SQLException
{
boolean useInteger = clazz == Integer.class;
try (Connection conn = schema.getScope().getConnection())
{
try
{
int paramCounter = 0;
// insert by 100's
int outerIndex = 0;
if (null != sql100 && paramList.size() >= 100)
{
try (PreparedStatement stmt100 = conn.prepareStatement(sql100))
{
for (; outerIndex < paramList.size() - 100; outerIndex += 100)
{
for (int index = outerIndex; index < outerIndex + 100; index++)
{
Number I = (Number)paramList.get(index);
if (null == I)
stmt100.setNull(index % 100 + 1, Types.INTEGER);
else if (useInteger)
stmt100.setInt(index % 100 + 1, I.intValue());
else
stmt100.setLong(index % 100 + 1, I.longValue());
paramCounter++;
}
stmt100.addBatch();
if (paramCounter > 10000)
{
stmt100.executeBatch();
paramCounter = 0;
}
}
if (paramCounter > 0)
{
stmt100.executeBatch();
paramCounter = 0;
}
}
}
// insert by 1's
try (PreparedStatement stmt1 = conn.prepareStatement(sql1))
{
for (int index = outerIndex; index < paramList.size(); index++)
{
Number I = (Number)paramList.get(index);
if (null == I)
stmt1.setNull(1, Types.INTEGER);
else if (useInteger)
stmt1.setInt(1, I.intValue());
else
stmt1.setLong(1, I.longValue());
stmt1.addBatch();
paramCounter++;
if (paramCounter > 1000)
{
stmt1.executeBatch();
paramCounter = 0;
}
}
if (paramCounter > 0)
stmt1.executeBatch();
}
}
catch (SQLException e)
{
if (e instanceof BatchUpdateException)
{
if (null != e.getNextException())
e = e.getNextException();
}
logException(new SQLFragment(sql1), conn, e, Level.WARN);
throw (e);
}
}
}
private static final Map<Class<?>, Getter> _getterMap = new HashMap<>(20);
public enum Getter
{
STRING(String.class) {
@Override
String getObject(ResultSet rs, int i) throws SQLException { return rs.getString(i); }
@Override
String getObject(ResultSet rs, String columnLabel) throws SQLException { return rs.getString(columnLabel); }
},
INTEGER(Integer.class) {
@Override
Integer getObject(ResultSet rs, int i) throws SQLException { int n = rs.getInt(i); return rs.wasNull() ? null : n ; }
@Override
Integer getObject(ResultSet rs, String columnLabel) throws SQLException { int n = rs.getInt(columnLabel); return rs.wasNull() ? null : n ; }
},
DOUBLE(Double.class) {
@Override
Double getObject(ResultSet rs, int i) throws SQLException { double d = rs.getDouble(i); return rs.wasNull() ? null : d ; }
@Override
Double getObject(ResultSet rs, String columnLabel) throws SQLException { double d = rs.getDouble(columnLabel); return rs.wasNull() ? null : d ; }
},
BOOLEAN(Boolean.class) {
@Override
Boolean getObject(ResultSet rs, int i) throws SQLException { boolean f = rs.getBoolean(i); return rs.wasNull() ? null : f ; }
@Override
Boolean getObject(ResultSet rs, String columnLabel) throws SQLException { boolean f = rs.getBoolean(columnLabel); return rs.wasNull() ? null : f ; }
},
LONG(Long.class) {
@Override
Long getObject(ResultSet rs, int i) throws SQLException { long l = rs.getLong(i); return rs.wasNull() ? null : l; }
@Override
Long getObject(ResultSet rs, String columnLabel) throws SQLException { long l = rs.getLong(columnLabel); return rs.wasNull() ? null : l; }
},
UTIL_DATE(Date.class) {
@Override
Date getObject(ResultSet rs, int i) throws SQLException { return rs.getTimestamp(i); }
@Override
Date getObject(ResultSet rs, String columnLabel) throws SQLException { return rs.getTimestamp(columnLabel); }
},
BYTES(byte[].class) {
@Override
Object getObject(ResultSet rs, int i) throws SQLException { return rs.getBytes(i); }
@Override
Object getObject(ResultSet rs, String columnLabel) throws SQLException { return rs.getBytes(columnLabel); }
},
TIMESTAMP(Timestamp.class) {
@Override
Object getObject(ResultSet rs, int i) throws SQLException { return rs.getTimestamp(i); }
@Override
Object getObject(ResultSet rs, String columnLabel) throws SQLException { return rs.getTimestamp(columnLabel); }
},
LOCAL_DATE(LocalDate.class) {
@Override
Object getObject(ResultSet rs, int i) throws SQLException { return convert(rs.getDate(i)); }
@Override
Object getObject(ResultSet rs, String columnLabel) throws SQLException { return convert(rs.getDate(columnLabel)); }
private LocalDate convert(@Nullable java.sql.Date sqlDate)
{
return null == sqlDate ? null : sqlDate.toLocalDate();
}
},
LOCAL_DATE_TIME(LocalDateTime.class) {
@Override
Object getObject(ResultSet rs, int i) throws SQLException { return convert(rs.getTimestamp(i)); }
@Override
Object getObject(ResultSet rs, String columnLabel) throws SQLException { return convert(rs.getTimestamp(columnLabel)); }
private LocalDateTime convert(@Nullable Timestamp timestamp)
{
return null == timestamp ? null : timestamp.toLocalDateTime();
}
},
OBJECT(Object.class) {
@Override
Object getObject(ResultSet rs, int i) throws SQLException { return rs.getObject(i); }
@Override
Object getObject(ResultSet rs, String columnLabel) throws SQLException { return rs.getObject(columnLabel); }
};
abstract Object getObject(ResultSet rs, int i) throws SQLException;
abstract Object getObject(ResultSet rs, String columnName) throws SQLException;
Object getObject(ResultSet rs) throws SQLException
{
return getObject(rs, 1);
}
Getter(Class<?> c)
{
_getterMap.put(c, this);
}
public static <K> @Nullable Getter forClass(Class<K> c)
{
return _getterMap.get(c);
}
}
// Standard SQLException catch block: log exception, query SQL, and params
static void logException(@Nullable SQLFragment sql, @Nullable Connection conn, SQLException e, Level logLevel)
{
Level level = getExceptionLogLevel(sql, e, logLevel);
if (null == level)
return;
if (SqlDialect.isConnectionLostException(e))
_log.error("Database connection lost during query, SQLState: {}", e.getSQLState(), e);
else if (sql == null)
_log.error("SQL Exception, no SQL query text available", e);
else
_log.log(level, "SQL Exception{}", e.getSQLState() == null ? "" : (" with SQLState: " + e.getSQLState()), e);
_logQuery(level, sql, conn);
}
/** Level at which logException() logs e and its SQL, or null if it shouldn't be logged */
static @Nullable Level getExceptionLogLevel(@Nullable SQLFragment sql, SQLException e, Level logLevel)
{
if (SqlDialect.isCancelException(e))
return null;
// A killed backend surfaces as an I/O error wrapping EOFException, which isIgnorable() mistakes for a client abort
boolean connectionLost = SqlDialect.isConnectionLostException(e);
if (!connectionLost && ExceptionUtil.isIgnorable(e))
return null;
// Treat a ConstraintException during INSERT/UPDATE as a WARNING. Treat all other SQLExceptions as an ERROR.
Level level = Level.ERROR;
if (!connectionLost && sql != null && RuntimeSQLException.isConstraintException(e))
{
String trim = sql.getSQL().trim();
if (Strings.CI.startsWith(trim, "INSERT") || Strings.CI.startsWith(trim, "UPDATE"))
level = Level.WARN;
}
return level.isMoreSpecificThan(logLevel) ? level : null;
}
static void debugException(SQLFragment sql, @Nullable Connection conn, SQLException e)
{
_log.debug(e);
_logQuery(Level.DEBUG, sql, conn);
}
/** Typical finally block cleanup. Tolerant of null or already closed JDBC resources */
static void doClose(@Nullable ResultSet rs, @Nullable Statement stmt, @Nullable Connection conn, @NotNull DbScope scope)
{
try
{
if (stmt == null && rs != null && !rs.isClosed())
stmt = rs.getStatement();
}
catch (SQLException x)
{
_log.error("doFinally", x);
}
try
{
if (null != rs) rs.close();
}
catch (SQLException x)
{
_log.error("doFinally", x);
}
try
{
if (null != stmt) stmt.close();
}
catch (SQLException x)
{
_log.error("doFinally", x);
}
if (null != conn) scope.releaseConnection(conn);
}
/**
* return a 'clean' list of fields to update
*/
protected static <K> Map<String, Object> _getTableData(TableInfo table, K from, boolean insert)
{
Map<String, Object> fields;
//noinspection unchecked
ObjectFactory<K> f = ObjectFactory.Registry.getFactory((Class<K>)from.getClass());
if (null == f)
throw new IllegalArgumentException("Could not find a matching object factory.");
fields = f.toMap(from, null);
return _getTableData(table, fields, insert);
}
protected static Map<String, Object> _getTableData(TableInfo table, Map<String, Object> fields, boolean insert)
{
if (!(fields instanceof CaseInsensitiveHashMap))
fields = new CaseInsensitiveHashMap<>(fields);
// special rename case
if (fields.containsKey("containerId"))
fields.put("container", fields.get("containerId"));
List<ColumnInfo> columns = table.getColumns();
Map<String, Object> m = new CaseInsensitiveHashMap<>(columns.size() * 2);
for (ColumnInfo column : columns)
{
String key = column.getName();
if (!insert && column.isReadOnly() || column.isAutoIncrement() || column.isVersionColumn())
continue;
if (!fields.containsKey(key))
{
if (Character.isUpperCase(key.charAt(0)))
{
key = Character.toLowerCase(key.charAt(0)) + key.substring(1);
if (!fields.containsKey(key))
continue;
}
else
continue;
}
Object v = fields.get(key);
if (v instanceof String s)
v = _trimRight(s);
m.put(column.getName(), v);
}
return m;
}
static String _trimRight(String s)
{
if (null == s) return "";
return StringUtils.stripEnd(s, "\t\r\n ");
}
protected static void _insertSpecialFields(User user, TableInfo table, Map<String, Object> fields, NowTimestamp now)
{
ColumnInfo col = table.getColumn(OWNER_COLUMN_NAME);
if (null != col && null != user)
fields.put(OWNER_COLUMN_NAME, user.getUserId());
col = table.getColumn(CREATED_BY_COLUMN_NAME);
if (null != col && null != user)
fields.put(CREATED_BY_COLUMN_NAME, user.getUserId());
col = table.getColumn(CREATED_COLUMN_NAME);
if (null != col)
{
Date dateCreated = (Date)fields.get(CREATED_COLUMN_NAME);
if (null == dateCreated || 0 == dateCreated.getTime())
fields.put(CREATED_COLUMN_NAME, now);
}
col = table.getColumn(ENTITY_ID_COLUMN_NAME);
if (col != null && fields.get(ENTITY_ID_COLUMN_NAME) == null)
fields.put(ENTITY_ID_COLUMN_NAME, GUID.makeGUID());
}
protected static void _copyInsertSpecialFields(Object returnObject, Map<String, Object> fields)
{
if (returnObject == fields)
return;
// make sure that any GUID generated in this routine is stored in the returned object
if (fields.containsKey(ENTITY_ID_COLUMN_NAME))
_setProperty(returnObject, ENTITY_ID_COLUMN_NAME, fields.get(ENTITY_ID_COLUMN_NAME));
if (fields.containsKey(OWNER_COLUMN_NAME))
_setProperty(returnObject, OWNER_COLUMN_NAME, fields.get(OWNER_COLUMN_NAME));
if (fields.containsKey(CREATED_COLUMN_NAME))
_setProperty(returnObject, CREATED_COLUMN_NAME, fields.get(CREATED_COLUMN_NAME));
if (fields.containsKey(CREATED_BY_COLUMN_NAME))
_setProperty(returnObject, CREATED_BY_COLUMN_NAME, fields.get(CREATED_BY_COLUMN_NAME));
}
protected static void _updateSpecialFields(@Nullable User user, TableInfo table, Map<String, Object> fields, NowTimestamp now)
{
ColumnInfo colModifiedBy = table.getColumn(MODIFIED_BY_COLUMN_NAME);
if (null != colModifiedBy && null != user)
fields.put(colModifiedBy.getName(), user.getUserId());
ColumnInfo colModified = table.getColumn(MODIFIED_COLUMN_NAME);
if (null != colModified)
fields.put(colModified.getName(), now);
ColumnInfo colVersion = table.getVersionColumn();
if (null != colVersion && colVersion != colModified && colVersion.getJdbcType() == JdbcType.TIMESTAMP)
fields.put(colVersion.getName(), now);
}
protected static void _copyUpdateSpecialFields(TableInfo table, Object returnObject, Map<String, Object> fields)
{
if (returnObject == fields)
return;
if (fields.containsKey(MODIFIED_BY_COLUMN_NAME))
_setProperty(returnObject, MODIFIED_BY_COLUMN_NAME, fields.get(MODIFIED_BY_COLUMN_NAME));
if (fields.containsKey(MODIFIED_COLUMN_NAME))
_setProperty(returnObject, MODIFIED_COLUMN_NAME, fields.get(MODIFIED_COLUMN_NAME));
ColumnInfo colModified = table.getColumn(MODIFIED_COLUMN_NAME);
ColumnInfo colVersion = table.getVersionColumn();
if (null != colVersion && colVersion != colModified && colVersion.getJdbcType() == JdbcType.TIMESTAMP)
_setProperty(returnObject, colVersion.getName(), fields.get(colVersion.getName()));
}
static private void _setProperty(Object fields, String propName, Object value)
{
// Replace marker NowTimestamp instances with Timestamp for default serialization
if (value instanceof NowTimestamp now)
value = new java.sql.Timestamp(now.getTime());
if (fields instanceof Map)
{
((Map<String, Object>) fields).put(propName, value);
}
else
{
if (Character.isUpperCase(propName.charAt(0)))
propName = Character.toLowerCase(propName.charAt(0)) + propName.substring(1);
try
{
if (PropertyUtils.isWriteable(fields, propName))
{
// use BeanUtils instead of PropertyUtils because BeanUtils will use a registered Converter
BeanUtils.copyProperty(fields, propName, value);
}
// UNDONE: horrible postgres hack..., not general fix
else if (propName.endsWith("id"))
{
propName = propName.substring(0,propName.length()-2) + "Id";
if (PropertyUtils.isWriteable(fields, propName))
BeanUtils.copyProperty(fields, propName, value);
}
}
catch (Exception x)
{
throw new RuntimeException(x);
}
}
}
/**
* @return a new Map<String, Object> if fieldsIn is a Map, otherwise returns modified version of fieldsIn.
* The row is not re-queried after the insert, so the returned value carries only the fields passed in plus the
* generated autoincrement key and special fields (e.g. created/createdBy) -- not any other database-computed
* values such as defaults, computed columns, or trigger-modified data. A record can be provided to insert, but
* it's returned unchanged, since it's immutable and can't receive the generated key or special fields.
* @throws RuntimeValidationException if there is a problem with the data that's detected before we try to actually do the insert
* @throws RuntimeSQLException if there is a problem communicating with the database or there is a constraint violation or similar error
*/
public static <K> K insert(@Nullable User user, TableInfo table, K fieldsIn)
{
assert assertInDb(table);
SQLFragment insertSQL = new SQLFragment();
SQLFragment columnSQL = new SQLFragment();
SQLFragment valueSQL = new SQLFragment();
ColumnInfo autoIncColumn = null;
String comma = "";
//noinspection unchecked
Map<String, Object> fields = fieldsIn instanceof Map ?
_getTableData(table, (Map<String, Object>)fieldsIn, true) :
_getTableData(table, fieldsIn, true);
NowTimestamp now = new NowTimestamp();
_insertSpecialFields(user, table, fields, now);
_updateSpecialFields(user, table, fields, now);
List<ColumnInfo> columns = table.getColumns();
for (ColumnInfo column : columns)
{
// note if(version) is not an no-op, it protects the isautoinc test from version columns implemented using sequences
if (column.isVersionColumn())
{
}
else if (column.isAutoIncrement())
autoIncColumn = column;
if (!fields.containsKey(column.getName()))
continue;
Object value = fields.get(column.getName());
if (!column.isAutoIncrement() &&
column.isRequired() &&
(null == value || value instanceof String s && s.isEmpty()) &&
!Table.AUTOPOPULATED_COLUMN_NAMES.contains(column.getName()) &&
column.getJdbcDefaultValue() == null)
{
throw new RuntimeValidationException("A value is required for field '" + column.getName() + "'", column.getName());
}
columnSQL.append(comma);
columnSQL.appendIdentifier(column.getSelectIdentifier());
valueSQL.append(comma);
if (null == value || value instanceof String s && s.isEmpty())
valueSQL.unsafeAppend("NULL");
else if (value instanceof NowTimestamp ts)
valueSQL.appendValue(ts);
else
{
// Validate the value
List<ColumnValidator> validators = ColumnValidators.create(column, null);
for (ColumnValidator v : validators)
{
String msg = v.validate(1, value);
if (msg != null)
throw new RuntimeValidationException(msg, column.getName()); // CONSIDER: would prefer throwing ValidationException instead, but it's not a RuntimeException
}
valueSQL.append("?");
if (value instanceof Parameter.JdbcParameterValue)
valueSQL.add(value);
else
valueSQL.add(new Parameter.TypedValue(value, column.getJdbcType()));
}
comma = ", ";
}
if (comma.isEmpty())
{
// NO COLUMNS TO INSERT
throw new IllegalArgumentException("Table.insert called with no column data. table=" + table + " object=" + fieldsIn);
}
insertSQL.unsafeAppend("INSERT INTO ");
insertSQL.append(table.getSelectName());
insertSQL.unsafeAppend("\n\t(");
insertSQL.append(columnSQL);
insertSQL.unsafeAppend(")\n\t");
insertSQL.unsafeAppend("VALUES (");
insertSQL.append(valueSQL);
insertSQL.append(")");
// CONSIDER reselect version column
if (null != autoIncColumn)
table.getSqlDialect().addReselect(insertSQL, autoIncColumn, null);
// If Map was handed in, then we hand back a Map
// UNDONE: use Table.select() to reselect and return new Object
//noinspection unchecked
K returnObject = (K) (fieldsIn instanceof Map && !(fieldsIn instanceof BoundMap) ? fields : fieldsIn);
DbSchema schema = table.getSchema();
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try (Parameter.ParameterList jdbcParameters = new Parameter.ParameterList())
{
conn = schema.getScope().getConnection();
stmt = prepareStatement(conn, insertSQL.getSQL(), insertSQL.getParams(), jdbcParameters);
if (null == autoIncColumn)
{
stmt.execute();
}
else
{
rs = table.getSqlDialect().executeWithResults(stmt);
rs.next();
_setProperty(returnObject, autoIncColumn.getName(), rs.getLong(1));
}
_copyInsertSpecialFields(returnObject, fields);
_copyUpdateSpecialFields(table, returnObject, fields);
}
catch (SQLException e)
{
logException(insertSQL, conn, e, Level.WARN);
throw new RuntimeSQLException(e);
}
finally
{
doClose(rs, stmt, conn, schema.getScope());
}
return returnObject;
}
public static <K> K update(@Nullable User user, TableInfo table, K fieldsIn, Object pkVals)
{
return update(user, table, fieldsIn, pkVals, null, Level.WARN);
}
public static <K> K update(@Nullable User user, TableInfo table, K fieldsIn, Object pkVals, @Nullable Filter filter, Level level)
{
return update(user, table, fieldsIn, null, pkVals, filter, level);
}
/**
* NOTE: this does not enforce that keyColumn is an appropriately unique column!
* @return fieldsIn itself (mutated in place) if it's a bean, or a new Map<String, Object> if fieldsIn is a Map.
* The row is not re-queried after the update, so the returned value reflects only the fields as passed in --
* not database-computed values such as version-column update expressions, defaults, or trigger-modified data.
*/
public static <K> K update(@Nullable User user, TableInfo table, K fieldsIn, @Nullable ColumnInfo keyColumn, Object pkVals, @Nullable Filter filter, Level level)
{
assert assertInDb(table);
assert null != pkVals;
SQLFragment setSQL = new SQLFragment();
SQLFragment whereSQL = new SQLFragment();
String comma = "";
// UNDONE -- rowVersion
List<ColumnInfo> columnPK;
if (null != keyColumn)
{
columnPK = Collections.singletonList(keyColumn);
}
else
{
columnPK = table.getPkColumns();
if (columnPK.isEmpty())
columnPK = table.getAlternateKeyColumns();
}
// Name-value pairs for the PK columns for this row
Map<String, Object> keys = new CaseInsensitiveHashMap<>();
if (columnPK.size() == 1 && !pkVals.getClass().isArray())