1 5 package org.h2.schema; 6 7 import java.sql.SQLException ; 8 9 import org.h2.engine.DbObject; 10 import org.h2.engine.Session; 11 import org.h2.jdbc.JdbcSQLException; 12 import org.h2.message.Message; 13 import org.h2.message.Trace; 14 import org.h2.table.Table; 15 16 public class Sequence extends SchemaObject { 17 private static final int BLOCK_INCREMENT = 32; 18 private long value = 1; 19 private long valueWithMargin; 20 private long increment = 1; 21 private boolean belongsToTable; 22 23 public Sequence(Schema schema, int id, String name, boolean belongsToTable) { 24 super(schema, id, name, Trace.SEQUENCE); 25 this.belongsToTable = belongsToTable; 26 } 27 28 public synchronized void setStartValue(long value) { 29 this.value = value; 30 this.valueWithMargin = value; 31 } 32 33 public boolean getBelongsToTable() { 34 return belongsToTable; 35 } 36 37 public long getIncrement() { 38 return increment; 39 } 40 41 public void setIncrement(long inc) throws JdbcSQLException { 42 if(increment == 0) { 43 throw Message.getSQLException(Message.INVALID_VALUE_2, new String []{"0", "INCREMENT"}, null); 44 } 45 this.increment = inc; 46 } 47 48 public String getCreateSQLForCopy(Table table, String quotedName) { 49 throw Message.getInternalError(); 50 } 51 52 public synchronized String getCreateSQL() { 53 StringBuffer buff = new StringBuffer (); 54 buff.append("CREATE SEQUENCE "); 55 buff.append(getSQL()); 56 buff.append(" START WITH "); 57 buff.append(value); 58 if(increment != 1) { 59 buff.append(" INCREMENT BY "); 60 buff.append(increment); 61 } 62 if(belongsToTable) { 63 buff.append(" BELONGS_TO_TABLE"); 64 } 65 return buff.toString(); 66 } 67 68 public synchronized long getNext() throws SQLException { 69 if((increment > 0 && value >= valueWithMargin) || (increment < 0 && value <= valueWithMargin)) { 70 valueWithMargin += increment*BLOCK_INCREMENT; 71 flush(); 72 } 73 long v = value; 74 value += increment; 75 return v; 76 } 77 78 public void flush() throws SQLException { 79 Session s = database.getSystemSession(); 82 synchronized(this) { 83 long realValue = value; 85 try { 86 value = valueWithMargin; 87 database.update(s, this); 88 } finally { 89 value = realValue; 90 } 91 } 92 s.commit(); 93 } 94 95 public void close() throws SQLException { 96 valueWithMargin = value; 97 flush(); 98 } 99 100 public int getType() { 101 return DbObject.SEQUENCE; 102 } 103 104 public void removeChildrenAndResources(Session session) { 105 invalidate(); 106 } 107 108 public void checkRename() { 109 } 111 112 public synchronized long getCurrentValue() { 113 return value - increment; 114 } 115 116 public void setBelongsToTable(boolean b) { 117 this.belongsToTable = b; 118 } 119 120 } 121 | Popular Tags |