proj_name
stringclasses
131 values
relative_path
stringlengths
30
228
class_name
stringlengths
1
68
func_name
stringlengths
1
48
masked_class
stringlengths
78
9.82k
func_body
stringlengths
46
9.61k
len_input
int64
29
2.01k
len_output
int64
14
1.94k
total
int64
55
2.05k
relevant_context
stringlengths
0
38.4k
lealone_Lealone
Lealone/lealone-db/src/main/java/com/lealone/db/index/standard/IndexKeyType.java
IndexKeyType
getMemory
class IndexKeyType extends ValueDataType { public IndexKeyType(DataHandler handler, CompareMode compareMode, int[] sortTypes) { super(handler, compareMode, sortTypes); } @Override public int compare(Object a, Object b) { if (a == b) { return 0; } if (a == null) { return -1; } else if (b == null) { return 1; } Value[] ax = ((IndexKey) a).columns; Value[] bx = ((IndexKey) b).columns; return compareValues(ax, bx); } @Override public int getMemory(Object obj) {<FILL_FUNCTION_BODY>} @Override public Object read(ByteBuffer buff) { ValueArray a = (ValueArray) DataBuffer.readValue(buff); return new IndexKey(a.getList()); } @Override public void write(DataBuffer buff, Object obj) { IndexKey k = (IndexKey) obj; buff.writeValue(ValueArray.get(k.columns)); } }
IndexKey k = (IndexKey) obj; int memory = 4; if (k == null) return memory; Value[] columns = k.columns; for (int i = 0, len = columns.length; i < len; i++) { Value c = columns[i]; if (c == null) memory += 4; else memory += c.getMemory(); } return memory;
291
111
402
<methods>public void <init>(com.lealone.db.DataHandler, com.lealone.db.value.CompareMode, int[]) ,public int compare(java.lang.Object, java.lang.Object) ,public int compareValues(com.lealone.db.value.Value[], com.lealone.db.value.Value[]) ,public boolean equals(java.lang.Object) ,public int getMemory(java.lang.Object) ,public int hashCode() ,public void read(java.nio.ByteBuffer, java.lang.Object[], int) ,public java.lang.Object read(java.nio.ByteBuffer) ,public void write(com.lealone.db.DataBuffer, java.lang.Object[], int) ,public void write(com.lealone.db.DataBuffer, java.lang.Object) <variables>final non-sealed com.lealone.db.value.CompareMode compareMode,final non-sealed com.lealone.db.DataHandler handler,final non-sealed int[] sortTypes
lealone_Lealone
Lealone/lealone-db/src/main/java/com/lealone/db/index/standard/StandardDelegateIndex.java
StandardDelegateIndex
find
class StandardDelegateIndex extends StandardIndex { private final StandardPrimaryIndex mainIndex; public StandardDelegateIndex(StandardPrimaryIndex mainIndex, StandardTable table, int id, String name, IndexType indexType) { super(table, id, name, indexType, IndexColumn.wrap(new Column[] { table.getColumn(mainIndex.getMainIndexColumn()) })); this.mainIndex = mainIndex; if (id < 0) { throw DbException.getInternalError("" + name); } } @Override public Row getRow(ServerSession session, long key) { return mainIndex.getRow(session, key); } @Override public Cursor find(ServerSession session, SearchRow first, SearchRow last) {<FILL_FUNCTION_BODY>} @Override public Cursor find(ServerSession session, CursorParameters<SearchRow> parameters) { return mainIndex.find(session, parameters); } @Override public SearchRow findFirstOrLast(ServerSession session, boolean first) { return mainIndex.findFirstOrLast(session, first); } @Override public int getColumnIndex(Column col) { if (col.getColumnId() == mainIndex.getMainIndexColumn()) { return 0; } return -1; } @Override public double getCost(ServerSession session, int[] masks, SortOrder sortOrder) { return 10 * getCostRangeIndex(masks, mainIndex.getRowCountApproximation(), sortOrder); } @Override public void remove(ServerSession session) { mainIndex.setMainIndexColumn(-1); } @Override public void truncate(ServerSession session) { // nothing to do } @Override public void checkRename() { // ok } @Override public long getRowCount(ServerSession session) { return mainIndex.getRowCount(session); } @Override public long getRowCountApproximation() { return mainIndex.getRowCountApproximation(); } @Override public long getDiskSpaceUsed() { return mainIndex.getDiskSpaceUsed(); } @Override public long getMemorySpaceUsed() { return mainIndex.getMemorySpaceUsed(); } @Override public boolean isInMemory() { return mainIndex.isInMemory(); } }
ValueLong min = mainIndex.getKey(first, StandardPrimaryIndex.MIN, StandardPrimaryIndex.MIN); // ifNull is MIN_VALUE as well, because the column is never NULL // so avoid returning all rows (returning one row is OK) ValueLong max = mainIndex.getKey(last, StandardPrimaryIndex.MAX, StandardPrimaryIndex.MIN); return mainIndex.find(session, min, max);
633
103
736
<methods>public boolean canGetFirstOrLast() ,public void close(com.lealone.db.session.ServerSession) <variables>
lealone_Lealone
Lealone/lealone-db/src/main/java/com/lealone/db/index/standard/ValueDataType.java
ValueDataType
compareValue
class ValueDataType implements StorageDataType { final DataHandler handler; final CompareMode compareMode; final int[] sortTypes; public ValueDataType(DataHandler handler, CompareMode compareMode, int[] sortTypes) { this.handler = handler; this.compareMode = compareMode; this.sortTypes = sortTypes; } protected boolean isUniqueKey() { return false; } @Override public int compare(Object a, Object b) { if (a == b) { return 0; } if (a instanceof ValueArray && b instanceof ValueArray) { Value[] ax = ((ValueArray) a).getList(); Value[] bx = ((ValueArray) b).getList(); return compareValues(ax, bx); } return compareValue((Value) a, (Value) b, SortOrder.ASCENDING); } public int compareValues(Value[] ax, Value[] bx) { int al = ax.length; int bl = bx.length; int len = Math.min(al, bl); // 唯一索引key不需要比较最后的rowId int size = isUniqueKey() ? len - 1 : len; for (int i = 0; i < size; i++) { int sortType = sortTypes[i]; int comp = compareValue(ax[i], bx[i], sortType); if (comp != 0) { return comp; } } if (len < al) { return -1; } else if (len < bl) { return 1; } return 0; } private int compareValue(Value a, Value b, int sortType) {<FILL_FUNCTION_BODY>} private int compareTypeSafe(Value a, Value b) { if (a == b) { return 0; } return a.compareTypeSafe(b, compareMode); } @Override public int getMemory(Object obj) { return getMemory((Value) obj); } private static int getMemory(Value v) { return v == null ? 0 : v.getMemory(); } @Override public void read(ByteBuffer buff, Object[] obj, int len) { for (int i = 0; i < len; i++) { obj[i] = read(buff); } } @Override public void write(DataBuffer buff, Object[] obj, int len) { for (int i = 0; i < len; i++) { write(buff, obj[i]); } } @Override public Object read(ByteBuffer buff) { return DataBuffer.readValue(buff); } @Override public void write(DataBuffer buff, Object obj) { Value x = (Value) obj; buff.writeValue(x); } @Override public int hashCode() { return compareMode.hashCode() ^ Arrays.hashCode(sortTypes); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } else if (!(obj instanceof ValueDataType)) { return false; } ValueDataType v = (ValueDataType) obj; if (!compareMode.equals(v.compareMode)) { return false; } return Arrays.equals(sortTypes, v.sortTypes); } }
if (a == b) { return 0; } // null is never stored; // comparison with null is used to retrieve all entries // in which case null is always lower than all entries // (even for descending ordered indexes) if (a == null) { return -1; } else if (b == null) { return 1; } boolean aNull = a == ValueNull.INSTANCE; boolean bNull = b == ValueNull.INSTANCE; if (aNull || bNull) { return SortOrder.compareNull(aNull, sortType); } int comp = compareTypeSafe(a, b); if ((sortType & SortOrder.DESCENDING) != 0) { comp = -comp; } return comp;
894
205
1,099
<no_super_class>
lealone_Lealone
Lealone/lealone-db/src/main/java/com/lealone/db/index/standard/VersionedValue.java
VersionedValue
toString
class VersionedValue { public final int version; // 表的元数据版本号 public final Value[] columns; public VersionedValue(int version, Value[] columns) { this.version = version; this.columns = columns; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
// StringBuilder buff = new StringBuilder("VersionedValue[ "); // buff.append("version = ").append(version); // buff.append(", columns = ").append(Arrays.toString(columns)).append(" ]"); return Arrays.toString(columns);
92
69
161
<no_super_class>
lealone_Lealone
Lealone/lealone-db/src/main/java/com/lealone/db/index/standard/VersionedValueType.java
VersionedValueType
getMemory
class VersionedValueType extends ValueDataType { final int columnCount; final EnumColumn[] enumColumns; public VersionedValueType(DataHandler handler, CompareMode compareMode, int[] sortTypes, int columnCount) { this(handler, compareMode, sortTypes, columnCount, null); } public VersionedValueType(DataHandler handler, CompareMode compareMode, int[] sortTypes, int columnCount, EnumColumn[] enumColumns) { super(handler, compareMode, sortTypes); this.columnCount = columnCount; this.enumColumns = enumColumns; } @Override public int compare(Object aObj, Object bObj) { if (aObj == bObj) { return 0; } if (aObj == null) { return -1; } else if (bObj == null) { return 1; } VersionedValue a = (VersionedValue) aObj; VersionedValue b = (VersionedValue) bObj; long comp = a.version - b.version; if (comp == 0) { return compareValues(a.columns, b.columns); } return Long.signum(comp); } @Override public int getMemory(Object obj) { VersionedValue v = (VersionedValue) obj; int memory = 4 + 4; if (v == null) return memory; Value[] columns = v.columns; for (int i = 0, len = columns.length; i < len; i++) { Value c = columns[i]; if (c == null) memory += 4; else memory += c.getMemory(); } return memory; } @Override public Object read(ByteBuffer buff) { int vertion = DataUtils.readVarInt(buff); ValueArray a = (ValueArray) DataBuffer.readValue(buff); if (enumColumns != null) setEnumColumns(a); return new VersionedValue(vertion, a.getList()); } @Override public void write(DataBuffer buff, Object obj) { VersionedValue v = (VersionedValue) obj; buff.putVarInt(v.version); buff.writeValue(ValueArray.get(v.columns)); } @Override public void writeMeta(DataBuffer buff, Object obj) { VersionedValue v = (VersionedValue) obj; buff.putVarInt(v.version); } @Override public Object readMeta(ByteBuffer buff, int columnCount) { int vertion = DataUtils.readVarInt(buff); Value[] columns = new Value[columnCount]; return new VersionedValue(vertion, columns); } @Override public void writeColumn(DataBuffer buff, Object obj, int columnIndex) { VersionedValue v = (VersionedValue) obj; Value[] columns = v.columns; if (columnIndex >= 0 && columnIndex < columns.length) buff.writeValue(columns[columnIndex]); } @Override public void readColumn(ByteBuffer buff, Object obj, int columnIndex) { VersionedValue v = (VersionedValue) obj; Value[] columns = v.columns; if (columnIndex >= 0 && columnIndex < columns.length) { Value value = DataBuffer.readValue(buff); columns[columnIndex] = value; if (enumColumns != null) setEnumColumn(value, columnIndex); } } @Override public void setColumns(Object oldObj, Object newObj, int[] columnIndexes) { if (columnIndexes != null) { VersionedValue oldValue = (VersionedValue) oldObj; VersionedValue newValue = (VersionedValue) newObj; Value[] oldColumns = oldValue.columns; Value[] newColumns = newValue.columns; for (int i : columnIndexes) { oldColumns[i] = newColumns[i]; } } } @Override public ValueArray getColumns(Object obj) { return ValueArray.get(((VersionedValue) obj).columns); } @Override public int getColumnCount() { return columnCount; } @Override public int getMemory(Object obj, int columnIndex) {<FILL_FUNCTION_BODY>} private void setEnumColumn(Value value, int columnIndex) { if (enumColumns[columnIndex] != null) enumColumns[columnIndex].setLabel(value); } private void setEnumColumns(ValueArray a) { for (int i = 0, len = a.getList().length; i < len; i++) { setEnumColumn(a.getValue(i), i); } } }
VersionedValue v = (VersionedValue) obj; Value[] columns = v.columns; if (columnIndex >= 0 && columnIndex < columns.length) { return columns[columnIndex].getMemory(); } else { return 0; }
1,228
69
1,297
<methods>public void <init>(com.lealone.db.DataHandler, com.lealone.db.value.CompareMode, int[]) ,public int compare(java.lang.Object, java.lang.Object) ,public int compareValues(com.lealone.db.value.Value[], com.lealone.db.value.Value[]) ,public boolean equals(java.lang.Object) ,public int getMemory(java.lang.Object) ,public int hashCode() ,public void read(java.nio.ByteBuffer, java.lang.Object[], int) ,public java.lang.Object read(java.nio.ByteBuffer) ,public void write(com.lealone.db.DataBuffer, java.lang.Object[], int) ,public void write(com.lealone.db.DataBuffer, java.lang.Object) <variables>final non-sealed com.lealone.db.value.CompareMode compareMode,final non-sealed com.lealone.db.DataHandler handler,final non-sealed int[] sortTypes
lealone_Lealone
Lealone/lealone-db/src/main/java/com/lealone/db/lock/DbObjectLock.java
DbObjectLock
unlock
class DbObjectLock extends Lock { public static final RuntimeException LOCKED_EXCEPTION = new RuntimeException(); private final DbObjectType type; private ArrayList<AsyncHandler<AsyncResult<Boolean>>> handlers; public DbObjectLock(DbObjectType type) { this.type = type; } @Override public String getLockType() { return type.name(); } public boolean lock(ServerSession session, boolean exclusive) { if (exclusive) return tryExclusiveLock(session); else return trySharedLock(session); } public boolean trySharedLock(ServerSession session) { return true; } public boolean tryExclusiveLock(ServerSession session) { return tryLock(session.getTransaction(), this, null); } @Override public void unlock(Session oldSession, boolean succeeded, Session newSession) {<FILL_FUNCTION_BODY>} public void addHandler(AsyncHandler<AsyncResult<Boolean>> handler) { if (handlers == null) handlers = new ArrayList<>(1); handlers.add(handler); } }
if (handlers != null) { handlers.forEach(h -> { h.handle(new AsyncResult<>(succeeded)); }); handlers = null; } unlock(oldSession, newSession);
296
65
361
<methods>public non-sealed void <init>() ,public int addWaitingTransaction(java.lang.Object, com.lealone.transaction.Transaction, com.lealone.db.session.Session) ,public com.lealone.db.lock.LockOwner getLockOwner() ,public abstract java.lang.String getLockType() ,public java.lang.Object getOldValue() ,public com.lealone.transaction.Transaction getTransaction() ,public boolean isLockedExclusivelyBy(com.lealone.db.session.Session) ,public boolean tryLock(com.lealone.transaction.Transaction, java.lang.Object, java.lang.Object) ,public void unlock(com.lealone.db.session.Session, boolean, com.lealone.db.session.Session) ,public void unlock(com.lealone.db.session.Session, com.lealone.db.session.Session) <variables>static final com.lealone.db.lock.NullLockOwner NULL,private final AtomicReference<com.lealone.db.lock.LockOwner> ref
lealone_Lealone
Lealone/lealone-db/src/main/java/com/lealone/db/result/Row.java
Row
setValue
class Row extends SimpleRow { public static final int MEMORY_CALCULATE = -1; private ITransactionalValue tv; private IPage page; public Row(Value[] data, int memory) { super(data); this.memory = memory; } public Value[] getValueList() { return data; } public ITransactionalValue getTValue() { return tv; } public void setTValue(ITransactionalValue tv) { this.tv = tv; } @Override public Value getValue(int i) { return i == -1 ? ValueLong.get(key) : data[i]; } @Override public void setValue(int i, Value v) {<FILL_FUNCTION_BODY>} public IPage getPage() { return page; } public void setPage(IPage page) { this.page = page; } }
if (i == -1) { key = v.getLong(); } else { data[i] = v; }
256
39
295
<methods>public void <init>(com.lealone.db.value.Value[]) ,public int getColumnCount() ,public int getMemory() ,public com.lealone.db.value.Value getValue(int) ,public void setValue(int, com.lealone.db.value.Value) ,public java.lang.String toString() <variables>protected final non-sealed com.lealone.db.value.Value[] data
lealone_Lealone
Lealone/lealone-db/src/main/java/com/lealone/db/result/SimpleRow.java
SimpleRow
toString
class SimpleRow extends RowBase { protected final Value[] data; public SimpleRow(Value[] data) { this.data = data; } @Override public int getColumnCount() { return data.length; } @Override public Value getValue(int index) { return data[index]; } @Override public void setValue(int index, Value v) { data[index] = v; } @Override public int getMemory() { if (memory > 0) { return memory; } int m = Constants.MEMORY_ROW; if (data != null) { int len = data.length; m += Constants.MEMORY_OBJECT + len * Constants.MEMORY_POINTER; for (int i = 0; i < len; i++) { Value v = data[i]; if (v != null) { m += v.getMemory(); } } } memory = m; return m; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
StatementBuilder buff = new StatementBuilder("( /* key:"); buff.append(getKey()); if (version != 0) { buff.append(" v:" + version); } buff.append(" */ "); if (data != null) { for (Value v : data) { buff.appendExceptFirst(", "); buff.append(v == null ? "null" : v.getTraceSQL()); } } return buff.append(')').toString();
302
129
431
<methods>public non-sealed void <init>() ,public long getKey() ,public int getVersion() ,public void setKey(long) ,public void setVersion(int) <variables>protected long key,protected int memory,protected int version
lealone_Lealone
Lealone/lealone-db/src/main/java/com/lealone/db/result/SimpleRowValue.java
SimpleRowValue
getMemory
class SimpleRowValue extends RowBase { private final int virtualColumnCount; private int index; private Value data; public SimpleRowValue(int columnCount) { this.virtualColumnCount = columnCount; } @Override public int getColumnCount() { return virtualColumnCount; } @Override public Value getValue(int idx) { return idx == index ? data : null; } @Override public void setValue(int idx, Value v) { index = idx; data = v; } @Override public int getMemory() {<FILL_FUNCTION_BODY>} @Override public String toString() { return "( /* " + key + " */ " + (data == null ? "null" : data.getTraceSQL()) + " )"; } }
if (memory == 0) { memory = Constants.MEMORY_OBJECT + (data == null ? 0 : data.getMemory()); } return memory;
222
46
268
<methods>public non-sealed void <init>() ,public long getKey() ,public int getVersion() ,public void setKey(long) ,public void setVersion(int) <variables>protected long key,protected int memory,protected int version
lealone_Lealone
Lealone/lealone-db/src/main/java/com/lealone/db/result/SortOrder.java
SortOrder
sort
class SortOrder implements Comparator<Value[]> { /** * This bit mask means the values should be sorted in ascending order. */ public static final int ASCENDING = 0; /** * This bit mask means the values should be sorted in descending order. */ public static final int DESCENDING = 1; /** * This bit mask means NULLs should be sorted before other data, no matter * if ascending or descending order is used. */ public static final int NULLS_FIRST = 2; /** * This bit mask means NULLs should be sorted after other data, no matter * if ascending or descending order is used. */ public static final int NULLS_LAST = 4; /** * The default sort order for NULL. */ private static final int DEFAULT_NULL_SORT = SysProperties.SORT_NULLS_HIGH ? 1 : -1; private final Database database; /** * The column indexes of the order by expressions within the query. */ private final int[] queryColumnIndexes; /** * The sort type bit mask (DESCENDING, NULLS_FIRST, NULLS_LAST). */ private final int[] sortTypes; /** * The order list. */ private final Column[] orderList; /** * Construct a new sort order object. * * @param database the database * @param queryColumnIndexes the column index list * @param sortType the sort order bit masks * @param orderList the original query order list (if this is a query) */ public SortOrder(Database database, int[] queryColumnIndexes, int[] sortType, Column[] orderList) { this.database = database; this.queryColumnIndexes = queryColumnIndexes; this.sortTypes = sortType; this.orderList = orderList; } /** * Create the SQL snippet that describes this sort order. * This is the SQL snippet that usually appears after the ORDER BY clause. * * @param list the expression list * @param visible the number of columns in the select list * @return the SQL snippet */ public String getSQL(IExpression[] list, int visible) { StatementBuilder buff = new StatementBuilder(); int i = 0; for (int idx : queryColumnIndexes) { buff.appendExceptFirst(", "); if (idx < visible) { buff.append(idx + 1); } else { buff.append('=').append(StringUtils.unEnclose(list[idx].getSQL())); } int type = sortTypes[i++]; if ((type & DESCENDING) != 0) { buff.append(" DESC"); } if ((type & NULLS_FIRST) != 0) { buff.append(" NULLS FIRST"); } else if ((type & NULLS_LAST) != 0) { buff.append(" NULLS LAST"); } } return buff.toString(); } /** * Compare two expressions where one of them is NULL. * * @param aNull whether the first expression is null * @param sortType the sort bit mask to use * @return the result of the comparison (-1 meaning the first expression * should appear before the second, 0 if they are equal) */ public static int compareNull(boolean aNull, int sortType) { if ((sortType & NULLS_FIRST) != 0) { return aNull ? -1 : 1; } else if ((sortType & NULLS_LAST) != 0) { return aNull ? 1 : -1; } else { // see also JdbcDatabaseMetaData.nullsAreSorted* int comp = aNull ? DEFAULT_NULL_SORT : -DEFAULT_NULL_SORT; return (sortType & DESCENDING) == 0 ? comp : -comp; } } /** * Compare two expression lists. * * @param a the first expression list * @param b the second expression list * @return the result of the comparison */ @Override public int compare(Value[] a, Value[] b) { for (int i = 0, len = queryColumnIndexes.length; i < len; i++) { int idx = queryColumnIndexes[i]; int type = sortTypes[i]; Value ao = a[idx]; Value bo = b[idx]; boolean aNull = ao == ValueNull.INSTANCE, bNull = bo == ValueNull.INSTANCE; if (aNull || bNull) { if (aNull == bNull) { continue; } return compareNull(aNull, type); } int comp = database.compare(ao, bo); if (comp != 0) { return (type & DESCENDING) == 0 ? comp : -comp; } } return 0; } /** * Sort a list of rows. * * @param rows the list of rows */ public void sort(ArrayList<Value[]> rows) { Collections.sort(rows, this); } /** * Sort a list of rows using offset and limit. * * @param rows the list of rows * @param offset the offset * @param limit the limit */ public void sort(ArrayList<Value[]> rows, int offset, int limit) {<FILL_FUNCTION_BODY>} /** * Get the column index list. This is the column indexes of the order by * expressions within the query. * <p> * For the query "select name, id from test order by id, name" this is {1, * 0} as the first order by expression (the column "id") is the second * column of the query, and the second order by expression ("name") is the * first column of the query. * * @return the list */ public int[] getQueryColumnIndexes() { return queryColumnIndexes; } /** * Get the column for the given table, if the sort column is for this table. * * @param index the column index (0, 1,..) * @param table the table * @return the column, or null */ public Column getColumn(int index, Table table) { if (orderList == null) { return null; } Column c = orderList[index]; if (c == null || c.getTable() != table) { return null; } return c; } /** * Get the sort order bit masks. * * @return the list */ public int[] getSortTypes() { return sortTypes; } }
int rowsSize = rows.size(); if (rows.isEmpty() || offset >= rowsSize || limit == 0) { return; } if (offset < 0) { offset = 0; } if (offset + limit > rowsSize) { limit = rowsSize - offset; } if (limit == 1 && offset == 0) { rows.set(0, Collections.min(rows, this)); return; } Value[][] arr = rows.toArray(new Value[rowsSize][]); Utils.sortTopN(arr, offset, limit, this); for (int i = 0, end = Math.min(offset + limit, rowsSize); i < end; i++) { rows.set(i, arr[i]); }
1,755
200
1,955
<no_super_class>
lealone_Lealone
Lealone/lealone-db/src/main/java/com/lealone/db/schema/UserAggregate.java
UserAggregate
getInstance
class UserAggregate extends SchemaObjectBase { private final String className; private Class<?> javaClass; public UserAggregate(Schema schema, int id, String name, String className, boolean force) { super(schema, id, name); this.className = className; if (!force) { getInstance(); } } @Override public DbObjectType getType() { return DbObjectType.AGGREGATE; } public String getJavaClassName() { return className; } public Aggregate getInstance() {<FILL_FUNCTION_BODY>} @Override public String getCreateSQL() { return "CREATE FORCE AGGREGATE " + getSQL() + " FOR " + database.quoteIdentifier(className); } @Override public String getDropSQL() { return "DROP AGGREGATE IF EXISTS " + getSQL(); } @Override public void checkRename() { throw DbException.getUnsupportedException("AGGREGATE"); } }
if (javaClass == null) { javaClass = Utils.loadUserClass(className); } try { return Utils.newInstance(javaClass); } catch (Exception e) { throw DbException.convert(e); }
279
69
348
<methods>public java.lang.String getSQL() ,public com.lealone.db.schema.Schema getSchema() ,public boolean isHidden() <variables>protected final non-sealed com.lealone.db.schema.Schema schema
lealone_Lealone
Lealone/lealone-db/src/main/java/com/lealone/db/service/JavaServiceExecutor.java
JavaServiceExecutor
init
class JavaServiceExecutor extends ServiceExecutorBase { private final Service service; private Map<String, Method> objectMethodMap; private Object implementClassObject; public JavaServiceExecutor(Service service) { this.service = service; } // 第一次调用时再初始化,否则会影响启动时间 private void init() {<FILL_FUNCTION_BODY>} @Override public Value executeService(String methodName, Value[] methodArgs) { init(); Method method = objectMethodMap.get(methodName); Object[] args = getServiceMethodArgs(methodName, methodArgs); try { Object ret = method.invoke(implementClassObject, args); if (ret == null) return ValueNull.INSTANCE; return ValueString.get(ret.toString()); } catch (Exception e) { throw DbException.convert(e); } } @Override public String executeService(String methodName, Map<String, Object> methodArgs) { init(); Method method = objectMethodMap.get(methodName); Object[] args = getServiceMethodArgs(methodName, methodArgs); try { Object ret = method.invoke(implementClassObject, args); if (ret == null) return null; return ret.toString(); } catch (Exception e) { throw DbException.convert(e); } } @Override public String executeService(String methodName, String json) { init(); Method method = objectMethodMap.get(methodName); Object[] args = getServiceMethodArgs(methodName, json); try { Object ret = method.invoke(implementClassObject, args); if (ret == null) return null; return ret.toString(); } catch (Exception e) { throw DbException.convert(e); } } }
if (implementClassObject != null) return; Class<?> implementClass; try { implementClass = Class.forName(service.getImplementBy()); implementClassObject = implementClass.getDeclaredConstructor().newInstance(); } catch (Exception e) { throw new RuntimeException("newInstance exception: " + service.getImplementBy(), e); } int size = service.getServiceMethods().size(); serviceMethodMap = new HashMap<>(size); objectMethodMap = new HashMap<>(size); if (size <= 0) { Method[] methods = implementClass.getDeclaredMethods(); for (int i = 0, len = methods.length; i < len; i++) { Method m = methods[i]; int modifiers = m.getModifiers(); if (!Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers)) { String name = m.getName().toUpperCase(); objectMethodMap.put(name, m); ServiceMethod sm = new ServiceMethod(); sm.setMethodName(name); Parameter[] parameters = m.getParameters(); ArrayList<Column> columns = new ArrayList<>(parameters.length); for (int c = 0; c < parameters.length; c++) { Parameter p = parameters[c]; int type = DataType.getTypeFromClass(p.getType()); Column column = new Column(p.getName().toUpperCase(), type); columns.add(column); } sm.setParameters(columns); sm.setReturnType(new Column("R", DataType.getTypeFromClass(m.getReturnType()))); serviceMethodMap.put(name, sm); } } } else { for (ServiceMethod serviceMethod : service.getServiceMethods()) { String serviceMethodName = serviceMethod.getMethodName(); serviceMethodMap.put(serviceMethodName, serviceMethod); String objectMethodName = CamelCaseHelper.toCamelFromUnderscore(serviceMethodName); try { // 不使用getDeclaredMethod,因为这里不考虑参数,只要方法名匹配即可 for (Method m : implementClass.getDeclaredMethods()) { if (m.getName().equals(objectMethodName)) { objectMethodMap.put(serviceMethodName, m); break; } } } catch (Exception e) { throw new RuntimeException("Method not found: " + objectMethodName, e); } } }
481
631
1,112
<methods>public non-sealed void <init>() <variables>protected Map<java.lang.String,com.lealone.db.service.ServiceMethod> serviceMethodMap
lealone_Lealone
Lealone/lealone-db/src/main/java/com/lealone/db/service/Service.java
Service
execute
class Service extends SchemaObjectBase { private String language; private String packageName; private String implementBy; private final String sql; private final String serviceExecutorClassName; private final List<ServiceMethod> serviceMethods; private ServiceExecutor executor; private StringBuilder executorCode; public Service(Schema schema, int id, String name, String sql, String serviceExecutorClassName, List<ServiceMethod> serviceMethods) { super(schema, id, name); this.sql = sql; this.serviceExecutorClassName = serviceExecutorClassName; this.serviceMethods = serviceMethods; } @Override public DbObjectType getType() { return DbObjectType.SERVICE; } public String getLanguage() { return language; } public void setLanguage(String language) { this.language = language; } public String getPackageName() { return packageName; } public void setPackageName(String packageName) { this.packageName = packageName; } public String getImplementBy() { return implementBy; } public void setImplementBy(String implementBy) { this.implementBy = implementBy; } public List<ServiceMethod> getServiceMethods() { return serviceMethods; } @Override public String getCreateSQL() { return sql; } public void setExecutorCode(StringBuilder executorCode) { this.executorCode = executorCode; } public void setExecutor(ServiceExecutor executor) { this.executor = executor; } // 延迟创建executor的实例,因为执行create service语句时,依赖的服务实现类还不存在 public ServiceExecutor getExecutor() { return getExecutor(false); } public ServiceExecutor getExecutor(boolean disableDynamicCompile) { if (executor == null) { synchronized (this) { if (executor == null) { // 跟spring boot集成时不支持动态编译 if (disableDynamicCompile) { executor = new JavaServiceExecutor(this); return executor; } if (executorCode != null) { String code = executorCode.toString(); executorCode = null; executor = SourceCompiler.compileAsInstance(serviceExecutorClassName, code); } else { executor = Utils.newInstance(serviceExecutorClassName); } } } } return executor; } public static Service getService(ServerSession session, Database db, String schemaName, String serviceName) { // 调用服务前数据库可能没有初始化 if (!db.isInitialized()) db.init(); Schema schema = db.findSchema(session, schemaName); if (schema == null) { throw DbException.get(ErrorCode.SCHEMA_NOT_FOUND_1, schemaName); } return schema.getService(session, serviceName); } private static void checkRight(ServerSession session, Service service) { session.getUser().checkRight(service, Right.EXECUTE); } // 通过jdbc调用 public static Value execute(ServerSession session, String serviceName, String methodName, Value[] methodArgs) { Service service = getService(session, session.getDatabase(), session.getCurrentSchemaName(), serviceName); checkRight(session, service); return service.getExecutor().executeService(methodName, methodArgs); } // 通过http调用 public static Object execute(ServerSession session, String serviceName, String methodName, Map<String, Object> methodArgs) { return execute(session, serviceName, methodName, methodArgs, false); } public static Object execute(ServerSession session, String serviceName, String methodName, Map<String, Object> methodArgs, boolean disableDynamicCompile) { String[] a = StringUtils.arraySplit(serviceName, '.'); if (a.length == 3) { Database db = LealoneDatabase.getInstance().getDatabase(a[0]); if (db.getSettings().databaseToUpper) { serviceName = serviceName.toUpperCase(); methodName = methodName.toUpperCase(); } Service service = getService(session, db, a[1], a[2]); checkRight(session, service); return service.getExecutor(disableDynamicCompile).executeService(methodName, methodArgs); } else { throw new RuntimeException("service " + serviceName + " not found"); } } // 通过json调用 public static Object execute(ServerSession session, String serviceName, String json) {<FILL_FUNCTION_BODY>} }
String[] a = StringUtils.arraySplit(serviceName, '.'); if (a.length == 4) { Database db = LealoneDatabase.getInstance().getDatabase(a[0]); String methodName = a[3]; if (db.getSettings().databaseToUpper) { methodName = methodName.toUpperCase(); } Service service = getService(session, db, a[1], a[2]); checkRight(session, service); return service.getExecutor().executeService(methodName, json); } else { throw new RuntimeException("service " + serviceName + " not found"); }
1,227
160
1,387
<methods>public java.lang.String getSQL() ,public com.lealone.db.schema.Schema getSchema() ,public boolean isHidden() <variables>protected final non-sealed com.lealone.db.schema.Schema schema
lealone_Lealone
Lealone/lealone-db/src/main/java/com/lealone/db/service/ServiceExecutorBase.java
ServiceExecutorBase
getServiceMethodArg
class ServiceExecutorBase implements ServiceExecutor { protected Map<String, ServiceMethod> serviceMethodMap; protected Object[] getServiceMethodArgs(String methodName, Value[] methodArgs) { Object[] args = new Object[methodArgs.length]; // 如果没有定义服务方法,直接把传递进来的方法参数转成对象 if (serviceMethodMap.isEmpty()) { for (int i = 0; i < methodArgs.length; i++) { Value v = methodArgs[i]; args[i] = getServiceMethodArg(v.getType(), v); } } else { ServiceMethod m = serviceMethodMap.get(methodName); List<Column> parameters = m.getParameters(); for (int i = 0; i < parameters.size(); i++) { Column c = parameters.get(i); Value v = methodArgs[i]; args[i] = getServiceMethodArg(c.getType(), v); } } return args; } protected Object getServiceMethodArg(int type, Value v) {<FILL_FUNCTION_BODY>} protected Object[] getServiceMethodArgs(String methodName, Map<String, Object> methodArgs) { if (serviceMethodMap.isEmpty()) { return null; } ServiceMethod m = serviceMethodMap.get(methodName); List<Column> parameters = m.getParameters(); Object[] args = new Object[parameters.size()]; for (int i = 0; i < parameters.size(); i++) { Column c = parameters.get(i); String cName = c.getName(); args[i] = getServiceMethodArg(cName, c.getType(), methodArgs); } return args; } protected Object getServiceMethodArg(String cName, int type, Map<String, Object> methodArgs) { Object arg = null; switch (type) { case Value.BOOLEAN: arg = toBoolean(cName, methodArgs); break; case Value.BYTE: arg = toByte(cName, methodArgs); break; case Value.SHORT: arg = toShort(cName, methodArgs); break; case Value.INT: arg = toInt(cName, methodArgs); break; case Value.LONG: arg = toLong(cName, methodArgs); break; case Value.DECIMAL: arg = toBigDecimal(cName, methodArgs); break; case Value.TIME: arg = toTime(cName, methodArgs); break; case Value.DATE: arg = toDate(cName, methodArgs); break; case Value.TIMESTAMP: arg = toTimestamp(cName, methodArgs); break; case Value.BYTES: arg = toBytes(cName, methodArgs); break; case Value.UUID: arg = toUUID(cName, methodArgs); break; case Value.STRING: case Value.STRING_IGNORECASE: case Value.STRING_FIXED: arg = toString(cName, methodArgs); break; case Value.BLOB: arg = toBlob(cName, methodArgs); break; case Value.CLOB: arg = toClob(cName, methodArgs); break; case Value.ARRAY: arg = toArray(cName, methodArgs); break; case Value.DOUBLE: arg = toDouble(cName, methodArgs); break; case Value.FLOAT: arg = toFloat(cName, methodArgs); break; case Value.NULL: case Value.JAVA_OBJECT: case Value.UNKNOWN: case Value.RESULT_SET: arg = toObject(cName, methodArgs); break; default: throw DbException.getInternalError("type=" + type); } return arg; } protected Object[] getServiceMethodArgs(String methodName, String json) { if (serviceMethodMap.isEmpty()) { return null; } ServiceMethod m = serviceMethodMap.get(methodName); List<Column> parameters = m.getParameters(); Object[] args = new Object[parameters.size()]; JsonArrayGetter getter = JsonArrayGetter.create(json); for (int i = 0; i < parameters.size(); i++) { Column c = parameters.get(i); args[i] = getter.getValue(i, c.getType()); } return args; } }
Object arg = null; switch (type) { case Value.BOOLEAN: arg = v.getBoolean(); break; case Value.BYTE: arg = v.getByte(); break; case Value.SHORT: arg = v.getShort(); break; case Value.INT: arg = v.getInt(); break; case Value.LONG: arg = v.getLong(); break; case Value.DECIMAL: arg = v.getBigDecimal(); break; case Value.TIME: arg = v.getFloat(); break; case Value.DATE: arg = v.getDate(); break; case Value.TIMESTAMP: arg = v.getTimestamp(); break; case Value.BYTES: arg = v.getBytes(); break; case Value.UUID: arg = v.getUuid(); break; case Value.STRING: case Value.STRING_IGNORECASE: case Value.STRING_FIXED: arg = v.getString(); break; case Value.BLOB: arg = v.getBlob(); break; case Value.CLOB: arg = v.getClob(); break; case Value.ARRAY: arg = v.getArray(); break; case Value.DOUBLE: arg = v.getDouble(); break; case Value.FLOAT: arg = v.getFloat(); break; case Value.NULL: case Value.JAVA_OBJECT: case Value.UNKNOWN: case Value.RESULT_SET: arg = v.getObject(); break; default: throw DbException.getInternalError("type=" + type); } return arg;
1,182
484
1,666
<no_super_class>
lealone_Lealone
Lealone/lealone-db/src/main/java/com/lealone/db/session/ServerSessionFactory.java
ServerSessionFactory
initDatabase
class ServerSessionFactory extends SessionFactoryBase { private static final ServerSessionFactory instance = new ServerSessionFactory(); public static ServerSessionFactory getInstance() { return instance; } @Override public Future<Session> createSession(ConnectionInfo ci, boolean allowRedirect) { if (ci.isEmbedded() && !SchedulerThread.isScheduler()) { Scheduler scheduler = EmbeddedScheduler.getScheduler(ci); AsyncCallback<Session> ac = AsyncCallback.create(ci.isSingleThreadCallback()); scheduler.handle(() -> { ServerSession session = createServerSession(ci); ac.setAsyncResult(session); }); return ac; } return Future.succeededFuture(createServerSession(ci)); } private ServerSession createServerSession(ConnectionInfo ci) { String dbName = ci.getDatabaseName(); // 内嵌数据库,如果不存在,则自动创建 if (ci.isEmbedded() && LealoneDatabase.getInstance().findDatabase(dbName) == null) { LealoneDatabase.getInstance().createEmbeddedDatabase(dbName, ci); } Database database = LealoneDatabase.getInstance().getDatabase(dbName); String targetNodes; if (ci.isEmbedded()) { targetNodes = null; } else { NetNode localNode = NetNode.getLocalTcpNode(); targetNodes = database.getTargetNodes(); // 为null时总是认为当前节点就是数据库所在的节点 if (targetNodes == null) { targetNodes = localNode.getHostAndPort(); } else if (!database.isTargetNode(localNode)) { ServerSession session = new ServerSession(database, LealoneDatabase.getInstance().getSystemSession().getUser(), 0); session.setTargetNodes(targetNodes); session.setRunMode(database.getRunMode()); session.setInvalid(true); return session; } } // 如果数据库正在关闭过程中,不等待重试了,直接抛异常 // 如果数据库已经关闭了,那么在接下来的init中会重新打开 if (database.isClosing()) { throw DbException.get(ErrorCode.DATABASE_IS_CLOSING); } if (!database.isInitialized() && !initDatabase(database, ci)) { return null; } User user = validateUser(database, ci); ServerSession session = database.createSession(user, ci); session.setTargetNodes(targetNodes); session.setRunMode(database.getRunMode()); return session; } // 只能有一个线程初始化数据库 private boolean initDatabase(Database database, ConnectionInfo ci) {<FILL_FUNCTION_BODY>} private User validateUser(Database database, ConnectionInfo ci) { User user = null; if (database.validateFilePasswordHash(ci.getProperty(DbSetting.CIPHER.getName(), null), ci.getFilePasswordHash())) { user = database.findUser(null, ci.getUserName()); if (user != null) { Mode mode = Mode.getInstance( ci.getProperty(DbSetting.MODE.name(), Mode.getDefaultMode().getName())); if (!user.validateUserPasswordHash(ci.getUserPasswordHash(), ci.getSalt(), mode)) { user = null; } else { database.setLastConnectionInfo(ci); } } } if (user == null) { throw DbException.get(ErrorCode.WRONG_USER_OR_PASSWORD); } return user; } }
SchedulerLock schedulerLock = database.getSchedulerLock(); if (schedulerLock.tryLock(SchedulerThread.currentScheduler())) { try { // sharding模式下访问remote page时会用到 database.setLastConnectionInfo(ci); database.init(); } finally { schedulerLock.unlock(); } return true; } return false;
934
105
1,039
<methods>public void <init>() ,public Class<? extends com.lealone.db.Plugin> getPluginClass() <variables>
lealone_Lealone
Lealone/lealone-db/src/main/java/com/lealone/db/stat/QueryStatisticsData.java
QueryStatisticsData
getQueries
class QueryStatisticsData { private static final Comparator<QueryEntry> QUERY_ENTRY_COMPARATOR = Comparator .comparingLong(q -> q.lastUpdateTime); private final HashMap<String, QueryEntry> map = new HashMap<>(); private int maxQueryEntries; public QueryStatisticsData(int maxQueryEntries) { this.maxQueryEntries = maxQueryEntries; } public synchronized void setMaxQueryEntries(int maxQueryEntries) { this.maxQueryEntries = maxQueryEntries; } public synchronized List<QueryEntry> getQueries() {<FILL_FUNCTION_BODY>} /** * Update query statistics. * * @param sqlStatement the statement being executed * @param executionTimeNanos the time in nanoseconds the query/update took * to execute * @param rowCount the query or update row count */ public synchronized void update(String sqlStatement, long executionTimeNanos, long rowCount) { QueryEntry entry = map.get(sqlStatement); if (entry == null) { entry = new QueryEntry(sqlStatement); map.put(sqlStatement, entry); } entry.update(executionTimeNanos, rowCount); // Age-out the oldest entries if the map gets too big. // Test against 1.5 x max-size so we don't do this too often if (map.size() > maxQueryEntries * 1.5f) { // Sort the entries by age ArrayList<QueryEntry> list = new ArrayList<>(map.values()); list.sort(QUERY_ENTRY_COMPARATOR); // Create a set of the oldest 1/3 of the entries HashSet<QueryEntry> oldestSet = new HashSet<>(list.subList(0, list.size() / 3)); // Loop over the map using the set and remove // the oldest 1/3 of the entries. for (Iterator<Entry<String, QueryEntry>> it = map.entrySet().iterator(); it.hasNext();) { Entry<String, QueryEntry> mapEntry = it.next(); if (oldestSet.contains(mapEntry.getValue())) { it.remove(); } } } } /** * The collected statistics for one query. */ public static final class QueryEntry { /** * The SQL statement. */ public final String sqlStatement; /** * The number of times the statement was executed. */ public int count; /** * The last time the statistics for this entry were updated, * in milliseconds since 1970. */ public long lastUpdateTime; /** * The minimum execution time, in nanoseconds. */ public long executionTimeMinNanos; /** * The maximum execution time, in nanoseconds. */ public long executionTimeMaxNanos; /** * The total execution time. */ public long executionTimeCumulativeNanos; /** * The minimum number of rows. */ public long rowCountMin; /** * The maximum number of rows. */ public long rowCountMax; /** * The total number of rows. */ public long rowCountCumulative; /** * The mean execution time. */ public double executionTimeMeanNanos; /** * The mean number of rows. */ public double rowCountMean; // Using Welford's method, see also // https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance // https://www.johndcook.com/blog/standard_deviation/ private double executionTimeM2Nanos; private double rowCountM2; public QueryEntry(String sql) { this.sqlStatement = sql; } /** * Update the statistics entry. * * @param timeNanos the execution time in nanos * @param rows the number of rows */ void update(long timeNanos, long rows) { count++; executionTimeMinNanos = Math.min(timeNanos, executionTimeMinNanos); executionTimeMaxNanos = Math.max(timeNanos, executionTimeMaxNanos); rowCountMin = Math.min(rows, rowCountMin); rowCountMax = Math.max(rows, rowCountMax); double rowDelta = rows - rowCountMean; rowCountMean += rowDelta / count; rowCountM2 += rowDelta * (rows - rowCountMean); double timeDelta = timeNanos - executionTimeMeanNanos; executionTimeMeanNanos += timeDelta / count; executionTimeM2Nanos += timeDelta * (timeNanos - executionTimeMeanNanos); executionTimeCumulativeNanos += timeNanos; rowCountCumulative += rows; lastUpdateTime = System.currentTimeMillis(); } public double getExecutionTimeStandardDeviation() { // population standard deviation return Math.sqrt(executionTimeM2Nanos / count); } public double getRowCountStandardDeviation() { // population standard deviation return Math.sqrt(rowCountM2 / count); } } }
// return a copy of the map so we don't have to // worry about external synchronization ArrayList<QueryEntry> list = new ArrayList<>(map.values()); // only return the newest 100 entries list.sort(QUERY_ENTRY_COMPARATOR); return list.subList(0, Math.min(list.size(), maxQueryEntries));
1,397
95
1,492
<no_super_class>
lealone_Lealone
Lealone/lealone-db/src/main/java/com/lealone/db/table/CreateTableData.java
CreateTableData
isMemoryTable
class CreateTableData { /** * The schema. */ public Schema schema; /** * The table name. */ public String tableName; /** * The object id. */ public int id; /** * The column list. */ public ArrayList<Column> columns = new ArrayList<>(); /** * Whether this is a temporary table. */ public boolean temporary; /** * Whether the table is global temporary. */ public boolean globalTemporary; /** * Whether the indexes should be persisted. */ public boolean persistIndexes; /** * Whether the data should be persisted. */ public boolean persistData; /** * Whether to create a new table. */ public boolean create; /** * The session. */ public ServerSession session; /** * The storage engine to use for creating the table. */ public String storageEngineName; /** * The storage engine parameters to use for creating the table. */ public CaseInsensitiveMap<String> storageEngineParams; /** * The table is hidden. */ public boolean isHidden; public boolean isMemoryTable() {<FILL_FUNCTION_BODY>} }
return !session.getDatabase().isPersistent() || globalTemporary || temporary || !persistData || id < 0;
346
34
380
<no_super_class>
lealone_Lealone
Lealone/lealone-db/src/main/java/com/lealone/db/table/MetaTable.java
MetaTable
add
class MetaTable extends Table { /** * The approximate number of rows of a meta table. */ public static final long ROW_COUNT_APPROXIMATION = 1000; protected final int type; protected final int indexColumn; protected final MetaIndex metaIndex; /** * Create a new metadata table. * * @param schema the schema * @param id the object id * @param type the meta table type */ public MetaTable(Schema schema, int id, int type) { // tableName will be set later super(schema, id, null, true, true); this.type = type; String indexColumnName = createColumns(); if (indexColumnName == null) { indexColumn = -1; metaIndex = null; } else { indexColumn = getColumn(indexColumnName).getColumnId(); IndexColumn[] indexCols = IndexColumn.wrap(new Column[] { columns[indexColumn] }); metaIndex = new MetaIndex(this, indexCols, false); } } public void setObjectName(String name) { this.name = name; } public abstract String createColumns(); public Column[] createColumns(String... names) { Column[] cols = new Column[names.length]; for (int i = 0; i < names.length; i++) { String nameType = names[i]; int idx = nameType.indexOf(' '); int dataType; String name; if (idx < 0) { dataType = database.getMode().lowerCaseIdentifiers ? Value.STRING_IGNORECASE : Value.STRING; name = nameType; } else { dataType = DataType.getTypeByName(nameType.substring(idx + 1)).type; name = nameType.substring(0, idx); } cols[i] = new Column(name, dataType); } return cols; } /** * Generate the data for the given metadata table using the given first and * last row filters. * * @param session the session * @param first the first row to return * @param last the last row to return * @return the generated rows */ public abstract ArrayList<Row> generateRows(ServerSession session, SearchRow first, SearchRow last); @Override public TableType getTableType() { return TableType.META_TABLE; } @Override public String getCreateSQL() { return null; } @Override public void removeChildrenAndResources(ServerSession session, DbObjectLock lock) { throw DbException.getUnsupportedException("META"); } @Override public Index getScanIndex(ServerSession session) { return new MetaIndex(this, IndexColumn.wrap(columns), true); } @Override public ArrayList<Index> getIndexes() { ArrayList<Index> list = new ArrayList<>(2); if (metaIndex == null) { return list; } list.add(getScanIndex(null)); // TODO re-use the index list.add(metaIndex); return list; } @Override public long getMaxDataModificationId() { return database.getModificationDataId(); } @Override public boolean isDeterministic() { return true; } @Override public boolean canReference() { return false; } @Override public boolean canDrop() { return false; } @Override public boolean canGetRowCount() { return false; } @Override public long getRowCount(ServerSession session) { throw DbException.getInternalError(); } @Override public long getRowCountApproximation() { return ROW_COUNT_APPROXIMATION; } protected void add(ArrayList<Row> rows, String... strings) {<FILL_FUNCTION_BODY>} }
Value[] values = new Value[strings.length]; for (int i = 0; i < strings.length; i++) { String s = strings[i]; Value v = (s == null) ? (Value) ValueNull.INSTANCE : ValueString.get(s); Column col = columns[i]; v = col.convert(v); values[i] = v; } Row row = new Row(values, 1); row.setKey(rows.size()); rows.add(row);
1,045
134
1,179
<methods>public void <init>(com.lealone.db.schema.Schema, int, java.lang.String, boolean, boolean) ,public void addConstraint(com.lealone.db.constraint.Constraint) ,public void addDependencies(Set<com.lealone.db.DbObject>) ,public com.lealone.db.index.Index addIndex(com.lealone.db.session.ServerSession, java.lang.String, int, com.lealone.db.index.IndexColumn[], com.lealone.db.index.IndexType, boolean, java.lang.String, com.lealone.db.lock.DbObjectLock) ,public Future<java.lang.Integer> addRow(com.lealone.db.session.ServerSession, com.lealone.db.result.Row) ,public void addSequence(com.lealone.db.schema.Sequence) ,public void addTrigger(com.lealone.db.schema.TriggerObject) ,public void addView(com.lealone.db.table.TableView) ,public void analyze(com.lealone.db.session.ServerSession, int) ,public abstract boolean canDrop() ,public abstract boolean canGetRowCount() ,public boolean canReference() ,public boolean canTruncate() ,public void checkRename() ,public void checkSupportAlter() ,public void checkWritingAllowed() ,public void close(com.lealone.db.session.ServerSession) ,public int compareTypeSafe(com.lealone.db.value.Value, com.lealone.db.value.Value) ,public boolean containsIndex() ,public boolean containsLargeObject() ,public boolean doesColumnExist(java.lang.String) ,public void dropSingleColumnConstraintsAndIndexes(com.lealone.db.session.ServerSession, com.lealone.db.table.Column, com.lealone.db.lock.DbObjectLock) ,public com.lealone.db.table.Column findColumn(java.lang.String) ,public com.lealone.db.index.Index findPrimaryKey() ,public void fire(com.lealone.db.session.ServerSession, int, boolean) ,public void fireAfterRow(com.lealone.db.session.ServerSession, com.lealone.db.result.Row, com.lealone.db.result.Row, boolean) ,public boolean fireBeforeRow(com.lealone.db.session.ServerSession, com.lealone.db.result.Row, com.lealone.db.result.Row) ,public boolean fireRow() ,public boolean getCheckForeignKeyConstraints() ,public List<com.lealone.db.DbObject> getChildren() ,public java.lang.String getCodePath() ,public com.lealone.db.table.Column getColumn(int) ,public com.lealone.db.table.Column getColumn(java.lang.String) ,public com.lealone.db.table.Column[] getColumns() ,public com.lealone.db.value.CompareMode getCompareMode() ,public ArrayList<com.lealone.db.constraint.Constraint> getConstraints() ,public com.lealone.db.DataHandler getDataHandler() ,public com.lealone.db.value.Value getDefaultValue(com.lealone.db.session.ServerSession, com.lealone.db.table.Column) ,public long getDiskSpaceUsed() ,public com.lealone.db.index.Index getIndexForColumn(com.lealone.db.table.Column) ,public ArrayList<com.lealone.db.index.Index> getIndexes() ,public abstract long getMaxDataModificationId() ,public synchronized com.lealone.db.result.Row getNullRow() ,public com.lealone.db.table.Column[] getOldColumns() ,public boolean getOnCommitDrop() ,public boolean getOnCommitTruncate() ,public java.lang.String getPackageName() ,public java.lang.String getParameter(java.lang.String) ,public Map<java.lang.String,java.lang.String> getParameters() ,public com.lealone.db.index.Index getPrimaryKey() ,public ArrayList<com.lealone.db.constraint.ConstraintReferential> getReferentialConstraints() ,public com.lealone.db.result.Row getRow(com.lealone.db.session.ServerSession, long) ,public com.lealone.db.result.Row getRow(com.lealone.db.result.Row) ,public abstract long getRowCount(com.lealone.db.session.ServerSession) ,public abstract long getRowCountApproximation() ,public com.lealone.db.table.Column getRowIdColumn() ,public abstract com.lealone.db.index.Index getScanIndex(com.lealone.db.session.ServerSession) ,public abstract com.lealone.db.table.TableType getTableType() ,public com.lealone.db.result.Row getTemplateRow() ,public com.lealone.db.result.SearchRow getTemplateSimpleRow(boolean) ,public com.lealone.db.DbObjectType getType() ,public int getVersion() ,public ArrayList<com.lealone.db.table.TableView> getViews() ,public boolean hasSelectTrigger() ,public int incrementAndGetVersion() ,public void initVersion() ,public abstract boolean isDeterministic() ,public boolean isGlobalTemporary() ,public boolean isHidden() ,public boolean isPersistData() ,public boolean isPersistIndexes() ,public boolean isRowChanged(com.lealone.db.result.Row) ,public boolean lock(com.lealone.db.session.ServerSession, boolean) ,public void removeChildrenAndResources(com.lealone.db.session.ServerSession, com.lealone.db.lock.DbObjectLock) ,public void removeConstraint(com.lealone.db.constraint.Constraint) ,public void removeIndex(com.lealone.db.index.Index) ,public void removeIndexOrTransferOwnership(com.lealone.db.session.ServerSession, com.lealone.db.index.Index, com.lealone.db.lock.DbObjectLock) ,public Future<java.lang.Integer> removeRow(com.lealone.db.session.ServerSession, com.lealone.db.result.Row) ,public Future<java.lang.Integer> removeRow(com.lealone.db.session.ServerSession, com.lealone.db.result.Row, boolean) ,public void removeSequence(com.lealone.db.schema.Sequence) ,public void removeTrigger(com.lealone.db.schema.TriggerObject) ,public void removeView(com.lealone.db.table.TableView) ,public void rename(java.lang.String) ,public void renameColumn(com.lealone.db.table.Column, java.lang.String) ,public void repair(com.lealone.db.session.ServerSession) ,public void setCheckForeignKeyConstraints(com.lealone.db.session.ServerSession, boolean, boolean) ,public void setCodePath(java.lang.String) ,public void setHidden(boolean) ,public void setNewColumns(com.lealone.db.table.Column[]) ,public void setOnCommitDrop(boolean) ,public void setOnCommitTruncate(boolean) ,public void setPackageName(java.lang.String) ,public void truncate(com.lealone.db.session.ServerSession) ,public boolean tryExclusiveLock(com.lealone.db.session.ServerSession) ,public int tryLockRow(com.lealone.db.session.ServerSession, com.lealone.db.result.Row, int[]) ,public boolean trySharedLock(com.lealone.db.session.ServerSession) ,public Future<java.lang.Integer> updateRow(com.lealone.db.session.ServerSession, com.lealone.db.result.Row, com.lealone.db.result.Row, int[]) ,public Future<java.lang.Integer> updateRow(com.lealone.db.session.ServerSession, com.lealone.db.result.Row, com.lealone.db.result.Row, int[], boolean) ,public void validateConvertUpdateSequence(com.lealone.db.session.ServerSession, com.lealone.db.result.Row) <variables>public static final int TYPE_CACHED,public static final int TYPE_MEMORY,private boolean checkForeignKeyConstraints,private java.lang.String codePath,private final non-sealed HashMap<java.lang.String,com.lealone.db.table.Column> columnMap,protected com.lealone.db.table.Column[] columns,private final non-sealed com.lealone.db.value.CompareMode compareMode,private ArrayList<com.lealone.db.constraint.Constraint> constraints,private final com.lealone.db.lock.DbObjectLock dbObjectLock,protected boolean isHidden,private com.lealone.db.result.Row nullRow,private boolean onCommitDrop,private boolean onCommitTruncate,private java.lang.String packageName,private final non-sealed boolean persistData,private final non-sealed boolean persistIndexes,private ArrayList<com.lealone.db.schema.Sequence> sequences,private ArrayList<com.lealone.db.schema.TriggerObject> triggers,private int version,private ArrayList<com.lealone.db.table.TableView> views
lealone_Lealone
Lealone/lealone-db/src/main/java/com/lealone/db/table/PerfMetaTable.java
PerfMetaTable
generateRows
class PerfMetaTable extends MetaTable { private static final int QUERY_STATISTICS = 0; public static int getMetaTableTypeCount() { return QUERY_STATISTICS + 1; } public PerfMetaTable(Schema schema, int id, int type) { super(schema, id, type); } @Override public String createColumns() { Column[] cols; String indexColumnName = null; switch (type) { case QUERY_STATISTICS: { setObjectName("QUERY_STATISTICS"); cols = createColumns("SQL_STATEMENT", "EXECUTION_COUNT INT", "MIN_EXECUTION_TIME DOUBLE", "MAX_EXECUTION_TIME DOUBLE", "CUMULATIVE_EXECUTION_TIME DOUBLE", "AVERAGE_EXECUTION_TIME DOUBLE", "STD_DEV_EXECUTION_TIME DOUBLE", "MIN_ROW_COUNT INT", "MAX_ROW_COUNT INT", "CUMULATIVE_ROW_COUNT LONG", "AVERAGE_ROW_COUNT DOUBLE", "STD_DEV_ROW_COUNT DOUBLE"); break; } default: throw DbException.getInternalError("type=" + type); } setColumns(cols); return indexColumnName; } @Override public ArrayList<Row> generateRows(ServerSession session, SearchRow first, SearchRow last) {<FILL_FUNCTION_BODY>} }
ArrayList<Row> rows = Utils.newSmallArrayList(); switch (type) { case QUERY_STATISTICS: { QueryStatisticsData statData = database.getQueryStatisticsData(); if (statData != null) { for (QueryStatisticsData.QueryEntry entry : statData.getQueries()) { add(rows, // SQL_STATEMENT entry.sqlStatement, // EXECUTION_COUNT "" + entry.count, // MIN_EXECUTION_TIME "" + entry.executionTimeMinNanos / 1000d / 1000, // MAX_EXECUTION_TIME "" + entry.executionTimeMaxNanos / 1000d / 1000, // CUMULATIVE_EXECUTION_TIME "" + entry.executionTimeCumulativeNanos / 1000d / 1000, // AVERAGE_EXECUTION_TIME "" + entry.executionTimeMeanNanos / 1000d / 1000, // STD_DEV_EXECUTION_TIME "" + entry.getExecutionTimeStandardDeviation() / 1000d / 1000, // MIN_ROW_COUNT "" + entry.rowCountMin, // MAX_ROW_COUNT "" + entry.rowCountMax, // CUMULATIVE_ROW_COUNT "" + entry.rowCountCumulative, // AVERAGE_ROW_COUNT "" + entry.rowCountMean, // STD_DEV_ROW_COUNT "" + entry.getRowCountStandardDeviation()); } } break; } default: throw DbException.getInternalError("type=" + type); } return rows;
398
469
867
<methods>public void <init>(com.lealone.db.schema.Schema, int, int) ,public boolean canDrop() ,public boolean canGetRowCount() ,public boolean canReference() ,public abstract java.lang.String createColumns() ,public transient com.lealone.db.table.Column[] createColumns(java.lang.String[]) ,public abstract ArrayList<com.lealone.db.result.Row> generateRows(com.lealone.db.session.ServerSession, com.lealone.db.result.SearchRow, com.lealone.db.result.SearchRow) ,public java.lang.String getCreateSQL() ,public ArrayList<com.lealone.db.index.Index> getIndexes() ,public long getMaxDataModificationId() ,public long getRowCount(com.lealone.db.session.ServerSession) ,public long getRowCountApproximation() ,public com.lealone.db.index.Index getScanIndex(com.lealone.db.session.ServerSession) ,public com.lealone.db.table.TableType getTableType() ,public boolean isDeterministic() ,public void removeChildrenAndResources(com.lealone.db.session.ServerSession, com.lealone.db.lock.DbObjectLock) ,public void setObjectName(java.lang.String) <variables>public static final long ROW_COUNT_APPROXIMATION,protected final non-sealed int indexColumn,protected final non-sealed com.lealone.db.index.MetaIndex metaIndex,protected final non-sealed int type
lealone_Lealone
Lealone/lealone-db/src/main/java/com/lealone/db/table/RangeTable.java
RangeTable
getScanIndex
class RangeTable extends Table { /** * The name of the range table. */ public static final String NAME = "SYSTEM_RANGE"; /** * The PostgreSQL alias for the range table. */ public static final String ALIAS = "GENERATE_SERIES"; private IExpression min, max, step; private boolean optimized; /** * Create a new range with the given start and end expressions. * * @param schema the schema (always the main schema) * @param min the start expression * @param max the end expression * @param noColumns whether this table has no columns */ public RangeTable(Schema schema, IExpression min, IExpression max, boolean noColumns) { super(schema, 0, NAME, true, true); Column[] cols = noColumns ? new Column[0] : new Column[] { new Column("X", Value.LONG) }; this.min = min; this.max = max; setColumns(cols); } public RangeTable(Schema schema, IExpression min, IExpression max, IExpression step, boolean noColumns) { this(schema, min, max, noColumns); this.step = step; } @Override public String getCreateSQL() { return null; } @Override public String getSQL() { String sql = NAME + "(" + min.getSQL() + ", " + max.getSQL(); if (step != null) { sql += ", " + step.getSQL(); } return sql + ")"; } @Override public TableType getTableType() { return TableType.RANGE_TABLE; } @Override public Index getScanIndex(ServerSession session) {<FILL_FUNCTION_BODY>} @Override public long getMaxDataModificationId() { return 0; } @Override public boolean isDeterministic() { return true; } @Override public boolean canReference() { return false; } @Override public boolean canDrop() { return false; } @Override public boolean canGetRowCount() { return true; } @Override public long getRowCount(ServerSession session) { return Math.max(0, getMax(session) - getMin(session) + 1); } @Override public long getRowCountApproximation() { return 100; } /** * Calculate and get the start value of this range. * * @param session the session * @return the start value */ public long getMin(ServerSession session) { optimize(session); return min.getValue(session).getLong(); } /** * Calculate and get the end value of this range. * * @param session the session * @return the end value */ public long getMax(ServerSession session) { optimize(session); return max.getValue(session).getLong(); } /** * Get the increment. * * @param session the session * @return the increment (1 by default) */ public long getStep(ServerSession session) { optimize(session); if (step == null) { return 1; } return step.getValue(session).getLong(); } private void optimize(ServerSession s) { if (!optimized) { min = min.optimize(s); max = max.optimize(s); if (step != null) { step = step.optimize(s); } optimized = true; } } }
if (getStep(session) == 0) { throw DbException.get(ErrorCode.STEP_SIZE_MUST_NOT_BE_ZERO); } return new RangeIndex(this, IndexColumn.wrap(columns));
967
63
1,030
<methods>public void <init>(com.lealone.db.schema.Schema, int, java.lang.String, boolean, boolean) ,public void addConstraint(com.lealone.db.constraint.Constraint) ,public void addDependencies(Set<com.lealone.db.DbObject>) ,public com.lealone.db.index.Index addIndex(com.lealone.db.session.ServerSession, java.lang.String, int, com.lealone.db.index.IndexColumn[], com.lealone.db.index.IndexType, boolean, java.lang.String, com.lealone.db.lock.DbObjectLock) ,public Future<java.lang.Integer> addRow(com.lealone.db.session.ServerSession, com.lealone.db.result.Row) ,public void addSequence(com.lealone.db.schema.Sequence) ,public void addTrigger(com.lealone.db.schema.TriggerObject) ,public void addView(com.lealone.db.table.TableView) ,public void analyze(com.lealone.db.session.ServerSession, int) ,public abstract boolean canDrop() ,public abstract boolean canGetRowCount() ,public boolean canReference() ,public boolean canTruncate() ,public void checkRename() ,public void checkSupportAlter() ,public void checkWritingAllowed() ,public void close(com.lealone.db.session.ServerSession) ,public int compareTypeSafe(com.lealone.db.value.Value, com.lealone.db.value.Value) ,public boolean containsIndex() ,public boolean containsLargeObject() ,public boolean doesColumnExist(java.lang.String) ,public void dropSingleColumnConstraintsAndIndexes(com.lealone.db.session.ServerSession, com.lealone.db.table.Column, com.lealone.db.lock.DbObjectLock) ,public com.lealone.db.table.Column findColumn(java.lang.String) ,public com.lealone.db.index.Index findPrimaryKey() ,public void fire(com.lealone.db.session.ServerSession, int, boolean) ,public void fireAfterRow(com.lealone.db.session.ServerSession, com.lealone.db.result.Row, com.lealone.db.result.Row, boolean) ,public boolean fireBeforeRow(com.lealone.db.session.ServerSession, com.lealone.db.result.Row, com.lealone.db.result.Row) ,public boolean fireRow() ,public boolean getCheckForeignKeyConstraints() ,public List<com.lealone.db.DbObject> getChildren() ,public java.lang.String getCodePath() ,public com.lealone.db.table.Column getColumn(int) ,public com.lealone.db.table.Column getColumn(java.lang.String) ,public com.lealone.db.table.Column[] getColumns() ,public com.lealone.db.value.CompareMode getCompareMode() ,public ArrayList<com.lealone.db.constraint.Constraint> getConstraints() ,public com.lealone.db.DataHandler getDataHandler() ,public com.lealone.db.value.Value getDefaultValue(com.lealone.db.session.ServerSession, com.lealone.db.table.Column) ,public long getDiskSpaceUsed() ,public com.lealone.db.index.Index getIndexForColumn(com.lealone.db.table.Column) ,public ArrayList<com.lealone.db.index.Index> getIndexes() ,public abstract long getMaxDataModificationId() ,public synchronized com.lealone.db.result.Row getNullRow() ,public com.lealone.db.table.Column[] getOldColumns() ,public boolean getOnCommitDrop() ,public boolean getOnCommitTruncate() ,public java.lang.String getPackageName() ,public java.lang.String getParameter(java.lang.String) ,public Map<java.lang.String,java.lang.String> getParameters() ,public com.lealone.db.index.Index getPrimaryKey() ,public ArrayList<com.lealone.db.constraint.ConstraintReferential> getReferentialConstraints() ,public com.lealone.db.result.Row getRow(com.lealone.db.session.ServerSession, long) ,public com.lealone.db.result.Row getRow(com.lealone.db.result.Row) ,public abstract long getRowCount(com.lealone.db.session.ServerSession) ,public abstract long getRowCountApproximation() ,public com.lealone.db.table.Column getRowIdColumn() ,public abstract com.lealone.db.index.Index getScanIndex(com.lealone.db.session.ServerSession) ,public abstract com.lealone.db.table.TableType getTableType() ,public com.lealone.db.result.Row getTemplateRow() ,public com.lealone.db.result.SearchRow getTemplateSimpleRow(boolean) ,public com.lealone.db.DbObjectType getType() ,public int getVersion() ,public ArrayList<com.lealone.db.table.TableView> getViews() ,public boolean hasSelectTrigger() ,public int incrementAndGetVersion() ,public void initVersion() ,public abstract boolean isDeterministic() ,public boolean isGlobalTemporary() ,public boolean isHidden() ,public boolean isPersistData() ,public boolean isPersistIndexes() ,public boolean isRowChanged(com.lealone.db.result.Row) ,public boolean lock(com.lealone.db.session.ServerSession, boolean) ,public void removeChildrenAndResources(com.lealone.db.session.ServerSession, com.lealone.db.lock.DbObjectLock) ,public void removeConstraint(com.lealone.db.constraint.Constraint) ,public void removeIndex(com.lealone.db.index.Index) ,public void removeIndexOrTransferOwnership(com.lealone.db.session.ServerSession, com.lealone.db.index.Index, com.lealone.db.lock.DbObjectLock) ,public Future<java.lang.Integer> removeRow(com.lealone.db.session.ServerSession, com.lealone.db.result.Row) ,public Future<java.lang.Integer> removeRow(com.lealone.db.session.ServerSession, com.lealone.db.result.Row, boolean) ,public void removeSequence(com.lealone.db.schema.Sequence) ,public void removeTrigger(com.lealone.db.schema.TriggerObject) ,public void removeView(com.lealone.db.table.TableView) ,public void rename(java.lang.String) ,public void renameColumn(com.lealone.db.table.Column, java.lang.String) ,public void repair(com.lealone.db.session.ServerSession) ,public void setCheckForeignKeyConstraints(com.lealone.db.session.ServerSession, boolean, boolean) ,public void setCodePath(java.lang.String) ,public void setHidden(boolean) ,public void setNewColumns(com.lealone.db.table.Column[]) ,public void setOnCommitDrop(boolean) ,public void setOnCommitTruncate(boolean) ,public void setPackageName(java.lang.String) ,public void truncate(com.lealone.db.session.ServerSession) ,public boolean tryExclusiveLock(com.lealone.db.session.ServerSession) ,public int tryLockRow(com.lealone.db.session.ServerSession, com.lealone.db.result.Row, int[]) ,public boolean trySharedLock(com.lealone.db.session.ServerSession) ,public Future<java.lang.Integer> updateRow(com.lealone.db.session.ServerSession, com.lealone.db.result.Row, com.lealone.db.result.Row, int[]) ,public Future<java.lang.Integer> updateRow(com.lealone.db.session.ServerSession, com.lealone.db.result.Row, com.lealone.db.result.Row, int[], boolean) ,public void validateConvertUpdateSequence(com.lealone.db.session.ServerSession, com.lealone.db.result.Row) <variables>public static final int TYPE_CACHED,public static final int TYPE_MEMORY,private boolean checkForeignKeyConstraints,private java.lang.String codePath,private final non-sealed HashMap<java.lang.String,com.lealone.db.table.Column> columnMap,protected com.lealone.db.table.Column[] columns,private final non-sealed com.lealone.db.value.CompareMode compareMode,private ArrayList<com.lealone.db.constraint.Constraint> constraints,private final com.lealone.db.lock.DbObjectLock dbObjectLock,protected boolean isHidden,private com.lealone.db.result.Row nullRow,private boolean onCommitDrop,private boolean onCommitTruncate,private java.lang.String packageName,private final non-sealed boolean persistData,private final non-sealed boolean persistIndexes,private ArrayList<com.lealone.db.schema.Sequence> sequences,private ArrayList<com.lealone.db.schema.TriggerObject> triggers,private int version,private ArrayList<com.lealone.db.table.TableView> views
lealone_Lealone
Lealone/lealone-db/src/main/java/com/lealone/db/table/TableAlterHistory.java
TableAlterHistory
getRecords
class TableAlterHistory { private PreparedStatement psGetVersion; private PreparedStatement psGetRecords; private PreparedStatement psAddRecord; private PreparedStatement psDeleteRecords; // 执行DROP DATABASE时调用这个方法,避免在删掉table_alter_history后还读它 public void cleanPreparedStatements() { psGetVersion = null; psGetRecords = null; psAddRecord = null; psDeleteRecords = null; } public void init(Connection conn) { try { Statement stmt = conn.createStatement(); stmt.executeUpdate("CREATE TABLE IF NOT EXISTS INFORMATION_SCHEMA.table_alter_history" + " (id int, version int, alter_type int, columns varchar, PRIMARY KEY(id, version))" + " PARAMETERS(" + StorageSetting.RUN_MODE.name() + "='" + RunMode.CLIENT_SERVER.name() + "')"); stmt.close(); psGetVersion = conn.prepareStatement( "select max(version) from INFORMATION_SCHEMA.table_alter_history where id = ?"); psGetRecords = conn.prepareStatement( "select id, version, alter_type, columns from INFORMATION_SCHEMA.table_alter_history " + "where id = ? and version > ? and version <= ?"); psAddRecord = conn.prepareStatement( "insert into INFORMATION_SCHEMA.table_alter_history values(?,?,?,?)"); psDeleteRecords = conn .prepareStatement("delete from INFORMATION_SCHEMA.table_alter_history where id = ?"); // 嵌入式执行prepareStatement会产生新的事务,所以这里需要提交一下 conn.commit(); } catch (SQLException e) { throw DbException.convert(e); } } public synchronized int getVersion(int id) { if (psGetVersion == null) DbException.throwInternalError(); int version; try { psGetVersion.setInt(1, id); ResultSet rs = psGetVersion.executeQuery(); if (rs.next()) { version = rs.getInt(1); } else { version = 0; } rs.close(); } catch (SQLException e) { throw DbException.convert(e); } return version; } public synchronized ArrayList<TableAlterHistoryRecord> getRecords(int id, int versionMin, int versionMax) {<FILL_FUNCTION_BODY>} public synchronized void addRecord(int id, int version, int alterType, String columns) { if (psAddRecord == null) return; try { psAddRecord.setInt(1, id); psAddRecord.setInt(2, version); psAddRecord.setInt(3, alterType); psAddRecord.setString(4, columns); psAddRecord.executeUpdate(); } catch (SQLException e) { throw DbException.convert(e); } } public synchronized void deleteRecords(int id) { if (psDeleteRecords == null) return; try { psDeleteRecords.setInt(1, id); psDeleteRecords.executeUpdate(); } catch (SQLException e) { throw DbException.convert(e); } } public static String getName() { return "table_alter_history"; } }
ArrayList<TableAlterHistoryRecord> records = new ArrayList<>(); if (psGetRecords == null) return records; try { psGetRecords.setInt(1, id); psGetRecords.setInt(2, versionMin); psGetRecords.setInt(3, versionMax); ResultSet rs = psGetRecords.executeQuery(); while (rs.next()) { records.add(new TableAlterHistoryRecord(rs.getInt(1), rs.getInt(2), rs.getInt(3), rs.getString(4))); } rs.close(); return records; } catch (SQLException e) { throw DbException.convert(e); }
912
191
1,103
<no_super_class>
lealone_Lealone
Lealone/lealone-db/src/main/java/com/lealone/db/table/TableAlterHistoryRecord.java
TableAlterHistoryRecord
redo
class TableAlterHistoryRecord { // private final int id; // private final int version; private final int alterType; private final String columns; public TableAlterHistoryRecord(int id, int version, int alterType, String columns) { // this.id = id; // this.version = version; this.alterType = alterType; this.columns = columns; } public Value[] redo(ServerSession session, Value[] values) {<FILL_FUNCTION_BODY>} }
if (alterType == SQLStatement.ALTER_TABLE_DROP_COLUMN) { int position = Integer.parseInt(columns); int len = values.length; if (len == 1) return new Value[0]; Value[] newValues = new Value[len - 1]; System.arraycopy(values, 0, newValues, 0, position); System.arraycopy(values, position + 1, newValues, position, len - position - 1); return newValues; } else if (alterType == SQLStatement.ALTER_TABLE_ALTER_COLUMN_CHANGE_TYPE) { int index = columns.indexOf(','); int position = Integer.parseInt(columns.substring(0, index)); Column column = (Column) session.getParser() .parseColumnForTable(columns.substring(index + 1)); values[position] = column.convert(values[position]); return values; } else if (alterType == SQLStatement.ALTER_TABLE_ADD_COLUMN) { String[] a = columns.split(","); int position = Integer.parseInt(a[0]); int len = a.length - 1 + values.length; Value[] newValues = new Value[len]; System.arraycopy(values, 0, newValues, 0, position); System.arraycopy(values, position, newValues, position + a.length - 1, values.length - position); Row row = new Row(newValues, 0); for (int i = 1; i < a.length; i++) { Column column = (Column) session.getParser().parseColumnForTable(a[i]); Value value = null; Value v2; if (column.isComputed()) { // force updating the value value = null; v2 = column.computeValue(session, row); } v2 = column.validateConvertUpdateSequence(session, value); if (v2 != value) { value = v2; } newValues[position++] = value; } return newValues; } return values;
135
539
674
<no_super_class>
lealone_Lealone
Lealone/lealone-db/src/main/java/com/lealone/db/table/TableAnalyzer.java
TableAnalyzer
analyzeIfRequired
class TableAnalyzer { private final Table table; private final AtomicBoolean analyzing = new AtomicBoolean(); private int nextAnalyze; private int changesSinceAnalyze; public TableAnalyzer(Table table, int nextAnalyze) { this.table = table; this.nextAnalyze = nextAnalyze; } public void reset() { changesSinceAnalyze = 0; } // 允许多线程运行,对changesSinceAnalyze计数虽然不是线程安全的,但不要求准确,所以不必用原子操作 public void analyzeIfRequired(ServerSession session) {<FILL_FUNCTION_BODY>} public void analyze(ServerSession session, int sample) { if (analyzing.compareAndSet(false, true)) { try { analyzeTable(session, table, sample, true); } finally { analyzing.set(false); } } } /** * Analyze this table. * * @param session the session * @param table the table * @param sample the number of sample rows * @param manual whether the command was called by the user */ private static void analyzeTable(ServerSession session, Table table, int sample, boolean manual) { if (table.getTableType() != TableType.STANDARD_TABLE || table.isHidden() || session == null) { return; } if (!manual) { if (table.hasSelectTrigger()) { return; } } if (table.isTemporary() && !table.isGlobalTemporary() && session.findLocalTempTable(table.getName()) == null) { return; } if (!session.getUser().hasRight(table, Right.SELECT)) { return; } if (session.getCancel() != 0) { // if the connection is closed and there is something to undo return; } Column[] columns = table.getColumns(); if (columns.length == 0) { return; } Database db = session.getDatabase(); StatementBuilder buff = new StatementBuilder("SELECT "); for (Column col : columns) { buff.appendExceptFirst(", "); int type = col.getType(); if (type == Value.BLOB || type == Value.CLOB) { // can not index LOB columns, so calculating // the selectivity is not required buff.append("MAX(NULL)"); } else { buff.append("SELECTIVITY(").append(col.getSQL()).append(')'); } } buff.append(" FROM ").append(table.getSQL()); if (sample > 0) { buff.append(" LIMIT ? SAMPLE_SIZE ? "); } String sql = buff.toString(); PreparedSQLStatement command = session.prepareStatement(sql); if (sample > 0) { List<? extends CommandParameter> params = command.getParameters(); params.get(0).setValue(ValueInt.get(1)); params.get(1).setValue(ValueInt.get(sample)); } Result result = command.query(0); result.next(); for (int j = 0; j < columns.length; j++) { Value v = result.currentRow()[j]; if (v != ValueNull.INSTANCE) { int selectivity = v.getInt(); columns[j].setSelectivity(selectivity); } } db.updateMeta(session, table); } }
if (nextAnalyze > changesSinceAnalyze++) { return; } if (analyzing.compareAndSet(false, true)) { changesSinceAnalyze = 0; int n = 2 * nextAnalyze; if (n > 0) { nextAnalyze = n; } int rows = session.getDatabase().getSettings().analyzeSample / 10; try { analyzeTable(session, table, rows, false); } finally { analyzing.set(false); } }
904
139
1,043
<no_super_class>
lealone_Lealone
Lealone/lealone-db/src/main/java/com/lealone/db/util/HashBase.java
HashBase
reset
class HashBase { private static final int MAX_LOAD = 90; /** * The bit mask to get the index from the hash code. */ protected int mask; /** * The number of slots in the table. */ protected int len; /** * The number of occupied slots, excluding the zero key (if any). */ protected int size; /** * The number of deleted slots. */ protected int deletedCount; /** * The level. The number of slots is 2 ^ level. */ protected int level; /** * Whether the zero key is used. */ protected boolean zeroKey; private int maxSize, minSize, maxDeleted; public HashBase() { reset(2); } /** * Increase the size of the underlying table and re-distribute the elements. * * @param newLevel the new level */ protected abstract void rehash(int newLevel); /** * Get the size of the map. * * @return the size */ public int size() { return size + (zeroKey ? 1 : 0); } /** * Check the size before adding an entry. This method resizes the map if * required. */ void checkSizePut() { if (deletedCount > size) { rehash(level); } if (size + deletedCount >= maxSize) { rehash(level + 1); } } /** * Check the size before removing an entry. This method resizes the map if * required. */ protected void checkSizeRemove() { if (size < minSize && level > 0) { rehash(level - 1); } else if (deletedCount > maxDeleted) { rehash(level); } } /** * Clear the map and reset the level to the specified value. * * @param newLevel the new level */ protected void reset(int newLevel) {<FILL_FUNCTION_BODY>} /** * Calculate the index for this hash code. * * @param hash the hash code * @return the index */ protected int getIndex(int hash) { return hash & mask; } }
minSize = size * 3 / 4; size = 0; level = newLevel; len = 2 << level; mask = len - 1; maxSize = (int) (len * MAX_LOAD / 100L); deletedCount = 0; maxDeleted = 20 + len / 2;
611
88
699
<no_super_class>
lealone_Lealone
Lealone/lealone-db/src/main/java/com/lealone/db/util/IntArray.java
IntArray
removeRange
class IntArray { private int[] data; private int size; private int hash; /** * Create an int array with the default initial capacity. */ public IntArray() { this(10); } /** * Create an int array with specified initial capacity. * * @param capacity the initial capacity */ public IntArray(int capacity) { data = new int[capacity]; } /** * Create an int array with the given values and size. * * @param data the int array */ public IntArray(int[] data) { this.data = data; size = data.length; } /** * Append a value. * * @param value the value to append */ public void add(int value) { if (size >= data.length) { ensureCapacity(size + size); } data[size++] = value; } /** * Get the value at the given index. * * @param index the index * @return the value */ public int get(int index) { if (SysProperties.CHECK) { if (index >= size) { throw new ArrayIndexOutOfBoundsException("i=" + index + " size=" + size); } } return data[index]; } /** * Remove the value at the given index. * * @param index the index */ public void remove(int index) { if (SysProperties.CHECK) { if (index >= size) { throw new ArrayIndexOutOfBoundsException("i=" + index + " size=" + size); } } System.arraycopy(data, index + 1, data, index, size - index - 1); size--; } /** * Ensure the the underlying array is large enough for the given number of * entries. * * @param minCapacity the minimum capacity */ public void ensureCapacity(int minCapacity) { minCapacity = Math.max(4, minCapacity); if (minCapacity >= data.length) { int[] d = new int[minCapacity]; System.arraycopy(data, 0, d, 0, data.length); data = d; } } public boolean equals(Object obj) { if (!(obj instanceof IntArray)) { return false; } IntArray other = (IntArray) obj; if (hashCode() != other.hashCode() || size != other.size) { return false; } for (int i = 0; i < size; i++) { if (data[i] != other.data[i]) { return false; } } return true; } public int hashCode() { if (hash != 0) { return hash; } int h = size + 1; for (int i = 0; i < size; i++) { h = h * 31 + data[i]; } hash = h; return h; } /** * Get the size of the list. * * @return the size */ public int size() { return size; } /** * Convert this list to an array. The target array must be big enough. * * @param array the target array */ public void toArray(int[] array) { System.arraycopy(data, 0, array, 0, size); } public String toString() { StatementBuilder buff = new StatementBuilder("{"); for (int i = 0; i < size; i++) { buff.appendExceptFirst(", "); buff.append(data[i]); } return buff.append('}').toString(); } /** * Remove a number of elements. * * @param fromIndex the index of the first item to remove * @param toIndex upper bound (exclusive) */ public void removeRange(int fromIndex, int toIndex) {<FILL_FUNCTION_BODY>} }
if (SysProperties.CHECK) { if (fromIndex > toIndex || toIndex > size) { throw new ArrayIndexOutOfBoundsException( "from=" + fromIndex + " to=" + toIndex + " size=" + size); } } System.arraycopy(data, toIndex, data, fromIndex, size - toIndex); size -= toIndex - fromIndex;
1,092
105
1,197
<no_super_class>
lealone_Lealone
Lealone/lealone-db/src/main/java/com/lealone/db/util/IntIntHashMap.java
IntIntHashMap
put
class IntIntHashMap extends HashBase { /** * The value indicating that the entry has not been found. */ public static final int NOT_FOUND = -1; private static final int DELETED = 1; private int[] keys; private int[] values; private int zeroValue; @Override protected void reset(int newLevel) { super.reset(newLevel); keys = new int[len]; values = new int[len]; } /** * Store the given key-value pair. The value is overwritten or added. * * @param key the key * @param value the value (-1 is not supported) */ public void put(int key, int value) {<FILL_FUNCTION_BODY>} /** * Remove the key-value pair with the given key. * * @param key the key */ public void remove(int key) { if (key == 0) { zeroKey = false; return; } checkSizeRemove(); int index = getIndex(key); int plus = 1; do { int k = keys[index]; if (k == key) { // found the record keys[index] = 0; values[index] = DELETED; deletedCount++; size--; return; } else if (k == 0 && values[index] == 0) { // found an empty record return; } index = (index + plus++) & mask; } while (plus <= len); // not found } @Override protected void rehash(int newLevel) { int[] oldKeys = keys; int[] oldValues = values; reset(newLevel); for (int i = 0; i < oldKeys.length; i++) { int k = oldKeys[i]; if (k != 0) { put(k, oldValues[i]); } } } /** * Get the value for the given key. This method returns NOT_FOUND if the * entry has not been found. * * @param key the key * @return the value or NOT_FOUND */ public int get(int key) { if (key == 0) { return zeroKey ? zeroValue : NOT_FOUND; } int index = getIndex(key); int plus = 1; do { int k = keys[index]; if (k == 0 && values[index] == 0) { // found an empty record return NOT_FOUND; } else if (k == key) { // found it return values[index]; } index = (index + plus++) & mask; } while (plus <= len); return NOT_FOUND; } }
if (key == 0) { zeroKey = true; zeroValue = value; return; } checkSizePut(); int index = getIndex(key); int plus = 1; int deleted = -1; do { int k = keys[index]; if (k == 0) { if (values[index] != DELETED) { // found an empty record if (deleted >= 0) { index = deleted; deletedCount--; } size++; keys[index] = key; values[index] = value; return; } // found a deleted record if (deleted < 0) { deleted = index; } } else if (k == key) { // update existing values[index] = value; return; } index = (index + plus++) & mask; } while (plus <= len); // no space DbException.throwInternalError("hashmap is full");
734
263
997
<methods>public void <init>() ,public int size() <variables>private static final int MAX_LOAD,protected int deletedCount,protected int len,protected int level,protected int mask,private int maxDeleted,private int maxSize,private int minSize,protected int size,protected boolean zeroKey
lealone_Lealone
Lealone/lealone-db/src/main/java/com/lealone/db/util/SourceCompiler.java
SCJavaFileManager
getJavaFileForOutput
class SCJavaFileManager extends ForwardingJavaFileManager<JavaFileManager> { private final ClassLoader classLoader; protected SCJavaFileManager(JavaFileManager fileManager, ClassLoader classLoader) { super(fileManager); this.classLoader = classLoader; } @Override public ClassLoader getClassLoader(Location location) { return classLoader; } @Override public Iterable<JavaFileObject> list(Location location, String packageName, Set<Kind> kinds, boolean recurse) throws IOException { return super.list(location, packageName, kinds, recurse); } @Override public JavaFileObject getJavaFileForOutput(Location location, String className, Kind kind, FileObject sibling) throws IOException {<FILL_FUNCTION_BODY>} }
if (sibling != null && sibling instanceof SCJavaFileObject) { return ((SCJavaFileObject) sibling).addOutputJavaFile(className); } throw new IOException( "The source file passed to getJavaFileForOutput() is not a SCJavaFileObject: " + sibling);
207
80
287
<no_super_class>
lealone_Lealone
Lealone/lealone-db/src/main/java/com/lealone/db/util/SynchronizedVerifier.java
SynchronizedVerifier
detectConcurrentAccess
class SynchronizedVerifier { private static volatile boolean enabled; private static final Map<Class<?>, AtomicBoolean> DETECT = Collections .synchronizedMap(new HashMap<Class<?>, AtomicBoolean>()); private static final Map<Object, Object> CURRENT = Collections .synchronizedMap(new IdentityHashMap<Object, Object>()); /** * Enable or disable detection for a given class. * * @param clazz the class * @param value the new value (true means detection is enabled) */ public static void setDetect(Class<?> clazz, boolean value) { if (value) { DETECT.put(clazz, new AtomicBoolean()); } else { AtomicBoolean b = DETECT.remove(clazz); if (b == null) { throw new AssertionError("Detection was not enabled"); } else if (!b.get()) { throw new AssertionError("No object of this class was tested"); } } enabled = DETECT.size() > 0; } /** * Verify the object is not accessed concurrently. * * @param o the object */ public static void check(Object o) { if (enabled) { detectConcurrentAccess(o); } } private static void detectConcurrentAccess(Object o) {<FILL_FUNCTION_BODY>} }
AtomicBoolean value = DETECT.get(o.getClass()); if (value != null) { value.set(true); if (CURRENT.remove(o) != null) { throw new AssertionError("Concurrent access"); } CURRENT.put(o, o); try { Thread.sleep(1); } catch (InterruptedException e) { // ignore } Object old = CURRENT.remove(o); if (old == null) { throw new AssertionError("Concurrent access"); } }
375
152
527
<no_super_class>
lealone_Lealone
Lealone/lealone-db/src/main/java/com/lealone/db/util/ValueHashMap.java
ValueHashMap
put
class ValueHashMap<V> extends HashBase { private Value[] keys; private V[] values; /** * Create a new value hash map. * * @return the object */ public static <T> ValueHashMap<T> newInstance() { return new ValueHashMap<T>(); } @Override @SuppressWarnings("unchecked") protected void reset(int newLevel) { super.reset(newLevel); keys = new Value[len]; values = (V[]) new Object[len]; } @Override protected void rehash(int newLevel) { Value[] oldKeys = keys; V[] oldValues = values; reset(newLevel); int len = oldKeys.length; for (int i = 0; i < len; i++) { Value k = oldKeys[i]; if (k != null && k != ValueNull.DELETED) { put(k, oldValues[i]); } } } private int getIndex(Value key) { return key.hashCode() & mask; } /** * Add or update a key value pair. * * @param key the key * @param value the new value */ public void put(Value key, V value) {<FILL_FUNCTION_BODY>} /** * Remove a key value pair. * * @param key the key */ public void remove(Value key) { checkSizeRemove(); int index = getIndex(key); int plus = 1; do { Value k = keys[index]; if (k == null) { // found an empty record return; } else if (k == ValueNull.DELETED) { // found a deleted record } else if (k.equals(key)) { // found the record keys[index] = ValueNull.DELETED; values[index] = null; deletedCount++; size--; return; } index = (index + plus++) & mask; } while (plus <= len); // not found } /** * Get the value for this key. This method returns null if the key was not * found. * * @param key the key * @return the value for the given key */ public V get(Value key) { int index = getIndex(key); int plus = 1; do { Value k = keys[index]; if (k == null) { // found an empty record return null; } else if (k == ValueNull.DELETED) { // found a deleted record } else if (k.equals(key)) { // found it return values[index]; } index = (index + plus++) & mask; } while (plus <= len); return null; } /** * Get the list of keys. * * @return all keys */ public ArrayList<Value> keys() { ArrayList<Value> list = new ArrayList<>(size); for (Value k : keys) { if (k != null && k != ValueNull.DELETED) { list.add(k); } } return list; } /** * Get the list of values. * * @return all values */ public ArrayList<V> values() { ArrayList<V> list = new ArrayList<>(size); int len = keys.length; for (int i = 0; i < len; i++) { Value k = keys[i]; if (k != null && k != ValueNull.DELETED) { list.add(values[i]); } } return list; } }
checkSizePut(); int index = getIndex(key); int plus = 1; int deleted = -1; do { Value k = keys[index]; if (k == null) { // found an empty record if (deleted >= 0) { index = deleted; deletedCount--; } size++; keys[index] = key; values[index] = value; return; } else if (k == ValueNull.DELETED) { // found a deleted record if (deleted < 0) { deleted = index; } } else if (k.equals(key)) { // update existing values[index] = value; return; } index = (index + plus++) & mask; } while (plus <= len); // no space DbException.throwInternalError("hashmap is full");
990
233
1,223
<methods>public void <init>() ,public int size() <variables>private static final int MAX_LOAD,protected int deletedCount,protected int len,protected int level,protected int mask,private int maxDeleted,private int maxSize,private int minSize,protected int size,protected boolean zeroKey
lealone_Lealone
Lealone/lealone-main/src/main/java/com/lealone/main/Shell.java
Shell
getConnection
class Shell extends LealoneClient { public static void main(String[] args) { Shell shell = new Shell(args); main(shell); } public Shell(String[] args) { super(args); } @Override protected Connection getConnection() throws SQLException {<FILL_FUNCTION_BODY>} }
ConnectionInfo ci = getConnectionInfo(); if (ci.isEmbedded()) { Lealone.embed(); } return getConnectionSync(ci);
90
45
135
<methods>public void <init>(java.lang.String[]) ,public java.lang.String[] getArgs() ,public static Future<com.lealone.client.jdbc.JdbcConnection> getConnection(java.lang.String) ,public static Future<com.lealone.client.jdbc.JdbcConnection> getConnection(java.lang.String, java.lang.String, java.lang.String) ,public static Future<com.lealone.client.jdbc.JdbcConnection> getConnection(java.lang.String, java.util.Properties) ,public static Future<com.lealone.client.jdbc.JdbcConnection> getConnection(com.lealone.db.ConnectionInfo) ,public static com.lealone.client.jdbc.JdbcConnection getConnectionSync(com.lealone.db.ConnectionInfo) ,public static void main(java.lang.String[]) ,public static void main(com.lealone.client.LealoneClient) ,public void showClientOrEmbeddedModeOptions() <variables>private static final char BOX_VERTICAL,private static final int HISTORY_COUNT,private static final int MAX_ROW_BUFFER,private final non-sealed java.lang.String[] args,private com.lealone.client.jdbc.JdbcConnection conn,private java.lang.String database,private boolean embedded,private final java.io.PrintStream err,private final ArrayList<java.lang.String> history,private java.lang.String host,private final java.io.InputStream in,private boolean listMode,private int maxColumnSize,private final java.io.PrintStream out,private java.lang.String password,private java.lang.String port,private final java.io.BufferedReader reader,private java.sql.Statement stat,private java.lang.String url,private java.lang.String user
lealone_Lealone
Lealone/lealone-main/src/main/java/com/lealone/main/config/Config.java
Config
mergeEngines
class Config { public String base_dir = "." + File.separator + Constants.PROJECT_NAME + "_data"; public String listen_address = "127.0.0.1"; public List<PluggableEngineDef> storage_engines; public List<PluggableEngineDef> transaction_engines; public List<PluggableEngineDef> sql_engines; public List<PluggableEngineDef> protocol_server_engines; public ServerEncryptionOptions server_encryption_options; public ClientEncryptionOptions client_encryption_options; public SchedulerDef scheduler; public Config() { } public Config(boolean isDefault) { if (!isDefault) return; storage_engines = new ArrayList<>(1); storage_engines.add(createEngineDef(Constants.DEFAULT_STORAGE_ENGINE_NAME, true, true)); transaction_engines = new ArrayList<>(1); transaction_engines.add(createEngineDef(Constants.DEFAULT_TRANSACTION_ENGINE_NAME, true, true)); sql_engines = new ArrayList<>(1); sql_engines.add(createEngineDef(Constants.DEFAULT_SQL_ENGINE_NAME, true, true)); protocol_server_engines = new ArrayList<>(1); protocol_server_engines.add(createEngineDef("TCP", true, false)); scheduler = new SchedulerDef(); scheduler.parameters.put("scheduler_count", Runtime.getRuntime().availableProcessors() + ""); mergeSchedulerParametersToEngines(); } private static PluggableEngineDef createEngineDef(String name, boolean enabled, boolean isDefault) { PluggableEngineDef e = new PluggableEngineDef(); e.name = name; e.enabled = enabled; e.is_default = isDefault; return e; } // 合并scheduler的参数到以下两种引擎,会用到 public void mergeSchedulerParametersToEngines() { for (PluggableEngineDef e : protocol_server_engines) { if (e.enabled) e.parameters.putAll(scheduler.parameters); } for (PluggableEngineDef e : transaction_engines) { if (e.enabled) e.parameters.putAll(scheduler.parameters); } } public void mergeProtocolServerParameters(String name, String host, String port) { if (host == null && port == null) return; Map<String, String> parameters = getProtocolServerParameters(name); if (host != null) parameters.put("host", host); if (port != null) parameters.put("port", port); } public Map<String, String> getProtocolServerParameters(String name) { if (protocol_server_engines != null) { for (PluggableEngineDef def : protocol_server_engines) { if (name.equalsIgnoreCase(def.name)) { return def.parameters; } } } return new HashMap<>(0); } public static String getProperty(String key) { return getProperty(key, null); } public static String getProperty(String key, String def) { return System.getProperty(Constants.PROJECT_NAME_PREFIX + key, def); } public static void setProperty(String key, String value) { System.setProperty(Constants.PROJECT_NAME_PREFIX + key, value); } public static Config getDefaultConfig() { return new Config(true); } public static Config mergeDefaultConfig(Config c) { // c是custom config Config d = getDefaultConfig(); if (c == null) return d; c.storage_engines = mergeEngines(c.storage_engines, d.storage_engines); c.transaction_engines = mergeEngines(c.transaction_engines, d.transaction_engines); c.sql_engines = mergeEngines(c.sql_engines, d.sql_engines); c.protocol_server_engines = mergeEngines(c.protocol_server_engines, d.protocol_server_engines); c.scheduler = mergeMap(d.scheduler, c.scheduler); c.mergeSchedulerParametersToEngines(); return c; } private static List<PluggableEngineDef> mergeEngines(List<PluggableEngineDef> newList, List<PluggableEngineDef> defaultList) {<FILL_FUNCTION_BODY>} private static <T extends MapPropertyTypeDef> T mergeMap(T defaultMap, T newMap) { if (defaultMap == null) return newMap; if (newMap == null) return defaultMap; defaultMap.parameters.putAll(newMap.parameters); return defaultMap; } public static abstract class MapPropertyTypeDef { public String name; public Map<String, String> parameters = new HashMap<>(); public MapPropertyTypeDef() { } public Map<String, String> getParameters() { return parameters; } public void setParameters(Map<String, String> parameters) { this.parameters = parameters; } } public static class SchedulerDef extends MapPropertyTypeDef { } public static class PluggableEngineDef extends MapPropertyTypeDef { public Boolean enabled = true; public Boolean is_default = false; } }
if (defaultList == null) return newList; if (newList == null) return defaultList; LinkedHashMap<String, PluggableEngineDef> map = new LinkedHashMap<>(); for (PluggableEngineDef e : defaultList) { map.put(e.name.toUpperCase(), e); } for (PluggableEngineDef e : newList) { String name = e.name.toUpperCase(); PluggableEngineDef defaultE = map.get(name); if (defaultE == null) { map.put(name, e); } else { defaultE.enabled = e.enabled; defaultE.parameters.putAll(e.parameters); } } return new ArrayList<>(map.values());
1,418
202
1,620
<no_super_class>
lealone_Lealone
Lealone/lealone-main/src/main/java/com/lealone/main/config/YamlConfigLoader.java
YamlConfigLoader
isYamlAvailable
class YamlConfigLoader implements ConfigLoader { private static final Logger logger = LoggerFactory.getLogger(YamlConfigLoader.class); private static URL getConfigURL() throws ConfigException { String configUrl = Config.getProperty("config"); if (configUrl != null) { URL url = getConfigURL(configUrl); if (url != null) return url; logger.warn("Config file not found: " + configUrl); } URL url = getConfigURL("lealone.yaml"); if (url == null) url = getConfigURL("lealone-test.yaml"); return url; } private static URL getConfigURL(String configUrl) throws ConfigException { return Utils.toURL(configUrl); } @Override public void applyConfig(Config config) throws ConfigException { } @Override public Config loadConfig() throws ConfigException { if (isYamlAvailable()) { return YamlLoader.loadConfig(); } else { logger.info("Use default config"); return null; } } private static boolean isYamlAvailable() {<FILL_FUNCTION_BODY>} // 避免对yaml的强依赖 private static class YamlLoader { private static Config loadConfig() throws ConfigException { URL url = getConfigURL(); if (url == null) { logger.info("Use default config"); return null; } try { logger.info("Loading config from {}", url); byte[] configBytes; try (InputStream is = url.openStream()) { configBytes = IOUtils.toByteArray(is); } catch (IOException e) { // getConfigURL should have ruled this out throw new AssertionError(e); } YamlConstructor configConstructor = new YamlConstructor(Config.class); addTypeDescription(configConstructor); MissingPropertiesChecker propertiesChecker = new MissingPropertiesChecker(); configConstructor.setPropertyUtils(propertiesChecker); Yaml yaml = new Yaml(configConstructor); yaml.addImplicitResolver(YamlConstructor.ENV_TAG, YamlConstructor.ENV_FORMAT, "$"); Config result = yaml.loadAs(new ByteArrayInputStream(configBytes), Config.class); propertiesChecker.check(); return result; } catch (YAMLException e) { throw new ConfigException("Invalid yaml", e); } } private static void addTypeDescription(Constructor configConstructor) { TypeDescription mapPropertyTypeDesc = new TypeDescription(MapPropertyTypeDef.class); mapPropertyTypeDesc.addPropertyParameters("parameters", String.class, String.class); configConstructor.addTypeDescription(mapPropertyTypeDesc); } } private static class MissingPropertiesChecker extends PropertyUtils { private final Set<String> missingProperties = new HashSet<>(); public MissingPropertiesChecker() { setSkipMissingProperties(true); } @Override public Property getProperty(Class<? extends Object> type, String name) { Property result = super.getProperty(type, name); if (result instanceof MissingProperty) { missingProperties.add(result.getName()); } return result; } public void check() throws ConfigException { if (!missingProperties.isEmpty()) { throw new ConfigException("Invalid yaml. " // + "Please remove properties " + missingProperties + " from your lealone.yaml"); } } } }
try { Class.forName("org.yaml.snakeyaml.Yaml"); return true; } catch (Exception e) { return false; }
895
49
944
<no_super_class>
lealone_Lealone
Lealone/lealone-main/src/main/java/com/lealone/main/config/YamlConstructor.java
ConstructEnv
construct
class ConstructEnv extends AbstractConstruct { @Override public Object construct(Node node) {<FILL_FUNCTION_BODY>} }
String val = constructScalar((ScalarNode) node); Matcher matcher = ENV_FORMAT.matcher(val); matcher.matches(); String name = matcher.group("name"); String value = matcher.group("value"); String separator = matcher.group("separator"); String suffix = matcher.group("suffix"); return apply(name, separator, (value != null ? value : ""), getEnv(name)) + (suffix != null ? suffix.trim() : "");
37
136
173
<no_super_class>
lealone_Lealone
Lealone/lealone-net/src/main/java/com/lealone/net/AsyncConnection.java
AsyncConnection
close
class AsyncConnection { protected final WritableChannel writableChannel; protected final boolean isServer; protected InetSocketAddress inetSocketAddress; protected boolean closed; public AsyncConnection(WritableChannel writableChannel, boolean isServer) { this.writableChannel = writableChannel; this.isServer = isServer; } public abstract void handle(NetBuffer buffer); public abstract ByteBuffer getPacketLengthByteBuffer(); public abstract int getPacketLength(); public WritableChannel getWritableChannel() { return writableChannel; } public String getHostAndPort() { return writableChannel.getHost() + ":" + writableChannel.getPort(); } public InetSocketAddress getInetSocketAddress() { return inetSocketAddress; } public void setInetSocketAddress(InetSocketAddress inetSocketAddress) { this.inetSocketAddress = inetSocketAddress; } public void close() {<FILL_FUNCTION_BODY>} public boolean isClosed() { return closed; } public void checkClosed() { if (closed) { String msg = "Connection[" + inetSocketAddress.getHostName() + "] is closed"; throw DbException.get(ErrorCode.CONNECTION_BROKEN_1, msg); } } public void handleException(Exception e) { } public void checkTimeout(long currentTime) { } public boolean isShared() { return false; } public int getSharedSize() { return 0; } public int getMaxSharedSize() { return 0; } public boolean isServer() { return isServer; } }
closed = true; if (writableChannel != null) { writableChannel.close(); }
463
32
495
<no_super_class>
lealone_Lealone
Lealone/lealone-net/src/main/java/com/lealone/net/AsyncConnectionPool.java
AsyncConnectionPool
getConnection
class AsyncConnectionPool { private final List<AsyncConnection> list; public AsyncConnectionPool(boolean isThreadSafe) { list = isThreadSafe ? new ArrayList<>() : new CopyOnWriteArrayList<>(); } public AsyncConnection getConnection(Map<String, String> config) {<FILL_FUNCTION_BODY>} public void addConnection(AsyncConnection conn) { list.add(conn); } public void removeConnection(AsyncConnection conn) { list.remove(conn); } public boolean isEmpty() { return list.isEmpty(); } public void close() { for (AsyncConnection c : list) { try { c.close(); } catch (Throwable e) { } } list.clear(); } public void checkTimeout(long currentTime) { for (AsyncConnection c : list) { c.checkTimeout(currentTime); } } public static int getMaxSharedSize(Map<String, String> config) { if (isShared(config)) return MapUtils.getInt(config, ConnectionSetting.MAX_SHARED_SIZE.name(), 3); else return 1; // 独享模式 } public static boolean isShared(Map<String, String> config) { // 为null时默认是共享模式 return MapUtils.getBoolean(config, ConnectionSetting.IS_SHARED.name(), true); } }
if (!isShared(config)) { // 专用连接如果空闲了也可以直接复用 for (AsyncConnection c : list) { if (c.getMaxSharedSize() == 1 && c.getSharedSize() == 0) return c; } return null; } AsyncConnection best = null; int min = Integer.MAX_VALUE; for (AsyncConnection c : list) { int maxSharedSize = c.getMaxSharedSize(); if (maxSharedSize == 1) continue; int size = c.getSharedSize(); if (maxSharedSize > 0 && size >= maxSharedSize) continue; if (size < min) { best = c; min = size; } } return best;
381
200
581
<no_super_class>
lealone_Lealone
Lealone/lealone-net/src/main/java/com/lealone/net/NetBuffer.java
NetBuffer
length
class NetBuffer { private final DataBuffer dataBuffer; private boolean onlyOnePacket; private boolean forWrite; public NetBuffer(DataBuffer dataBuffer) { this.dataBuffer = dataBuffer; this.forWrite = true; } public NetBuffer(DataBuffer dataBuffer, boolean onlyOnePacket) { this.dataBuffer = dataBuffer; this.onlyOnePacket = onlyOnePacket; } public ByteBuffer getAndFlipBuffer() { return dataBuffer.getAndFlipBuffer(); } public ByteBuffer getByteBuffer() { return dataBuffer.getBuffer(); } public int length() {<FILL_FUNCTION_BODY>} public short getUnsignedByte(int pos) { return dataBuffer.getUnsignedByte(pos); } public void read(byte[] dst, int off, int len) { dataBuffer.read(dst, off, len); } public NetBuffer appendByte(byte b) { dataBuffer.put(b); return this; } public NetBuffer appendBytes(byte[] bytes, int offset, int len) { dataBuffer.put(bytes, offset, len); return this; } public NetBuffer appendInt(int i) { dataBuffer.putInt(i); return this; } public NetBuffer setByte(int pos, byte b) { dataBuffer.putByte(pos, b); return this; } public boolean isOnlyOnePacket() { return onlyOnePacket; } public void recycle() { if (onlyOnePacket || forWrite) dataBuffer.close(); } public NetBuffer flip() { dataBuffer.getAndFlipBuffer(); return this; } }
if (forWrite) return dataBuffer.position(); if (onlyOnePacket) return dataBuffer.limit(); int pos = dataBuffer.position(); if (pos > 0) return pos; else return dataBuffer.limit();
473
69
542
<no_super_class>
lealone_Lealone
Lealone/lealone-net/src/main/java/com/lealone/net/NetBufferOutputStream.java
NetBufferOutputStream
flush
class NetBufferOutputStream extends OutputStream { protected final WritableChannel writableChannel; protected final int initialSizeHint; protected final DataBufferFactory dataBufferFactory; protected NetBuffer buffer; public NetBufferOutputStream(WritableChannel writableChannel, int initialSizeHint, DataBufferFactory dataBufferFactory) { this.writableChannel = writableChannel; this.initialSizeHint = initialSizeHint; this.dataBufferFactory = dataBufferFactory; reset(); } @Override public void write(int b) { buffer.appendByte((byte) b); } @Override public void write(byte b[], int off, int len) { buffer.appendBytes(b, off, len); } @Override public void flush() throws IOException { flush(true); } public void flush(boolean reset) throws IOException {<FILL_FUNCTION_BODY>} protected void reset() { buffer = writableChannel.getBufferFactory().createBuffer(initialSizeHint, dataBufferFactory); } }
buffer.flip(); if (reset) { NetBuffer old = buffer; reset(); writableChannel.write(old); // 警告: 不能像下面这样用,调用write后会很快写数据到接收端,然后另一个线程很快又收到响应, // 在调用reset前又继续用原来的buffer写,从而导致产生非常难找的协议与并发问题,我就为这个问题痛苦排查过大半天。 // writableChannel.write(buffer); // reset(); } else { writableChannel.write(buffer); buffer = null; }
279
158
437
<methods>public void <init>() ,public void close() throws java.io.IOException,public void flush() throws java.io.IOException,public static java.io.OutputStream nullOutputStream() ,public abstract void write(int) throws java.io.IOException,public void write(byte[]) throws java.io.IOException,public void write(byte[], int, int) throws java.io.IOException<variables>
lealone_Lealone
Lealone/lealone-net/src/main/java/com/lealone/net/NetClientBase.java
NetClientBase
initSocket
class NetClientBase implements NetClient { // 使用InetSocketAddress为key而不是字符串,是因为像localhost和127.0.0.1这两种不同格式实际都是同一个意思, // 如果用字符串,就会产生两条AsyncConnection,这是没必要的。 private final Map<InetSocketAddress, AsyncConnectionPool> asyncConnections; private final AtomicBoolean closed = new AtomicBoolean(false); private final boolean isThreadSafe; public NetClientBase(boolean isThreadSafe) { asyncConnections = isThreadSafe ? new HashMap<>() : new ConcurrentHashMap<>(); this.isThreadSafe = isThreadSafe; ShutdownHookUtils.addShutdownHook(this, () -> { close(); }); } @Override public boolean isThreadSafe() { return isThreadSafe; } protected abstract void createConnectionInternal(Map<String, String> config, NetNode node, // AsyncConnectionManager connectionManager, AsyncCallback<AsyncConnection> ac, Scheduler scheduler); @Override public Future<AsyncConnection> createConnection(Map<String, String> config, NetNode node, AsyncConnectionManager connectionManager, Scheduler scheduler) { InetSocketAddress inetSocketAddress = node.getInetSocketAddress(); AsyncConnection asyncConnection = getConnection(config, inetSocketAddress); if (asyncConnection == null) { AsyncCallback<AsyncConnection> ac = AsyncCallback.create(true); createConnectionInternal(config, node, connectionManager, ac, scheduler); return ac; } else { return Future.succeededFuture(asyncConnection); } } private AsyncConnection getConnection(Map<String, String> config, InetSocketAddress inetSocketAddress) { AsyncConnectionPool pool = asyncConnections.get(inetSocketAddress); return pool == null ? null : pool.getConnection(config); } @Override public void removeConnection(AsyncConnection conn) { if (conn == null) return; AsyncConnectionPool pool = asyncConnections.get(conn.getInetSocketAddress()); if (pool != null) { pool.removeConnection(conn); if (pool.isEmpty()) { asyncConnections.remove(conn.getInetSocketAddress()); } } if (!conn.isClosed()) conn.close(); } @Override public void addConnection(InetSocketAddress inetSocketAddress, AsyncConnection conn) { checkClosed(); AsyncConnectionPool pool = asyncConnections.get(inetSocketAddress); if (pool == null) { pool = new AsyncConnectionPool(isThreadSafe); AsyncConnectionPool old = asyncConnections.putIfAbsent(inetSocketAddress, pool); if (old != null) pool = old; } pool.addConnection(conn); } @Override public boolean isClosed() { return closed.get(); } @Override public void close() { if (!closed.compareAndSet(false, true)) return; for (AsyncConnectionPool pool : asyncConnections.values()) { pool.close(); } asyncConnections.clear(); } protected void checkClosed() { if (isClosed()) { throw new RuntimeException("NetClient is closed"); } } @Override public void checkTimeout(long currentTime) { if (!asyncConnections.isEmpty()) { for (AsyncConnectionPool pool : asyncConnections.values()) { pool.checkTimeout(currentTime); } } } protected void initSocket(Socket socket, Map<String, String> config) throws SocketException {<FILL_FUNCTION_BODY>} public static class ClientAttachment extends NioAttachment { public AsyncConnectionManager connectionManager; public InetSocketAddress inetSocketAddress; public AsyncCallback<AsyncConnection> ac; public int maxSharedSize; } }
int socketRecvBuffer = MapUtils.getInt(config, ConnectionSetting.SOCKET_RECV_BUFFER_SIZE.name(), 16 * 1024); int socketSendBuffer = MapUtils.getInt(config, ConnectionSetting.SOCKET_SEND_BUFFER_SIZE.name(), 8 * 1024); socket.setReceiveBufferSize(socketRecvBuffer); socket.setSendBufferSize(socketSendBuffer); socket.setTcpNoDelay(true); socket.setKeepAlive(true); socket.setReuseAddress(true);
1,022
151
1,173
<no_super_class>
lealone_Lealone
Lealone/lealone-net/src/main/java/com/lealone/net/NetScheduler.java
NetScheduler
runEventLoop
class NetScheduler extends SchedulerBase { protected final NetEventLoop netEventLoop; public NetScheduler(int id, String name, int schedulerCount, Map<String, String> config, boolean isThreadSafe) { super(id, name, schedulerCount, config); netEventLoop = NetFactory.getFactory(config).createNetEventLoop(loopInterval, isThreadSafe); netEventLoop.setScheduler(this); } @Override public DataBufferFactory getDataBufferFactory() { return netEventLoop.getDataBufferFactory(); } @Override public NetEventLoop getNetEventLoop() { return netEventLoop; } @Override public Selector getSelector() { return netEventLoop.getSelector(); } @Override public void registerAccepter(ProtocolServer server, ServerSocketChannel serverChannel) { DbException.throwInternalError(); } // --------------------- 网络事件循环 --------------------- @Override public void wakeUp() { netEventLoop.wakeup(); } @Override protected void runEventLoop() {<FILL_FUNCTION_BODY>} @Override protected void onStopped() { super.onStopped(); netEventLoop.close(); } }
try { netEventLoop.write(); netEventLoop.select(); netEventLoop.handleSelectedKeys(); } catch (Throwable t) { getLogger().warn("Failed to runEventLoop", t); }
338
61
399
<methods>public void <init>(int, java.lang.String, int, Map<java.lang.String,java.lang.String>) ,public void accept(java.nio.channels.SelectionKey) ,public void addPendingTransaction(com.lealone.transaction.PendingTransaction) ,public void addPeriodicTask(com.lealone.db.async.AsyncPeriodicTask) ,public void addSession(com.lealone.db.session.Session) ,public void addSessionInfo(java.lang.Object) ,public void addSessionInitTask(java.lang.Object) ,public void addWaitingScheduler(com.lealone.db.scheduler.Scheduler) ,public SchedulerListener<R> createSchedulerListener() ,public void executeNextStatement() ,public com.lealone.db.session.Session getCurrentSession() ,public com.lealone.db.DataBufferFactory getDataBufferFactory() ,public com.lealone.storage.fs.FileStorage getFsyncingFileStorage() ,public int getId() ,public long getLoad() ,public java.lang.String getName() ,public java.lang.Object getNetEventLoop() ,public com.lealone.transaction.PendingTransaction getPendingTransaction() ,public com.lealone.db.scheduler.SchedulerFactory getSchedulerFactory() ,public java.nio.channels.Selector getSelector() ,public com.lealone.db.scheduler.SchedulerThread getThread() ,public void handlePageOperation(com.lealone.storage.page.PageOperation) ,public boolean isFsyncDisabled() ,public boolean isStarted() ,public boolean isStopped() ,public void registerAccepter(com.lealone.server.ProtocolServer, java.nio.channels.ServerSocketChannel) ,public void removePeriodicTask(com.lealone.db.async.AsyncPeriodicTask) ,public void removeSession(com.lealone.db.session.Session) ,public void removeSessionInfo(java.lang.Object) ,public void setCurrentSession(com.lealone.db.session.Session) ,public void setFsyncDisabled(boolean) ,public void setFsyncingFileStorage(com.lealone.storage.fs.FileStorage) ,public void setSchedulerFactory(com.lealone.db.scheduler.SchedulerFactory) ,public synchronized void start() ,public synchronized void stop() ,public java.lang.String toString() ,public void validateSession(boolean) ,public void wakeUpWaitingSchedulers() ,public void wakeUpWaitingSchedulers(boolean) ,public boolean yieldIfNeeded(com.lealone.sql.PreparedSQLStatement) <variables>protected com.lealone.db.session.Session currentSession,protected boolean fsyncDisabled,protected com.lealone.storage.fs.FileStorage fsyncingFileStorage,protected final java.util.concurrent.atomic.AtomicBoolean hasWaitingSchedulers,protected final non-sealed int id,protected final non-sealed long loopInterval,protected final non-sealed java.lang.String name,protected final LinkableList<com.lealone.transaction.PendingTransaction> pendingTransactions,protected final LinkableList<com.lealone.db.async.AsyncPeriodicTask> periodicTasks,protected com.lealone.db.scheduler.SchedulerFactory schedulerFactory,protected boolean started,protected boolean stopped,protected com.lealone.db.scheduler.SchedulerThread thread,protected final non-sealed AtomicReferenceArray<com.lealone.db.scheduler.Scheduler> waitingSchedulers
lealone_Lealone
Lealone/lealone-net/src/main/java/com/lealone/net/NetServerBase.java
NetServerBase
checkBindException
class NetServerBase extends ProtocolServerBase implements NetServer { protected AsyncConnectionManager connectionManager; @Override public void setConnectionManager(AsyncConnectionManager connectionManager) { this.connectionManager = connectionManager; } private void check() { if (connectionManager == null) throw DbException.getInternalError("connectionManager is null"); } public AsyncConnection createConnection(WritableChannel writableChannel, Scheduler scheduler) { check(); return connectionManager.createConnection(writableChannel, true, scheduler); } public void removeConnection(AsyncConnection conn) { check(); connectionManager.removeConnection(conn); } protected void checkBindException(Throwable e, String message) {<FILL_FUNCTION_BODY>} }
String address = host + ":" + port; if (e instanceof BindException) { if (e.getMessage().contains("in use")) { message += ", " + address + " is in use by another process. Change host:port in lealone.yaml " + "to values that do not conflict with other services."; e = null; } else if (e.getMessage().contains("Cannot assign requested address")) { message += ". Unable to bind to address " + address + ". Set host:port in lealone.yaml to an interface you can bind to, e.g.," + " your private IP address."; e = null; } } if (e == null) throw new ConfigException(message); else throw new ConfigException(message, e);
205
202
407
<methods>public boolean allow(java.lang.String) ,public boolean getAllowOthers() ,public java.lang.String getBaseDir() ,public Map<java.lang.String,java.lang.String> getConfig() ,public java.lang.String getHost() ,public java.lang.String getName() ,public int getPort() ,public com.lealone.common.security.EncryptionOptions.ServerEncryptionOptions getServerEncryptionOptions() ,public int getSessionTimeout() ,public java.lang.String getType() ,public java.lang.String getURL() ,public void init(Map<java.lang.String,java.lang.String>) ,public boolean isDaemon() ,public boolean isSSL() ,public boolean isStarted() ,public boolean isStopped() ,public void setServerEncryptionOptions(com.lealone.common.security.EncryptionOptions.ServerEncryptionOptions) ,public synchronized void start() ,public synchronized void stop() <variables>protected boolean allowOthers,protected java.lang.String baseDir,protected Map<java.lang.String,java.lang.String> config,protected boolean daemon,protected java.lang.String host,protected java.lang.String name,protected int port,protected com.lealone.common.security.EncryptionOptions.ServerEncryptionOptions serverEncryptionOptions,protected int sessionTimeout,protected boolean ssl,protected boolean started,protected boolean stopped,protected HashSet<java.lang.String> whiteList
lealone_Lealone
Lealone/lealone-net/src/main/java/com/lealone/net/TcpClientConnection.java
TcpClientConnection
handleResponse
class TcpClientConnection extends TransferConnection { private static final Logger logger = LoggerFactory.getLogger(TcpClientConnection.class); private final Map<Integer, Session> sessions; private final Map<Integer, AsyncCallback<?>> callbackMap; private final AtomicInteger nextId = new AtomicInteger(0); private final int maxSharedSize; private final NetClient netClient; private Throwable pendingException; public TcpClientConnection(WritableChannel writableChannel, NetClient netClient, int maxSharedSize) { super(writableChannel, false); this.netClient = netClient; this.maxSharedSize = maxSharedSize; if (netClient.isThreadSafe()) { sessions = new HashMap<>(); callbackMap = new HashMap<>(); } else { sessions = new ConcurrentHashMap<>(); callbackMap = new ConcurrentHashMap<>(); } } public int getNextId() { return nextId.incrementAndGet(); } public int getCurrentId() { return nextId.get(); } @Override public void addAsyncCallback(int packetId, AsyncCallback<?> ac) { callbackMap.put(packetId, ac); } public void removeAsyncCallback(int packetId) { callbackMap.remove(packetId); } @Override public void close() { // 如果还有回调未处理需要设置异常,避免等待回调结果的线程一直死等 if (!callbackMap.isEmpty()) { DbException e; if (pendingException != null) { e = DbException.convert(pendingException); pendingException = null; } else { e = DbException.get(ErrorCode.CONNECTION_BROKEN_1, "unexpected status " + Session.STATUS_CLOSED); } for (AsyncCallback<?> callback : callbackMap.values()) { callback.setDbException(e, true); } } super.close(); for (Session s : sessions.values()) { try { s.close(); } catch (Exception e) { // 忽略异常 } } sessions.clear(); } private Session getSession(int sessionId) { return sessions.get(sessionId); } public void addSession(int sessionId, Session session) { sessions.put(sessionId, session); } public Session removeSession(int sessionId) { Session session = sessions.remove(sessionId); // 不在这里删除连接,这会导致很多问题 // if (netClient != null && sessions.isEmpty()) { // netClient.removeConnection(inetSocketAddress); // } return session; } @Override protected void handleResponse(TransferInputStream in, int packetId, int status) throws IOException {<FILL_FUNCTION_BODY>} @Override public void handleException(Exception e) { pendingException = e; netClient.removeConnection(this); } public Throwable getPendingException() { return pendingException; } @Override public void checkTimeout(long currentTime) { for (AsyncCallback<?> ac : callbackMap.values()) { ac.checkTimeout(currentTime); } } @Override public boolean isShared() { return true; } @Override public int getSharedSize() { return sessions.size(); } @Override public int getMaxSharedSize() { return maxSharedSize; } }
checkClosed(); String newTargetNodes = null; Session session = null; DbException e = null; if (status == Session.STATUS_OK) { // ok } else if (status == Session.STATUS_ERROR) { e = parseError(in); } else if (status == Session.STATUS_CLOSED) { in = null; } else if (status == Session.STATUS_RUN_MODE_CHANGED) { int sessionId = in.readInt(); session = getSession(sessionId); newTargetNodes = in.readString(); } else { e = DbException.get(ErrorCode.CONNECTION_BROKEN_1, "unexpected status " + status); } AsyncCallback<?> ac = callbackMap.remove(packetId); if (ac == null) { String msg = "Async callback is null, may be a bug! packetId = " + packetId; if (e != null) { logger.warn(msg, e); } else { logger.warn(msg); } return; } if (e != null) ac.setAsyncResult(e); else ac.run(in); if (newTargetNodes != null) session.runModeChanged(newTargetNodes);
931
340
1,271
<methods>public void <init>(com.lealone.net.WritableChannel, boolean) ,public com.lealone.net.TransferOutputStream createTransferOutputStream(com.lealone.db.session.Session) ,public com.lealone.db.DataBufferFactory getDataBufferFactory() ,public int getPacketLength() ,public java.nio.ByteBuffer getPacketLengthByteBuffer() ,public int getPacketLengthByteBufferCapacity() ,public void handle(com.lealone.net.NetBuffer) ,public void sendError(com.lealone.db.session.Session, int, java.lang.Throwable) <variables>private static final com.lealone.common.logging.Logger logger,protected final java.nio.ByteBuffer packetLengthByteBuffer
lealone_Lealone
Lealone/lealone-net/src/main/java/com/lealone/net/TransferConnection.java
TransferConnection
parseError
class TransferConnection extends AsyncConnection { private static final Logger logger = LoggerFactory.getLogger(TransferConnection.class); protected final ByteBuffer packetLengthByteBuffer = ByteBuffer .allocate(getPacketLengthByteBufferCapacity()); public TransferConnection(WritableChannel writableChannel, boolean isServer) { super(writableChannel, isServer); } public DataBufferFactory getDataBufferFactory() { return writableChannel.getDataBufferFactory(); } public int getPacketLengthByteBufferCapacity() { return 4; } @Override public ByteBuffer getPacketLengthByteBuffer() { return packetLengthByteBuffer; } @Override public int getPacketLength() { return packetLengthByteBuffer.getInt(); } public TransferOutputStream createTransferOutputStream(Session session) { return new TransferOutputStream(session, writableChannel, getDataBufferFactory()); } protected void handleRequest(TransferInputStream in, int packetId, int packetType) throws IOException { throw DbException.getInternalError("handleRequest"); } protected void handleResponse(TransferInputStream in, int packetId, int status) throws IOException { throw DbException.getInternalError("handleResponse"); } protected void addAsyncCallback(int packetId, AsyncCallback<?> ac) { throw DbException.getInternalError("addAsyncCallback"); } protected static DbException parseError(TransferInputStream in) {<FILL_FUNCTION_BODY>} public void sendError(Session session, int packetId, Throwable t) { try { SQLException e = DbException.convert(t).getSQLException(); StringWriter writer = new StringWriter(); e.printStackTrace(new PrintWriter(writer)); String trace = writer.toString(); String message; String sql; if (e instanceof JdbcSQLException) { JdbcSQLException j = (JdbcSQLException) e; message = j.getOriginalMessage(); sql = j.getSQL(); } else { message = e.getMessage(); sql = null; } TransferOutputStream out = createTransferOutputStream(session); out.writeResponseHeader(packetId, Session.STATUS_ERROR); out.writeString(e.getSQLState()).writeString(message).writeString(sql) .writeInt(e.getErrorCode()).writeString(trace).flush(); } catch (Exception e2) { if (session != null) session.close(); else if (writableChannel != null) { writableChannel.close(); } logger.error("Failed to send error", e2); } } @Override public void handle(NetBuffer buffer) { if (!buffer.isOnlyOnePacket()) { DbException.throwInternalError("NetBuffer must be OnlyOnePacket"); } try { TransferInputStream in = new TransferInputStream(buffer); boolean isRequest = in.readByte() == TransferOutputStream.REQUEST; int packetId = in.readInt(); if (isRequest) { int packetType = in.readInt(); handleRequest(in, packetId, packetType); } else { int status = in.readInt(); handleResponse(in, packetId, status); } } catch (Throwable e) { if (isServer) logger.error("Failed to handle packet", e); else throw DbException.convert(e); } } }
Throwable t; try { String sqlState = in.readString(); String message = in.readString(); String sql = in.readString(); int errorCode = in.readInt(); String stackTrace = in.readString(); JdbcSQLException s = new JdbcSQLException(message, sql, sqlState, errorCode, null, stackTrace); t = s; if (errorCode == ErrorCode.CONNECTION_BROKEN_1) { IOException e = new IOException(s.toString()); e.initCause(s); t = e; } } catch (Exception e) { t = e; } return DbException.convert(t);
899
186
1,085
<methods>public void <init>(com.lealone.net.WritableChannel, boolean) ,public void checkClosed() ,public void checkTimeout(long) ,public void close() ,public java.lang.String getHostAndPort() ,public java.net.InetSocketAddress getInetSocketAddress() ,public int getMaxSharedSize() ,public abstract int getPacketLength() ,public abstract java.nio.ByteBuffer getPacketLengthByteBuffer() ,public int getSharedSize() ,public com.lealone.net.WritableChannel getWritableChannel() ,public abstract void handle(com.lealone.net.NetBuffer) ,public void handleException(java.lang.Exception) ,public boolean isClosed() ,public boolean isServer() ,public boolean isShared() ,public void setInetSocketAddress(java.net.InetSocketAddress) <variables>protected boolean closed,protected java.net.InetSocketAddress inetSocketAddress,protected final non-sealed boolean isServer,protected final non-sealed com.lealone.net.WritableChannel writableChannel
lealone_Lealone
Lealone/lealone-net/src/main/java/com/lealone/net/TransferInputStream.java
DataReader
readChar
class DataReader extends Reader { private final InputStream in; /** * Create a new data reader. * * @param in the input stream */ public DataReader(InputStream in) { this.in = in; } /** * Read a byte. * * @return the byte */ private byte readByte() throws IOException { int x = in.read(); if (x < 0) { throw new FastEOFException(); } return (byte) x; } /** * Read one character from the input stream. * * @return the character */ private char readChar() throws IOException {<FILL_FUNCTION_BODY>} @Override public void close() throws IOException { // ignore } @Override public int read(char[] buff, int off, int len) throws IOException { int i = 0; try { for (; i < len; i++) { buff[i] = readChar(); } return len; } catch (EOFException e) { return i; } } }
int x = readByte() & 0xff; if (x < 0x80) { return (char) x; } else if (x >= 0xe0) { return (char) (((x & 0xf) << 12) + ((readByte() & 0x3f) << 6) + (readByte() & 0x3f)); } else { return (char) (((x & 0x1f) << 6) + (readByte() & 0x3f)); }
301
134
435
<no_super_class>
lealone_Lealone
Lealone/lealone-net/src/main/java/com/lealone/net/bio/BioNetClient.java
BioNetClient
createConnectionInternal
class BioNetClient extends NetClientBase { public BioNetClient() { super(true); } @Override protected void createConnectionInternal(Map<String, String> config, NetNode node, AsyncConnectionManager connectionManager, AsyncCallback<AsyncConnection> ac, Scheduler scheduler) {<FILL_FUNCTION_BODY>} }
InetSocketAddress inetSocketAddress = node.getInetSocketAddress(); int networkTimeout = MapUtils.getInt(config, ConnectionSetting.NETWORK_TIMEOUT.name(), Constants.DEFAULT_NETWORK_TIMEOUT); Socket socket = null; try { socket = new Socket(); socket.setSoTimeout(networkTimeout); initSocket(socket, config); socket.connect(inetSocketAddress, networkTimeout); AsyncConnection conn; BioWritableChannel writableChannel = new BioWritableChannel(config, socket, inetSocketAddress); if (connectionManager != null) { conn = connectionManager.createConnection(writableChannel, false, null); } else { conn = new TcpClientConnection(writableChannel, this, 1); } conn.setInetSocketAddress(inetSocketAddress); addConnection(inetSocketAddress, conn); ac.setAsyncResult(conn); } catch (Exception e) { if (socket != null) { try { socket.close(); } catch (Throwable t) { } } ac.setAsyncResult(e); }
94
299
393
<methods>public void <init>(boolean) ,public void addConnection(java.net.InetSocketAddress, com.lealone.net.AsyncConnection) ,public void checkTimeout(long) ,public void close() ,public Future<com.lealone.net.AsyncConnection> createConnection(Map<java.lang.String,java.lang.String>, com.lealone.net.NetNode, com.lealone.net.AsyncConnectionManager, com.lealone.db.scheduler.Scheduler) ,public boolean isClosed() ,public boolean isThreadSafe() ,public void removeConnection(com.lealone.net.AsyncConnection) <variables>private final non-sealed Map<java.net.InetSocketAddress,com.lealone.net.AsyncConnectionPool> asyncConnections,private final java.util.concurrent.atomic.AtomicBoolean closed,private final non-sealed boolean isThreadSafe
lealone_Lealone
Lealone/lealone-net/src/main/java/com/lealone/net/bio/BioWritableChannel.java
BioWritableChannel
write
class BioWritableChannel implements WritableChannel { private final String host; private final int port; private final int maxPacketSize; private Socket socket; private DataInputStream in; private DataOutputStream out; private DataBuffer dataBuffer; public BioWritableChannel(Map<String, String> config, Socket socket, InetSocketAddress address) throws IOException { host = address.getHostString(); port = address.getPort(); maxPacketSize = getMaxPacketSize(config); this.socket = socket; in = new DataInputStream(new BufferedInputStream(socket.getInputStream(), 64 * 1024)); out = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream(), 64 * 1024)); } public DataBuffer getDataBuffer(int capacity) { if (dataBuffer == null) { dataBuffer = DataBuffer.create(null, capacity, false); } else if (dataBuffer.capacity() > 8096) dataBuffer = DataBuffer.create(null, 8096, false); dataBuffer.clear(); return dataBuffer; } @Override public void write(NetBuffer data) {<FILL_FUNCTION_BODY>} @Override public void close() { if (socket != null) { try { socket.close(); } catch (Throwable t) { } socket = null; in = null; out = null; } } @Override public String getHost() { return host; } @Override public int getPort() { return port; } @Override public NetBufferFactory getBufferFactory() { return NetBufferFactory.getInstance(); } @Override public boolean isBio() { return true; } @Override public void read(AsyncConnection conn) { try { if (conn.isClosed()) return; int packetLength = in.readInt(); checkPacketLength(maxPacketSize, packetLength); DataBuffer dataBuffer = getDataBuffer(packetLength); // 返回的DatBuffer的Capacity可能大于packetLength,所以设置一下limit,不会多读 dataBuffer.limit(packetLength); ByteBuffer buffer = dataBuffer.getBuffer(); in.read(buffer.array(), buffer.arrayOffset(), packetLength); NetBuffer netBuffer = new NetBuffer(dataBuffer, true); conn.handle(netBuffer); } catch (Exception e) { conn.handleException(e); } } @Override public DataBufferFactory getDataBufferFactory() { return new BioDataBufferFactory(this); } public static int getMaxPacketSize(Map<String, String> config) { return MapUtils.getInt(config, ConnectionSetting.MAX_PACKET_SIZE.name(), 16 * 1024 * 1024); } public static void checkPacketLength(int maxPacketSize, int packetLength) throws IOException { if (packetLength > maxPacketSize) throw new IOException( "Packet too large, maxPacketSize: " + maxPacketSize + ", receive: " + packetLength); } }
ByteBuffer bb = data.getByteBuffer(); try { if (bb.hasArray()) { out.write(bb.array(), bb.arrayOffset(), bb.limit()); } else { byte[] bytes = new byte[bb.limit()]; bb.get(bytes); out.write(bytes); } out.flush(); } catch (IOException e) { throw DbException.convert(e); }
849
119
968
<no_super_class>
lealone_Lealone
Lealone/lealone-net/src/main/java/com/lealone/net/nio/NioNetClient.java
NioNetClient
createConnectionInternal
class NioNetClient extends NetClientBase { public NioNetClient() { super(false); } @Override protected void createConnectionInternal(Map<String, String> config, NetNode node, // AsyncConnectionManager connectionManager, AsyncCallback<AsyncConnection> ac, Scheduler scheduler) {<FILL_FUNCTION_BODY>} }
InetSocketAddress inetSocketAddress = node.getInetSocketAddress(); SocketChannel channel = null; NetEventLoop eventLoop = (NetEventLoop) scheduler.getNetEventLoop(); try { channel = SocketChannel.open(); channel.configureBlocking(false); initSocket(channel.socket(), config); ClientAttachment attachment = new ClientAttachment(); attachment.connectionManager = connectionManager; attachment.inetSocketAddress = inetSocketAddress; attachment.ac = ac; attachment.maxSharedSize = AsyncConnectionPool.getMaxSharedSize(config); channel.register(eventLoop.getSelector(), SelectionKey.OP_CONNECT, attachment); channel.connect(inetSocketAddress); // 如果前面已经在执行事件循环,此时就不能再次进入事件循环 // 否则两次删除SelectionKey会出现java.util.ConcurrentModificationException if (!eventLoop.isInLoop()) { if (eventLoop.getSelector().selectNow() > 0) { eventLoop.handleSelectedKeys(); } } } catch (Exception e) { eventLoop.closeChannel(channel); ac.setAsyncResult(e); }
97
300
397
<methods>public void <init>(boolean) ,public void addConnection(java.net.InetSocketAddress, com.lealone.net.AsyncConnection) ,public void checkTimeout(long) ,public void close() ,public Future<com.lealone.net.AsyncConnection> createConnection(Map<java.lang.String,java.lang.String>, com.lealone.net.NetNode, com.lealone.net.AsyncConnectionManager, com.lealone.db.scheduler.Scheduler) ,public boolean isClosed() ,public boolean isThreadSafe() ,public void removeConnection(com.lealone.net.AsyncConnection) <variables>private final non-sealed Map<java.net.InetSocketAddress,com.lealone.net.AsyncConnectionPool> asyncConnections,private final java.util.concurrent.atomic.AtomicBoolean closed,private final non-sealed boolean isThreadSafe
lealone_Lealone
Lealone/lealone-net/src/main/java/com/lealone/net/nio/NioServerAccepter.java
NioServerAccepter
accept
class NioServerAccepter extends NetServerBase { private static final Logger logger = LoggerFactory.getLogger(NioServerAccepter.class); private ServerSocketChannel serverChannel; @Override public synchronized void start() { if (isStarted()) return; super.start(); try { serverChannel = ServerSocketChannel.open(); serverChannel.socket().bind(new InetSocketAddress(getHost(), getPort())); serverChannel.configureBlocking(false); connectionManager.registerAccepter(serverChannel); } catch (Exception e) { checkBindException(e, "Failed to start protocol server accepter"); } } @Override public synchronized void stop() { if (isStopped()) return; super.stop(); if (serverChannel != null) { try { serverChannel.close(); serverChannel = null; } catch (Throwable e) { } } } @Override public void accept(Scheduler scheduler) {<FILL_FUNCTION_BODY>} }
SocketChannel channel = null; AsyncConnection conn = null; try { channel = serverChannel.accept(); channel.configureBlocking(false); NioWritableChannel writableChannel = new NioWritableChannel(channel, null); conn = createConnection(writableChannel, scheduler); } catch (Throwable e) { if (conn != null) { removeConnection(conn); } NioEventLoop.closeChannelSilently(channel); // 按Ctrl+C退出时accept可能抛出异常,此时就不需要记录日志了 if (!isStopped()) { logger.warn(getName() + " failed to accept connection", e); } }
284
182
466
<methods>public non-sealed void <init>() ,public com.lealone.net.AsyncConnection createConnection(com.lealone.net.WritableChannel, com.lealone.db.scheduler.Scheduler) ,public void removeConnection(com.lealone.net.AsyncConnection) ,public void setConnectionManager(com.lealone.net.AsyncConnectionManager) <variables>protected com.lealone.net.AsyncConnectionManager connectionManager
lealone_Lealone
Lealone/lealone-server/src/main/java/com/lealone/server/AsyncServer.java
AsyncServer
register
class AsyncServer<T extends AsyncConnection> extends DelegatedProtocolServer implements AsyncConnectionManager { private final AtomicInteger connectionSize = new AtomicInteger(); private SchedulerFactory schedulerFactory; private int serverId; public SchedulerFactory getSchedulerFactory() { return schedulerFactory; } public int getServerId() { return serverId; } @Override public void init(Map<String, String> config) { if (!config.containsKey("port")) config.put("port", String.valueOf(getDefaultPort())); if (!config.containsKey("name")) config.put("name", getName()); serverId = AsyncServerManager.allocateServerId(); AsyncServerManager.addServer(this); NetFactory factory = NetFactory.getFactory(config); NetServer netServer = factory.createNetServer(); netServer.setConnectionManager(this); setProtocolServer(netServer); netServer.init(config); schedulerFactory = SchedulerFactory.initDefaultSchedulerFactory(GlobalScheduler.class.getName(), config); } @Override public synchronized void start() { if (isStarted()) return; super.start(); ProtocolServerEngine.startedServers.add(this); // 等所有的Server启动完成后再在Lealone.main中调用SchedulerFactory.start // 确保所有的初始PeriodicTask都在main线程中注册 } @Override public void stop() { synchronized (this) { if (isStopped()) return; super.stop(); ProtocolServerEngine.startedServers.remove(this); AsyncServerManager.removeServer(this); } // 同步块不能包含下面的代码,否则执行System.exit时会触发ShutdownHook又调用到stop, // 而System.exit又需要等所有ShutdownHook结束后才能退出,所以就死锁了 if (ProtocolServerEngine.startedServers.isEmpty()) { TransactionEngine.getDefaultTransactionEngine().close(); schedulerFactory.stop(); // 如果当前线程是ShutdownHook不能再执行System.exit,否则无法退出 if (!Thread.currentThread().getName().contains("ShutdownHook")) System.exit(0); } } protected int getConnectionSize() { return connectionSize.get(); } protected abstract int getDefaultPort(); protected T createConnection(WritableChannel writableChannel, Scheduler scheduler) { throw DbException.getUnsupportedException("createConnection"); } protected void beforeRegister(T conn, Scheduler scheduler) { // do nothing } protected void afterRegister(T conn, Scheduler scheduler) { // do nothing } protected void register(T conn, Scheduler scheduler, WritableChannel writableChannel) {<FILL_FUNCTION_BODY>} @Override public T createConnection(WritableChannel writableChannel, boolean isServer, Scheduler scheduler) { if (getAllowOthers() || allow(writableChannel.getHost())) { T conn = createConnection(writableChannel, scheduler); connectionSize.incrementAndGet(); register(conn, scheduler, writableChannel); return conn; } else { writableChannel.close(); throw DbException.get(ErrorCode.REMOTE_CONNECTION_NOT_ALLOWED); } } @Override public void removeConnection(AsyncConnection conn) { connectionSize.decrementAndGet(); conn.close(); } @Override public void registerAccepter(ServerSocketChannel serverChannel) { Scheduler scheduler = schedulerFactory.getScheduler(); scheduler.registerAccepter(this, serverChannel); } public boolean isRoundRobinAcceptEnabled() { return true; } }
beforeRegister(conn, scheduler); NetEventLoop eventLoop = (NetEventLoop) scheduler.getNetEventLoop(); writableChannel.setEventLoop(eventLoop); // 替换掉原来的 eventLoop.register(conn); afterRegister(conn, scheduler);
1,017
73
1,090
<methods>public non-sealed void <init>() ,public boolean allow(java.lang.String) ,public boolean getAllowOthers() ,public java.lang.String getBaseDir() ,public Map<java.lang.String,java.lang.String> getConfig() ,public java.lang.String getHost() ,public java.lang.String getName() ,public int getPort() ,public com.lealone.server.ProtocolServer getProtocolServer() ,public com.lealone.common.security.EncryptionOptions.ServerEncryptionOptions getServerEncryptionOptions() ,public int getSessionTimeout() ,public java.lang.String getType() ,public java.lang.String getURL() ,public void init(Map<java.lang.String,java.lang.String>) ,public boolean isDaemon() ,public boolean isSSL() ,public boolean isStarted() ,public boolean isStopped() ,public void setProtocolServer(com.lealone.server.ProtocolServer) ,public void setServerEncryptionOptions(com.lealone.common.security.EncryptionOptions.ServerEncryptionOptions) ,public void start() ,public void stop() <variables>protected com.lealone.server.ProtocolServer protocolServer
lealone_Lealone
Lealone/lealone-server/src/main/java/com/lealone/server/AsyncServerManager.java
AsyncServerManager
addServer
class AsyncServerManager { private static final BitField serverIds = new BitField(); private static final ArrayList<AsyncServer<?>> servers = new ArrayList<>(1); // 注册网络ACCEPT事件,个数会动态增减 private static RegisterAccepterTask[] registerAccepterTasks = new RegisterAccepterTask[1]; public static int allocateServerId() { synchronized (serverIds) { int i = serverIds.nextClearBit(0); serverIds.set(i); return i; } } public static void clearServerId(int id) { synchronized (serverIds) { serverIds.clear(id); } } public static boolean isServerIdEnabled(int id) { synchronized (serverIds) { return serverIds.get(id); } } public static void addServer(AsyncServer<?> server) {<FILL_FUNCTION_BODY>} public static void removeServer(AsyncServer<?> server) { synchronized (servers) { servers.remove(server); int serverId = server.getServerId(); // 删除最后一个元素时才需要变动数组 if (serverId > 0 && serverId == registerAccepterTasks.length - 1) { RegisterAccepterTask[] tasks = new RegisterAccepterTask[serverId]; System.arraycopy(registerAccepterTasks, 0, tasks, 0, serverId); registerAccepterTasks = tasks; } else { registerAccepterTasks[serverId] = null; } clearServerId(serverId); } } private static class RegisterAccepterTask { private AsyncServer<?> asyncServer; private ServerSocketChannel serverChannel; private Scheduler currentScheduler; private boolean needRegisterAccepter; // 避免重复注册ACCEPT事件 private void run(Scheduler currentScheduler) { try { serverChannel.register(currentScheduler.getSelector(), SelectionKey.OP_ACCEPT, this); needRegisterAccepter = false; } catch (ClosedChannelException e) { currentScheduler.getLogger().warn("Failed to register server channel: " + serverChannel); } } } public static void registerAccepter(AsyncServer<?> asyncServer, ServerSocketChannel serverChannel, Scheduler currentScheduler) { int serverId = asyncServer.getServerId(); // Server重新启动后对应的元素可能已经删除,需要重新加入 if (serverId >= registerAccepterTasks.length) { addServer(asyncServer); } RegisterAccepterTask task = registerAccepterTasks[serverId]; // Server重新启动后对应的元素可能为null,重新创建一个即可 if (task == null) { task = new RegisterAccepterTask(); registerAccepterTasks[serverId] = task; } task.asyncServer = asyncServer; task.serverChannel = serverChannel; task.currentScheduler = currentScheduler; task.needRegisterAccepter = true; } public static void runRegisterAccepterTasks(Scheduler currentScheduler) { RegisterAccepterTask[] tasks = registerAccepterTasks; for (int i = 0; i < tasks.length; i++) { RegisterAccepterTask task = tasks[i]; if (task != null && task.needRegisterAccepter && task.currentScheduler == currentScheduler) task.run(currentScheduler); } } public static void accept(SelectionKey key, Scheduler currentScheduler) { RegisterAccepterTask task = (RegisterAccepterTask) key.attachment(); task.asyncServer.getProtocolServer().accept(currentScheduler); if (task.asyncServer.isRoundRobinAcceptEnabled()) { Scheduler scheduler = currentScheduler.getSchedulerFactory().getScheduler(); // 如果下一个负责处理网络accept事件的调度器又是当前调度器,那么不需要做什么 if (scheduler != currentScheduler) { key.interestOps(key.interestOps() & ~SelectionKey.OP_ACCEPT); scheduler.registerAccepter(task.asyncServer, task.serverChannel); } } } }
synchronized (servers) { servers.add(server); // serverId从0开始 int serverId = server.getServerId(); if (serverId >= registerAccepterTasks.length) { RegisterAccepterTask[] tasks = new RegisterAccepterTask[serverId + 1]; System.arraycopy(registerAccepterTasks, 0, tasks, 0, registerAccepterTasks.length); tasks[tasks.length - 1] = new RegisterAccepterTask(); registerAccepterTasks = tasks; } else { registerAccepterTasks[serverId] = new RegisterAccepterTask(); } }
1,097
166
1,263
<no_super_class>
lealone_Lealone
Lealone/lealone-server/src/main/java/com/lealone/server/handler/BatchStatementPacketHandlers.java
PreparedUpdate
handle
class PreparedUpdate implements PacketHandler<BatchStatementPreparedUpdate> { @Override public Packet handle(PacketHandleTask task, BatchStatementPreparedUpdate packet) {<FILL_FUNCTION_BODY>} }
ServerSession session = task.session; int commandId = packet.commandId; int size = packet.size; PreparedSQLStatement command = (PreparedSQLStatement) session.getCache(commandId); List<? extends CommandParameter> params = command.getParameters(); int[] results = new int[size]; AtomicInteger count = new AtomicInteger(size); LinkableTask[] subTasks = new LinkableTask[size]; for (int i = 0; i < size; i++) { final int index = i; final Value[] values = packet.batchParameters.get(i); LinkableTask subTask = new LinkableTask() { @Override public void run() { // 不能放到外面设置,否则只取到最后一项 for (int j = 0; j < values.length; j++) { CommandParameter p = params.get(j); p.setValue(values[j]); } submitYieldableCommand(task, command, results, count, index); } }; subTasks[i] = subTask; } packet.batchParameters.clear(); task.si.submitTasks(subTasks); return null;
60
306
366
<methods>public non-sealed void <init>() ,public static PacketHandler#RAW getHandler(com.lealone.server.protocol.PacketType) ,public static PacketHandler#RAW getHandler(int) ,public static void register(com.lealone.server.protocol.PacketType, PacketHandler<? extends com.lealone.server.protocol.Packet>) <variables>private static PacketHandler#RAW[] handlers
lealone_Lealone
Lealone/lealone-server/src/main/java/com/lealone/server/handler/LobPacketHandlers.java
Read
handle
class Read implements PacketHandler<LobRead> { @Override public Packet handle(ServerSession session, LobRead packet) {<FILL_FUNCTION_BODY>} }
long lobId = packet.lobId; byte[] hmac = packet.hmac; long offset = packet.offset; int length = packet.length; SmallLRUCache<String, InputStream> lobs = session.getLobCache(); try { boolean useTableLobStorage = false; int tableId = TransferOutputStream.verifyLobMac(session, hmac, lobId); if (tableId < 0) { tableId = -tableId; useTableLobStorage = true; } String key = tableId + "_" + lobId; CachedInputStream cachedInputStream = (CachedInputStream) lobs.get(key); if (cachedInputStream == null) { cachedInputStream = new CachedInputStream(null); lobs.put(key, cachedInputStream); } if (cachedInputStream.getPos() != offset) { DataHandler dh = useTableLobStorage ? session.getDatabase().getDataHandler(tableId) : session.getDatabase(); // only the lob id is used ValueLob lob = ValueLob.create(Value.BLOB, dh, tableId, lobId, hmac, -1); lob.setUseTableLobStorage(useTableLobStorage); InputStream lobIn = dh.getLobStorage().getInputStream(lob, hmac, -1); cachedInputStream = new CachedInputStream(lobIn); lobs.put(key, cachedInputStream); lobIn.skip(offset); } // limit the buffer size length = Math.min(16 * Constants.IO_BUFFER_SIZE, length); byte[] buff = new byte[length]; length = IOUtils.readFully(cachedInputStream, buff); if (length != buff.length) { byte[] newBuff = new byte[length]; System.arraycopy(buff, 0, newBuff, 0, length); buff = newBuff; } return new LobReadAck(buff); } catch (IOException e) { throw DbException.convert(e); }
49
526
575
<methods>public non-sealed void <init>() ,public static PacketHandler#RAW getHandler(com.lealone.server.protocol.PacketType) ,public static PacketHandler#RAW getHandler(int) ,public static void register(com.lealone.server.protocol.PacketType, PacketHandler<? extends com.lealone.server.protocol.Packet>) <variables>private static PacketHandler#RAW[] handlers
lealone_Lealone
Lealone/lealone-server/src/main/java/com/lealone/server/handler/PacketHandlers.java
UpdateBase
createYieldableUpdate
class UpdateBase<P extends Packet> implements PacketHandler<P> { protected void createYieldableUpdate(PacketHandleTask task, PreparedSQLStatement stmt) {<FILL_FUNCTION_BODY>} protected Packet createAckPacket(PacketHandleTask task, int updateCount) { return new StatementUpdateAck(updateCount); } }
if (stmt instanceof StatementList) { StatementListPacketHandlers.updateHandler.createYieldableUpdate(task, stmt); return; } PreparedSQLStatement.Yieldable<?> yieldable = stmt.createYieldableUpdate(ar -> { if (ar.isSucceeded()) { int updateCount = ar.getResult(); task.conn.sendResponse(task, createAckPacket(task, updateCount)); } else { task.conn.sendError(task.session, task.packetId, ar.getCause()); } }); task.si.submitYieldableCommand(task.packetId, yieldable);
97
177
274
<no_super_class>
lealone_Lealone
Lealone/lealone-server/src/main/java/com/lealone/server/handler/PreparedStatementPacketHandlers.java
PreparedStatementPacketHandlers
register
class PreparedStatementPacketHandlers extends PacketHandlers { static void register() {<FILL_FUNCTION_BODY>} private static PreparedSQLStatement prepareStatement(ServerSession session, int commandId, String sql) { PreparedSQLStatement command = session.prepareStatement(sql, -1); command.setId(commandId); session.addCache(commandId, command); return command; } private static class Prepare implements PacketHandler<PreparedStatementPrepare> { @Override public Packet handle(ServerSession session, PreparedStatementPrepare packet) { PreparedSQLStatement command = prepareStatement(session, packet.commandId, packet.sql); return new PreparedStatementPrepareAck(command.isQuery()); } } private static class PrepareReadParams implements PacketHandler<PreparedStatementPrepareReadParams> { @Override public Packet handle(ServerSession session, PreparedStatementPrepareReadParams packet) { PreparedSQLStatement command = prepareStatement(session, packet.commandId, packet.sql); return new PreparedStatementPrepareReadParamsAck(command.isQuery(), command.getParameters()); } } private static class PreparedQuery extends PreparedQueryPacketHandler<PreparedStatementQuery> { @Override public Packet handle(PacketHandleTask task, PreparedStatementQuery packet) { return handlePacket(task, packet); } } private static class PreparedUpdate extends PreparedUpdatePacketHandler<PreparedStatementUpdate> { @Override public Packet handle(PacketHandleTask task, PreparedStatementUpdate packet) { return handlePacket(task, packet); } } private static class GetMetaData implements PacketHandler<PreparedStatementGetMetaData> { @Override public Packet handle(ServerSession session, PreparedStatementGetMetaData packet) { PreparedSQLStatement command = (PreparedSQLStatement) session.getCache(packet.commandId); Result result = command.getMetaData().get(); return new PreparedStatementGetMetaDataAck(result); } } private static class Close implements PacketHandler<PreparedStatementClose> { @Override public Packet handle(ServerSession session, PreparedStatementClose packet) { PreparedSQLStatement command = (PreparedSQLStatement) session.removeCache(packet.commandId, true); if (command != null) { command.close(); } return null; } } }
register(PacketType.PREPARED_STATEMENT_PREPARE, new Prepare()); register(PacketType.PREPARED_STATEMENT_PREPARE_READ_PARAMS, new PrepareReadParams()); register(PacketType.PREPARED_STATEMENT_QUERY, new PreparedQuery()); register(PacketType.PREPARED_STATEMENT_UPDATE, new PreparedUpdate()); register(PacketType.PREPARED_STATEMENT_GET_META_DATA, new GetMetaData()); register(PacketType.PREPARED_STATEMENT_CLOSE, new Close());
646
150
796
<methods>public non-sealed void <init>() ,public static PacketHandler#RAW getHandler(com.lealone.server.protocol.PacketType) ,public static PacketHandler#RAW getHandler(int) ,public static void register(com.lealone.server.protocol.PacketType, PacketHandler<? extends com.lealone.server.protocol.Packet>) <variables>private static PacketHandler#RAW[] handlers
lealone_Lealone
Lealone/lealone-server/src/main/java/com/lealone/server/handler/ResultPacketHandlers.java
Close
handle
class Close implements PacketHandler<ResultClose> { @Override public Packet handle(ServerSession session, ResultClose packet) {<FILL_FUNCTION_BODY>} }
Result result = (Result) session.removeCache(packet.resultId, true); if (result != null) { result.close(); } return null;
47
48
95
<methods>public non-sealed void <init>() ,public static PacketHandler#RAW getHandler(com.lealone.server.protocol.PacketType) ,public static PacketHandler#RAW getHandler(int) ,public static void register(com.lealone.server.protocol.PacketType, PacketHandler<? extends com.lealone.server.protocol.Packet>) <variables>private static PacketHandler#RAW[] handlers
lealone_Lealone
Lealone/lealone-server/src/main/java/com/lealone/server/handler/SessionPacketHandlers.java
CancelStatement
handle
class CancelStatement implements PacketHandler<SessionCancelStatement> { @Override public Packet handle(ServerSession session, SessionCancelStatement packet) {<FILL_FUNCTION_BODY>} }
PreparedSQLStatement command = (PreparedSQLStatement) session.removeCache(packet.statementId, true); if (command != null) { command.cancel(); command.close(); } else { session.cancelStatement(packet.statementId); } return null;
51
81
132
<methods>public non-sealed void <init>() ,public static PacketHandler#RAW getHandler(com.lealone.server.protocol.PacketType) ,public static PacketHandler#RAW getHandler(int) ,public static void register(com.lealone.server.protocol.PacketType, PacketHandler<? extends com.lealone.server.protocol.Packet>) <variables>private static PacketHandler#RAW[] handlers
lealone_Lealone
Lealone/lealone-server/src/main/java/com/lealone/server/handler/StatementListPacketHandlers.java
Update
createYieldableUpdate
class Update extends UpdatePacketHandler<StatementUpdate> { private void handleAsyncResult(PacketHandleTask task, AsyncResult<?> ar, AtomicInteger count, AtomicReference<Integer> resultRef, AtomicReference<Throwable> causeRef) { if (ar.isFailed() && causeRef.get() == null) causeRef.set(ar.getCause()); if (count.decrementAndGet() == 0) { if (causeRef.get() != null) { task.conn.sendError(task.session, task.packetId, causeRef.get()); } else { task.conn.sendResponse(task, createAckPacket(task, resultRef.get())); } } } @Override protected void createYieldableUpdate(PacketHandleTask task, PreparedSQLStatement stmt) {<FILL_FUNCTION_BODY>} }
StatementList statementList = (StatementList) stmt; String[] statements = statementList.getRemaining().split(";"); AtomicInteger count = new AtomicInteger(); AtomicReference<Integer> resultRef = new AtomicReference<>(); AtomicReference<Throwable> causeRef = new AtomicReference<>(); for (int i = 0; i < statements.length; i++) { statements[i] = statements[i].trim(); if (!statements[i].isEmpty()) { final String sql = statements[i]; LinkableTask subTask = new LinkableTask() { @Override public void run() { PreparedSQLStatement command = task.session.prepareStatement(sql, -1); PreparedSQLStatement.Yieldable<?> yieldable; if (command.isQuery()) { yieldable = command.createYieldableQuery(-1, false, ar -> { handleAsyncResult(task, ar, count, resultRef, causeRef); }); } else { yieldable = command.createYieldableUpdate(ar -> { handleAsyncResult(task, ar, count, resultRef, causeRef); }); } task.si.submitYieldableCommand(task.packetId, yieldable); } }; count.incrementAndGet(); task.si.submitTasks(subTask); } } PreparedSQLStatement.Yieldable<?> yieldable = statementList.getFirstStatement() .createYieldableUpdate(ar -> { if (ar.isSucceeded()) { int updateCount = ar.getResult(); resultRef.set(updateCount); } else { causeRef.set(ar.getCause()); } }); task.si.submitYieldableCommand(task.packetId, yieldable);
230
465
695
<no_super_class>
lealone_Lealone
Lealone/lealone-server/src/main/java/com/lealone/server/scheduler/PacketHandleTask.java
PacketHandleTask
handlePacket
class PacketHandleTask extends LinkableTask { private static final Logger logger = LoggerFactory.getLogger(PacketHandleTask.class); public final TcpServerConnection conn; public final TransferInputStream in; public final int packetId; public final int packetType; public final ServerSession session; public final int sessionId; public final SessionInfo si; public PacketHandleTask(TcpServerConnection conn, TransferInputStream in, int packetId, int packetType, SessionInfo si) { this.conn = conn; this.in = in; this.packetId = packetId; this.packetType = packetType; this.session = si.getSession(); this.sessionId = si.getSessionId(); this.si = si; } @Override public void run() { try { handlePacket(); } catch (Throwable e) { String message = "Failed to handle packet, packetId: {}, packetType: {}, sessionId: {}"; logger.error(message, e, packetId, packetType, sessionId); conn.sendError(session, packetId, e); } finally { // 确保无论出现什么情况都能关闭,调用closeInputStream两次也是无害的 in.closeInputStream(); } } private void handlePacket() throws Exception {<FILL_FUNCTION_BODY>} }
int version = session.getProtocolVersion(); PacketDecoder<? extends Packet> decoder = PacketDecoders.getDecoder(packetType); Packet packet = decoder.decode(in, version); in.closeInputStream(); // 到这里输入流已经读完,及时释放NetBuffer @SuppressWarnings("unchecked") PacketHandler<Packet> handler = PacketHandlers.getHandler(packetType); if (handler != null) { Packet ack = handler.handle(this, packet); if (ack != null) { conn.sendResponse(this, ack); } } else { logger.warn("Unknow packet type: {}", packetType); }
356
188
544
<methods>public non-sealed void <init>() <variables>
lealone_Lealone
Lealone/lealone-server/src/main/java/com/lealone/server/scheduler/SessionInfo.java
SessionInfo
checkSessionTimeout
class SessionInfo extends LinkableBase<SessionInfo> implements ServerSession.TimeoutListener { private static final Logger logger = LoggerFactory.getLogger(SessionInfo.class); private final Scheduler scheduler; private final AsyncServerConnection conn; private final ServerSession session; private final int sessionId; // 客户端的sessionId private final int sessionTimeout; private long lastActiveTime; // task统一由scheduler调度执行 private final LinkableList<LinkableTask> tasks = new LinkableList<>(); public SessionInfo(Scheduler scheduler, AsyncServerConnection conn, ServerSession session, int sessionId, int sessionTimeout) { this.scheduler = scheduler; this.conn = conn; this.session = session; this.sessionId = sessionId; this.sessionTimeout = sessionTimeout; updateLastActiveTime(); } SessionInfo copy(ServerSession session) { return new SessionInfo(this.scheduler, this.conn, session, this.sessionId, this.sessionTimeout); } private void updateLastActiveTime() { lastActiveTime = System.currentTimeMillis(); } public ServerSession getSession() { return session; } public int getSessionId() { return sessionId; } private void addTask(LinkableTask task) { tasks.add(task); } public void submitTask(LinkableTask task) { updateLastActiveTime(); if (canHandleNextSessionTask()) // 如果可以直接处理下一个task就不必加到队列了 runTask(task); else addTask(task); } public void submitTasks(LinkableTask... tasks) { updateLastActiveTime(); for (LinkableTask task : tasks) addTask(task); } public void submitYieldableCommand(int packetId, PreparedSQLStatement.Yieldable<?> yieldable) { YieldableCommand yieldableCommand = new YieldableCommand(packetId, yieldable, sessionId); session.setYieldableCommand(yieldableCommand); // 执行此方法的当前线程就是scheduler,所以不用唤醒scheduler } public void remove() { scheduler.removeSessionInfo(this); } void checkSessionTimeout(long currentTime) {<FILL_FUNCTION_BODY>} private void runTask(AsyncTask task) { ServerSession old = (ServerSession) scheduler.getCurrentSession(); scheduler.setCurrentSession(session); try { task.run(); } catch (Throwable e) { logger.warn("Failed to run async session task: " + task + ", session id: " + sessionId, e); } finally { scheduler.setCurrentSession(old); } } // 在同一session中,只有前面一条SQL执行完后才可以执行下一条 private boolean canHandleNextSessionTask() { return session.canExecuteNextCommand(); } void runSessionTasks() { // 只有当前语句执行完了才能执行下一条命令 if (session.getYieldableCommand() != null) { return; } if (!tasks.isEmpty() && session.canExecuteNextCommand()) { LinkableTask task = tasks.getHead(); while (task != null) { runTask(task); task = task.next; tasks.setHead(task); tasks.decrementSize(); // 执行Update或Query包的解析任务时会通过submitYieldableCommand设置 if (session.getYieldableCommand() != null) break; } if (tasks.getHead() == null) tasks.setTail(null); } } YieldableCommand getYieldableCommand(boolean checkTimeout) { return session.getYieldableCommand(checkTimeout, this); } void sendError(int packetId, Throwable e) { // 如果session没有对应的connection不需要发送错误信息 if (conn != null) conn.sendError(session, packetId, e); else logger.error("", e); } @Override public void onTimeout(YieldableCommand c, Throwable e) { sendError(c.getPacketId(), e); } boolean isMarkClosed() { if (session.isMarkClosed()) { if (conn != null) { conn.closeSession(this); if (conn.getSessionCount() == 0) conn.close(); } return true; } return false; } }
if (sessionTimeout <= 0) return; if (lastActiveTime + sessionTimeout < currentTime) { conn.closeSession(this); logger.warn("Client session timeout, session id: " + sessionId // + ", host: " + conn.getWritableChannel().getHost() // + ", port: " + conn.getWritableChannel().getPort()); }
1,193
100
1,293
<methods>public non-sealed void <init>() ,public com.lealone.server.scheduler.SessionInfo getNext() ,public void setNext(com.lealone.server.scheduler.SessionInfo) <variables>public com.lealone.server.scheduler.SessionInfo next
lealone_Lealone
Lealone/lealone-server/src/main/java/com/lealone/server/scheduler/SessionValidator.java
SessionValidator
validate
class SessionValidator { private volatile long wrongPasswordDelay = SysProperties.DELAY_WRONG_PASSWORD_MIN; private long lastTime; private long delay; /** * This method is called after validating user name and password. If user * name and password were correct, the sleep time is reset, otherwise this * method waits some time (to make brute force / rainbow table attacks * harder) and then throws a 'wrong user or password' exception. The delay * is a bit randomized to protect against timing attacks. Also the delay * doubles after each unsuccessful logins, to make brute force attacks * harder. * * There is only one exception message both for wrong user and for * wrong password, to make it harder to get the list of user names. This * method must only be called from one place, so it is not possible from the * stack trace to see if the user name was wrong or the password. * * @param isUserAndPasswordCorrect if the user name or the password was correct * @throws DbException the exception 'wrong user or password' */ public void validate(boolean isUserAndPasswordCorrect) {<FILL_FUNCTION_BODY>} public boolean canHandleNextSessionInitTask() { if (delay > 0) { if (lastTime + delay > System.currentTimeMillis()) return false; delay = 0; } return true; } }
int min = SysProperties.DELAY_WRONG_PASSWORD_MIN; if (isUserAndPasswordCorrect) { long delay = wrongPasswordDelay; if (delay > min && delay > 0) { // delay up to the last delay // an attacker can't know how long it will be this.delay = MathUtils.secureRandomInt((int) delay); wrongPasswordDelay = min; lastTime = System.currentTimeMillis(); } } else { this.delay = wrongPasswordDelay; int max = SysProperties.DELAY_WRONG_PASSWORD_MAX; if (max <= 0) { max = Integer.MAX_VALUE; } wrongPasswordDelay += wrongPasswordDelay; if (wrongPasswordDelay > max || wrongPasswordDelay < 0) { wrongPasswordDelay = max; } if (min > 0) { // a bit more to protect against timing attacks this.delay += Math.abs(MathUtils.secureRandomLong() % 100); } lastTime = System.currentTimeMillis(); }
366
278
644
<no_super_class>
lealone_Lealone
Lealone/lealone-sql/src/main/java/com/lealone/sql/SQLEngineBase.java
SQLEngineBase
createConditionAndOr
class SQLEngineBase extends PluginBase implements SQLEngine { public SQLEngineBase(String name) { super(name); } public abstract SQLParserBase createParser(ServerSession session); @Override public SQLParserBase createParser(Session session) { return createParser((ServerSession) session); } @Override public CommandParameter createParameter(int index) { return new Parameter(index); } @Override public IExpression createValueExpression(Value value) { return ValueExpression.get(value); } @Override public IExpression createSequenceValue(Object sequence) { return new SequenceValue((Sequence) sequence); } @Override public IExpression createConditionAndOr(boolean and, IExpression left, IExpression right) {<FILL_FUNCTION_BODY>} @Override public Class<? extends Plugin> getPluginClass() { return SQLEngine.class; } }
return new ConditionAndOr(and ? ConditionAndOr.AND : ConditionAndOr.OR, (Expression) left, (Expression) right);
258
37
295
<methods>public void <init>() ,public void <init>(java.lang.String) ,public synchronized void close() ,public Map<java.lang.String,java.lang.String> getConfig() ,public java.lang.String getName() ,public Class<? extends com.lealone.db.Plugin> getPluginClass() ,public com.lealone.db.Plugin.State getState() ,public synchronized void init(Map<java.lang.String,java.lang.String>) ,public boolean isInited() ,public boolean isStarted() ,public boolean isStopped() ,public void setName(java.lang.String) ,public void start() ,public void stop() <variables>protected Map<java.lang.String,java.lang.String> config,protected java.lang.String name,protected com.lealone.db.Plugin.State state
lealone_Lealone
Lealone/lealone-sql/src/main/java/com/lealone/sql/StatementList.java
StatementList
executeRemaining
class StatementList extends StatementBase { private final StatementBase firstStatement; private final String remaining; public StatementList(ServerSession session, StatementBase firstStatement, String remaining) { super(session); this.firstStatement = firstStatement; this.remaining = remaining; } public StatementBase getFirstStatement() { return firstStatement; } public String getRemaining() { return remaining; } @Override public int getType() { return firstStatement.getType(); } @Override public Future<Result> getMetaData() { return firstStatement.getMetaData(); } @Override public ArrayList<Parameter> getParameters() { return firstStatement.getParameters(); } private void executeRemaining() {<FILL_FUNCTION_BODY>} @Override public PreparedSQLStatement prepare() { firstStatement.prepare(); return this; } @Override public boolean isQuery() { return firstStatement.isQuery(); } @Override public Result query(int maxRows) { Result result = firstStatement.query(maxRows); executeRemaining(); return result; } @Override public int update() { int updateCount = firstStatement.update(); executeRemaining(); return updateCount; } }
StatementBase remainingStatement = (StatementBase) session.prepareStatement(remaining, -1); if (remainingStatement.isQuery()) { remainingStatement.query(0); } else { remainingStatement.update(); }
360
62
422
<methods>public void <init>(com.lealone.db.session.ServerSession) ,public boolean canReuse() ,public void cancel() ,public void checkCanceled() ,public void checkParameters() ,public void close() ,public YieldableBase<com.lealone.db.result.Result> createYieldableQuery(int, boolean, AsyncHandler<AsyncResult<com.lealone.db.result.Result>>) ,public YieldableBase<java.lang.Integer> createYieldableUpdate(AsyncHandler<AsyncResult<java.lang.Integer>>) ,public Future<com.lealone.db.result.Result> executeQuery(int, boolean) ,public Future<java.lang.Integer> executeUpdate() ,public int getCurrentRowNumber() ,public int getFetchSize() ,public int getId() ,public Future<com.lealone.db.result.Result> getMetaData() ,public long getModificationMetaId() ,public ArrayList<com.lealone.sql.expression.Parameter> getParameters() ,public java.lang.String getPlanSQL() ,public int getPriority() ,public java.lang.String getSQL() ,public com.lealone.db.session.ServerSession getSession() ,public abstract int getType() ,public boolean isQuery() ,public boolean needRecompile() ,public com.lealone.sql.PreparedSQLStatement prepare() ,public Future<java.lang.Boolean> prepare(boolean) ,public com.lealone.db.result.Result query(int) ,public void reuse() ,public boolean setCurrentRowNumber(int) ,public boolean setCurrentRowNumber(int, boolean) ,public void setFetchSize(int) ,public void setId(int) ,public void setModificationMetaId(long) ,public void setObjectId(int) ,public void setParameterList(ArrayList<com.lealone.sql.expression.Parameter>) ,public void setPrepareAlways(boolean) ,public void setPriority(int) ,public com.lealone.common.exceptions.DbException setRow(com.lealone.common.exceptions.DbException, int, java.lang.String) ,public void setSQL(java.lang.String) ,public void setSession(com.lealone.db.session.ServerSession) ,public java.lang.String toString() ,public void trace(long, int) ,public int update() <variables>private boolean canReuse,private int currentRowNumber,private int fetchSize,private long modificationMetaId,private int objectId,protected ArrayList<com.lealone.sql.expression.Parameter> parameters,protected boolean prepareAlways,protected int priority,private int rowScanCount,protected com.lealone.db.session.ServerSession session,protected java.lang.String sql,private int statementId
lealone_Lealone
Lealone/lealone-sql/src/main/java/com/lealone/sql/admin/CreatePlugin.java
CreatePlugin
update
class CreatePlugin extends AdminStatement { private String pluginName; private String implementBy; private String classPath; private boolean ifNotExists; private CaseInsensitiveMap<String> parameters; public CreatePlugin(ServerSession session) { super(session); } @Override public int getType() { return SQLStatement.CREATE_PLUGIN; } public void setPluginName(String name) { this.pluginName = name; } public void setImplementBy(String implementBy) { this.implementBy = implementBy; } public void setClassPath(String classPath) { this.classPath = classPath; } public void setIfNotExists(boolean ifNotExists) { this.ifNotExists = ifNotExists; } public void setParameters(CaseInsensitiveMap<String> parameters) { this.parameters = parameters; } @Override public int update() {<FILL_FUNCTION_BODY>} }
LealoneDatabase.checkAdminRight(session, "create plugin"); LealoneDatabase lealoneDB = LealoneDatabase.getInstance(); DbObjectLock lock = lealoneDB.tryExclusivePluginLock(session); if (lock == null) return -1; PluginObject pluginObject = lealoneDB.findPluginObject(session, pluginName); if (pluginObject != null) { if (ifNotExists) { return 0; } throw DbException.get(ErrorCode.PLUGIN_ALREADY_EXISTS_1, pluginName); } Plugin plugin = null; URLClassLoader cl = null; if (classPath != null) { String[] a = classPath.split(","); URL[] urls = new URL[a.length]; for (int i = 0; i < a.length; i++) { urls[i] = Utils.toURL(a[i]); } cl = new URLClassLoader(urls, Plugin.class.getClassLoader()); try { plugin = Utils.newInstance(cl.loadClass(implementBy)); } catch (Throwable t) { try { cl.close(); } catch (Exception e) { } throw DbException.convert(t); } } else { plugin = Utils.newInstance(implementBy); } if (parameters == null) parameters = new CaseInsensitiveMap<>(); parameters.put("plugin_name", pluginName); plugin.init(parameters); int id = getObjectId(lealoneDB); pluginObject = new PluginObject(lealoneDB, id, pluginName, implementBy, classPath, parameters); pluginObject.setPlugin(plugin); pluginObject.setClassLoader(cl); lealoneDB.addDatabaseObject(session, pluginObject, lock); // 将缓存过期掉 lealoneDB.getNextModificationMetaId(); return 0;
267
504
771
<methods>public void <init>(com.lealone.db.session.ServerSession) ,public boolean needRecompile() <variables>
lealone_Lealone
Lealone/lealone-sql/src/main/java/com/lealone/sql/admin/DropPlugin.java
DropPlugin
update
class DropPlugin extends AdminStatement { private String pluginName; private boolean ifExists; public DropPlugin(ServerSession session) { super(session); } @Override public int getType() { return SQLStatement.DROP_PLUGIN; } public void setPluginName(String name) { this.pluginName = name; } public void setIfExists(boolean ifExists) { this.ifExists = ifExists; } @Override public int update() {<FILL_FUNCTION_BODY>} }
LealoneDatabase.checkAdminRight(session, "drop plugin"); LealoneDatabase lealoneDB = LealoneDatabase.getInstance(); DbObjectLock lock = lealoneDB.tryExclusivePluginLock(session); if (lock == null) return -1; PluginObject pluginObject = lealoneDB.findPluginObject(session, pluginName); if (pluginObject == null) { if (!ifExists) throw DbException.get(ErrorCode.PLUGIN_NOT_FOUND_1, pluginName); } else { pluginObject.close(); lealoneDB.removeDatabaseObject(session, pluginObject, lock); // 将缓存过期掉 lealoneDB.getNextModificationMetaId(); } return 0;
152
193
345
<methods>public void <init>(com.lealone.db.session.ServerSession) ,public boolean needRecompile() <variables>
lealone_Lealone
Lealone/lealone-sql/src/main/java/com/lealone/sql/admin/ShutdownDatabase.java
ShutdownDatabase
update
class ShutdownDatabase extends AdminStatement { private final Database db; private final boolean immediately; public ShutdownDatabase(ServerSession session, Database db, boolean immediately) { super(session); this.db = db; this.immediately = immediately; } @Override public int getType() { return SQLStatement.SHUTDOWN_DATABASE; } @Override public int update() {<FILL_FUNCTION_BODY>} }
LealoneDatabase.checkAdminRight(session, "shutdown database"); // 如果是LealoneDatabase什么都不做 if (LealoneDatabase.isMe(db.getName())) return 0; DbObjectLock lock = LealoneDatabase.getInstance().tryExclusiveDatabaseLock(session); if (lock == null) return -1; db.markClosed(); if (immediately) { db.shutdownImmediately(); } else if (db.getSessionCount() == 0) { db.closeIfNeeded(); } return 0;
127
147
274
<methods>public void <init>(com.lealone.db.session.ServerSession) ,public boolean needRecompile() <variables>
lealone_Lealone
Lealone/lealone-sql/src/main/java/com/lealone/sql/admin/ShutdownPlugin.java
ShutdownPlugin
update
class ShutdownPlugin extends AdminStatement { private final String pluginName; public ShutdownPlugin(ServerSession session, String pluginName) { super(session); this.pluginName = pluginName; } @Override public int getType() { return SQLStatement.SHUTDOWN_PLUGIN; } @Override public int update() {<FILL_FUNCTION_BODY>} }
LealoneDatabase.checkAdminRight(session, "shutdown plugin"); LealoneDatabase lealoneDB = LealoneDatabase.getInstance(); DbObjectLock lock = lealoneDB.tryExclusivePluginLock(session); if (lock == null) return -1; PluginObject pluginObject = lealoneDB.findPluginObject(session, pluginName); if (pluginObject == null) { throw DbException.get(ErrorCode.PLUGIN_NOT_FOUND_1, pluginName); } pluginObject.stop(); // 将缓存过期掉 lealoneDB.getNextModificationMetaId(); return 0;
112
165
277
<methods>public void <init>(com.lealone.db.session.ServerSession) ,public boolean needRecompile() <variables>
lealone_Lealone
Lealone/lealone-sql/src/main/java/com/lealone/sql/admin/ShutdownServer.java
ShutdownServer
update
class ShutdownServer extends AdminStatement { private final int port; private final String name; public ShutdownServer(ServerSession session, int port, String name) { super(session); this.port = port; this.name = name; } @Override public int getType() { return SQLStatement.SHUTDOWN_SERVER; } @Override public int update() {<FILL_FUNCTION_BODY>} public static ProtocolServerEngine getProtocolServerEngine(String name) { ProtocolServerEngine e = PluginManager.getPlugin(ProtocolServerEngine.class, name); if (e == null) { throw DbException.get(ErrorCode.PLUGIN_NOT_FOUND_1, name); } return e; } }
LealoneDatabase.checkAdminRight(session, "shutdown server"); // 通过指定的名称来关闭server if (name != null) { ProtocolServerEngine e = getProtocolServerEngine(name); e.stop(); } else { // 通过指定的端口号来关闭server,如果端口号小于0就关闭所有server ThreadUtils.start("ShutdownServerThread-Port-" + port, () -> { for (ProtocolServer server : ProtocolServerEngine.startedServers) { if (port < 0 || server.getPort() == port) { server.stop(); } } }); } return 0;
210
177
387
<methods>public void <init>(com.lealone.db.session.ServerSession) ,public boolean needRecompile() <variables>
lealone_Lealone
Lealone/lealone-sql/src/main/java/com/lealone/sql/admin/StartPlugin.java
StartPlugin
update
class StartPlugin extends AdminStatement { private final String pluginName; public StartPlugin(ServerSession session, String pluginName) { super(session); this.pluginName = pluginName; } @Override public int getType() { return SQLStatement.START_PLUGIN; } @Override public int update() {<FILL_FUNCTION_BODY>} }
LealoneDatabase.checkAdminRight(session, "start plugin"); LealoneDatabase lealoneDB = LealoneDatabase.getInstance(); DbObjectLock lock = lealoneDB.tryExclusivePluginLock(session); if (lock == null) return -1; PluginObject pluginObject = lealoneDB.findPluginObject(session, pluginName); if (pluginObject == null) { throw DbException.get(ErrorCode.PLUGIN_NOT_FOUND_1, pluginName); } pluginObject.start(); // 将缓存过期掉 lealoneDB.getNextModificationMetaId(); return 0;
107
164
271
<methods>public void <init>(com.lealone.db.session.ServerSession) ,public boolean needRecompile() <variables>
lealone_Lealone
Lealone/lealone-sql/src/main/java/com/lealone/sql/admin/StartServer.java
StartServer
update
class StartServer extends AdminStatement { private final String name; private final CaseInsensitiveMap<String> parameters; public StartServer(ServerSession session, String name, CaseInsensitiveMap<String> parameters) { super(session); this.name = name; if (parameters == null) parameters = new CaseInsensitiveMap<>(); this.parameters = parameters; } @Override public int getType() { return SQLStatement.START_SERVER; } @Override public int update() {<FILL_FUNCTION_BODY>} }
LealoneDatabase.checkAdminRight(session, "start server"); ProtocolServerEngine e = ShutdownServer.getProtocolServerEngine(name); if (!e.isInited()) e.init(parameters); e.start(); return 0;
150
68
218
<methods>public void <init>(com.lealone.db.session.ServerSession) ,public boolean needRecompile() <variables>
lealone_Lealone
Lealone/lealone-sql/src/main/java/com/lealone/sql/ddl/AlterDatabase.java
AlterDatabase
update
class AlterDatabase extends DatabaseStatement { private final Database db; public AlterDatabase(ServerSession session, Database db, RunMode runMode, CaseInsensitiveMap<String> parameters) { super(session, db.getName()); this.db = db; this.parameters = parameters; validateParameters(); } @Override public int getType() { return SQLStatement.ALTER_DATABASE; } @Override public int update() {<FILL_FUNCTION_BODY>} }
LealoneDatabase.checkAdminRight(session, "alter database"); if (parameters == null || parameters.isEmpty()) return 0; if (LealoneDatabase.getInstance().tryExclusiveDatabaseLock(session) == null) return -1; db.updateDbSettings(session, parameters); return 0;
137
82
219
<methods>public java.lang.String getDatabaseName() ,public boolean isDatabaseStatement() <variables>protected final non-sealed java.lang.String dbName,protected CaseInsensitiveMap<java.lang.String> parameters
lealone_Lealone
Lealone/lealone-sql/src/main/java/com/lealone/sql/ddl/AlterIndexRename.java
AlterIndexRename
update
class AlterIndexRename extends SchemaStatement { private Index oldIndex; private String newIndexName; public AlterIndexRename(ServerSession session, Schema schema) { super(session, schema); } @Override public int getType() { return SQLStatement.ALTER_INDEX_RENAME; } public void setOldIndex(Index index) { oldIndex = index; } public void setNewName(String name) { newIndexName = name; } @Override public int update() {<FILL_FUNCTION_BODY>} }
session.getUser().checkRight(oldIndex.getTable(), Right.ALL); DbObjectLock lock = schema.tryExclusiveLock(DbObjectType.INDEX, session); if (lock == null) return -1; if (schema.findIndex(session, newIndexName) != null || newIndexName.equals(oldIndex.getName())) { throw DbException.get(ErrorCode.INDEX_ALREADY_EXISTS_1, newIndexName); } schema.rename(session, oldIndex, newIndexName, lock); return 0;
160
146
306
<methods>public void <init>(com.lealone.db.session.ServerSession, com.lealone.db.schema.Schema) <variables>protected final non-sealed com.lealone.db.schema.Schema schema
lealone_Lealone
Lealone/lealone-sql/src/main/java/com/lealone/sql/ddl/AlterSchemaRename.java
AlterSchemaRename
update
class AlterSchemaRename extends DefinitionStatement { private Schema oldSchema; private String newSchemaName; public AlterSchemaRename(ServerSession session) { super(session); } @Override public int getType() { return SQLStatement.ALTER_SCHEMA_RENAME; } public void setOldSchema(Schema schema) { oldSchema = schema; } public void setNewName(String name) { newSchemaName = name; } @Override public int update() {<FILL_FUNCTION_BODY>} }
session.getUser().checkSchemaAdmin(); Database db = session.getDatabase(); DbObjectLock lock = db.tryExclusiveSchemaLock(session); if (lock == null) return -1; if (!oldSchema.canDrop()) { throw DbException.get(ErrorCode.SCHEMA_CAN_NOT_BE_DROPPED_1, oldSchema.getName()); } if (db.findSchema(session, newSchemaName) != null || newSchemaName.equals(oldSchema.getName())) { throw DbException.get(ErrorCode.SCHEMA_ALREADY_EXISTS_1, newSchemaName); } db.renameDatabaseObject(session, oldSchema, newSchemaName, lock); ArrayList<SchemaObject> all = db.getAllSchemaObjects(); for (SchemaObject schemaObject : all) { db.updateMeta(session, schemaObject); } return 0;
156
238
394
<methods>public boolean isDDL() <variables>
lealone_Lealone
Lealone/lealone-sql/src/main/java/com/lealone/sql/ddl/AlterSequence.java
AlterSequence
update
class AlterSequence extends SchemaStatement { private Table table; private Sequence sequence; private Expression start; private Expression increment; private Boolean cycle; private Expression minValue; private Expression maxValue; private Expression cacheSize; private Boolean transactional; public AlterSequence(ServerSession session, Schema schema) { super(session, schema); } @Override public int getType() { return SQLStatement.ALTER_SEQUENCE; } public void setSequence(Sequence sequence) { this.sequence = sequence; } public void setColumn(Column column) { table = column.getTable(); sequence = column.getSequence(); if (sequence == null) { throw DbException.get(ErrorCode.SEQUENCE_NOT_FOUND_1, column.getSQL()); } } public void setStartWith(Expression start) { this.start = start; } public void setIncrement(Expression increment) { this.increment = increment; } public void setCycle(Boolean cycle) { this.cycle = cycle; } public void setMinValue(Expression minValue) { this.minValue = minValue; } public void setMaxValue(Expression maxValue) { this.maxValue = maxValue; } public void setCacheSize(Expression cacheSize) { this.cacheSize = cacheSize; } public void setTransactional(boolean transactional) { this.transactional = transactional; } @Override public int update() {<FILL_FUNCTION_BODY>} private Long getLong(Expression expr) { return CreateSequence.getLong(session, expr); } }
if (table != null) { session.getUser().checkRight(table, Right.ALL); } sequence.tryLock(session, false); Sequence newSequence = sequence.copy(); if (cycle != null) { newSequence.setCycle(cycle); } if (cacheSize != null) { long size = cacheSize.optimize(session).getValue(session).getLong(); newSequence.setCacheSize(size); } if (transactional != null) { newSequence.setTransactional(transactional.booleanValue()); } if (start != null || minValue != null || maxValue != null || increment != null) { Long startValue = getLong(start); Long min = getLong(minValue); Long max = getLong(maxValue); Long inc = getLong(increment); newSequence.modify(startValue, min, max, inc); } newSequence.setOldSequence(sequence); schema.update(session, newSequence, sequence.getOldRow(), sequence.getLock()); sequence.unlockIfNotTransactional(session); return 0;
465
294
759
<methods>public void <init>(com.lealone.db.session.ServerSession, com.lealone.db.schema.Schema) <variables>protected final non-sealed com.lealone.db.schema.Schema schema
lealone_Lealone
Lealone/lealone-sql/src/main/java/com/lealone/sql/ddl/AlterTableDropConstraint.java
AlterTableDropConstraint
update
class AlterTableDropConstraint extends SchemaStatement { private String constraintName; private final boolean ifExists; public AlterTableDropConstraint(ServerSession session, Schema schema, boolean ifExists) { super(session, schema); this.ifExists = ifExists; } @Override public int getType() { return SQLStatement.ALTER_TABLE_DROP_CONSTRAINT; } public void setConstraintName(String string) { constraintName = string; } @Override public int update() {<FILL_FUNCTION_BODY>} }
DbObjectLock lock = schema.tryExclusiveLock(DbObjectType.CONSTRAINT, session); if (lock == null) return -1; Constraint constraint = schema.findConstraint(session, constraintName); if (constraint == null) { if (!ifExists) { throw DbException.get(ErrorCode.CONSTRAINT_NOT_FOUND_1, constraintName); } } else { session.getUser().checkRight(constraint.getTable(), Right.ALL); session.getUser().checkRight(constraint.getRefTable(), Right.ALL); schema.remove(session, constraint, lock); } return 0;
154
170
324
<methods>public void <init>(com.lealone.db.session.ServerSession, com.lealone.db.schema.Schema) <variables>protected final non-sealed com.lealone.db.schema.Schema schema
lealone_Lealone
Lealone/lealone-sql/src/main/java/com/lealone/sql/ddl/AlterTableRename.java
AlterTableRename
update
class AlterTableRename extends SchemaStatement { private Table oldTable; private String newTableName; private boolean hidden; public AlterTableRename(ServerSession session, Schema schema) { super(session, schema); } @Override public int getType() { return SQLStatement.ALTER_TABLE_RENAME; } public void setOldTable(Table table) { oldTable = table; } public void setNewTableName(String name) { newTableName = name; } public void setHidden(boolean hidden) { this.hidden = hidden; } @Override public int update() {<FILL_FUNCTION_BODY>} }
session.getUser().checkRight(oldTable, Right.ALL); DbObjectLock lock = tryAlterTable(oldTable); if (lock == null) return -1; Table t = schema.findTableOrView(session, newTableName); if (t != null && hidden && newTableName.equals(oldTable.getName())) { if (!t.isHidden()) { oldTable.setHidden(true); session.getDatabase().updateMeta(session, oldTable); } return 0; } if (t != null || newTableName.equals(oldTable.getName())) { throw DbException.get(ErrorCode.TABLE_OR_VIEW_ALREADY_EXISTS_1, newTableName); } if (oldTable.isTemporary()) { throw DbException.getUnsupportedException("temp table"); } schema.rename(session, oldTable, newTableName, lock); return 0;
191
251
442
<methods>public void <init>(com.lealone.db.session.ServerSession, com.lealone.db.schema.Schema) <variables>protected final non-sealed com.lealone.db.schema.Schema schema
lealone_Lealone
Lealone/lealone-sql/src/main/java/com/lealone/sql/ddl/AlterTableRenameColumn.java
AlterTableRenameColumn
update
class AlterTableRenameColumn extends SchemaStatement { private Table table; private Column column; private String newName; public AlterTableRenameColumn(ServerSession session, Schema schema) { super(session, schema); } @Override public int getType() { return SQLStatement.ALTER_TABLE_ALTER_COLUMN_RENAME; } public void setTable(Table table) { this.table = table; } public void setColumn(Column column) { this.column = column; } public void setNewColumnName(String newName) { this.newName = newName; } @Override public int update() {<FILL_FUNCTION_BODY>} }
session.getUser().checkRight(table, Right.ALL); DbObjectLock lock = tryAlterTable(table); if (lock == null) return -1; table.checkSupportAlter(); // we need to update CHECK constraint // since it might reference the name of the column Expression newCheckExpr = (Expression) column.getCheckConstraint(session, newName); table.renameColumn(column, newName); column.removeCheckConstraint(); SingleColumnResolver resolver = new SingleColumnResolver(column); column.addCheckConstraint(session, newCheckExpr, resolver); table.setModified(); Database db = session.getDatabase(); db.updateMeta(session, table); for (DbObject child : table.getChildren()) { if (child.getCreateSQL() != null) { db.updateMeta(session, child); } } return 0;
199
235
434
<methods>public void <init>(com.lealone.db.session.ServerSession, com.lealone.db.schema.Schema) <variables>protected final non-sealed com.lealone.db.schema.Schema schema
lealone_Lealone
Lealone/lealone-sql/src/main/java/com/lealone/sql/ddl/AlterTableSet.java
AlterTableSet
update
class AlterTableSet extends SchemaStatement { private final Table table; private final int type; private final boolean value; private boolean checkExisting; public AlterTableSet(ServerSession session, Table table, int type, boolean value) { super(session, table.getSchema()); this.table = table; this.type = type; this.value = value; } @Override public int getType() { return type; } public void setCheckExisting(boolean b) { this.checkExisting = b; } @Override public int update() {<FILL_FUNCTION_BODY>} }
session.getUser().checkRight(table, Right.ALL); DbObjectLock lock = tryAlterTable(table); if (lock == null) return -1; switch (type) { case SQLStatement.ALTER_TABLE_SET_REFERENTIAL_INTEGRITY: table.setCheckForeignKeyConstraints(session, value, value ? checkExisting : false); break; default: DbException.throwInternalError("type=" + type); } return 0;
176
135
311
<methods>public void <init>(com.lealone.db.session.ServerSession, com.lealone.db.schema.Schema) <variables>protected final non-sealed com.lealone.db.schema.Schema schema
lealone_Lealone
Lealone/lealone-sql/src/main/java/com/lealone/sql/ddl/AlterUser.java
AlterUser
update
class AlterUser extends UserStatement { private int type; private User user; private String newName; private boolean admin; public AlterUser(ServerSession session) { super(session); } @Override public int getType() { return type; } public void setType(int type) { this.type = type; } public void setUser(User user) { this.user = user; } public void setNewName(String newName) { this.newName = newName; } public void setAdmin(boolean admin) { this.admin = admin; } @Override public int update() {<FILL_FUNCTION_BODY>} }
Database db = session.getDatabase(); DbObjectLock lock = db.tryExclusiveAuthLock(session); if (lock == null) return -1; switch (type) { case SQLStatement.ALTER_USER_SET_PASSWORD: if (user != session.getUser()) { session.getUser().checkAdmin(); } if (hash != null && salt != null) { CreateUser.setSaltAndHash(user, session, salt, hash); } else { CreateUser.setPassword(user, session, password); } db.updateMeta(session, user); break; case SQLStatement.ALTER_USER_RENAME: session.getUser().checkAdmin(); if (db.findUser(session, newName) != null || newName.equals(user.getName())) { throw DbException.get(ErrorCode.USER_ALREADY_EXISTS_1, newName); } db.renameDatabaseObject(session, user, newName, lock); break; case SQLStatement.ALTER_USER_ADMIN: session.getUser().checkAdmin(); if (!admin) { user.checkOwnsNoSchemas(session); } user.setAdmin(admin); db.updateMeta(session, user); break; default: DbException.throwInternalError("type=" + type); } return 0;
200
366
566
<methods>public void setHash(com.lealone.sql.expression.Expression) ,public void setHashMongo(com.lealone.sql.expression.Expression) ,public void setHashMySQL(com.lealone.sql.expression.Expression) ,public void setHashPostgreSQL(com.lealone.sql.expression.Expression) ,public void setPassword(com.lealone.sql.expression.Expression) ,public void setSalt(com.lealone.sql.expression.Expression) ,public void setSaltMongo(com.lealone.sql.expression.Expression) ,public void setSaltMySQL(com.lealone.sql.expression.Expression) ,public void setSaltPostgreSQL(com.lealone.sql.expression.Expression) <variables>protected com.lealone.sql.expression.Expression hash,protected com.lealone.sql.expression.Expression hashMongo,protected com.lealone.sql.expression.Expression hashMySQL,protected com.lealone.sql.expression.Expression hashPostgreSQL,protected com.lealone.sql.expression.Expression password,protected com.lealone.sql.expression.Expression salt,protected com.lealone.sql.expression.Expression saltMongo,protected com.lealone.sql.expression.Expression saltMySQL,protected com.lealone.sql.expression.Expression saltPostgreSQL
lealone_Lealone
Lealone/lealone-sql/src/main/java/com/lealone/sql/ddl/AlterView.java
AlterView
update
class AlterView extends SchemaStatement { private TableView view; public AlterView(ServerSession session, Schema schema) { super(session, schema); } @Override public int getType() { return SQLStatement.ALTER_VIEW; } public void setView(TableView view) { this.view = view; } @Override public int update() {<FILL_FUNCTION_BODY>} }
session.getUser().checkRight(view, Right.ALL); if (schema.tryExclusiveLock(DbObjectType.TABLE_OR_VIEW, session) == null) return -1; DbException e = view.recompile(session, false); if (e != null) { throw e; } return 0;
123
93
216
<methods>public void <init>(com.lealone.db.session.ServerSession, com.lealone.db.schema.Schema) <variables>protected final non-sealed com.lealone.db.schema.Schema schema
lealone_Lealone
Lealone/lealone-sql/src/main/java/com/lealone/sql/ddl/Analyze.java
Analyze
update
class Analyze extends DefinitionStatement { /** * The sample size. */ private int sample; public Analyze(ServerSession session) { super(session); sample = session.getDatabase().getSettings().analyzeSample; } @Override public int getType() { return SQLStatement.ANALYZE; } public void setSample(int sample) { this.sample = sample; } @Override public int update() {<FILL_FUNCTION_BODY>} }
session.getUser().checkAdmin(); Database db = session.getDatabase(); for (Table table : db.getAllTablesAndViews(false)) { table.analyze(session, sample); } return 0;
141
63
204
<methods>public boolean isDDL() <variables>
lealone_Lealone
Lealone/lealone-sql/src/main/java/com/lealone/sql/ddl/CreateAggregate.java
CreateAggregate
update
class CreateAggregate extends SchemaStatement { private String name; private String javaClassName; private boolean ifNotExists; private boolean force; public CreateAggregate(ServerSession session, Schema schema) { super(session, schema); } @Override public int getType() { return SQLStatement.CREATE_AGGREGATE; } public void setName(String name) { this.name = name; } public void setJavaClassName(String string) { this.javaClassName = string; } public void setIfNotExists(boolean ifNotExists) { this.ifNotExists = ifNotExists; } public void setForce(boolean force) { this.force = force; } @Override public int update() {<FILL_FUNCTION_BODY>} }
session.getUser().checkAdmin(); DbObjectLock lock = schema.tryExclusiveLock(DbObjectType.AGGREGATE, session); if (lock == null) return -1; if (schema.findAggregate(session, name) != null || schema.findFunction(session, name) != null) { if (!ifNotExists) { throw DbException.get(ErrorCode.FUNCTION_ALIAS_ALREADY_EXISTS_1, name); } } else { int id = getObjectId(); UserAggregate aggregate = new UserAggregate(schema, id, name, javaClassName, force); schema.add(session, aggregate, lock); } return 0;
226
187
413
<methods>public void <init>(com.lealone.db.session.ServerSession, com.lealone.db.schema.Schema) <variables>protected final non-sealed com.lealone.db.schema.Schema schema
lealone_Lealone
Lealone/lealone-sql/src/main/java/com/lealone/sql/ddl/CreateConstant.java
CreateConstant
update
class CreateConstant extends SchemaStatement { private String constantName; private Expression expression; private boolean ifNotExists; public CreateConstant(ServerSession session, Schema schema) { super(session, schema); } @Override public int getType() { return SQLStatement.CREATE_CONSTANT; } public void setConstantName(String constantName) { this.constantName = constantName; } public void setExpression(Expression expr) { this.expression = expr; } public void setIfNotExists(boolean ifNotExists) { this.ifNotExists = ifNotExists; } @Override public int update() {<FILL_FUNCTION_BODY>} }
session.getUser().checkAdmin(); DbObjectLock lock = schema.tryExclusiveLock(DbObjectType.CONSTANT, session); if (lock == null) return -1; // 当成功获得排它锁后,不管以下代码是正常还是异常返回都不需要在这里手工释放锁, // 排它锁会在事务提交或回滚时自动被释放。 if (schema.findConstant(session, constantName) != null) { if (ifNotExists) { return 0; } throw DbException.get(ErrorCode.CONSTANT_ALREADY_EXISTS_1, constantName); } int id = getObjectId(); expression = expression.optimize(session); Value value = expression.getValue(session); Constant constant = new Constant(schema, id, constantName, value); schema.add(session, constant, lock); return 0;
196
237
433
<methods>public void <init>(com.lealone.db.session.ServerSession, com.lealone.db.schema.Schema) <variables>protected final non-sealed com.lealone.db.schema.Schema schema
lealone_Lealone
Lealone/lealone-sql/src/main/java/com/lealone/sql/ddl/CreateDatabase.java
CreateDatabase
update
class CreateDatabase extends DatabaseStatement { private final boolean ifNotExists; public CreateDatabase(ServerSession session, String dbName, boolean ifNotExists, RunMode runMode, CaseInsensitiveMap<String> parameters) { super(session, dbName); if (parameters == null) parameters = new CaseInsensitiveMap<>(); this.ifNotExists = ifNotExists; this.parameters = parameters; validateParameters(); } @Override public int getType() { return SQLStatement.CREATE_DATABASE; } @Override public int update() {<FILL_FUNCTION_BODY>} }
LealoneDatabase.checkAdminRight(session, "create database"); LealoneDatabase lealoneDB = LealoneDatabase.getInstance(); DbObjectLock lock = lealoneDB.tryExclusiveDatabaseLock(session); if (lock == null) return -1; if (LealoneDatabase.isMe(dbName) || lealoneDB.findDatabase(dbName) != null) { if (ifNotExists) { return 0; } throw DbException.get(ErrorCode.DATABASE_ALREADY_EXISTS_1, dbName); } // 设置默认SQL引擎 if (!parameters.containsKey(DbSetting.DEFAULT_SQL_ENGINE.name())) { Mode mode = session.getDatabase().getMode(); if (mode.isMySQL()) { parameters.put(DbSetting.DEFAULT_SQL_ENGINE.name(), mode.getName()); } } int id = getObjectId(lealoneDB); Database newDB = new Database(id, dbName, parameters); newDB.setRunMode(RunMode.CLIENT_SERVER); lealoneDB.addDatabaseObject(session, newDB, lock); // 将缓存过期掉 lealoneDB.getNextModificationMetaId(); // LealoneDatabase在启动过程中执行CREATE DATABASE时,不对数据库初始化 if (!lealoneDB.isStarting()) { newDB.init(); newDB.createRootUserIfNotExists(); } return 0;
165
386
551
<methods>public java.lang.String getDatabaseName() ,public boolean isDatabaseStatement() <variables>protected final non-sealed java.lang.String dbName,protected CaseInsensitiveMap<java.lang.String> parameters
lealone_Lealone
Lealone/lealone-sql/src/main/java/com/lealone/sql/ddl/CreateFunctionAlias.java
CreateFunctionAlias
update
class CreateFunctionAlias extends SchemaStatement { private String aliasName; private String javaClassMethod; private boolean deterministic; private boolean ifNotExists; private boolean force; private String source; private boolean bufferResultSetToLocalTemp = true; public CreateFunctionAlias(ServerSession session, Schema schema) { super(session, schema); } @Override public int getType() { return SQLStatement.CREATE_ALIAS; } public void setAliasName(String name) { this.aliasName = name; } /** * Set the qualified method name after removing whitespace. * * @param method the qualified method name */ public void setJavaClassMethod(String method) { this.javaClassMethod = StringUtils.replaceAll(method, " ", ""); } public void setDeterministic(boolean deterministic) { this.deterministic = deterministic; } public void setIfNotExists(boolean ifNotExists) { this.ifNotExists = ifNotExists; } public void setForce(boolean force) { this.force = force; } public void setSource(String source) { this.source = source; } /** * Should the return value ResultSet be buffered in a local temporary file? * * @param b the new value */ public void setBufferResultSetToLocalTemp(boolean b) { this.bufferResultSetToLocalTemp = b; } @Override public int update() {<FILL_FUNCTION_BODY>} }
session.getUser().checkAdmin(); DbObjectLock lock = schema.tryExclusiveLock(DbObjectType.FUNCTION_ALIAS, session); if (lock == null) return -1; if (schema.findFunction(session, aliasName) != null) { if (!ifNotExists) { throw DbException.get(ErrorCode.FUNCTION_ALIAS_ALREADY_EXISTS_1, aliasName); } } else { int id = getObjectId(); FunctionAlias functionAlias; if (javaClassMethod != null) { functionAlias = FunctionAlias.newInstance(schema, id, aliasName, javaClassMethod, force, bufferResultSetToLocalTemp); } else { functionAlias = FunctionAlias.newInstanceFromSource(schema, id, aliasName, source, force, bufferResultSetToLocalTemp); } functionAlias.setDeterministic(deterministic); schema.add(session, functionAlias, lock); } return 0;
421
270
691
<methods>public void <init>(com.lealone.db.session.ServerSession, com.lealone.db.schema.Schema) <variables>protected final non-sealed com.lealone.db.schema.Schema schema
lealone_Lealone
Lealone/lealone-sql/src/main/java/com/lealone/sql/ddl/CreateIndex.java
CreateIndex
update
class CreateIndex extends SchemaStatement { private String tableName; private String indexName; private IndexColumn[] indexColumns; private boolean ifNotExists; private boolean primaryKey, unique, hash; private String comment; public CreateIndex(ServerSession session, Schema schema) { super(session, schema); } @Override public int getType() { return SQLStatement.CREATE_INDEX; } public void setTableName(String tableName) { this.tableName = tableName; } public void setIndexName(String indexName) { this.indexName = indexName; } public void setIndexColumns(IndexColumn[] columns) { this.indexColumns = columns; } public void setIfNotExists(boolean ifNotExists) { this.ifNotExists = ifNotExists; } public void setPrimaryKey(boolean b) { this.primaryKey = b; } public void setUnique(boolean b) { this.unique = b; } public void setHash(boolean b) { this.hash = b; } public void setComment(String comment) { this.comment = comment; } @Override public int update() {<FILL_FUNCTION_BODY>} }
DbObjectLock lock = schema.tryExclusiveLock(DbObjectType.INDEX, session); if (lock == null) return -1; Table table = schema.getTableOrView(session, tableName); if (schema.findIndex(session, indexName) != null) { if (ifNotExists) { return 0; } throw DbException.get(ErrorCode.INDEX_ALREADY_EXISTS_1, indexName); } if (!table.tryExclusiveLock(session)) return -1; session.getUser().checkRight(table, Right.ALL); int id = getObjectId(); if (indexName == null) { if (primaryKey) { indexName = table.getSchema().getUniqueIndexName(session, table, Constants.PREFIX_PRIMARY_KEY); } else { indexName = table.getSchema().getUniqueIndexName(session, table, Constants.PREFIX_INDEX); } } IndexType indexType; if (primaryKey) { if (table.findPrimaryKey() != null) { throw DbException.get(ErrorCode.SECOND_PRIMARY_KEY); } indexType = IndexType.createPrimaryKey(hash); } else if (unique) { indexType = IndexType.createUnique(hash); } else { indexType = IndexType.createNonUnique(hash); } IndexColumn.mapColumns(indexColumns, table); boolean create = !session.getDatabase().isStarting(); table.addIndex(session, indexName, id, indexColumns, indexType, create, comment, lock); return 0;
344
432
776
<methods>public void <init>(com.lealone.db.session.ServerSession, com.lealone.db.schema.Schema) <variables>protected final non-sealed com.lealone.db.schema.Schema schema
lealone_Lealone
Lealone/lealone-sql/src/main/java/com/lealone/sql/ddl/CreateRole.java
CreateRole
update
class CreateRole extends AuthStatement { private String roleName; private boolean ifNotExists; public CreateRole(ServerSession session) { super(session); } @Override public int getType() { return SQLStatement.CREATE_ROLE; } public void setRoleName(String name) { this.roleName = name; } public void setIfNotExists(boolean ifNotExists) { this.ifNotExists = ifNotExists; } @Override public int update() {<FILL_FUNCTION_BODY>} }
session.getUser().checkAdmin(); Database db = session.getDatabase(); DbObjectLock lock = db.tryExclusiveAuthLock(session); if (lock == null) return -1; if (db.findUser(session, roleName) != null) { throw DbException.get(ErrorCode.USER_ALREADY_EXISTS_1, roleName); } if (db.findRole(session, roleName) != null) { if (ifNotExists) { return 0; } throw DbException.get(ErrorCode.ROLE_ALREADY_EXISTS_1, roleName); } int id = getObjectId(); Role role = new Role(db, id, roleName, false); db.addDatabaseObject(session, role, lock); return 0;
154
219
373
<no_super_class>
lealone_Lealone
Lealone/lealone-sql/src/main/java/com/lealone/sql/ddl/CreateSchema.java
CreateSchema
update
class CreateSchema extends DefinitionStatement { private String schemaName; private String authorization; private boolean ifNotExists; public CreateSchema(ServerSession session) { super(session); } @Override public int getType() { return SQLStatement.CREATE_SCHEMA; } public void setSchemaName(String name) { this.schemaName = name; } public void setAuthorization(String userName) { this.authorization = userName; } public void setIfNotExists(boolean ifNotExists) { this.ifNotExists = ifNotExists; } @Override public int update() {<FILL_FUNCTION_BODY>} }
session.getUser().checkSchemaAdmin(); Database db = session.getDatabase(); DbObjectLock lock = db.tryExclusiveSchemaLock(session); if (lock == null) return -1; User user = db.getUser(session, authorization); // during DB startup, the Right/Role records have not yet been loaded if (!db.isStarting()) { user.checkSchemaAdmin(); } if (db.findSchema(session, schemaName) != null) { if (ifNotExists) { return 0; } throw DbException.get(ErrorCode.SCHEMA_ALREADY_EXISTS_1, schemaName); } int id = getObjectId(); Schema schema = new Schema(db, id, schemaName, user, false); db.addDatabaseObject(session, schema, lock); return 0;
189
229
418
<methods>public boolean isDDL() <variables>
lealone_Lealone
Lealone/lealone-sql/src/main/java/com/lealone/sql/ddl/CreateSequence.java
CreateSequence
update
class CreateSequence extends SchemaStatement { private String sequenceName; private boolean ifNotExists; private boolean cycle; private Expression minValue; private Expression maxValue; private Expression start; private Expression increment; private Expression cacheSize; private boolean belongsToTable; private boolean transactional; public CreateSequence(ServerSession session, Schema schema) { super(session, schema); } @Override public int getType() { return SQLStatement.CREATE_SEQUENCE; } public void setSequenceName(String sequenceName) { this.sequenceName = sequenceName; } public void setIfNotExists(boolean ifNotExists) { this.ifNotExists = ifNotExists; } public void setCycle(boolean cycle) { this.cycle = cycle; } public void setMinValue(Expression minValue) { this.minValue = minValue; } public void setMaxValue(Expression maxValue) { this.maxValue = maxValue; } public void setStartWith(Expression start) { this.start = start; } public void setIncrement(Expression increment) { this.increment = increment; } public void setCacheSize(Expression cacheSize) { this.cacheSize = cacheSize; } public void setBelongsToTable(boolean belongsToTable) { this.belongsToTable = belongsToTable; } public void setTransactional(boolean transactional) { this.transactional = transactional; } @Override public int update() {<FILL_FUNCTION_BODY>} private Long getLong(Expression expr) { return getLong(session, expr); } static Long getLong(ServerSession session, Expression expr) { if (expr == null) { return null; } return expr.optimize(session).getValue(session).getLong(); } }
DbObjectLock lock = schema.tryExclusiveLock(DbObjectType.SEQUENCE, session); if (lock == null) return -1; if (schema.findSequence(session, sequenceName) != null) { if (ifNotExists) { return 0; } throw DbException.get(ErrorCode.SEQUENCE_ALREADY_EXISTS_1, sequenceName); } int id = getObjectId(); Long startValue = getLong(start); Long inc = getLong(increment); Long cache = getLong(cacheSize); Long min = getLong(minValue); Long max = getLong(maxValue); Sequence sequence = new Sequence(schema, id, sequenceName, startValue, inc, cache, min, max, cycle, belongsToTable); sequence.setTransactional(transactional); schema.add(session, sequence, lock); return 0;
521
240
761
<methods>public void <init>(com.lealone.db.session.ServerSession, com.lealone.db.schema.Schema) <variables>protected final non-sealed com.lealone.db.schema.Schema schema
lealone_Lealone
Lealone/lealone-sql/src/main/java/com/lealone/sql/ddl/CreateTrigger.java
CreateTrigger
update
class CreateTrigger extends SchemaStatement { private String triggerName; private boolean ifNotExists; private boolean insteadOf; private boolean before; private int typeMask; private boolean rowBased; private int queueSize = TriggerObject.DEFAULT_QUEUE_SIZE; private boolean noWait; private String tableName; private String triggerClassName; private String triggerSource; private boolean force; private boolean onRollback; public CreateTrigger(ServerSession session, Schema schema) { super(session, schema); } @Override public int getType() { return SQLStatement.CREATE_TRIGGER; } public void setTriggerName(String name) { this.triggerName = name; } public void setIfNotExists(boolean ifNotExists) { this.ifNotExists = ifNotExists; } public void setInsteadOf(boolean insteadOf) { this.insteadOf = insteadOf; } public void setBefore(boolean before) { this.before = before; } public void setTypeMask(int typeMask) { this.typeMask = typeMask; } public void setRowBased(boolean rowBased) { this.rowBased = rowBased; } public void setQueueSize(int size) { this.queueSize = size; } public void setNoWait(boolean noWait) { this.noWait = noWait; } public void setTableName(String tableName) { this.tableName = tableName; } public void setTriggerClassName(String triggerClassName) { this.triggerClassName = triggerClassName; } public void setTriggerSource(String triggerSource) { this.triggerSource = triggerSource; } public void setForce(boolean force) { this.force = force; } public void setOnRollback(boolean onRollback) { this.onRollback = onRollback; } @Override public int update() {<FILL_FUNCTION_BODY>} }
DbObjectLock lock = schema.tryExclusiveLock(DbObjectType.TRIGGER, session); if (lock == null) return -1; if (schema.findTrigger(session, triggerName) != null) { if (ifNotExists) { return 0; } throw DbException.get(ErrorCode.TRIGGER_ALREADY_EXISTS_1, triggerName); } if ((typeMask & Trigger.SELECT) == Trigger.SELECT && rowBased) { throw DbException.get(ErrorCode.TRIGGER_SELECT_AND_ROW_BASED_NOT_SUPPORTED, triggerName); } int id = getObjectId(); Table table = schema.getTableOrView(session, tableName); TriggerObject trigger = new TriggerObject(schema, id, triggerName, table); trigger.setInsteadOf(insteadOf); trigger.setBefore(before); trigger.setNoWait(noWait); trigger.setQueueSize(queueSize); trigger.setRowBased(rowBased); trigger.setTypeMask(typeMask); trigger.setOnRollback(onRollback); if (this.triggerClassName != null) { trigger.setTriggerClassName(triggerClassName, force); } else { trigger.setTriggerSource(triggerSource, force); } lock.addHandler(ar -> { if (ar.isSucceeded()) table.addTrigger(trigger); }); schema.add(session, trigger, lock); return 0;
555
403
958
<methods>public void <init>(com.lealone.db.session.ServerSession, com.lealone.db.schema.Schema) <variables>protected final non-sealed com.lealone.db.schema.Schema schema
lealone_Lealone
Lealone/lealone-sql/src/main/java/com/lealone/sql/ddl/CreateUser.java
CreateUser
update
class CreateUser extends UserStatement { private String userName; private boolean admin; private String comment; private boolean ifNotExists; public CreateUser(ServerSession session) { super(session); } @Override public int getType() { return SQLStatement.CREATE_USER; } public void setUserName(String userName) { this.userName = userName; } public void setAdmin(boolean b) { admin = b; } public void setComment(String comment) { this.comment = comment; } public void setIfNotExists(boolean ifNotExists) { this.ifNotExists = ifNotExists; } @Override public int update() {<FILL_FUNCTION_BODY>} /** * Set the salt and hash for the given user. * * @param user the user * @param session the session * @param salt the salt * @param hash the hash */ static void setSaltAndHash(User user, ServerSession session, Expression salt, Expression hash) { user.setSaltAndHash(getByteArray(session, salt), getByteArray(session, hash)); } private static byte[] getByteArray(ServerSession session, Expression e) { String s = e.optimize(session).getValue(session).getString(); return s == null ? new byte[0] : StringUtils.convertHexToBytes(s); } /** * Set the password for the given user. * * @param user the user * @param session the session * @param password the password */ static void setPassword(User user, ServerSession session, Expression password) { String pwd = password.optimize(session).getValue(session).getString(); PasswordHash.setPassword(user, pwd); } }
session.getUser().checkAdmin(); Database db = session.getDatabase(); DbObjectLock lock = db.tryExclusiveAuthLock(session); if (lock == null) return -1; if (db.findRole(session, userName) != null) { throw DbException.get(ErrorCode.ROLE_ALREADY_EXISTS_1, userName); } if (db.findUser(session, userName) != null) { if (ifNotExists) { return 0; } throw DbException.get(ErrorCode.USER_ALREADY_EXISTS_1, userName); } int id = getObjectId(); User user = new User(db, id, userName, false); user.setAdmin(admin); user.setComment(comment); if (hash != null && salt != null) { setSaltAndHash(user, session, salt, hash); } else if (password != null) { setPassword(user, session, password); } else { throw DbException.getInternalError(); } if (hashMongo != null && saltMongo != null) user.setSaltAndHashMongo(getByteArray(session, saltMongo), getByteArray(session, hashMongo)); if (hashMySQL != null && saltMySQL != null) user.setSaltAndHashMySQL(getByteArray(session, saltMySQL), getByteArray(session, hashMySQL)); if (hashPostgreSQL != null && saltPostgreSQL != null) user.setSaltAndHashPostgreSQL(getByteArray(session, saltPostgreSQL), getByteArray(session, hashPostgreSQL)); db.addDatabaseObject(session, user, lock); return 0;
486
460
946
<methods>public void setHash(com.lealone.sql.expression.Expression) ,public void setHashMongo(com.lealone.sql.expression.Expression) ,public void setHashMySQL(com.lealone.sql.expression.Expression) ,public void setHashPostgreSQL(com.lealone.sql.expression.Expression) ,public void setPassword(com.lealone.sql.expression.Expression) ,public void setSalt(com.lealone.sql.expression.Expression) ,public void setSaltMongo(com.lealone.sql.expression.Expression) ,public void setSaltMySQL(com.lealone.sql.expression.Expression) ,public void setSaltPostgreSQL(com.lealone.sql.expression.Expression) <variables>protected com.lealone.sql.expression.Expression hash,protected com.lealone.sql.expression.Expression hashMongo,protected com.lealone.sql.expression.Expression hashMySQL,protected com.lealone.sql.expression.Expression hashPostgreSQL,protected com.lealone.sql.expression.Expression password,protected com.lealone.sql.expression.Expression salt,protected com.lealone.sql.expression.Expression saltMongo,protected com.lealone.sql.expression.Expression saltMySQL,protected com.lealone.sql.expression.Expression saltPostgreSQL
lealone_Lealone
Lealone/lealone-sql/src/main/java/com/lealone/sql/ddl/CreateUserDataType.java
CreateUserDataType
update
class CreateUserDataType extends SchemaStatement { private String typeName; private Column column; private boolean ifNotExists; public CreateUserDataType(ServerSession session, Schema schema) { super(session, schema); } @Override public int getType() { return SQLStatement.CREATE_DOMAIN; } public void setTypeName(String name) { this.typeName = name; } public void setColumn(Column column) { this.column = column; } public void setIfNotExists(boolean ifNotExists) { this.ifNotExists = ifNotExists; } @Override public int update() {<FILL_FUNCTION_BODY>} }
session.getUser().checkAdmin(); DbObjectLock lock = schema.tryExclusiveLock(DbObjectType.USER_DATATYPE, session); if (lock == null) return -1; if (schema.findUserDataType(session, typeName) != null) { if (ifNotExists) { return 0; } throw DbException.get(ErrorCode.USER_DATA_TYPE_ALREADY_EXISTS_1, typeName); } DataType builtIn = DataType.getTypeByName(typeName); if (builtIn != null) { if (!builtIn.hidden) { throw DbException.get(ErrorCode.USER_DATA_TYPE_ALREADY_EXISTS_1, typeName); } Table table = session.getDatabase().getFirstUserTable(); if (table != null) { throw DbException.get(ErrorCode.USER_DATA_TYPE_ALREADY_EXISTS_1, typeName + " (" + table.getSQL() + ")"); } } int id = getObjectId(); UserDataType type = new UserDataType(schema, id, typeName); type.setColumn(column); schema.add(session, type, lock); return 0;
194
329
523
<methods>public void <init>(com.lealone.db.session.ServerSession, com.lealone.db.schema.Schema) <variables>protected final non-sealed com.lealone.db.schema.Schema schema
lealone_Lealone
Lealone/lealone-sql/src/main/java/com/lealone/sql/ddl/CreateView.java
CreateView
update
class CreateView extends SchemaStatement { private String viewName; private boolean ifNotExists; private Query select; private String selectSQL; private String[] columnNames; private String comment; private boolean orReplace; private boolean force; public CreateView(ServerSession session, Schema schema) { super(session, schema); } @Override public int getType() { return SQLStatement.CREATE_VIEW; } public void setViewName(String name) { viewName = name; } public void setIfNotExists(boolean ifNotExists) { this.ifNotExists = ifNotExists; } public void setSelect(Query select) { this.select = select; } public void setSelectSQL(String selectSQL) { this.selectSQL = selectSQL; } public void setColumnNames(String[] cols) { this.columnNames = cols; } public void setComment(String comment) { this.comment = comment; } public void setOrReplace(boolean orReplace) { this.orReplace = orReplace; } public void setForce(boolean force) { this.force = force; } @Override public int update() {<FILL_FUNCTION_BODY>} }
DbObjectLock lock = schema.tryExclusiveLock(DbObjectType.TABLE_OR_VIEW, session); if (lock == null) return -1; Database db = session.getDatabase(); TableView view = null; Table old = getSchema().findTableOrView(session, viewName); if (old != null) { if (ifNotExists) { return 0; } if (!orReplace || old.getTableType() != TableType.VIEW) { throw DbException.get(ErrorCode.VIEW_ALREADY_EXISTS_1, viewName); } view = (TableView) old; } int id = getObjectId(); String querySQL; if (select == null) { querySQL = selectSQL; } else { ArrayList<Parameter> params = select.getParameters(); if (params != null && params.size() > 0) { throw DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED_1, "parameters in views"); } querySQL = select.getPlanSQL(); } ServerSession sysSession = db.getSystemSession(); try { if (view == null) { Schema schema = session.getDatabase().getSchema(session, session.getCurrentSchemaName()); sysSession.setCurrentSchema(schema); view = new TableView(getSchema(), id, viewName, querySQL, null, columnNames, sysSession, false); } else { view.replace(querySQL, columnNames, sysSession, false, force); } } finally { sysSession.setCurrentSchema(db.getSchema(session, Constants.SCHEMA_MAIN)); } if (comment != null) { view.setComment(comment); } if (old == null) { getSchema().add(session, view, lock); } else { db.updateMeta(session, view); } return 0;
350
508
858
<methods>public void <init>(com.lealone.db.session.ServerSession, com.lealone.db.schema.Schema) <variables>protected final non-sealed com.lealone.db.schema.Schema schema
lealone_Lealone
Lealone/lealone-sql/src/main/java/com/lealone/sql/ddl/DatabaseStatement.java
DatabaseStatement
validateParameters
class DatabaseStatement extends DefinitionStatement { protected final String dbName; protected CaseInsensitiveMap<String> parameters; protected DatabaseStatement(ServerSession session, String dbName) { super(session); this.dbName = dbName; } @Override public boolean isDatabaseStatement() { return true; } public String getDatabaseName() { return dbName; } protected void validateParameters() {<FILL_FUNCTION_BODY>} }
if (parameters == null || parameters.isEmpty()) return; CaseInsensitiveMap<String> parameters = new CaseInsensitiveMap<>(this.parameters); HashSet<String> recognizedSettingOptions = new HashSet<>(DbSetting.values().length); for (DbSetting s : DbSetting.values()) recognizedSettingOptions.add(s.name()); parameters.removeAll(recognizedSettingOptions); if (!parameters.isEmpty()) { throw new ConfigException(String.format("Unrecognized parameters: %s for database %s, " // + "recognized database setting options: %s", // parameters.keySet(), dbName, recognizedSettingOptions)); }
129
168
297
<methods>public boolean isDDL() <variables>
lealone_Lealone
Lealone/lealone-sql/src/main/java/com/lealone/sql/ddl/DropAggregate.java
DropAggregate
update
class DropAggregate extends SchemaStatement { private String name; private boolean ifExists; public DropAggregate(ServerSession session, Schema schema) { super(session, schema); } @Override public int getType() { return SQLStatement.DROP_AGGREGATE; } public void setName(String name) { this.name = name; } public void setIfExists(boolean ifExists) { this.ifExists = ifExists; } @Override public int update() {<FILL_FUNCTION_BODY>} }
session.getUser().checkAdmin(); DbObjectLock lock = schema.tryExclusiveLock(DbObjectType.AGGREGATE, session); if (lock == null) return -1; UserAggregate aggregate = schema.findAggregate(session, name); if (aggregate == null) { if (!ifExists) { throw DbException.get(ErrorCode.AGGREGATE_NOT_FOUND_1, name); } } else { schema.remove(session, aggregate, lock); } return 0;
158
145
303
<methods>public void <init>(com.lealone.db.session.ServerSession, com.lealone.db.schema.Schema) <variables>protected final non-sealed com.lealone.db.schema.Schema schema
lealone_Lealone
Lealone/lealone-sql/src/main/java/com/lealone/sql/ddl/DropConstant.java
DropConstant
update
class DropConstant extends SchemaStatement { private String constantName; private boolean ifExists; public DropConstant(ServerSession session, Schema schema) { super(session, schema); } @Override public int getType() { return SQLStatement.DROP_CONSTANT; } public void setConstantName(String constantName) { this.constantName = constantName; } public void setIfExists(boolean b) { ifExists = b; } @Override public int update() {<FILL_FUNCTION_BODY>} }
session.getUser().checkAdmin(); DbObjectLock lock = schema.tryExclusiveLock(DbObjectType.CONSTANT, session); if (lock == null) return -1; Constant constant = schema.findConstant(session, constantName); if (constant == null) { if (!ifExists) { throw DbException.get(ErrorCode.CONSTANT_NOT_FOUND_1, constantName); } } else { schema.remove(session, constant, lock); } return 0;
156
140
296
<methods>public void <init>(com.lealone.db.session.ServerSession, com.lealone.db.schema.Schema) <variables>protected final non-sealed com.lealone.db.schema.Schema schema
lealone_Lealone
Lealone/lealone-sql/src/main/java/com/lealone/sql/ddl/DropDatabase.java
DropDatabase
update
class DropDatabase extends DatabaseStatement { private boolean ifExists; public DropDatabase(ServerSession session, String dbName) { super(session, dbName); } @Override public int getType() { return SQLStatement.DROP_DATABASE; } public void setIfExists(boolean ifExists) { this.ifExists = ifExists; } @Override public int update() {<FILL_FUNCTION_BODY>} }
LealoneDatabase.checkAdminRight(session, "drop database"); if (LealoneDatabase.isMe(dbName)) { throw DbException.get(ErrorCode.CANNOT_DROP_LEALONE_DATABASE); } LealoneDatabase lealoneDB = LealoneDatabase.getInstance(); DbObjectLock lock = lealoneDB.tryExclusiveDatabaseLock(session); if (lock == null) return -1; Database db = lealoneDB.getDatabase(dbName); if (db == null) { if (!ifExists) throw DbException.get(ErrorCode.DATABASE_NOT_FOUND_1, dbName); } else { lealoneDB.removeDatabaseObject(session, db, lock); // Lealone不同于H2数据库,在H2的一个数据库中可以访问另一个数据库的对象,而Lealone不允许, // 所以在H2中需要一个对象一个对象地删除,这样其他数据库中的对象对他们的引用才能解除, // 而Lealone只要在LealoneDatabase中删除对当前数据库的引用然后删除底层的文件即可。 db.markClosed(); db.drop(); } return 0;
126
311
437
<methods>public java.lang.String getDatabaseName() ,public boolean isDatabaseStatement() <variables>protected final non-sealed java.lang.String dbName,protected CaseInsensitiveMap<java.lang.String> parameters
lealone_Lealone
Lealone/lealone-sql/src/main/java/com/lealone/sql/ddl/DropFunctionAlias.java
DropFunctionAlias
update
class DropFunctionAlias extends SchemaStatement { private String aliasName; private boolean ifExists; public DropFunctionAlias(ServerSession session, Schema schema) { super(session, schema); } @Override public int getType() { return SQLStatement.DROP_ALIAS; } public void setAliasName(String name) { this.aliasName = name; } public void setIfExists(boolean ifExists) { this.ifExists = ifExists; } @Override public int update() {<FILL_FUNCTION_BODY>} }
session.getUser().checkAdmin(); DbObjectLock lock = schema.tryExclusiveLock(DbObjectType.FUNCTION_ALIAS, session); if (lock == null) return -1; FunctionAlias functionAlias = schema.findFunction(session, aliasName); if (functionAlias == null) { if (!ifExists) { throw DbException.get(ErrorCode.FUNCTION_ALIAS_NOT_FOUND_1, aliasName); } } else { schema.remove(session, functionAlias, lock); } return 0;
163
154
317
<methods>public void <init>(com.lealone.db.session.ServerSession, com.lealone.db.schema.Schema) <variables>protected final non-sealed com.lealone.db.schema.Schema schema
lealone_Lealone
Lealone/lealone-sql/src/main/java/com/lealone/sql/ddl/DropIndex.java
DropIndex
update
class DropIndex extends SchemaStatement { private String indexName; private boolean ifExists; public DropIndex(ServerSession session, Schema schema) { super(session, schema); } @Override public int getType() { return SQLStatement.DROP_INDEX; } public void setIndexName(String indexName) { this.indexName = indexName; } public void setIfExists(boolean b) { ifExists = b; } @Override public int update() {<FILL_FUNCTION_BODY>} }
DbObjectLock lock = schema.tryExclusiveLock(DbObjectType.INDEX, session); if (lock == null) return -1; Index index = schema.findIndex(session, indexName); if (index == null) { if (!ifExists) { throw DbException.get(ErrorCode.INDEX_NOT_FOUND_1, indexName); } } else { Table table = index.getTable(); session.getUser().checkRight(table, Right.ALL); Constraint pkConstraint = null; ArrayList<Constraint> constraints = table.getConstraints(); for (int i = 0; constraints != null && i < constraints.size(); i++) { Constraint cons = constraints.get(i); if (cons.usesIndex(index)) { // can drop primary key index (for compatibility) if (Constraint.PRIMARY_KEY.equals(cons.getConstraintType())) { pkConstraint = cons; } else { throw DbException.get(ErrorCode.INDEX_BELONGS_TO_CONSTRAINT_2, indexName, cons.getName()); } } } table.setModified(); if (pkConstraint != null) { schema.remove(session, pkConstraint, lock); } else { schema.remove(session, index, lock); } } return 0;
154
355
509
<methods>public void <init>(com.lealone.db.session.ServerSession, com.lealone.db.schema.Schema) <variables>protected final non-sealed com.lealone.db.schema.Schema schema
lealone_Lealone
Lealone/lealone-sql/src/main/java/com/lealone/sql/ddl/DropRole.java
DropRole
update
class DropRole extends AuthStatement { private String roleName; private boolean ifExists; public DropRole(ServerSession session) { super(session); } @Override public int getType() { return SQLStatement.DROP_ROLE; } public void setRoleName(String roleName) { this.roleName = roleName; } public void setIfExists(boolean ifExists) { this.ifExists = ifExists; } @Override public int update() {<FILL_FUNCTION_BODY>} }
session.getUser().checkAdmin(); Database db = session.getDatabase(); DbObjectLock lock = db.tryExclusiveAuthLock(session); if (lock == null) return -1; if (roleName.equals(Constants.PUBLIC_ROLE_NAME)) { throw DbException.get(ErrorCode.ROLE_CAN_NOT_BE_DROPPED_1, roleName); } Role role = db.findRole(session, roleName); if (role == null) { if (!ifExists) { throw DbException.get(ErrorCode.ROLE_NOT_FOUND_1, roleName); } } else { db.removeDatabaseObject(session, role, lock); } return 0;
152
201
353
<no_super_class>
lealone_Lealone
Lealone/lealone-sql/src/main/java/com/lealone/sql/ddl/DropSchema.java
DropSchema
update
class DropSchema extends DefinitionStatement { private String schemaName; private boolean ifExists; public DropSchema(ServerSession session) { super(session); } @Override public int getType() { return SQLStatement.DROP_SCHEMA; } public void setSchemaName(String name) { this.schemaName = name; } public void setIfExists(boolean ifExists) { this.ifExists = ifExists; } @Override public int update() {<FILL_FUNCTION_BODY>} }
session.getUser().checkAdmin(); Database db = session.getDatabase(); DbObjectLock lock = db.tryExclusiveSchemaLock(session); if (lock == null) return -1; Schema schema = db.findSchema(session, schemaName); if (schema == null) { if (!ifExists) { throw DbException.get(ErrorCode.SCHEMA_NOT_FOUND_1, schemaName); } } else { if (!schema.canDrop()) { throw DbException.get(ErrorCode.SCHEMA_CAN_NOT_BE_DROPPED_1, schemaName); } db.removeDatabaseObject(session, schema, lock); } return 0;
151
192
343
<methods>public boolean isDDL() <variables>
lealone_Lealone
Lealone/lealone-sql/src/main/java/com/lealone/sql/ddl/DropSequence.java
DropSequence
update
class DropSequence extends SchemaStatement { private String sequenceName; private boolean ifExists; public DropSequence(ServerSession session, Schema schema) { super(session, schema); } @Override public int getType() { return SQLStatement.DROP_SEQUENCE; } public void setSequenceName(String sequenceName) { this.sequenceName = sequenceName; } public void setIfExists(boolean b) { ifExists = b; } @Override public int update() {<FILL_FUNCTION_BODY>} }
session.getUser().checkAdmin(); DbObjectLock lock = schema.tryExclusiveLock(DbObjectType.SEQUENCE, session); if (lock == null) return -1; Sequence sequence = schema.findSequence(session, sequenceName); if (sequence == null) { if (!ifExists) { throw DbException.get(ErrorCode.SEQUENCE_NOT_FOUND_1, sequenceName); } } else { if (sequence.getBelongsToTable()) { throw DbException.get(ErrorCode.SEQUENCE_BELONGS_TO_A_TABLE_1, sequenceName); } schema.remove(session, sequence, lock); } return 0;
156
189
345
<methods>public void <init>(com.lealone.db.session.ServerSession, com.lealone.db.schema.Schema) <variables>protected final non-sealed com.lealone.db.schema.Schema schema