Debian Codegraph @

src/main/org/h2/command/query/ForUpdate.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.command.query;
7
8 import org.h2.message.DbException;
9 import org.h2.util.HasSQL;
10 import org.h2.util.StringUtils;
11
12 /**
13 * FOR UPDATE clause.
14 */
15 public final class ForUpdate implements HasSQL {
16
17 /**
18 * Type of FOR UPDATE clause.
19 */
20 public enum Type {
21
22 /**
23 * Use default lock timeout.
24 */
25 DEFAULT,
26
27 /**
28 * Use specified lock timeout.
29 */
30 WAIT,
31
32 /**
33 * Use zero timeout.
34 */
35 NOWAIT,
36
37 /**
38 * Skip locked rows.
39 */
40 SKIP_LOCKED;
41
42 }
43
44 /**
45 * FOR UPDATE clause without additional parameters.
46 */
47 public static final ForUpdate DEFAULT = new ForUpdate(Type.DEFAULT, -1);
48
49 /**
50 * FOR UPDATE NOWAIT clause.
51 */
52 public static final ForUpdate NOWAIT = new ForUpdate(Type.NOWAIT, 0);
53
54 /**
55 * FOR UPDATE SKIP LOCKED clause.
56 */
57 public static final ForUpdate SKIP_LOCKED = new ForUpdate(Type.SKIP_LOCKED, -2);
58
59 /**
60 * Returns FOR UPDATE WAIT N clause.
61 *
62 * @param timeoutMillis
63 * timeout in milliseconds
64 * @return FOR UPDATE WAIT N clause
65 */
66 public static final ForUpdate wait(int timeoutMillis) {
67 if (timeoutMillis < 0) {
68 throw DbException.getInvalidValueException("timeout", timeoutMillis);
69 }
70 if (timeoutMillis == 0) {
71 return NOWAIT;
72 }
73 return new ForUpdate(Type.WAIT, timeoutMillis);
74 }
75
76 private final Type type;
77
78 private final int timeoutMillis;
79
80 private ForUpdate(Type type, int timeoutMillis) {
81 this.type = type;
82 this.timeoutMillis = timeoutMillis;
83 }
84
85 /**
86 * Returns type of FOR UPDATE clause.
87 *
88 * @return type of FOR UPDATE clause
89 */
90 public Type getType() {
91 return type;
92 }
93
94 /**
95 * Returns timeout in milliseconds.
96 *
97 * @return timeout in milliseconds for {@link Type#WAIT}, {@code 0} for
98 * {@link Type#NOWAIT}, {@code -2} for {@link Type#SKIP_LOCKED},
99 * {@code -1} for default timeout
100 */
101 public int getTimeoutMillis() {
102 return timeoutMillis;
103 }
104
105 @Override
106 public StringBuilder getSQL(StringBuilder builder, int sqlFlags) {
107 builder.append(" FOR UPDATE");
108 switch (type) {
109 case WAIT: {
110 builder.append(" WAIT ").append(timeoutMillis / 1_000);
111 int millis = timeoutMillis % 1_000;
112 if (millis > 0) {
113 StringUtils.appendZeroPadded(builder.append('.'), 3, millis);
114 }
115 break;
116 }
117 case NOWAIT:
118 builder.append(" NOWAIT");
119 break;
120 case SKIP_LOCKED:
121 builder.append(" SKIP LOCKED");
122 break;
123 default:
124 }
125 return builder;
126 }
127
128 }