Debian Codegraph @

src/main/org/h2/table/Column.java

raw
1 /*
2 * Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0,
3 * and the EPL 1.0 (https://h2database.com/html/license.html).
4 * Initial Developer: H2 Group
5 */
6 package org.h2.table;
7
8 import java.sql.ResultSetMetaData;
9 import java.util.Objects;
10
11 import org.h2.api.ErrorCode;
12 import org.h2.command.Parser;
13 import org.h2.command.ddl.SequenceOptions;
14 import org.h2.engine.CastDataProvider;
15 import org.h2.engine.Constants;
16 import org.h2.engine.SessionLocal;
17 import org.h2.expression.Expression;
18 import org.h2.expression.ExpressionVisitor;
19 import org.h2.expression.ValueExpression;
20 import org.h2.message.DbException;
21 import org.h2.result.Row;
22 import org.h2.schema.Domain;
23 import org.h2.schema.Schema;
24 import org.h2.schema.Sequence;
25 import org.h2.util.HasSQL;
26 import org.h2.util.ParserUtil;
27 import org.h2.util.StringUtils;
28 import org.h2.value.TypeInfo;
29 import org.h2.value.Typed;
30 import org.h2.value.Value;
31 import org.h2.value.ValueNull;
32 import org.h2.value.ValueUuid;
33
34 /**
35 * This class represents a column in a table.
36 */
37 public final class Column implements HasSQL, Typed, ColumnTemplate {
38
39 /**
40 * The name of the rowid pseudo column.
41 */
42 public static final String ROWID = "_ROWID_";
43
44 /**
45 * This column is not nullable.
46 */
47 public static final int NOT_NULLABLE =
48 ResultSetMetaData.columnNoNulls;
49
50 /**
51 * This column is nullable.
52 */
53 public static final int NULLABLE =
54 ResultSetMetaData.columnNullable;
55
56 /**
57 * It is not know whether this column is nullable.
58 */
59 public static final int NULLABLE_UNKNOWN =
60 ResultSetMetaData.columnNullableUnknown;
61
62 private TypeInfo type;
63 private Table table;
64 private String name;
65 private int columnId;
66 private boolean nullable = true;
67 private Expression defaultExpression;
68 private Expression onUpdateExpression;
69 private SequenceOptions identityOptions;
70 private boolean defaultOnNull;
71 private Sequence sequence;
72 private boolean isGeneratedAlways;
73 private GeneratedColumnResolver generatedTableFilter;
74 private int selectivity;
75 private String comment;
76 private boolean primaryKey;
77 private boolean visible = true;
78 private boolean rowId;
79 private Domain domain;
80
81 /**
82 * Appends the specified columns to the specified builder.
83 *
84 * @param builder
85 * string builder
86 * @param columns
87 * columns
88 * @param sqlFlags
89 * formatting flags
90 * @return the specified string builder
91 */
92 public static StringBuilder writeColumns(StringBuilder builder, Column[] columns, int sqlFlags) {
93 for (int i = 0, l = columns.length; i < l; i++) {
94 if (i > 0) {
95 builder.append(", ");
96 }
97 columns[i].getSQL(builder, sqlFlags);
98 }
99 return builder;
100 }
101
102 /**
103 * Appends the specified columns to the specified builder.
104 *
105 * @param builder
106 * string builder
107 * @param columns
108 * columns
109 * @param separator
110 * separator
111 * @param suffix
112 * additional SQL to append after each column
113 * @param sqlFlags
114 * formatting flags
115 * @return the specified string builder
116 */
117 public static StringBuilder writeColumns(StringBuilder builder, Column[] columns, String separator,
118 String suffix, int sqlFlags) {
119 for (int i = 0, l = columns.length; i < l; i++) {
120 if (i > 0) {
121 builder.append(separator);
122 }
123 columns[i].getSQL(builder, sqlFlags).append(suffix);
124 }
125 return builder;
126 }
127
128 public Column(String name, TypeInfo type) {
129 this.name = name;
130 this.type = type;
131 }
132
133 public Column(String name, TypeInfo type, Table table, int columnId) {
134 this.name = name;
135 this.type = type;
136 this.table = table;
137 this.columnId = columnId;
138 }
139
140 @Override
141 public boolean equals(Object o) {
142 if (o == this) {
143 return true;
144 } else if (!(o instanceof Column)) {
145 return false;
146 }
147 Column other = (Column) o;
148 if (table == null || other.table == null ||
149 name == null || other.name == null) {
150 return false;
151 }
152 if (table != other.table) {
153 return false;
154 }
155 return name.equals(other.name);
156 }
157
158 @Override
159 public int hashCode() {
160 if (table == null || name == null) {
161 return 0;
162 }
163 return table.getId() ^ name.hashCode();
164 }
165
166 public Column getClone() {
167 Column newColumn = new Column(name, type);
168 newColumn.copy(this);
169 return newColumn;
170 }
171
172 /**
173 * Convert a value to this column's type without precision and scale checks.
174 *
175 * @param provider the cast information provider
176 * @param v the value
177 * @return the value
178 */
179 public Value convert(CastDataProvider provider, Value v) {
180 try {
181 return v.convertTo(type, provider, this);
182 } catch (DbException e) {
183 if (e.getErrorCode() == ErrorCode.DATA_CONVERSION_ERROR_1) {
184 e = getDataConversionError(v, e);
185 }
186 throw e;
187 }
188 }
189
190 /**
191 * Returns whether this column is an identity column.
192 *
193 * @return whether this column is an identity column
194 */
195 public boolean isIdentity() {
196 return sequence != null || identityOptions != null;
197 }
198
199 /**
200 * Returns whether this column is a generated column.
201 *
202 * @return whether this column is a generated column
203 */
204 public boolean isGenerated() {
205 return isGeneratedAlways && defaultExpression != null;
206 }
207
208 /**
209 * Returns whether this column is a generated column or always generated
210 * identity column.
211 *
212 * @return whether this column is a generated column or always generated
213 * identity column
214 */
215 public boolean isGeneratedAlways() {
216 return isGeneratedAlways;
217 }
218
219 /**
220 * Set the default value in the form of a generated expression of other
221 * columns.
222 *
223 * @param expression the computed expression
224 */
225 public void setGeneratedExpression(Expression expression) {
226 this.isGeneratedAlways = true;
227 this.defaultExpression = expression;
228 }
229
230 /**
231 * Set the table and column id.
232 *
233 * @param table the table
234 * @param columnId the column index
235 */
236 public void setTable(Table table, int columnId) {
237 this.table = table;
238 this.columnId = columnId;
239 }
240
241 public Table getTable() {
242 return table;
243 }
244
245 @Override
246 public void setDefaultExpression(SessionLocal session, Expression defaultExpression) {
247 // also to test that no column names are used
248 if (defaultExpression != null) {
249 defaultExpression = defaultExpression.optimize(session);
250 if (defaultExpression.isConstant()) {
251 defaultExpression = ValueExpression.get(
252 defaultExpression.getValue(session));
253 }
254 }
255 this.defaultExpression = defaultExpression;
256 this.isGeneratedAlways = false;
257 }
258
259 @Override
260 public void setOnUpdateExpression(SessionLocal session, Expression onUpdateExpression) {
261 // also to test that no column names are used
262 if (onUpdateExpression != null) {
263 onUpdateExpression = onUpdateExpression.optimize(session);
264 if (onUpdateExpression.isConstant()) {
265 onUpdateExpression = ValueExpression.get(onUpdateExpression.getValue(session));
266 }
267 }
268 this.onUpdateExpression = onUpdateExpression;
269 }
270
271 public int getColumnId() {
272 return columnId;
273 }
274
275 @Override
276 public String getSQL(int sqlFlags) {
277 return rowId ? name : Parser.quoteIdentifier(name, sqlFlags);
278 }
279
280 @Override
281 public StringBuilder getSQL(StringBuilder builder, int sqlFlags) {
282 return rowId ? builder.append(name) : ParserUtil.quoteIdentifier(builder, name, sqlFlags);
283 }
284
285 /**
286 * Appends the table name and column name to the specified builder.
287 *
288 * @param builder the string builder
289 * @param sqlFlags formatting flags
290 * @return the specified string builder
291 */
292 public StringBuilder getSQLWithTable(StringBuilder builder, int sqlFlags) {
293 return getSQL(table.getSQL(builder, sqlFlags).append('.'), sqlFlags);
294 }
295
296 public String getName() {
297 return name;
298 }
299
300 @Override
301 public TypeInfo getType() {
302 return type;
303 }
304
305 public void setNullable(boolean b) {
306 nullable = b;
307 }
308
309 public boolean getVisible() {
310 return visible;
311 }
312
313 public void setVisible(boolean b) {
314 visible = b;
315 }
316
317 @Override
318 public Domain getDomain() {
319 return domain;
320 }
321
322 @Override
323 public void setDomain(Domain domain) {
324 this.domain = domain;
325 }
326
327 /**
328 * Returns whether this column is a row identity column.
329 *
330 * @return true for _ROWID_ column, false otherwise
331 */
332 public boolean isRowId() {
333 return rowId;
334 }
335
336 /**
337 * Set row identity flag.
338 *
339 * @param rowId true _ROWID_ column, false otherwise
340 */
341 public void setRowId(boolean rowId) {
342 this.rowId = rowId;
343 }
344
345 /**
346 * Validate the value, convert it if required, and update the sequence value
347 * if required. If the value is null, the default value (NULL if no default
348 * is set) is returned. Domain constraints are validated as well.
349 *
350 * @param session the session
351 * @param value the value or null
352 * @param row the row
353 * @return the new or converted value
354 */
355 Value validateConvertUpdateSequence(SessionLocal session, Value value, Row row) {
356 check: {
357 if (value == null) {
358 if (sequence != null) {
359 value = session.getNextValueFor(sequence, null);
360 break check;
361 }
362 value = getDefaultOrGenerated(session, row);
363 }
364 if (value == ValueNull.INSTANCE && !nullable) {
365 throw DbException.get(ErrorCode.NULL_NOT_ALLOWED, name);
366 }
367 }
368 try {
369 value = value.convertForAssignTo(type, session, name);
370 } catch (DbException e) {
371 if (e.getErrorCode() == ErrorCode.DATA_CONVERSION_ERROR_1) {
372 e = getDataConversionError(value, e);
373 }
374 throw e;
375 }
376 if (domain != null) {
377 domain.checkConstraints(session, value);
378 }
379 if (sequence != null && session.getMode().updateSequenceOnManualIdentityInsertion) {
380 updateSequenceIfRequired(session, value.getLong());
381 }
382 return value;
383 }
384
385 private Value getDefaultOrGenerated(SessionLocal session, Row row) {
386 Value value;
387 Expression localDefaultExpression = getEffectiveDefaultExpression();
388 if (localDefaultExpression == null) {
389 value = ValueNull.INSTANCE;
390 } else {
391 if (isGeneratedAlways) {
392 synchronized (this) {
393 generatedTableFilter.set(row);
394 try {
395 value = localDefaultExpression.getValue(session);
396 } finally {
397 generatedTableFilter.set(null);
398 }
399 }
400 } else {
401 value = localDefaultExpression.getValue(session);
402 }
403 }
404 return value;
405 }
406
407 private DbException getDataConversionError(Value value, DbException cause) {
408 StringBuilder builder = new StringBuilder().append(value.getTraceSQL()).append(" (");
409 if (table != null) {
410 builder.append(table.getName()).append(": ");
411 }
412 builder.append(getCreateSQL()).append(')');
413 return DbException.get(ErrorCode.DATA_CONVERSION_ERROR_1, cause, builder.toString());
414 }
415
416 private void updateSequenceIfRequired(SessionLocal session, long value) {
417 if (sequence.getCycle() == Sequence.Cycle.EXHAUSTED) {
418 return;
419 }
420 long current = sequence.getCurrentValue();
421 long inc = sequence.getIncrement();
422 if (inc > 0) {
423 if (value < current) {
424 return;
425 }
426 } else if (value > current) {
427 return;
428 }
429 try {
430 sequence.modify(value + inc, null, null, null, null, null, null);
431 } catch (DbException ex) {
432 if (ex.getErrorCode() == ErrorCode.SEQUENCE_ATTRIBUTES_INVALID_7) {
433 return;
434 }
435 throw ex;
436 }
437 sequence.flush(session);
438 }
439
440 /**
441 * Initialize the sequence for this column.
442 *
443 * @param session the session
444 * @param schema the schema where the sequence should be generated
445 * @param id the object id
446 * @param temporary true if the sequence is temporary and does not need to
447 * be stored
448 */
449 public void initializeSequence(SessionLocal session, Schema schema, int id, boolean temporary) {
450 if (identityOptions == null) {
451 throw DbException.getInternalError();
452 }
453 String sequenceName;
454 do {
455 sequenceName = "SYSTEM_SEQUENCE_"
456 + StringUtils.toUpperEnglish(ValueUuid.getNewRandom().getString().replace('-', '_'));
457 } while (schema.findSequence(sequenceName) != null);
458 identityOptions.setDataType(type);
459 Sequence seq = new Sequence(session, schema, id, sequenceName, identityOptions, true);
460 seq.setTemporary(temporary);
461 session.getDatabase().addSchemaObject(session, seq);
462 // This method also ensures NOT NULL
463 setSequence(seq, isGeneratedAlways);
464 }
465
466 @Override
467 public void prepareExpressions(SessionLocal session) {
468 if (defaultExpression != null) {
469 if (isGeneratedAlways) {
470 generatedTableFilter = new GeneratedColumnResolver(table);
471 defaultExpression.mapColumns(generatedTableFilter, 0, Expression.MAP_INITIAL);
472 }
473 defaultExpression = defaultExpression.optimize(session);
474 }
475 if (onUpdateExpression != null) {
476 onUpdateExpression = onUpdateExpression.optimize(session);
477 }
478 if (domain != null) {
479 domain.prepareExpressions(session);
480 }
481 }
482
483 public String getCreateSQLWithoutName() {
484 return getCreateSQL(new StringBuilder(), false);
485 }
486
487 public String getCreateSQL() {
488 return getCreateSQL(false);
489 }
490
491 /**
492 * Get this columns part of CREATE TABLE SQL statement.
493 *
494 * @param forMeta whether this is for the metadata table
495 * @return the SQL statement
496 */
497 public String getCreateSQL(boolean forMeta) {
498 StringBuilder builder = new StringBuilder();
499 if (name != null) {
500 ParserUtil.quoteIdentifier(builder, name, DEFAULT_SQL_FLAGS).append(' ');
501 }
502 return getCreateSQL(builder, forMeta);
503 }
504
505 private String getCreateSQL(StringBuilder builder, boolean forMeta) {
506 if (domain != null) {
507 domain.getSQL(builder, DEFAULT_SQL_FLAGS);
508 } else {
509 type.getSQL(builder, DEFAULT_SQL_FLAGS);
510 }
511 if (!visible) {
512 builder.append(" INVISIBLE ");
513 }
514 if (sequence != null) {
515 builder.append(" GENERATED ").append(isGeneratedAlways ? "ALWAYS" : "BY DEFAULT").append(" AS IDENTITY");
516 if (!forMeta) {
517 sequence.getSequenceOptionsSQL(builder.append('(')).append(')');
518 }
519 } else if (defaultExpression != null) {
520 if (isGeneratedAlways) {
521 defaultExpression.getEnclosedSQL(builder.append(" GENERATED ALWAYS AS "), DEFAULT_SQL_FLAGS);
522 } else {
523 defaultExpression.getUnenclosedSQL(builder.append(" DEFAULT "), DEFAULT_SQL_FLAGS);
524 }
525 }
526 if (onUpdateExpression != null) {
527 onUpdateExpression.getUnenclosedSQL(builder.append(" ON UPDATE "), DEFAULT_SQL_FLAGS);
528 }
529 if (defaultOnNull) {
530 builder.append(" DEFAULT ON NULL");
531 }
532 if (forMeta && sequence != null) {
533 sequence.getSQL(builder.append(" SEQUENCE "), DEFAULT_SQL_FLAGS);
534 }
535 if (selectivity != 0) {
536 builder.append(" SELECTIVITY ").append(selectivity);
537 }
538 if (comment != null) {
539 StringUtils.quoteStringSQL(builder.append(" COMMENT "), comment);
540 }
541 if (!nullable) {
542 builder.append(" NOT NULL");
543 }
544 return builder.toString();
545 }
546
547 public boolean isNullable() {
548 return nullable;
549 }
550
551 @Override
552 public Expression getDefaultExpression() {
553 return defaultExpression;
554 }
555
556 @Override
557 public Expression getEffectiveDefaultExpression() {
558 /*
559 * Identity columns may not have a default expression and may not use an
560 * expression from domain.
561 *
562 * Generated columns always have an own expression.
563 */
564 if (sequence != null) {
565 return null;
566 }
567 return defaultExpression != null ? defaultExpression
568 : domain != null ? domain.getEffectiveDefaultExpression() : null;
569 }
570
571 @Override
572 public Expression getOnUpdateExpression() {
573 return onUpdateExpression;
574 }
575
576 @Override
577 public Expression getEffectiveOnUpdateExpression() {
578 /*
579 * Identity and generated columns may not have an on update expression
580 * and may not use an expression from domain.
581 */
582 if (sequence != null || isGeneratedAlways) {
583 return null;
584 }
585 return onUpdateExpression != null ? onUpdateExpression
586 : domain != null ? domain.getEffectiveOnUpdateExpression() : null;
587 }
588
589 /**
590 * Whether the column has any identity options.
591 *
592 * @return true if yes
593 */
594 public boolean hasIdentityOptions() {
595 return identityOptions != null;
596 }
597
598 /**
599 * Set the identity options of this column.
600 *
601 * @param identityOptions
602 * identity column options
603 * @param generatedAlways
604 * whether value should be always generated
605 */
606 public void setIdentityOptions(SequenceOptions identityOptions, boolean generatedAlways) {
607 this.identityOptions = identityOptions;
608 this.isGeneratedAlways = generatedAlways;
609 removeNonIdentityProperties();
610 }
611
612 private void removeNonIdentityProperties() {
613 nullable = false;
614 onUpdateExpression = defaultExpression = null;
615 }
616
617 /**
618 * Returns identity column options, or {@code null} if sequence was already
619 * created or this column is not an identity column.
620 *
621 * @return identity column options, or {@code null}
622 */
623 public SequenceOptions getIdentityOptions() {
624 return identityOptions;
625 }
626
627 public void setDefaultOnNull(boolean defaultOnNull) {
628 this.defaultOnNull = defaultOnNull;
629 }
630
631 public boolean isDefaultOnNull() {
632 return defaultOnNull;
633 }
634
635 /**
636 * Rename the column. This method will only set the column name to the new
637 * value.
638 *
639 * @param newName the new column name
640 */
641 public void rename(String newName) {
642 this.name = newName;
643 }
644
645 /**
646 * Set the sequence to generate the value.
647 *
648 * @param sequence the sequence
649 * @param generatedAlways whether the value of the sequence is always used
650 */
651 public void setSequence(Sequence sequence, boolean generatedAlways) {
652 this.sequence = sequence;
653 this.isGeneratedAlways = generatedAlways;
654 this.identityOptions = null;
655 if (sequence != null) {
656 removeNonIdentityProperties();
657 if (sequence.getDatabase().getMode().identityColumnsHaveDefaultOnNull) {
658 defaultOnNull = true;
659 }
660 }
661 }
662
663 public Sequence getSequence() {
664 return sequence;
665 }
666
667 /**
668 * Get the selectivity of the column. Selectivity 100 means values are
669 * unique, 10 means every distinct value appears 10 times on average.
670 *
671 * @return the selectivity
672 */
673 public int getSelectivity() {
674 return selectivity == 0 ? Constants.SELECTIVITY_DEFAULT : selectivity;
675 }
676
677 /**
678 * Set the new selectivity of a column.
679 *
680 * @param selectivity the new value
681 */
682 public void setSelectivity(int selectivity) {
683 selectivity = selectivity < 0 ? 0 : (selectivity > 100 ? 100 : selectivity);
684 this.selectivity = selectivity;
685 }
686
687 @Override
688 public String getDefaultSQL() {
689 return defaultExpression == null ? null
690 : defaultExpression.getUnenclosedSQL(new StringBuilder(), DEFAULT_SQL_FLAGS).toString();
691 }
692
693 @Override
694 public String getOnUpdateSQL() {
695 return onUpdateExpression == null ? null
696 : onUpdateExpression.getUnenclosedSQL(new StringBuilder(), DEFAULT_SQL_FLAGS).toString();
697 }
698
699 public void setComment(String comment) {
700 this.comment = comment != null && !comment.isEmpty() ? comment : null;
701 }
702
703 public String getComment() {
704 return comment;
705 }
706
707 public void setPrimaryKey(boolean primaryKey) {
708 this.primaryKey = primaryKey;
709 }
710
711 /**
712 * Visit the default expression, the check constraint, and the sequence (if
713 * any).
714 *
715 * @param visitor the visitor
716 * @return true if every visited expression returned true, or if there are
717 * no expressions
718 */
719 boolean isEverything(ExpressionVisitor visitor) {
720 if (visitor.getType() == ExpressionVisitor.GET_DEPENDENCIES) {
721 if (sequence != null) {
722 visitor.getDependencies().add(sequence);
723 }
724 }
725 Expression e = getEffectiveDefaultExpression();
726 if (e != null && !e.isEverything(visitor)) {
727 return false;
728 }
729 e = getEffectiveOnUpdateExpression();
730 if (e != null && !e.isEverything(visitor)) {
731 return false;
732 }
733 return true;
734 }
735
736 public boolean isPrimaryKey() {
737 return primaryKey;
738 }
739
740 @Override
741 public String toString() {
742 return name;
743 }
744
745 /**
746 * Check whether the new column is of the same type and not more restricted
747 * than this column.
748 *
749 * @param newColumn the new (target) column
750 * @return true if the new column is compatible
751 */
752 public boolean isWideningConversion(Column newColumn) {
753 TypeInfo newType = newColumn.type;
754 int valueType = type.getValueType();
755 if (valueType != newType.getValueType()) {
756 return false;
757 }
758 long precision = type.getPrecision();
759 long newPrecision = newType.getPrecision();
760 if (precision > newPrecision
761 || precision < newPrecision && (valueType == Value.CHAR || valueType == Value.BINARY)) {
762 return false;
763 }
764 if (type.getScale() != newType.getScale()) {
765 return false;
766 }
767 if (!Objects.equals(type.getExtTypeInfo(), newType.getExtTypeInfo())) {
768 return false;
769 }
770 if (nullable && !newColumn.nullable) {
771 return false;
772 }
773 if (primaryKey != newColumn.primaryKey) {
774 return false;
775 }
776 if (identityOptions != null || newColumn.identityOptions != null) {
777 return false;
778 }
779 if (domain != newColumn.domain) {
780 return false;
781 }
782 if (defaultExpression != null || newColumn.defaultExpression != null) {
783 return false;
784 }
785 if (isGeneratedAlways || newColumn.isGeneratedAlways) {
786 return false;
787 }
788 if (onUpdateExpression != null || newColumn.onUpdateExpression != null) {
789 return false;
790 }
791 return true;
792 }
793
794 /**
795 * Copy the data of the source column into the current column.
796 *
797 * @param source the source column
798 */
799 public void copy(Column source) {
800 name = source.name;
801 type = source.type;
802 domain = source.domain;
803 // table is not set
804 // columnId is not set
805 nullable = source.nullable;
806 defaultExpression = source.defaultExpression;
807 onUpdateExpression = source.onUpdateExpression;
808 // identityOptions field is not set
809 defaultOnNull = source.defaultOnNull;
810 sequence = source.sequence;
811 comment = source.comment;
812 generatedTableFilter = source.generatedTableFilter;
813 isGeneratedAlways = source.isGeneratedAlways;
814 selectivity = source.selectivity;
815 primaryKey = source.primaryKey;
816 visible = source.visible;
817 }
818
819 }