Debian Codegraph @

src/main/org/h2/schema/Sequence.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.schema;
7
8 import org.h2.api.ErrorCode;
9 import org.h2.command.ddl.SequenceOptions;
10 import org.h2.engine.DbObject;
11 import org.h2.engine.SessionLocal;
12 import org.h2.message.DbException;
13 import org.h2.message.Trace;
14 import org.h2.value.TypeInfo;
15 import org.h2.value.Value;
16 import org.h2.value.ValueBigint;
17
18 /**
19 * A sequence is created using the statement
20 * CREATE SEQUENCE
21 */
22 public final class Sequence extends SchemaObject {
23
24 /**
25 * CYCLE clause and sequence state.
26 */
27 public enum Cycle {
28
29 /**
30 * Sequence is cycled.
31 */
32 CYCLE,
33
34 /**
35 * Sequence is not cycled and isn't exhausted yet.
36 */
37 NO_CYCLE,
38
39 /**
40 * Sequence is not cycled and was already exhausted.
41 */
42 EXHAUSTED;
43
44 /**
45 * Return whether sequence is cycled.
46 *
47 * @return {@code true} if sequence is cycled, {@code false} if sequence
48 * is not cycled
49 */
50 public boolean isCycle() {
51 return this == CYCLE;
52 }
53
54 }
55
56 /**
57 * The default cache size for sequences.
58 */
59 public static final int DEFAULT_CACHE_SIZE = 32;
60
61 private long baseValue;
62 private long margin;
63
64 private TypeInfo dataType;
65
66 private long increment;
67 private long cacheSize;
68 private long startValue;
69 private long minValue;
70 private long maxValue;
71 private Cycle cycle;
72 private boolean belongsToTable;
73 private boolean writeWithMargin;
74
75 /**
76 * Creates a new sequence.
77 *
78 * @param session
79 * the session
80 * @param schema
81 * the schema
82 * @param id
83 * the object id
84 * @param name
85 * the sequence name
86 * @param options
87 * the sequence options
88 * @param belongsToTable
89 * whether this sequence belongs to a table (for generated
90 * columns)
91 */
92 public Sequence(SessionLocal session, Schema schema, int id, String name, SequenceOptions options,
93 boolean belongsToTable) {
94 super(schema, id, name, Trace.SEQUENCE);
95 dataType = options.getDataType();
96 if (dataType == null) {
97 options.setDataType(dataType = session.getMode().decimalSequences ? TypeInfo.TYPE_NUMERIC_BIGINT
98 : TypeInfo.TYPE_BIGINT);
99 }
100 long bounds[] = options.getBounds();
101 Long t = options.getIncrement(session);
102 long increment = t != null ? t : 1;
103 Long start = options.getStartValue(session);
104 Long min = options.getMinValue(null, session);
105 Long max = options.getMaxValue(null, session);
106 long minValue = min != null ? min : getDefaultMinValue(start, increment, bounds);
107 long maxValue = max != null ? max : getDefaultMaxValue(start, increment, bounds);
108 long startValue = start != null ? start : increment >= 0 ? minValue : maxValue;
109 Long restart = options.getRestartValue(session, startValue);
110 long baseValue = restart != null ? restart : startValue;
111 t = options.getCacheSize(session);
112 long cacheSize;
113 boolean mayAdjustCacheSize;
114 if (t != null) {
115 cacheSize = t;
116 mayAdjustCacheSize = false;
117 } else {
118 cacheSize = DEFAULT_CACHE_SIZE;
119 mayAdjustCacheSize = true;
120 }
121 cacheSize = checkOptions(baseValue, startValue, minValue, maxValue, increment, cacheSize, mayAdjustCacheSize);
122 Cycle cycle = options.getCycle();
123 if (cycle == null) {
124 cycle = Cycle.NO_CYCLE;
125 } else if (cycle == Cycle.EXHAUSTED) {
126 baseValue = startValue;
127 }
128 this.margin = this.baseValue = baseValue;
129 this.increment = increment;
130 this.cacheSize = cacheSize;
131 this.startValue = startValue;
132 this.minValue = minValue;
133 this.maxValue = maxValue;
134 this.cycle = cycle;
135 this.belongsToTable = belongsToTable;
136 }
137
138 /**
139 * Allows the base value, start value, min value, max value, increment and
140 * cache size to be updated atomically, including atomic validation. Useful
141 * because setting these attributes one after the other could otherwise
142 * result in an invalid sequence state (e.g. min value > max value, start
143 * value < min value, etc).
144 * @param baseValue
145 * the base value ({@code null} if restart is not requested)
146 * @param startValue
147 * the new start value ({@code null} if no change)
148 * @param minValue
149 * the new min value ({@code null} if no change)
150 * @param maxValue
151 * the new max value ({@code null} if no change)
152 * @param increment
153 * the new increment ({@code null} if no change)
154 * @param cycle
155 * the new cycle value, or {@code null} if no change
156 * @param cacheSize
157 * the new cache size ({@code null} if no change)
158 */
159 public synchronized void modify(Long baseValue, Long startValue, Long minValue, Long maxValue, Long increment,
160 Cycle cycle, Long cacheSize) {
161 long baseValueAsLong = baseValue != null ? baseValue : this.baseValue;
162 long startValueAsLong = startValue != null ? startValue : this.startValue;
163 long minValueAsLong = minValue != null ? minValue : this.minValue;
164 long maxValueAsLong = maxValue != null ? maxValue : this.maxValue;
165 long incrementAsLong = increment != null ? increment : this.increment;
166 long cacheSizeAsLong;
167 boolean mayAdjustCacheSize;
168 if (cacheSize != null) {
169 cacheSizeAsLong = cacheSize;
170 mayAdjustCacheSize = false;
171 } else {
172 cacheSizeAsLong = this.cacheSize;
173 mayAdjustCacheSize = true;
174 }
175 cacheSizeAsLong = checkOptions(baseValueAsLong, startValueAsLong, minValueAsLong, maxValueAsLong,
176 incrementAsLong, cacheSizeAsLong, mayAdjustCacheSize);
177 if (cycle == null) {
178 cycle = this.cycle;
179 if (cycle == Cycle.EXHAUSTED && baseValue != null) {
180 cycle = Cycle.NO_CYCLE;
181 }
182 } else if (cycle == Cycle.EXHAUSTED) {
183 baseValueAsLong = startValueAsLong;
184 }
185 this.margin = this.baseValue = baseValueAsLong;
186 this.startValue = startValueAsLong;
187 this.minValue = minValueAsLong;
188 this.maxValue = maxValueAsLong;
189 this.increment = incrementAsLong;
190 this.cacheSize = cacheSizeAsLong;
191 this.cycle = cycle;
192 }
193
194 /**
195 * Validates the specified prospective base value, start value, min value,
196 * max value, increment, and cache size relative to each other, since each
197 * of their respective validities are contingent on the values of the other
198 * parameters.
199 *
200 * @param baseValue
201 * the prospective base value
202 * @param startValue
203 * the prospective start value
204 * @param minValue
205 * the prospective min value
206 * @param maxValue
207 * the prospective max value
208 * @param increment
209 * the prospective increment
210 * @param cacheSize
211 * the prospective cache size
212 * @param mayAdjustCacheSize
213 * whether cache size may be adjusted, cache size 0 is adjusted
214 * unconditionally to 1
215 * @return the prospective or adjusted cache size
216 */
217 private long checkOptions(long baseValue, long startValue, long minValue, long maxValue, long increment,
218 long cacheSize, boolean mayAdjustCacheSize) {
219 if (minValue <= baseValue && baseValue <= maxValue //
220 && minValue <= startValue && startValue <= maxValue //
221 && minValue < maxValue && increment != 0L) {
222 long range = maxValue - minValue;
223 if (Long.compareUnsigned(Math.abs(increment), range) <= 0 && cacheSize >= 0L) {
224 if (cacheSize <= 1L) {
225 return 1L;
226 }
227 long maxCacheSize = getMaxCacheSize(range, increment);
228 if (cacheSize <= maxCacheSize) {
229 return cacheSize;
230 }
231 if (mayAdjustCacheSize) {
232 return maxCacheSize;
233 }
234 }
235 }
236 throw DbException.get(ErrorCode.SEQUENCE_ATTRIBUTES_INVALID_7, getName(), Long.toString(baseValue),
237 Long.toString(startValue), Long.toString(minValue), Long.toString(maxValue), Long.toString(increment),
238 Long.toString(cacheSize));
239 }
240
241 private static long getMaxCacheSize(long range, long increment) {
242 if (increment > 0L) {
243 if (range < 0) {
244 range = Long.MAX_VALUE;
245 } else {
246 range += increment;
247 if (range < 0) {
248 range = Long.MAX_VALUE;
249 }
250 }
251 } else {
252 range = -range;
253 if (range > 0) {
254 range = Long.MIN_VALUE;
255 } else {
256 range += increment;
257 if (range >= 0) {
258 range = Long.MIN_VALUE;
259 }
260 }
261 }
262 return range / increment;
263 }
264
265 /**
266 * Calculates default min value.
267 *
268 * @param startValue the start value of the sequence.
269 * @param increment the increment of the sequence value.
270 * @param bounds min and max bounds of data type of the sequence
271 * @return min value.
272 */
273 public static long getDefaultMinValue(Long startValue, long increment, long[] bounds) {
274 long v = increment >= 0 ? 1 : bounds[0];
275 if (startValue != null && increment >= 0 && startValue < v) {
276 v = startValue;
277 }
278 return v;
279 }
280
281 /**
282 * Calculates default max value.
283 *
284 * @param startValue the start value of the sequence.
285 * @param increment the increment of the sequence value.
286 * @param bounds min and max bounds of data type of the sequence
287 * @return min value.
288 */
289 public static long getDefaultMaxValue(Long startValue, long increment, long[] bounds) {
290 long v = increment >= 0 ? bounds[1] : -1;
291 if (startValue != null && increment < 0 && startValue > v) {
292 v = startValue;
293 }
294 return v;
295 }
296
297 public boolean getBelongsToTable() {
298 return belongsToTable;
299 }
300
301 public TypeInfo getDataType() {
302 return dataType;
303 }
304
305 public int getEffectivePrecision() {
306 TypeInfo dataType = this.dataType;
307 switch (dataType.getValueType()) {
308 case Value.NUMERIC: {
309 int p = (int) dataType.getPrecision();
310 int s = dataType.getScale();
311 if (p - s > ValueBigint.DECIMAL_PRECISION) {
312 return ValueBigint.DECIMAL_PRECISION + s;
313 }
314 return p;
315 }
316 case Value.DECFLOAT:
317 return Math.min((int) dataType.getPrecision(), ValueBigint.DECIMAL_PRECISION);
318 default:
319 return (int) dataType.getPrecision();
320 }
321 }
322
323 public long getIncrement() {
324 return increment;
325 }
326
327 public long getStartValue() {
328 return startValue;
329 }
330
331 public long getMinValue() {
332 return minValue;
333 }
334
335 public long getMaxValue() {
336 return maxValue;
337 }
338
339 public Cycle getCycle() {
340 return cycle;
341 }
342
343 @Override
344 public String getDropSQL() {
345 if (getBelongsToTable()) {
346 return null;
347 }
348 StringBuilder builder = new StringBuilder("DROP SEQUENCE IF EXISTS ");
349 return getSQL(builder, DEFAULT_SQL_FLAGS).toString();
350 }
351
352 @Override
353 public String getCreateSQL() {
354 StringBuilder builder = getSQL(new StringBuilder("CREATE SEQUENCE "), DEFAULT_SQL_FLAGS);
355 if (dataType.getValueType() != Value.BIGINT) {
356 dataType.getSQL(builder.append(" AS "), DEFAULT_SQL_FLAGS);
357 }
358 builder.append(' ');
359 synchronized (this) {
360 getSequenceOptionsSQL(builder, writeWithMargin ? margin : baseValue);
361 }
362 if (belongsToTable) {
363 builder.append(" BELONGS_TO_TABLE");
364 }
365 return builder.toString();
366 }
367
368 /**
369 * Append the options part of the SQL statement to create the sequence.
370 *
371 * @param builder the builder
372 * @return the builder
373 */
374 public synchronized StringBuilder getSequenceOptionsSQL(StringBuilder builder) {
375 return getSequenceOptionsSQL(builder, baseValue);
376 }
377
378 private StringBuilder getSequenceOptionsSQL(StringBuilder builder, long value) {
379 builder.append("START WITH ").append(startValue);
380 if (value != startValue && cycle != Cycle.EXHAUSTED) {
381 builder.append(" RESTART WITH ").append(value);
382 }
383 if (increment != 1) {
384 builder.append(" INCREMENT BY ").append(increment);
385 }
386 long[] bounds = SequenceOptions.getBounds(dataType);
387 if (minValue != getDefaultMinValue(value, increment, bounds)) {
388 builder.append(" MINVALUE ").append(minValue);
389 }
390 if (maxValue != getDefaultMaxValue(value, increment, bounds)) {
391 builder.append(" MAXVALUE ").append(maxValue);
392 }
393 if (cycle == Cycle.CYCLE) {
394 builder.append(" CYCLE");
395 } else if (cycle == Cycle.EXHAUSTED) {
396 builder.append(" EXHAUSTED");
397 }
398 if (cacheSize != DEFAULT_CACHE_SIZE) {
399 if (cacheSize == 1) {
400 builder.append(" NO CACHE");
401 } else if (cacheSize > DEFAULT_CACHE_SIZE //
402 || cacheSize != getMaxCacheSize(maxValue - minValue, increment)) {
403 builder.append(" CACHE ").append(cacheSize);
404 }
405 }
406 return builder;
407 }
408
409 /**
410 * Get the next value for this sequence. Should not be called directly, use
411 * {@link SessionLocal#getNextValueFor(Sequence, org.h2.command.Prepared)} instead.
412 *
413 * @param session the session
414 * @return the next value
415 */
416 public Value getNext(SessionLocal session) {
417 long result;
418 boolean needsFlush;
419 synchronized (this) {
420 if (cycle == Cycle.EXHAUSTED) {
421 throw DbException.get(ErrorCode.SEQUENCE_EXHAUSTED, getName());
422 }
423 result = baseValue;
424 long newBase = result + increment;
425 needsFlush = increment > 0 ? increment(result, newBase) : decrement(result, newBase);
426 }
427 if (needsFlush) {
428 flush(session);
429 }
430 return ValueBigint.get(result).castTo(dataType, session);
431 }
432
433 private boolean increment(long oldBase, long newBase) {
434 boolean needsFlush = false;
435 /*
436 * If old base is not negative and new base is negative there is an
437 * overflow.
438 */
439 if (newBase > maxValue || (~oldBase & newBase) < 0) {
440 newBase = minValue;
441 needsFlush = true;
442 if (cycle == Cycle.CYCLE) {
443 margin = newBase + increment * (cacheSize - 1);
444 } else {
445 margin = newBase;
446 cycle = Cycle.EXHAUSTED;
447 }
448 } else if (newBase > margin) {
449 long newMargin = newBase + increment * (cacheSize - 1);
450 if (newMargin > maxValue || (~newBase & newMargin) < 0) {
451 /*
452 * Don't cache values near the end of the sequence for
453 * simplicity.
454 */
455 newMargin = newBase;
456 }
457 margin = newMargin;
458 needsFlush = true;
459 }
460 baseValue = newBase;
461 return needsFlush;
462 }
463
464 private boolean decrement(long oldBase, long newBase) {
465 boolean needsFlush = false;
466 /*
467 * If old base is negative and new base is not negative there is an
468 * overflow.
469 */
470 if (newBase < minValue || (oldBase & ~newBase) < 0) {
471 newBase = maxValue;
472 needsFlush = true;
473 if (cycle == Cycle.CYCLE) {
474 margin = newBase + increment * (cacheSize - 1);
475 } else {
476 margin = newBase;
477 cycle = Cycle.EXHAUSTED;
478 }
479 } else if (newBase < margin) {
480 long newMargin = newBase + increment * (cacheSize - 1);
481 if (newMargin < minValue || (newBase & ~newMargin) < 0) {
482 /*
483 * Don't cache values near the end of the sequence for
484 * simplicity.
485 */
486 newMargin = newBase;
487 }
488 margin = newMargin;
489 needsFlush = true;
490 }
491 baseValue = newBase;
492 return needsFlush;
493 }
494
495 /**
496 * Flush the current value to disk.
497 */
498 public void flushWithoutMargin() {
499 if (margin != baseValue) {
500 margin = baseValue;
501 flush(null);
502 }
503 }
504
505 /**
506 * Flush the current value, including the margin, to disk.
507 *
508 * @param session the session
509 */
510 public void flush(SessionLocal session) {
511 if (isTemporary()) {
512 return;
513 }
514 if (session == null || !database.isSysTableLockedBy(session)) {
515 // This session may not lock the sys table (except if it has already
516 // locked it) because it must be committed immediately, otherwise
517 // other threads can not access the sys table.
518 SessionLocal sysSession = database.getSystemSession();
519 synchronized (sysSession) {
520 flushInternal(sysSession);
521 sysSession.commit(false);
522 }
523 } else {
524 synchronized (session) {
525 flushInternal(session);
526 }
527 }
528 }
529
530 private void flushInternal(SessionLocal session) {
531 final boolean metaWasLocked = database.lockMeta(session);
532 // just for this case, use the value with the margin
533 try {
534 writeWithMargin = true;
535 database.updateMeta(session, this);
536 } finally {
537 writeWithMargin = false;
538 if (!metaWasLocked) {
539 database.unlockMeta(session);
540 }
541 }
542 }
543
544 /**
545 * Flush the current value to disk and close this object.
546 */
547 public void close() {
548 flushWithoutMargin();
549 }
550
551 @Override
552 public int getType() {
553 return DbObject.SEQUENCE;
554 }
555
556 @Override
557 public void removeChildrenAndResources(SessionLocal session) {
558 database.removeMeta(session, getId());
559 invalidate();
560 }
561
562 public synchronized long getBaseValue() {
563 // Use synchronized because baseValue is not volatile
564 return baseValue;
565 }
566
567 public synchronized long getCurrentValue() {
568 return baseValue - increment;
569 }
570
571 public void setBelongsToTable(boolean b) {
572 this.belongsToTable = b;
573 }
574
575 public long getCacheSize() {
576 return cacheSize;
577 }
578
579 }