01: /*
02: * Copyright 2004-2008 H2 Group. Licensed under the H2 License, Version 1.0
03: * (http://h2database.com/html/license.html).
04: * Initial Developer: H2 Group
05: */
06: package org.h2.command.ddl;
07:
08: import java.sql.SQLException;
09:
10: import org.h2.constant.ErrorCode;
11: import org.h2.engine.Database;
12: import org.h2.engine.Session;
13: import org.h2.expression.Expression;
14: import org.h2.message.Message;
15: import org.h2.schema.Schema;
16: import org.h2.schema.Sequence;
17:
18: /**
19: * This class represents the statement
20: * CREATE SEQUENCE
21: */
22: public class CreateSequence extends SchemaCommand {
23:
24: private String sequenceName;
25: private boolean ifNotExists;
26: private Expression start;
27: private Expression increment;
28: private Expression cacheSize;
29: private boolean belongsToTable;
30:
31: public CreateSequence(Session session, Schema schema) {
32: super (session, schema);
33: }
34:
35: public void setSequenceName(String sequenceName) {
36: this .sequenceName = sequenceName;
37: }
38:
39: public void setIfNotExists(boolean ifNotExists) {
40: this .ifNotExists = ifNotExists;
41: }
42:
43: public int update() throws SQLException {
44: session.commit(true);
45: Database db = session.getDatabase();
46: if (getSchema().findSequence(sequenceName) != null) {
47: if (ifNotExists) {
48: return 0;
49: }
50: throw Message.getSQLException(
51: ErrorCode.SEQUENCE_ALREADY_EXISTS_1, sequenceName);
52: }
53: int id = getObjectId(false, true);
54: Sequence sequence = new Sequence(getSchema(), id, sequenceName,
55: belongsToTable);
56: sequence.setStartValue(getLong(start, 1));
57: sequence.setIncrement(getLong(increment, 1));
58: sequence.setCacheSize(getLong(cacheSize,
59: Sequence.DEFAULT_CACHE_SIZE));
60: db.addSchemaObject(session, sequence);
61: return 0;
62: }
63:
64: private long getLong(Expression expr, long defaultValue)
65: throws SQLException {
66: if (expr == null) {
67: return defaultValue;
68: } else {
69: return expr.optimize(session).getValue(session).getLong();
70: }
71: }
72:
73: public void setStartWith(Expression start) {
74: this .start = start;
75: }
76:
77: public void setIncrement(Expression increment) {
78: this .increment = increment;
79: }
80:
81: public void setBelongsToTable(boolean belongsToTable) {
82: this .belongsToTable = belongsToTable;
83: }
84:
85: public void setCacheSize(Expression cacheSize) {
86: this.cacheSize = cacheSize;
87: }
88:
89: }
|