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-sql/src/main/java/com/lealone/sql/ddl/DropService.java
|
DropService
|
update
|
class DropService extends SchemaStatement {
private String serviceName;
private boolean ifExists;
public DropService(ServerSession session, Schema schema) {
super(session, schema);
}
@Override
public int getType() {
return SQLStatement.DROP_SERVICE;
}
public void setServiceName(String serviceName) {
this.serviceName = serviceName;
}
public void setIfExists(boolean b) {
ifExists = b;
}
@Override
public int update() {<FILL_FUNCTION_BODY>}
}
|
session.getUser().checkAdmin();
DbObjectLock lock = schema.tryExclusiveLock(DbObjectType.SERVICE, session);
if (lock == null)
return -1;
Service service = schema.findService(session, serviceName);
if (service == null) {
if (!ifExists) {
throw DbException.get(ErrorCode.SERVICE_NOT_FOUND_1, serviceName);
}
} else {
schema.remove(session, service, lock);
}
return 0;
| 155
| 138
| 293
|
<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/DropTable.java
|
DropTable
|
executeDrop
|
class DropTable extends SchemaStatement {
private String tableName;
private boolean ifExists;
private int dropAction;
private Table table;
private DropTable next;
public DropTable(ServerSession session, Schema schema) {
super(session, schema);
dropAction = session.getDatabase().getSettings().dropRestrict ? ConstraintReferential.RESTRICT
: ConstraintReferential.CASCADE;
}
@Override
public int getType() {
return SQLStatement.DROP_TABLE;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
public void setIfExists(boolean b) {
ifExists = b;
if (next != null) {
next.setIfExists(b);
}
}
public void setDropAction(int dropAction) {
this.dropAction = dropAction;
if (next != null) {
next.setDropAction(dropAction);
}
}
/**
* Chain another drop table statement to this statement.
*
* @param drop the statement to add
*/
public void addNextDropTable(DropTable drop) {
if (next == null) {
next = drop;
} else {
next.addNextDropTable(drop);
}
}
private boolean prepareDrop() {
table = schema.findTableOrView(session, tableName);
if (table == null) {
if (!ifExists) {
throw DbException.get(ErrorCode.TABLE_OR_VIEW_NOT_FOUND_1, tableName);
}
} else {
session.getUser().checkRight(table, Right.ALL);
if (!table.canDrop()) {
throw DbException.get(ErrorCode.CANNOT_DROP_TABLE_1, tableName);
}
if (dropAction == ConstraintReferential.RESTRICT) {
ArrayList<TableView> views = table.getViews();
if (views != null && views.size() > 0) {
StatementBuilder buff = new StatementBuilder();
for (TableView v : views) {
buff.appendExceptFirst(", ");
buff.append(v.getName());
}
throw DbException.get(ErrorCode.CANNOT_DROP_2, tableName, buff.toString());
}
}
if (!table.tryExclusiveLock(session))
return false;
}
if (next != null) {
return next.prepareDrop();
}
return true;
}
private void executeDrop(DbObjectLock lock) {<FILL_FUNCTION_BODY>}
@Override
public int update() {
DbObjectLock lock = schema.tryExclusiveLock(DbObjectType.TABLE_OR_VIEW, session);
if (lock == null)
return -1;
if (!prepareDrop())
return -1;
executeDrop(lock);
return 0;
}
}
|
// need to get the table again, because it may be dropped already
// meanwhile (dependent object, or same object)
table = schema.findTableOrView(session, tableName);
if (table != null) {
int id = table.getId();
table.setModified();
schema.remove(session, table, lock);
Database db = session.getDatabase();
db.getTableAlterHistory().deleteRecords(id);
}
if (next != null) {
next.executeDrop(lock);
}
| 775
| 138
| 913
|
<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/DropTrigger.java
|
DropTrigger
|
update
|
class DropTrigger extends SchemaStatement {
private String triggerName;
private boolean ifExists;
public DropTrigger(ServerSession session, Schema schema) {
super(session, schema);
}
@Override
public int getType() {
return SQLStatement.DROP_TRIGGER;
}
public void setTriggerName(String triggerName) {
this.triggerName = triggerName;
}
public void setIfExists(boolean b) {
ifExists = b;
}
@Override
public int update() {<FILL_FUNCTION_BODY>}
}
|
DbObjectLock lock = schema.tryExclusiveLock(DbObjectType.TRIGGER, session);
if (lock == null)
return -1;
TriggerObject trigger = schema.findTrigger(session, triggerName);
if (trigger == null) {
if (!ifExists) {
throw DbException.get(ErrorCode.TRIGGER_NOT_FOUND_1, triggerName);
}
} else {
Table table = trigger.getTable();
session.getUser().checkRight(table, Right.ALL);
schema.remove(session, trigger, lock);
}
return 0;
| 159
| 159
| 318
|
<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/DropUser.java
|
DropUser
|
update
|
class DropUser extends AuthStatement {
private String userName;
private boolean ifExists;
public DropUser(ServerSession session) {
super(session);
}
@Override
public int getType() {
return SQLStatement.DROP_USER;
}
public void setUserName(String userName) {
this.userName = userName;
}
public void setIfExists(boolean b) {
ifExists = b;
}
@Override
public int update() {<FILL_FUNCTION_BODY>}
}
|
session.getUser().checkAdmin();
Database db = session.getDatabase();
DbObjectLock lock = db.tryExclusiveAuthLock(session);
if (lock == null)
return -1;
User user = db.findUser(session, userName);
if (user == null) {
if (!ifExists) {
throw DbException.get(ErrorCode.USER_NOT_FOUND_1, userName);
}
} else {
if (user == session.getUser()) {
int adminUserCount = 0;
for (User u : db.getAllUsers()) {
if (u.isAdmin()) {
adminUserCount++;
}
}
// 运行到这里时当前用户必定是有Admin权限的,如果当前用户想删除它自己,
// 同时系统中又没有其他Admin权限的用户了,那么不允许它删除自己
if (adminUserCount == 1) {
throw DbException.get(ErrorCode.CANNOT_DROP_CURRENT_USER);
}
}
user.checkOwnsNoSchemas(session); // 删除用户前需要删除它拥有的所有Schema,否则不允许删
db.removeDatabaseObject(session, user, lock);
}
return 0;
| 147
| 325
| 472
|
<no_super_class>
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/ddl/DropUserDataType.java
|
DropUserDataType
|
update
|
class DropUserDataType extends SchemaStatement {
private String typeName;
private boolean ifExists;
public DropUserDataType(ServerSession session, Schema schema) {
super(session, schema);
}
@Override
public int getType() {
return SQLStatement.DROP_DOMAIN;
}
public void setTypeName(String name) {
this.typeName = name;
}
public void setIfExists(boolean ifExists) {
this.ifExists = ifExists;
}
@Override
public int update() {<FILL_FUNCTION_BODY>}
}
|
session.getUser().checkAdmin();
DbObjectLock lock = schema.tryExclusiveLock(DbObjectType.USER_DATATYPE, session);
if (lock == null)
return -1;
UserDataType type = schema.findUserDataType(session, typeName);
if (type == null) {
if (!ifExists) {
throw DbException.get(ErrorCode.USER_DATA_TYPE_NOT_FOUND_1, typeName);
}
} else {
schema.remove(session, type, lock);
}
return 0;
| 161
| 149
| 310
|
<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/DropView.java
|
DropView
|
update
|
class DropView extends SchemaStatement {
private String viewName;
private boolean ifExists;
private int dropAction;
public DropView(ServerSession session, Schema schema) {
super(session, schema);
dropAction = session.getDatabase().getSettings().dropRestrict ? ConstraintReferential.RESTRICT
: ConstraintReferential.CASCADE;
}
@Override
public int getType() {
return SQLStatement.DROP_VIEW;
}
public void setViewName(String viewName) {
this.viewName = viewName;
}
public void setIfExists(boolean b) {
ifExists = b;
}
public void setDropAction(int dropAction) {
this.dropAction = dropAction;
}
@Override
public int update() {<FILL_FUNCTION_BODY>}
}
|
DbObjectLock lock = schema.tryExclusiveLock(DbObjectType.TABLE_OR_VIEW, session);
if (lock == null)
return -1;
Table view = schema.findTableOrView(session, viewName);
if (view == null) {
if (!ifExists) {
throw DbException.get(ErrorCode.VIEW_NOT_FOUND_1, viewName);
}
} else {
if (view.getTableType() != TableType.VIEW) {
throw DbException.get(ErrorCode.VIEW_NOT_FOUND_1, viewName);
}
session.getUser().checkRight(view, Right.ALL);
if (dropAction == ConstraintReferential.RESTRICT) {
for (DbObject child : view.getChildren()) {
if (child instanceof TableView) {
throw DbException.get(ErrorCode.CANNOT_DROP_2, viewName, child.getName());
}
}
}
schema.remove(session, view, lock);
}
return 0;
| 230
| 278
| 508
|
<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/GrantRevoke.java
|
GrantRevoke
|
update
|
class GrantRevoke extends AuthStatement {
private final ArrayList<DbObject> dbObjects = new ArrayList<>();
private int operationType;
private int rightMask;
private ArrayList<String> roleNames;
private Schema schema;
private RightOwner grantee;
public GrantRevoke(ServerSession session) {
super(session);
}
@Override
public int getType() {
return operationType;
}
public void setOperationType(int operationType) {
this.operationType = operationType;
}
/**
* Add the specified right bit to the rights bitmap.
*
* @param right the right bit
*/
public void addRight(int right) {
this.rightMask |= right;
}
/**
* Add the specified role to the list of roles.
*
* @param roleName the role
*/
public void addRoleName(String roleName) {
if (roleNames == null) {
roleNames = new ArrayList<>();
}
roleNames.add(roleName);
}
public void setGranteeName(String granteeName) {
Database db = session.getDatabase();
grantee = db.findUser(session, granteeName);
if (grantee == null) {
grantee = db.findRole(session, granteeName);
if (grantee == null) {
throw DbException.get(ErrorCode.USER_OR_ROLE_NOT_FOUND_1, granteeName);
}
}
}
/**
* Add the specified table to the list of tables.
*
* @param table the table
*/
public void addTable(Table table) {
dbObjects.add(table);
}
public void addService(Service service) {
dbObjects.add(service);
}
/**
* Set the specified schema
*
* @param schema the schema
*/
public void setSchema(Schema schema) {
this.schema = schema;
}
/**
* @return true if this command is using Roles
*/
public boolean isRoleMode() {
return roleNames != null;
}
/**
* @return true if this command is using Rights
*/
public boolean isRightMode() {
return rightMask != 0;
}
@Override
public int update() {<FILL_FUNCTION_BODY>}
private void grantRight(DbObjectLock lock) {
if (schema != null) {
grantRight(schema, lock);
}
for (DbObject object : dbObjects) {
grantRight(object, lock);
}
}
private void grantRight(DbObject object, DbObjectLock lock) {
Database db = session.getDatabase();
Right right = grantee.getRightForObject(object);
if (right == null) {
int id = getObjectId();
right = new Right(db, id, grantee, rightMask, object);
grantee.grantRight(object, right);
db.addDatabaseObject(session, right, lock);
} else {
right.setRightMask(right.getRightMask() | rightMask);
db.updateMeta(session, right);
}
}
private void grantRole(Role grantedRole, DbObjectLock lock) {
if (grantedRole != grantee && grantee.isRoleGranted(grantedRole)) {
return;
}
if (grantee instanceof Role) {
Role granteeRole = (Role) grantee;
if (grantedRole.isRoleGranted(granteeRole)) {
// cyclic role grants are not allowed
throw DbException.get(ErrorCode.ROLE_ALREADY_GRANTED_1, grantedRole.getSQL());
}
}
Database db = session.getDatabase();
int id = getObjectId();
Right right = new Right(db, id, grantee, grantedRole);
db.addDatabaseObject(session, right, lock);
grantee.grantRole(grantedRole, right);
}
private void revokeRight(DbObjectLock lock) {
if (schema != null) {
revokeRight(schema, lock);
}
for (DbObject object : dbObjects) {
revokeRight(object, lock);
}
}
private void revokeRight(DbObject object, DbObjectLock lock) {
Right right = grantee.getRightForObject(object);
if (right == null) {
return;
}
int mask = right.getRightMask();
int newRight = mask & ~rightMask;
Database db = session.getDatabase();
if (newRight == 0) {
db.removeDatabaseObject(session, right, lock);
} else {
right.setRightMask(newRight);
db.updateMeta(session, right);
}
}
private void revokeRole(Role grantedRole, DbObjectLock lock) {
Right right = grantee.getRightForRole(grantedRole);
if (right == null) {
return;
}
Database db = session.getDatabase();
db.removeDatabaseObject(session, right, lock);
}
}
|
session.getUser().checkAdmin();
Database db = session.getDatabase();
DbObjectLock lock = db.tryExclusiveAuthLock(session);
if (lock == null)
return -1;
if (roleNames != null) {
for (String name : roleNames) {
Role grantedRole = db.findRole(session, name);
if (grantedRole == null) {
throw DbException.get(ErrorCode.ROLE_NOT_FOUND_1, name);
}
if (operationType == SQLStatement.GRANT) {
grantRole(grantedRole, lock);
} else if (operationType == SQLStatement.REVOKE) {
revokeRole(grantedRole, lock);
} else {
DbException.throwInternalError("type=" + operationType);
}
}
} else {
if (operationType == SQLStatement.GRANT) {
grantRight(lock);
} else if (operationType == SQLStatement.REVOKE) {
revokeRight(lock);
} else {
DbException.throwInternalError("type=" + operationType);
}
}
return 0;
| 1,334
| 299
| 1,633
|
<no_super_class>
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/ddl/PrepareProcedure.java
|
PrepareProcedure
|
update
|
class PrepareProcedure extends DefinitionStatement {
private String procedureName;
private StatementBase prepared;
public PrepareProcedure(ServerSession session) {
super(session);
}
@Override
public int getType() {
return SQLStatement.PREPARE;
}
public void setProcedureName(String name) {
this.procedureName = name;
}
public void setPrepared(StatementBase prep) {
this.prepared = prep;
}
@Override
public ArrayList<Parameter> getParameters() {
return new ArrayList<>(0);
}
@Override
public void checkParameters() {
// no not check parameters
}
@Override
public int update() {<FILL_FUNCTION_BODY>}
}
|
Procedure proc = new Procedure(procedureName, prepared);
prepared.setParameterList(parameters);
prepared.setPrepareAlways(prepareAlways);
prepared.prepare();
session.addProcedure(proc);
return 0;
| 206
| 66
| 272
|
<methods>public boolean isDDL() <variables>
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/ddl/SchemaStatement.java
|
SchemaStatement
|
tryAlterTable
|
class SchemaStatement extends DefinitionStatement {
protected final Schema schema;
/**
* Create a new statement.
*
* @param session the session
* @param schema the schema
*/
public SchemaStatement(ServerSession session, Schema schema) {
super(session);
this.schema = schema;
session.getUser().checkSystemSchema(session, schema);
}
/**
* Get the schema
*
* @return the schema
*/
protected Schema getSchema() {
return schema;
}
protected DbObjectLock tryAlterTable(Table table) {<FILL_FUNCTION_BODY>}
}
|
// 先用schema级别的排它锁来避免其他事务也来执行Alter Table操作
DbObjectLock lock = schema.tryExclusiveLock(DbObjectType.TABLE_OR_VIEW, session);
if (lock == null)
return null;
// 再用table级别的共享锁来避免其他事务进行Drop Table操作,但是不阻止DML操作
if (!table.trySharedLock(session))
return null;
return lock;
| 171
| 119
| 290
|
<methods>public boolean isDDL() <variables>
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/ddl/SetComment.java
|
SetComment
|
update
|
class SetComment extends DefinitionStatement {
private String schemaName;
private String objectName;
private DbObjectType objectType;
private String columnName;
private boolean column;
private Expression expr;
public SetComment(ServerSession session) {
super(session);
}
@Override
public int getType() {
return SQLStatement.COMMENT;
}
public void setSchemaName(String schemaName) {
this.schemaName = schemaName;
}
public void setObjectName(String objectName) {
this.objectName = objectName;
}
public void setObjectType(DbObjectType objectType) {
this.objectType = objectType;
}
public void setColumnName(String columnName) {
this.columnName = columnName;
}
public void setColumn(boolean column) {
this.column = column;
}
public void setCommentExpression(Expression expr) {
this.expr = expr;
}
private Schema getSchema() {
return session.getDatabase().getSchema(session, schemaName);
}
@Override
public int update() {<FILL_FUNCTION_BODY>}
}
|
session.getUser().checkAdmin();
Database db = session.getDatabase();
DbObjectLock lock = db.tryExclusiveCommentLock(session);
if (lock == null)
return -1;
DbObject object = null;
if (schemaName == null) {
schemaName = session.getCurrentSchemaName();
}
switch (objectType) {
case CONSTANT:
object = getSchema().getConstant(session, objectName);
break;
case CONSTRAINT:
object = getSchema().getConstraint(session, objectName);
break;
case INDEX:
object = getSchema().getIndex(session, objectName);
break;
case SEQUENCE:
object = getSchema().getSequence(session, objectName);
break;
case TABLE_OR_VIEW:
object = getSchema().getTableOrView(session, objectName);
break;
case TRIGGER:
object = getSchema().getTrigger(session, objectName);
break;
case FUNCTION_ALIAS:
object = getSchema().getFunction(session, objectName);
break;
case USER_DATATYPE:
object = getSchema().getUserDataType(session, objectName);
break;
case ROLE:
schemaName = null;
object = db.getRole(session, objectName);
break;
case USER:
schemaName = null;
object = db.getUser(session, objectName);
break;
case SCHEMA:
schemaName = null;
object = db.getSchema(session, objectName);
break;
default:
}
if (object == null) {
throw DbException.get(ErrorCode.GENERAL_ERROR_1, objectName);
}
String text = expr.optimize(session).getValue(session).getString();
if (column) {
Table table = (Table) object;
table.getColumn(columnName).setComment(text);
} else {
object.setComment(text);
}
if (column || objectType == DbObjectType.TABLE_OR_VIEW || objectType == DbObjectType.USER
|| objectType == DbObjectType.INDEX || objectType == DbObjectType.CONSTRAINT) {
db.updateMeta(session, object);
} else {
Comment comment = db.findComment(session, object);
if (comment == null) {
if (text == null) {
// reset a non-existing comment - nothing to do
} else {
int id = getObjectId();
comment = new Comment(db, id, object);
comment.setCommentText(text);
db.addDatabaseObject(session, comment, lock);
}
} else {
if (text == null) {
db.removeDatabaseObject(session, comment, lock);
} else {
comment.setCommentText(text);
db.updateMeta(session, comment);
}
}
}
return 0;
| 314
| 764
| 1,078
|
<methods>public boolean isDDL() <variables>
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/ddl/TruncateTable.java
|
TruncateTable
|
update
|
class TruncateTable extends SchemaStatement {
private Table table;
public TruncateTable(ServerSession session, Schema schema) {
super(session, schema);
}
@Override
public int getType() {
return SQLStatement.TRUNCATE_TABLE;
}
public void setTable(Table table) {
this.table = table;
}
@Override
public int update() {<FILL_FUNCTION_BODY>}
}
|
session.getUser().checkRight(table, Right.DELETE);
if (!table.canTruncate()) {
throw DbException.get(ErrorCode.CANNOT_TRUNCATE_1, table.getSQL());
}
if (!table.tryExclusiveLock(session))
return -1;
table.truncate(session);
return 0;
| 125
| 99
| 224
|
<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/dml/Backup.java
|
Backup
|
update
|
class Backup extends ManipulationStatement {
private String fileName;
private String lastDate;
public Backup(ServerSession session) {
super(session);
}
@Override
public int getType() {
return SQLStatement.BACKUP;
}
@Override
public boolean needRecompile() {
return false;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public void setLastDate(String lastDate) {
this.lastDate = lastDate;
}
@Override
public int update() {<FILL_FUNCTION_BODY>}
}
|
session.getUser().checkAdmin();
Database db = session.getDatabase();
if (!db.isPersistent()) {
throw DbException.get(ErrorCode.DATABASE_IS_NOT_PERSISTENT);
}
Long ld = lastDate != null ? Date.valueOf(lastDate).getTime() : null;
db.backupTo(fileName, ld);
return 0;
| 172
| 107
| 279
|
<methods>public void <init>(com.lealone.db.session.ServerSession) <variables>
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/dml/Call.java
|
Call
|
prepare
|
class Call extends ManipulationStatement {
private boolean isResultSet;
private Expression expression;
private Expression[] expressions;
public Call(ServerSession session) {
super(session);
}
@Override
public int getType() {
return SQLStatement.CALL;
}
@Override
public boolean isCacheable() {
return !isResultSet;
}
public void setExpression(Expression expression) {
this.expression = expression;
}
@Override
public boolean isQuery() {
return true;
}
@Override
public Future<Result> getMetaData() {
LocalResult result;
if (isResultSet) {
Expression[] expr = expression.getExpressionColumns(session);
result = new LocalResult(session, expr, expr.length);
} else {
result = new LocalResult(session, expressions, 1);
}
result.done();
return Future.succeededFuture(result);
}
@Override
public PreparedSQLStatement prepare() {<FILL_FUNCTION_BODY>}
@Override
public int update() {
Value v = expression.getValue(session);
int type = v.getType();
switch (type) {
case Value.RESULT_SET:
// this will throw an exception
// methods returning a result set may not be called like this.
return super.update();
case Value.UNKNOWN:
case Value.NULL:
return 0;
default:
return v.getInt();
}
}
@Override
public Result query(int maxRows) {
setCurrentRowNumber(1);
Value v = expression.getValue(session);
if (isResultSet) {
v = v.convertTo(Value.RESULT_SET);
ResultSet rs = v.getResultSet();
return LocalResult.read(session, Expression.getExpressionColumns(session, rs), rs, maxRows);
}
LocalResult result = new LocalResult(session, expressions, 1);
Value[] row = { v };
result.addRow(row);
result.done();
return result;
}
}
|
expression = expression.optimize(session);
expressions = new Expression[] { expression };
isResultSet = expression.getType() == Value.RESULT_SET;
if (isResultSet) {
prepareAlways = true;
}
return this;
| 559
| 68
| 627
|
<methods>public void <init>(com.lealone.db.session.ServerSession) <variables>
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/dml/Delete.java
|
Delete
|
prepare
|
class Delete extends UpDel {
public Delete(ServerSession session) {
super(session);
}
@Override
public int getType() {
return SQLStatement.DELETE;
}
@Override
public String getPlanSQL() {
StatementBuilder buff = new StatementBuilder();
buff.append("DELETE ");
buff.append("FROM ").append(tableFilter.getPlanSQL(false));
appendPlanSQL(buff);
return buff.toString();
}
@Override
public PreparedSQLStatement prepare() {<FILL_FUNCTION_BODY>}
@Override
public YieldableBase<Integer> createYieldableUpdate(
AsyncHandler<AsyncResult<Integer>> asyncHandler) {
return new YieldableDelete(this, asyncHandler);
}
private static class YieldableDelete extends YieldableUpDel {
public YieldableDelete(Delete statement, AsyncHandler<AsyncResult<Integer>> asyncHandler) {
super(statement, asyncHandler, statement.tableFilter, statement.limitExpr,
statement.condition);
}
@Override
protected int getRightMask() {
return Right.DELETE;
}
@Override
protected int getTriggerType() {
return Trigger.DELETE;
}
@Override
protected boolean upDelRow(Row oldRow) {
boolean done = false;
if (table.fireRow()) {
done = table.fireBeforeRow(session, oldRow, null);
}
if (!done) {
removeRow(oldRow);
}
return !done;
}
private void removeRow(Row row) {
onPendingOperationStart();
table.removeRow(session, row, true).onComplete(ar -> {
if (ar.isSucceeded() && table.fireRow()) {
table.fireAfterRow(session, row, null, false);
}
onPendingOperationComplete(ar);
});
}
}
}
|
if (condition != null) {
condition.mapColumns(tableFilter, 0);
condition = condition.optimize(session);
condition.createIndexConditions(session, tableFilter);
tableFilter.createColumnIndexes(condition);
}
tableFilter.preparePlan(session, 1);
return this;
| 508
| 84
| 592
|
<methods>public void <init>(com.lealone.db.session.ServerSession) ,public int getPriority() ,public boolean isCacheable() ,public void setCondition(com.lealone.sql.expression.Expression) ,public void setLimit(com.lealone.sql.expression.Expression) ,public void setTableFilter(com.lealone.sql.optimizer.TableFilter) ,public int update() <variables>protected com.lealone.sql.expression.Expression condition,protected com.lealone.sql.expression.Expression limitExpr,protected com.lealone.sql.optimizer.TableFilter tableFilter
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/dml/ExecuteProcedure.java
|
ExecuteProcedure
|
setParameters
|
class ExecuteProcedure extends ExecuteStatement {
private final Procedure procedure;
public ExecuteProcedure(ServerSession session, Procedure procedure) {
super(session);
this.procedure = procedure;
}
@Override
public boolean isQuery() {
return stmt().isQuery();
}
@Override
public Future<Result> getMetaData() {
return stmt().getMetaData();
}
private StatementBase stmt() {
return (StatementBase) procedure.getPrepared();
}
private void setParameters() {<FILL_FUNCTION_BODY>}
@Override
public int update() {
setParameters();
return stmt().update();
}
@Override
public Result query(int limit) {
setParameters();
return stmt().query(limit);
}
}
|
ArrayList<Parameter> params = stmt().getParameters();
if (params == null)
return;
int size = Math.min(params.size(), expressions.size());
for (int i = 0; i < size; i++) {
Expression expr = expressions.get(i);
Parameter p = params.get(i);
p.setValue(expr.getValue(session));
}
| 223
| 104
| 327
|
<methods>public void <init>(com.lealone.db.session.ServerSession) ,public int getType() ,public void setExpression(int, com.lealone.sql.expression.Expression) <variables>protected final ArrayList<com.lealone.sql.expression.Expression> expressions
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/dml/ExecuteService.java
|
ExecuteService
|
prepare
|
class ExecuteService extends ExecuteStatement {
private final String serviceName;
private final String methodName;
private final Expression[] resultExpressions;
public ExecuteService(ServerSession session, String serviceName, String methodName) {
super(session);
this.serviceName = serviceName;
this.methodName = methodName;
ValueExpression e = ValueExpression.get(ValueString.get(serviceName + "." + methodName + "()"));
resultExpressions = new Expression[] { e };
}
@Override
public boolean isCacheable() {
return true;
}
@Override
public boolean isQuery() {
return true;
}
@Override
public Future<Result> getMetaData() {
LocalResult result = new LocalResult(session, resultExpressions, 1);
result.done();
return Future.succeededFuture(result);
}
@Override
public PreparedSQLStatement prepare() {<FILL_FUNCTION_BODY>}
@Override
public int update() {
execute();
return 0;
}
@Override
public Result query(int maxRows) {
setCurrentRowNumber(1);
Value v = execute();
Value[] row = { v };
LocalResult result = new LocalResult(session, resultExpressions, 1);
result.addRow(row);
result.done();
return result;
}
private Value execute() {
int size = expressions.size();
Value[] methodArgs = new Value[size];
for (int i = 0; i < size; i++) {
methodArgs[i] = expressions.get(i).getValue(session);
}
return Service.execute(session, serviceName, methodName, methodArgs);
}
}
|
for (int i = 0, size = expressions.size(); i < size; i++) {
Expression e = expressions.get(i).optimize(session);
expressions.set(i, e);
}
return this;
| 459
| 61
| 520
|
<methods>public void <init>(com.lealone.db.session.ServerSession) ,public int getType() ,public void setExpression(int, com.lealone.sql.expression.Expression) <variables>protected final ArrayList<com.lealone.sql.expression.Expression> expressions
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/dml/Explain.java
|
Explain
|
query
|
class Explain extends ManipulationStatement {
private StatementBase command;
private LocalResult result;
private boolean executeCommand;
public Explain(ServerSession session) {
super(session);
}
@Override
public int getType() {
return SQLStatement.EXPLAIN;
}
@Override
public boolean isQuery() {
return true;
}
public void setCommand(StatementBase command) {
this.command = command;
}
public void setExecuteCommand(boolean executeCommand) {
this.executeCommand = executeCommand;
}
@Override
public Future<Result> getMetaData() {
Result r = query(-1);
return Future.succeededFuture(r);
}
@Override
public PreparedSQLStatement prepare() {
command.prepare();
return this;
}
@Override
public Result query(int maxRows) {<FILL_FUNCTION_BODY>}
private void add(String text) {
Value[] row = { ValueString.get(text) };
result.addRow(row);
}
}
|
Column column = new Column("PLAN", Value.STRING);
Database db = session.getDatabase();
ExpressionColumn expr = new ExpressionColumn(db, column);
Expression[] expressions = { expr };
result = new LocalResult(session, expressions, 1);
if (maxRows >= 0) {
String plan;
if (executeCommand) {
db.statisticsStart();
if (command.isQuery()) {
command.query(maxRows);
} else {
command.update();
}
plan = command.getPlanSQL();
Map<String, Integer> statistics = db.statisticsEnd();
if (statistics != null) {
int total = 0;
for (Entry<String, Integer> e : statistics.entrySet()) {
total += e.getValue();
}
if (total > 0) {
statistics = new TreeMap<String, Integer>(statistics);
StringBuilder buff = new StringBuilder();
if (statistics.size() > 1) {
buff.append("total: ").append(total).append('\n');
}
for (Entry<String, Integer> e : statistics.entrySet()) {
int value = e.getValue();
int percent = (int) (100L * value / total);
buff.append(e.getKey()).append(": ").append(value);
if (statistics.size() > 1) {
buff.append(" (").append(percent).append("%)");
}
buff.append('\n');
}
plan += "\n/*\n" + buff.toString() + "*/";
}
}
} else {
plan = command.getPlanSQL();
}
add(plan);
}
result.done();
return result;
| 292
| 450
| 742
|
<methods>public void <init>(com.lealone.db.session.ServerSession) <variables>
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/dml/Insert.java
|
YieldableInsert
|
startInternal
|
class YieldableInsert extends YieldableMerSert {
public YieldableInsert(Insert statement, AsyncHandler<AsyncResult<Integer>> asyncHandler) {
super(statement, asyncHandler);
}
@Override
protected boolean startInternal() {<FILL_FUNCTION_BODY>}
@Override
protected void stopInternal() {
table.fire(session, Trigger.INSERT, false);
}
@Override
protected void merSert(Row row) {
addRowInternal(row);
}
}
|
if (!table.trySharedLock(session))
return true;
session.getUser().checkRight(table, Right.INSERT);
table.fire(session, Trigger.INSERT, true);
return super.startInternal();
| 138
| 59
| 197
|
<methods>public void <init>(com.lealone.db.session.ServerSession) ,public void addRow(com.lealone.sql.expression.Expression[]) ,public void clearRows() ,public int getPriority() ,public boolean isCacheable() ,public com.lealone.sql.PreparedSQLStatement prepare() ,public void setColumns(com.lealone.db.table.Column[]) ,public void setQuery(com.lealone.sql.query.Query) ,public void setTable(com.lealone.db.table.Table) <variables>protected com.lealone.db.table.Column[] columns,protected final ArrayList<com.lealone.sql.expression.Expression[]> list,protected com.lealone.sql.query.Query query,protected com.lealone.db.table.Table table
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/dml/MerSert.java
|
YieldableMerSert
|
addRow
|
class YieldableMerSert extends YieldableLoopUpdateBase
implements ResultTarget {
final MerSert statement;
final Table table;
final int listSize;
int index;
YieldableBase<Result> yieldableQuery;
public YieldableMerSert(MerSert statement, AsyncHandler<AsyncResult<Integer>> asyncHandler) {
super(statement, asyncHandler);
this.statement = statement;
table = statement.table;
listSize = statement.list.size();
}
@Override
protected boolean startInternal() {
statement.setCurrentRowNumber(0);
if (statement.query != null) {
yieldableQuery = statement.query.createYieldableQuery(0, false, null, this);
}
return false;
}
@Override
protected void executeLoopUpdate() {
if (table.containsLargeObject()) {
DataHandler dh = session.getDataHandler();
session.setDataHandler(table.getDataHandler()); // lob字段通过FILE_READ函数赋值时会用到
try {
executeLoopUpdate0();
} finally {
session.setDataHandler(dh);
}
} else {
executeLoopUpdate0();
}
}
private void executeLoopUpdate0() {
if (yieldableQuery == null) {
while (pendingException == null && index < listSize) {
merSert(createNewRow());
if (yieldIfNeeded(++index)) {
return;
}
}
onLoopEnd();
} else {
yieldableQuery.run();
if (yieldableQuery.isStopped()) {
onLoopEnd();
}
}
}
protected Row createNewRow() {
Row newRow = table.getTemplateRow(); // newRow的长度是全表字段的个数,会>=columns的长度
Expression[] expr = statement.list.get(index);
int columnLen = statement.columns.length;
for (int i = 0; i < columnLen; i++) {
Column c = statement.columns[i];
int index = c.getColumnId(); // 从0开始
Expression e = expr[i];
if (e != null) {
// e can be null (DEFAULT)
e = e.optimize(session);
try {
Value v = c.convert(e.getValue(session));
newRow.setValue(index, v);
} catch (DbException ex) {
throw statement.setRow(ex, this.index + 1, getSQL(expr));
}
}
}
return newRow;
}
protected Row createNewRow(Value[] values) {
Row newRow = table.getTemplateRow();
for (int i = 0, len = statement.columns.length; i < len; i++) {
Column c = statement.columns[i];
int index = c.getColumnId();
try {
Value v = c.convert(values[i]);
newRow.setValue(index, v);
} catch (DbException ex) {
throw statement.setRow(ex, updateCount.get() + 1, getSQL(values));
}
}
return newRow;
}
protected void addRowInternal(Row newRow) {
table.validateConvertUpdateSequence(session, newRow);
boolean done = table.fireBeforeRow(session, null, newRow); // INSTEAD OF触发器会返回true
if (!done) {
onPendingOperationStart();
table.addRow(session, newRow).onComplete(ar -> {
if (ar.isSucceeded()) {
try {
// 有可能抛出异常
table.fireAfterRow(session, null, newRow, false);
} catch (Throwable e) {
setPendingException(e);
}
}
onPendingOperationComplete(ar);
});
}
}
protected abstract void merSert(Row row);
// 以下实现ResultTarget接口,可以在执行查询时,边查边增加新记录
@Override
public boolean addRow(Value[] values) {<FILL_FUNCTION_BODY>}
@Override
public int getRowCount() {
return updateCount.get();
}
}
|
merSert(createNewRow(values));
if (yieldIfNeeded(updateCount.get() + 1)) {
return true;
}
return false;
| 1,096
| 47
| 1,143
|
<methods>public void <init>(com.lealone.db.session.ServerSession) <variables>
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/dml/Merge.java
|
YieldableMerge
|
merSert
|
class YieldableMerge extends YieldableMerSert {
final Merge mergeStatement;
public YieldableMerge(Merge statement, AsyncHandler<AsyncResult<Integer>> asyncHandler) {
super(statement, asyncHandler);
this.mergeStatement = statement;
}
@Override
protected boolean startInternal() {
if (!table.trySharedLock(session))
return true;
session.getUser().checkRight(table, Right.INSERT);
session.getUser().checkRight(table, Right.UPDATE);
table.fire(session, Trigger.UPDATE | Trigger.INSERT, true);
return super.startInternal();
}
@Override
protected void stopInternal() {
table.fire(session, Trigger.UPDATE | Trigger.INSERT, false);
}
@Override
protected void merSert(Row row) {<FILL_FUNCTION_BODY>}
}
|
ArrayList<Parameter> k = mergeStatement.update.getParameters();
for (int i = 0; i < statement.columns.length; i++) {
Column col = statement.columns[i];
Value v = row.getValue(col.getColumnId());
if (v == null)
v = ValueNull.INSTANCE;
Parameter p = k.get(i);
p.setValue(v);
}
for (int i = 0; i < mergeStatement.keys.length; i++) {
Column col = mergeStatement.keys[i];
Value v = row.getValue(col.getColumnId());
if (v == null) {
throw DbException.get(ErrorCode.COLUMN_CONTAINS_NULL_VALUES_1, col.getSQL());
}
Parameter p = k.get(statement.columns.length + i);
p.setValue(v);
}
// 先更新,如果没有记录被更新,说明是一条新的记录,接着再插入
int count = mergeStatement.update.update();
if (count > 0) {
updateCount.addAndGet(count);
} else if (count == 0) {
addRowInternal(row);
} else if (count != 1) {
throw DbException.get(ErrorCode.DUPLICATE_KEY_1, table.getSQL());
}
| 233
| 346
| 579
|
<methods>public void <init>(com.lealone.db.session.ServerSession) ,public void addRow(com.lealone.sql.expression.Expression[]) ,public void clearRows() ,public int getPriority() ,public boolean isCacheable() ,public com.lealone.sql.PreparedSQLStatement prepare() ,public void setColumns(com.lealone.db.table.Column[]) ,public void setQuery(com.lealone.sql.query.Query) ,public void setTable(com.lealone.db.table.Table) <variables>protected com.lealone.db.table.Column[] columns,protected final ArrayList<com.lealone.sql.expression.Expression[]> list,protected com.lealone.sql.query.Query query,protected com.lealone.db.table.Table table
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/dml/RunScript.java
|
RunScript
|
update
|
class RunScript extends ScriptBase {
/**
* The byte order mark.
* 0xfeff because this is the Unicode char
* represented by the UTF-8 byte order mark (EF BB BF).
*/
private static final char UTF8_BOM = '\uFEFF';
private Charset charset = Constants.UTF8;
public RunScript(ServerSession session) {
super(session);
}
@Override
public int getType() {
return SQLStatement.RUNSCRIPT;
}
public void setCharset(Charset charset) {
this.charset = charset;
}
@Override
public int update() {<FILL_FUNCTION_BODY>}
private void execute(String sql) {
try {
StatementBase command = (StatementBase) session.prepareStatement(sql);
if (command.isQuery()) {
command.query(0);
} else {
command.update();
}
if (session.isAutoCommit()) {
session.commit();
}
} catch (DbException e) {
throw e.addSQL(sql);
}
}
}
|
session.getUser().checkAdmin();
int count = 0;
try {
openInput();
BufferedReader reader = new BufferedReader(new InputStreamReader(in, charset));
// if necessary, strip the BOM from the front of the file
reader.mark(1);
if (reader.read() != UTF8_BOM) {
reader.reset();
}
ScriptReader r = new ScriptReader(reader);
while (true) {
String sql = r.readStatement();
if (sql == null) {
break;
}
execute(sql);
count++;
if ((count & 127) == 0) {
checkCanceled();
}
}
reader.close();
} catch (IOException e) {
throw DbException.convertIOException(e, null);
} finally {
closeIO();
}
return count;
| 299
| 231
| 530
|
<methods>public void <init>(com.lealone.db.session.ServerSession) ,public boolean needRecompile() ,public void setCipher(java.lang.String) ,public void setCompressionAlgorithm(java.lang.String) ,public void setFileNameExpr(com.lealone.sql.expression.Expression) ,public void setPassword(com.lealone.sql.expression.Expression) <variables>private static final java.lang.String SCRIPT_SQL,private java.lang.String cipher,private java.lang.String compressionAlgorithm,private java.lang.String fileName,private com.lealone.sql.expression.Expression fileNameExpr,private com.lealone.storage.fs.FileStorage fileStorage,protected java.io.InputStream in,protected java.io.OutputStream out,private com.lealone.sql.expression.Expression password
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/dml/ScriptBase.java
|
ScriptBase
|
openOutput
|
class ScriptBase extends ManipulationStatement {
/**
* The default name of the script file if .zip compression is used.
*/
private static final String SCRIPT_SQL = "script.sql";
/**
* The output stream.
*/
protected OutputStream out;
/**
* The input stream.
*/
protected InputStream in;
/**
* The file name (if set).
*/
private Expression fileNameExpr;
private Expression password;
private String fileName;
private String cipher;
private FileStorage fileStorage;
private String compressionAlgorithm;
public ScriptBase(ServerSession session) {
super(session);
}
public void setCipher(String c) {
cipher = c;
}
private boolean isEncrypted() {
return cipher != null;
}
public void setPassword(Expression password) {
this.password = password;
}
public void setFileNameExpr(Expression file) {
this.fileNameExpr = file;
}
protected String getFileName() {
if (fileNameExpr != null && fileName == null) {
fileName = fileNameExpr.optimize(session).getValue(session).getString();
if (fileName == null || fileName.trim().length() == 0) {
fileName = "script.sql";
}
// 如果是一个不包含目录的文件名,自动加上ScriptDirectory
if (FileUtils.getName(fileName).equals(fileName)) {
String dir = SysProperties.getScriptDirectory();
fileName = FileUtils.getDirWithSeparator(dir) + fileName;
}
}
return fileName;
}
/**
* Delete the target file.
*/
void deleteStore() {
String file = getFileName();
if (file != null) {
FileUtils.delete(file);
}
}
private void initStore() {
Database db = session.getDatabase();
byte[] key = null;
if (cipher != null && password != null) {
char[] pass = password.optimize(session).getValue(session).getString().toCharArray();
key = SHA256.getKeyPasswordHash("script", pass);
}
String file = getFileName();
fileStorage = FileStorage.open(db, file, "rw", cipher, key);
fileStorage.setCheckedWriting(false);
}
/**
* Open the output stream.
*/
void openOutput() {<FILL_FUNCTION_BODY>}
/**
* Open the input stream.
*/
void openInput() {
String file = getFileName();
if (file == null) {
return;
}
if (isEncrypted()) {
initStore();
in = new FileStorageInputStream(fileStorage, session.getDatabase(),
compressionAlgorithm != null, false);
} else {
InputStream inStream;
try {
inStream = FileUtils.newInputStream(file);
} catch (IOException e) {
throw DbException.convertIOException(e, file);
}
in = new BufferedInputStream(inStream, Constants.IO_BUFFER_SIZE);
in = CompressTool.wrapInputStream(in, compressionAlgorithm, SCRIPT_SQL);
if (in == null) {
throw DbException.get(ErrorCode.FILE_NOT_FOUND_1, SCRIPT_SQL + " in " + file);
}
}
}
/**
* Close input and output streams.
*/
void closeIO() {
IOUtils.closeSilently(out);
out = null;
IOUtils.closeSilently(in);
in = null;
if (fileStorage != null) {
fileStorage.closeSilently();
fileStorage = null;
}
}
@Override
public boolean needRecompile() {
return false;
}
public void setCompressionAlgorithm(String algorithm) {
this.compressionAlgorithm = algorithm;
}
}
|
String file = getFileName();
if (file == null) {
return;
}
if (isEncrypted()) {
initStore();
out = new FileStorageOutputStream(fileStorage, session.getDatabase(), compressionAlgorithm);
// always use a big buffer, otherwise end-of-block is written a lot
out = new BufferedOutputStream(out, Constants.IO_BUFFER_SIZE_COMPRESS);
} else {
OutputStream o;
try {
o = FileUtils.newOutputStream(file, false);
} catch (IOException e) {
throw DbException.convertIOException(e, null);
}
out = new BufferedOutputStream(o, Constants.IO_BUFFER_SIZE);
out = CompressTool.wrapOutputStream(out, compressionAlgorithm, SCRIPT_SQL);
}
| 1,042
| 207
| 1,249
|
<methods>public void <init>(com.lealone.db.session.ServerSession) <variables>
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/dml/SetSession.java
|
SetSession
|
update
|
class SetSession extends SetStatement {
private final SessionSetting setting;
public SetSession(ServerSession session, SessionSetting type) {
super(session);
this.setting = type;
}
@Override
protected String getSettingName() {
return setting.getName();
}
@Override
public int update() {<FILL_FUNCTION_BODY>}
}
|
Database database = session.getDatabase();
switch (setting) {
case LOCK_TIMEOUT:
session.setLockTimeout(getAndValidateIntValue());
break;
case QUERY_TIMEOUT:
session.setQueryTimeout(getAndValidateIntValue());
break;
case SCHEMA:
Schema schema = database.getSchema(session, stringValue);
session.setCurrentSchema(schema);
break;
case SCHEMA_SEARCH_PATH:
session.setSchemaSearchPath(stringValueList);
break;
case VARIABLE:
Expression expr = expression.optimize(session);
session.setVariable(stringValue, expr.getValue(session));
break;
case THROTTLE:
session.setThrottle(getAndValidateIntValue());
break;
case TRANSACTION_ISOLATION_LEVEL:
if (stringValue != null)
session.setTransactionIsolationLevel(stringValue);
else
session.setTransactionIsolationLevel(getIntValue());
// 直接提交事务,开启新事务时用新的隔离级别
session.commit();
break;
case VALUE_VECTOR_FACTORY_NAME:
session.setValueVectorFactoryName(getStringValue());
break;
case EXPRESSION_COMPILE_THRESHOLD:
session.setExpressionCompileThreshold(getIntValue());
break;
case OLAP_OPERATOR_FACTORY_NAME:
session.setOlapOperatorFactoryName(getStringValue());
break;
case OLAP_THRESHOLD:
session.setOlapThreshold(getIntValue());
break;
case OLAP_BATCH_SIZE:
session.setOlapBatchSize(getIntValue());
break;
default:
DbException.throwInternalError("unknown setting type: " + setting);
}
databaseChanged(database);
return 0;
| 100
| 499
| 599
|
<methods>public void <init>(com.lealone.db.session.ServerSession) ,public int getType() ,public boolean needRecompile() ,public void setExpression(com.lealone.sql.expression.Expression) ,public void setInt(int) ,public void setString(java.lang.String) ,public void setStringArray(java.lang.String[]) <variables>protected com.lealone.sql.expression.Expression expression,protected java.lang.String stringValue,protected java.lang.String[] stringValueList
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/dml/SetStatement.java
|
SetStatement
|
databaseChanged
|
class SetStatement extends ManipulationStatement {
protected Expression expression;
protected String stringValue;
protected String[] stringValueList;
public SetStatement(ServerSession session) {
super(session);
}
@Override
public int getType() {
return SQLStatement.SET;
}
protected abstract String getSettingName();
@Override
public boolean needRecompile() {
return false;
}
public void setStringArray(String[] list) {
this.stringValueList = list;
}
public void setString(String v) {
this.stringValue = v;
}
public void setExpression(Expression expression) {
this.expression = expression;
}
public void setInt(int value) {
this.expression = ValueExpression.get(ValueInt.get(value));
}
protected int getIntValue() {
expression = expression.optimize(session);
return expression.getValue(session).getInt();
}
protected String getStringValue() {
if (stringValue != null)
return stringValue;
else if (stringValueList != null)
return StringUtils.arrayCombine(stringValueList, ',');
else if (expression != null)
return expression.optimize(session).getValue(session).getString();
else
return "";
}
protected int getAndValidateIntValue() {
return getAndValidateIntValue(0);
}
protected int getAndValidateIntValue(int lessThan) {
int value = getIntValue();
if (value < lessThan) {
throw DbException.getInvalidValueException(getSettingName(), value);
}
return value;
}
protected boolean getAndValidateBooleanValue() {
int value = getIntValue();
if (value < 0 || value > 1) {
throw DbException.getInvalidValueException(getSettingName(), value);
}
return value == 1;
}
protected void databaseChanged(Database db) {<FILL_FUNCTION_BODY>}
}
|
// the meta data information has changed
db.getNextModificationDataId();
// query caches might be affected as well, for example
// when changing the compatibility mode
db.getNextModificationMetaId();
| 531
| 56
| 587
|
<methods>public void <init>(com.lealone.db.session.ServerSession) <variables>
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/dml/TransactionStatement.java
|
TransactionStatement
|
update
|
class TransactionStatement extends ManipulationStatement {
private final int type;
private String savepointName;
public TransactionStatement(ServerSession session, int type) {
super(session);
this.type = type;
}
@Override
public int getType() {
return type;
}
@Override
public boolean isCacheable() {
return true;
}
@Override
public boolean isTransactionStatement() {
return true;
}
@Override
public boolean needRecompile() {
return false;
}
public void setSavepointName(String name) {
if (INTERNAL_SAVEPOINT.equals(name))
throw DbException.getUnsupportedException("Savepoint name cannot use " + INTERNAL_SAVEPOINT);
this.savepointName = name;
}
public void setTransactionName(String string) {
// 2PC语句已经废弃
}
@Override
public int update() {<FILL_FUNCTION_BODY>}
}
|
switch (type) {
case SQLStatement.SET_AUTOCOMMIT_TRUE:
session.setAutoCommit(true);
break;
case SQLStatement.SET_AUTOCOMMIT_FALSE:
session.setAutoCommit(false);
break;
case SQLStatement.BEGIN:
session.begin();
break;
case SQLStatement.COMMIT:
// 在session.stopCurrentCommand中处理
// session.asyncCommit(null);
break;
case SQLStatement.ROLLBACK:
session.rollback();
break;
case SQLStatement.SAVEPOINT:
session.addSavepoint(savepointName);
break;
case SQLStatement.ROLLBACK_TO_SAVEPOINT:
session.rollbackToSavepoint(savepointName);
break;
case SQLStatement.CHECKPOINT:
session.getUser().checkAdmin();
session.getDatabase().checkpoint();
break;
// 以下三个是跟2PC相关的语句,已经废弃
case SQLStatement.PREPARE_COMMIT:
case SQLStatement.COMMIT_TRANSACTION:
case SQLStatement.ROLLBACK_TRANSACTION:
break;
default:
DbException.throwInternalError("type=" + type);
}
return 0;
| 272
| 334
| 606
|
<methods>public void <init>(com.lealone.db.session.ServerSession) <variables>
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/dml/UpDel.java
|
UpDel
|
appendPlanSQL
|
class UpDel extends ManipulationStatement {
protected TableFilter tableFilter;
protected Expression condition;
/**
* The limit expression as specified in the LIMIT or TOP clause.
*/
protected Expression limitExpr;
public UpDel(ServerSession session) {
super(session);
}
@Override
public boolean isCacheable() {
return true;
}
public void setTableFilter(TableFilter tableFilter) {
this.tableFilter = tableFilter;
}
public void setCondition(Expression condition) {
this.condition = condition;
}
public void setLimit(Expression limit) {
this.limitExpr = limit;
}
@Override
public int getPriority() {
if (getCurrentRowNumber() > 0)
return priority;
priority = NORM_PRIORITY - 1;
return priority;
}
@Override
public int update() {
return syncExecute(createYieldableUpdate(null));
}
protected void appendPlanSQL(StatementBuilder buff) {<FILL_FUNCTION_BODY>}
protected static abstract class YieldableUpDel extends YieldableLoopUpdateBase {
protected final Table table;
private final int limitRows; // 如果是0,表示不删除任何记录;如果小于0,表示没有限制
private final ExpressionEvaluator conditionEvaluator;
private final TableIterator tableIterator;
public YieldableUpDel(StatementBase statement, AsyncHandler<AsyncResult<Integer>> asyncHandler,
TableFilter tableFilter, Expression limitExpr, Expression condition) {
super(statement, asyncHandler);
table = tableFilter.getTable();
int limitRows = -1;
if (limitExpr != null) {
Value v = limitExpr.getValue(session);
if (v != ValueNull.INSTANCE) {
limitRows = v.getInt();
}
}
this.limitRows = limitRows;
if (limitRows == 0) {
tableIterator = new TableIterator(session, tableFilter) {
@Override
public boolean next() {
return false;
}
};
} else {
tableIterator = new TableIterator(session, tableFilter);
}
if (condition == null)
conditionEvaluator = new AlwaysTrueEvaluator();
else
conditionEvaluator = new ExpressionInterpreter(session, condition);
}
protected abstract int getRightMask();
protected abstract int getTriggerType();
protected abstract boolean upDelRow(Row oldRow);
@Override
protected boolean startInternal() {
if (!table.trySharedLock(session))
return true;
session.getUser().checkRight(table, getRightMask());
table.fire(session, getTriggerType(), true);
statement.setCurrentRowNumber(0);
tableIterator.start();
return false;
}
@Override
protected void stopInternal() {
table.fire(session, getTriggerType(), false);
}
protected int[] getUpdateColumnIndexes() {
return null;
}
@Override
protected void executeLoopUpdate() {
try {
if (table.containsLargeObject()) {
DataHandler dh = session.getDataHandler();
session.setDataHandler(table.getDataHandler()); // lob字段通过FILE_READ函数赋值时会用到
try {
executeLoopUpdate0();
} finally {
session.setDataHandler(dh);
}
} else {
executeLoopUpdate0();
}
} catch (RuntimeException e) {
if (DbObjectLock.LOCKED_EXCEPTION == e) {
tableIterator.onLockedException();
} else {
throw e;
}
}
}
private void executeLoopUpdate0() {
while (tableIterator.next() && pendingException == null) {
// 不能直接return,执行完一次后再return,否则执行next()得到的记录被跳过了,会产生严重的问题
boolean yield = yieldIfNeeded(++loopCount);
if (conditionEvaluator.getBooleanValue()) {
int ret = tableIterator.tryLockRow(getUpdateColumnIndexes());
if (ret < 0) {
continue;
} else if (ret == 0) { // 被其他事务锁住了
return;
}
Row row = tableIterator.getRow();
if (upDelRow(row)) {
if (limitRows > 0 && updateCount.get() >= limitRows) {
break;
}
}
}
if (yield)
return;
}
onLoopEnd();
}
}
}
|
if (condition != null) {
buff.append("\nWHERE ").append(StringUtils.unEnclose(condition.getSQL()));
}
if (limitExpr != null) {
buff.append("\nLIMIT (").append(StringUtils.unEnclose(limitExpr.getSQL())).append(')');
}
| 1,185
| 85
| 1,270
|
<methods>public void <init>(com.lealone.db.session.ServerSession) <variables>
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/dml/Update.java
|
YieldableUpdate
|
updateRow
|
class YieldableUpdate extends YieldableUpDel {
final Update statement;
final Column[] columns;
final int[] updateColumnIndexes;
final int columnCount;
public YieldableUpdate(Update statement, AsyncHandler<AsyncResult<Integer>> asyncHandler) {
super(statement, asyncHandler, statement.tableFilter, statement.limitExpr,
statement.condition);
this.statement = statement;
columns = table.getColumns();
columnCount = columns.length;
int size = statement.columns.size();
updateColumnIndexes = new int[size];
for (int i = 0; i < size; i++) {
updateColumnIndexes[i] = statement.columns.get(i).getColumnId();
}
}
@Override
protected int getRightMask() {
return Right.UPDATE;
}
@Override
protected int getTriggerType() {
return Trigger.UPDATE;
}
@Override
public int[] getUpdateColumnIndexes() {
return updateColumnIndexes;
}
@Override
protected boolean upDelRow(Row oldRow) {
Row newRow = createNewRow(oldRow);
table.validateConvertUpdateSequence(session, newRow);
boolean done = false;
if (table.fireRow()) {
done = table.fireBeforeRow(session, oldRow, newRow);
}
if (!done) {
updateRow(oldRow, newRow);
}
return !done;
}
private Row createNewRow(Row oldRow) {
Row newRow = table.getTemplateRow();
newRow.setKey(oldRow.getKey()); // 复用原来的行号
for (int i = 0; i < columnCount; i++) {
Column column = columns[i];
Expression newExpr = statement.expressionMap.get(column);
Value newValue;
if (newExpr == null) {
newValue = oldRow.getValue(i);
} else if (newExpr == ValueExpression.getDefault()) {
newValue = table.getDefaultValue(session, column);
} else {
newValue = column.convert(newExpr.getValue(session));
}
newRow.setValue(i, newValue);
}
return newRow;
}
private void updateRow(Row oldRow, Row newRow) {<FILL_FUNCTION_BODY>}
}
|
onPendingOperationStart();
table.updateRow(session, oldRow, newRow, updateColumnIndexes, true).onComplete(ar -> {
if (ar.isSucceeded() && table.fireRow()) {
table.fireAfterRow(session, oldRow, newRow, false);
}
onPendingOperationComplete(ar);
});
| 611
| 93
| 704
|
<methods>public void <init>(com.lealone.db.session.ServerSession) ,public int getPriority() ,public boolean isCacheable() ,public void setCondition(com.lealone.sql.expression.Expression) ,public void setLimit(com.lealone.sql.expression.Expression) ,public void setTableFilter(com.lealone.sql.optimizer.TableFilter) ,public int update() <variables>protected com.lealone.sql.expression.Expression condition,protected com.lealone.sql.expression.Expression limitExpr,protected com.lealone.sql.optimizer.TableFilter tableFilter
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/executor/YieldableBase.java
|
YieldableBase
|
recompileIfNeeded
|
class YieldableBase<T> implements Yieldable<T> {
protected StatementBase statement;
protected final ServerSession session;
protected final Trace trace;
protected final AsyncHandler<AsyncResult<T>> asyncHandler;
protected AsyncResult<T> asyncResult;
protected long startTimeNanos;
protected boolean started;
protected Throwable pendingException;
protected boolean stopped;
protected boolean yieldEnabled = true;
public YieldableBase(StatementBase statement, AsyncHandler<AsyncResult<T>> asyncHandler) {
this.statement = statement;
this.session = statement.getSession();
this.trace = session.getTrace(TraceModuleType.COMMAND);
this.asyncHandler = asyncHandler;
}
// 子类通常只需要实现以下三个方法
protected boolean startInternal() {
return false;
}
protected void stopInternal() {
}
protected abstract void executeInternal();
protected void setPendingException(Throwable pendingException) {
if (this.pendingException == null)
this.pendingException = pendingException;
}
protected void setResult(T result, int rowCount) {
if (result != null) {
asyncResult = new AsyncResult<>(result);
}
if (rowCount < 0) {
setProgress(DatabaseEventListener.STATE_STATEMENT_WAITING);
} else {
statement.trace(startTimeNanos, rowCount);
setProgress(DatabaseEventListener.STATE_STATEMENT_END);
}
}
@Override
public T getResult() {
return asyncResult != null ? asyncResult.getResult() : null;
}
@Override
public int getPriority() {
return statement.getPriority();
}
@Override
public ServerSession getSession() {
return session;
}
@Override
public PreparedSQLStatement getStatement() {
return statement;
}
@Override
public final void run() {
try {
if (!started) {
if (start()) {
session.setStatus(SessionStatus.STATEMENT_RUNNING);
return;
}
started = true;
}
session.getDatabase().checkPowerOff();
executeInternal();
} catch (Throwable t) {
pendingException = t;
}
if (pendingException != null) {
if (DbObjectLock.LOCKED_EXCEPTION == pendingException) // 忽略
pendingException = null;
else
handleException(pendingException);
} else if (session.getStatus() == SessionStatus.STATEMENT_COMPLETED) {
stop();
}
}
private boolean start() {
if (session.isExclusiveMode() && session.getDatabase().addWaitingSession(session)) {
return true;
}
if (session.getDatabase().getQueryStatistics() || trace.isInfoEnabled()) {
startTimeNanos = System.nanoTime();
}
recompileIfNeeded();
session.startCurrentCommand(statement);
setProgress(DatabaseEventListener.STATE_STATEMENT_START);
statement.checkParameters();
return startInternal();
}
private void recompileIfNeeded() {<FILL_FUNCTION_BODY>}
private void setProgress(int state) {
session.getDatabase().setProgress(state, statement.getSQL(), 0, 0);
}
private void handleException(Throwable t) {
DbException e = DbException.convert(t).addSQL(statement.getSQL());
SQLException s = e.getSQLException();
Database database = session.getDatabase();
database.exceptionThrown(s, statement.getSQL());
if (s.getErrorCode() == ErrorCode.OUT_OF_MEMORY) {
database.shutdownImmediately();
throw e;
}
database.checkPowerOff();
if (!statement.isQuery()) {
if (s.getErrorCode() == ErrorCode.DEADLOCK_1) {
session.rollback();
} else {
// 手动提交模式如果不设置状态会导致不能执行下一条语句
session.setStatus(SessionStatus.STATEMENT_COMPLETED);
session.rollbackCurrentCommand();
}
}
if (asyncHandler != null) {
asyncResult = new AsyncResult<>(e);
asyncHandler.handle(asyncResult);
asyncResult = null; // 不需要再回调了
stop();
} else {
stop();
throw e;
}
}
@Override
public void stop() {
stopped = true;
stopInternal();
session.stopCurrentCommand(statement, asyncHandler, asyncResult);
if (startTimeNanos > 0 && trace.isInfoEnabled()) {
long timeMillis = (System.nanoTime() - startTimeNanos) / 1000 / 1000;
// 如果一条sql的执行时间大于100毫秒,记下它
if (timeMillis > Constants.SLOW_QUERY_LIMIT_MS) {
trace.info("slow query: {0} ms, sql: {1}", timeMillis, statement.getSQL());
}
}
}
@Override
public boolean isStopped() {
return stopped;
}
public void disableYield() {
yieldEnabled = false;
}
public boolean yieldIfNeeded(int rowNumber) {
if (statement.setCurrentRowNumber(rowNumber, yieldEnabled)) {
session.setStatus(SessionStatus.STATEMENT_YIELDED);
return true;
}
return false;
}
}
|
if (statement.needRecompile()) {
statement.setModificationMetaId(0);
String sql = statement.getSQL();
ArrayList<Parameter> oldParams = statement.getParameters();
statement = (StatementBase) session.parseStatement(sql);
long mod = statement.getModificationMetaId();
statement.setModificationMetaId(0);
ArrayList<Parameter> newParams = statement.getParameters();
for (int i = 0, size = newParams.size(); i < size; i++) {
Parameter old = oldParams.get(i);
if (old.isValueSet()) {
Value v = old.getValue(session);
Parameter p = newParams.get(i);
p.setValue(v);
}
}
statement.prepare();
statement.setModificationMetaId(mod);
}
| 1,444
| 212
| 1,656
|
<no_super_class>
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/executor/YieldableLocalUpdate.java
|
YieldableLocalUpdate
|
executeInternal
|
class YieldableLocalUpdate extends YieldableUpdateBase {
public YieldableLocalUpdate(StatementBase statement,
AsyncHandler<AsyncResult<Integer>> asyncHandler) {
super(statement, asyncHandler);
}
@Override
protected void executeInternal() {<FILL_FUNCTION_BODY>}
}
|
session.setStatus(SessionStatus.STATEMENT_RUNNING);
int updateCount = statement.update();
setResult(updateCount);
// 返回的值为负数时,表示当前语句无法正常执行,需要等待其他事务释放锁。
// 当 updateCount<0 时不能再设置为 WAITING 状态,
// 一方面已经设置过了,另一方面如果此时其他事务释放锁了再设置会导致当前语句在后续无法执行。
if (updateCount >= 0) {
session.setStatus(SessionStatus.STATEMENT_COMPLETED);
}
| 82
| 150
| 232
|
<methods>public void <init>(com.lealone.sql.StatementBase, AsyncHandler<AsyncResult<java.lang.Integer>>) <variables>
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/executor/YieldableLoopUpdateBase.java
|
YieldableLoopUpdateBase
|
handleResult
|
class YieldableLoopUpdateBase extends YieldableUpdateBase {
protected final AtomicInteger updateCount = new AtomicInteger();
protected int loopCount;
private boolean loopEnd;
private int pendingOperationCount;
public YieldableLoopUpdateBase(StatementBase statement,
AsyncHandler<AsyncResult<Integer>> asyncHandler) {
super(statement, asyncHandler);
}
@Override
protected void executeInternal() {
while (!loopEnd && pendingException == null) {
session.setStatus(SessionStatus.STATEMENT_RUNNING);
executeLoopUpdate();
if (session.getStatus() == SessionStatus.STATEMENT_YIELDED
|| session.getStatus() == SessionStatus.WAITING) {
return;
}
}
handleResult();
}
protected abstract void executeLoopUpdate();
private void handleResult() {<FILL_FUNCTION_BODY>}
protected void onLoopEnd() {
// 循环已经结束了,但是异步更新可能没有完成,所以先把状态改成STATEMENT_RUNNING,避免调度器空转
session.setStatus(SessionStatus.STATEMENT_RUNNING);
loopEnd = true;
}
protected void onPendingOperationStart() {
pendingOperationCount++;
}
// 执行回调的线程跟执行命令的线程都是同一个
protected void onPendingOperationComplete(AsyncResult<Integer> ar) {
if (ar.isSucceeded()) {
updateCount.incrementAndGet();
} else {
setPendingException(ar.getCause());
}
pendingOperationCount--;
handleResult();
}
}
|
if (loopEnd && pendingOperationCount <= 0) {
setResult(updateCount.get());
session.setStatus(SessionStatus.STATEMENT_COMPLETED);
}
| 425
| 47
| 472
|
<methods>public void <init>(com.lealone.sql.StatementBase, AsyncHandler<AsyncResult<java.lang.Integer>>) <variables>
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/expression/Alias.java
|
Alias
|
getColumnName
|
class Alias extends Expression {
private final String alias;
private Expression expr;
private final boolean aliasColumnName;
public Alias(Expression expression, String alias, boolean aliasColumnName) {
this.expr = expression;
this.alias = alias;
this.aliasColumnName = aliasColumnName;
}
@Override
public Expression getNonAliasExpression() {
return expr;
}
@Override
public Value getValue(ServerSession session) {
return expr.getValue(session);
}
@Override
public int getType() {
return expr.getType();
}
@Override
public Expression optimize(ServerSession session) {
expr = expr.optimize(session);
return this;
}
@Override
public int getScale() {
return expr.getScale();
}
@Override
public long getPrecision() {
return expr.getPrecision();
}
@Override
public int getDisplaySize() {
return expr.getDisplaySize();
}
@Override
public boolean isAutoIncrement() {
return expr.isAutoIncrement();
}
@Override
public String getSQL() {
return expr.getSQL() + " AS " + LealoneSQLParser.quoteIdentifier(alias);
}
@Override
public String getAlias() {
return alias;
}
@Override
public int getNullable() {
return expr.getNullable();
}
@Override
public int getCost() {
return expr.getCost();
}
@Override
public String getTableName() {
if (aliasColumnName) {
return super.getTableName();
}
return expr.getTableName();
}
@Override
public String getColumnName() {<FILL_FUNCTION_BODY>}
@Override
public <R> R accept(ExpressionVisitor<R> visitor) {
return visitor.visitAlias(this);
}
}
|
if (!(expr instanceof ExpressionColumn) || aliasColumnName) {
return super.getColumnName();
}
return expr.getColumnName();
| 538
| 42
| 580
|
<methods>public non-sealed void <init>() ,public R accept(ExpressionVisitor<R>) ,public void addFilterConditions(com.lealone.sql.optimizer.TableFilter, boolean) ,public void createIndexConditions(com.lealone.db.session.ServerSession, com.lealone.sql.optimizer.TableFilter) ,public java.lang.String getAlias() ,public boolean getBooleanValue(com.lealone.db.session.ServerSession) ,public java.lang.String getColumnName() ,public void getColumns(Set<?>) ,public abstract int getCost() ,public void getDependencies(Set<?>) ,public abstract int getDisplaySize() ,public com.lealone.sql.expression.Expression[] getExpressionColumns(com.lealone.db.session.ServerSession) ,public static com.lealone.sql.expression.Expression[] getExpressionColumns(com.lealone.db.session.ServerSession, com.lealone.db.value.ValueArray) ,public static com.lealone.sql.expression.Expression[] getExpressionColumns(com.lealone.db.session.ServerSession, java.sql.ResultSet) ,public com.lealone.sql.expression.Expression getNonAliasExpression() ,public com.lealone.sql.expression.Expression getNotIfPossible(com.lealone.db.session.ServerSession) ,public int getNullable() ,public abstract long getPrecision() ,public abstract java.lang.String getSQL() ,public abstract int getScale() ,public java.lang.String getSchemaName() ,public java.lang.String getTableName() ,public abstract int getType() ,public com.lealone.db.value.Value getValue(com.lealone.db.session.Session) ,public abstract com.lealone.db.value.Value getValue(com.lealone.db.session.ServerSession) ,public boolean isAutoIncrement() ,public boolean isConstant() ,public boolean isEvaluatable() ,public boolean isValueSet() ,public boolean isWildcard() ,public void mapColumns(com.lealone.sql.optimizer.ColumnResolver, int) ,public abstract com.lealone.sql.expression.Expression optimize(com.lealone.db.session.ServerSession) ,public com.lealone.sql.expression.Expression optimize(com.lealone.db.session.Session) ,public java.lang.String toString() ,public void updateAggregate(com.lealone.db.session.ServerSession) <variables>private boolean addedToFilter
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/expression/ExpressionList.java
|
ExpressionList
|
getValue
|
class ExpressionList extends Expression {
private final Expression[] list;
public ExpressionList(Expression[] list) {
this.list = list;
}
public Expression[] getList() {
return list;
}
@Override
public Value getValue(ServerSession session) {<FILL_FUNCTION_BODY>}
@Override
public int getType() {
return Value.ARRAY;
}
@Override
public Expression optimize(ServerSession session) {
boolean allConst = true;
for (int i = 0; i < list.length; i++) {
Expression e = list[i].optimize(session);
if (!e.isConstant()) {
allConst = false;
}
list[i] = e;
}
if (allConst) {
return ValueExpression.get(getValue(session));
}
return this;
}
@Override
public int getScale() {
return 0;
}
@Override
public long getPrecision() {
return Integer.MAX_VALUE;
}
@Override
public int getDisplaySize() {
return Integer.MAX_VALUE;
}
@Override
public String getSQL() {
StatementBuilder buff = new StatementBuilder("(");
for (Expression e : list) {
buff.appendExceptFirst(", ");
buff.append(e.getSQL());
}
if (list.length == 1) {
buff.append(',');
}
return buff.append(')').toString();
}
@Override
public int getCost() {
int cost = 1;
for (Expression e : list) {
cost += e.getCost();
}
return cost;
}
@Override
public Expression[] getExpressionColumns(ServerSession session) {
ExpressionColumn[] expr = new ExpressionColumn[list.length];
for (int i = 0; i < list.length; i++) {
Expression e = list[i];
Column col = new Column("C" + (i + 1), e.getType(), e.getPrecision(), e.getScale(),
e.getDisplaySize());
expr[i] = new ExpressionColumn(session.getDatabase(), col);
}
return expr;
}
@Override
public <R> R accept(ExpressionVisitor<R> visitor) {
return visitor.visitExpressionList(this);
}
}
|
Value[] v = new Value[list.length];
for (int i = 0; i < list.length; i++) {
v[i] = list[i].getValue(session);
}
return ValueArray.get(v);
| 638
| 63
| 701
|
<methods>public non-sealed void <init>() ,public R accept(ExpressionVisitor<R>) ,public void addFilterConditions(com.lealone.sql.optimizer.TableFilter, boolean) ,public void createIndexConditions(com.lealone.db.session.ServerSession, com.lealone.sql.optimizer.TableFilter) ,public java.lang.String getAlias() ,public boolean getBooleanValue(com.lealone.db.session.ServerSession) ,public java.lang.String getColumnName() ,public void getColumns(Set<?>) ,public abstract int getCost() ,public void getDependencies(Set<?>) ,public abstract int getDisplaySize() ,public com.lealone.sql.expression.Expression[] getExpressionColumns(com.lealone.db.session.ServerSession) ,public static com.lealone.sql.expression.Expression[] getExpressionColumns(com.lealone.db.session.ServerSession, com.lealone.db.value.ValueArray) ,public static com.lealone.sql.expression.Expression[] getExpressionColumns(com.lealone.db.session.ServerSession, java.sql.ResultSet) ,public com.lealone.sql.expression.Expression getNonAliasExpression() ,public com.lealone.sql.expression.Expression getNotIfPossible(com.lealone.db.session.ServerSession) ,public int getNullable() ,public abstract long getPrecision() ,public abstract java.lang.String getSQL() ,public abstract int getScale() ,public java.lang.String getSchemaName() ,public java.lang.String getTableName() ,public abstract int getType() ,public com.lealone.db.value.Value getValue(com.lealone.db.session.Session) ,public abstract com.lealone.db.value.Value getValue(com.lealone.db.session.ServerSession) ,public boolean isAutoIncrement() ,public boolean isConstant() ,public boolean isEvaluatable() ,public boolean isValueSet() ,public boolean isWildcard() ,public void mapColumns(com.lealone.sql.optimizer.ColumnResolver, int) ,public abstract com.lealone.sql.expression.Expression optimize(com.lealone.db.session.ServerSession) ,public com.lealone.sql.expression.Expression optimize(com.lealone.db.session.Session) ,public java.lang.String toString() ,public void updateAggregate(com.lealone.db.session.ServerSession) <variables>private boolean addedToFilter
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/expression/Parameter.java
|
Parameter
|
getNullable
|
class Parameter extends Expression implements CommandParameter {
private Value value;
private Column column;
private final int index;
public Parameter(int index) {
this.index = index;
}
@Override
public String getSQL() {
return "?" + (index + 1);
}
@Override
public int getIndex() {
return index;
}
@Override
public void setValue(Value v, boolean closeOld) {
// don't need to close the old value as temporary files are anyway removed
this.value = v;
}
@Override
public void setValue(Value v) {
this.value = v;
}
@Override
public Value getValue() {
if (value == null) {
// to allow parameters in function tables
return ValueNull.INSTANCE;
}
return value;
}
@Override
public Value getValue(ServerSession session) {
return getValue();
}
@Override
public int getType() {
if (value != null) {
return value.getType();
}
if (column != null) {
return column.getType();
}
return Value.UNKNOWN;
}
@Override
public void checkSet() {
if (value == null) {
throw DbException.get(ErrorCode.PARAMETER_NOT_SET_1, "#" + (index + 1));
}
}
@Override
public boolean isValueSet() {
return value != null;
}
@Override
public Expression optimize(ServerSession session) {
return this;
}
@Override
public boolean isConstant() {
return false;
}
@Override
public int getScale() {
if (value != null) {
return value.getScale();
}
if (column != null) {
return column.getScale();
}
return 0;
}
@Override
public long getPrecision() {
if (value != null) {
return value.getPrecision();
}
if (column != null) {
return column.getPrecision();
}
return 0;
}
@Override
public int getDisplaySize() {
if (value != null) {
return value.getDisplaySize();
}
if (column != null) {
return column.getDisplaySize();
}
return 0;
}
@Override
public int getNullable() {<FILL_FUNCTION_BODY>}
@Override
public int getCost() {
return 0;
}
@Override
public Expression getNotIfPossible(ServerSession session) {
return new Comparison(session, Comparison.EQUAL, this,
ValueExpression.get(ValueBoolean.get(false)));
}
public void setColumn(Column column) {
this.column = column;
}
@Override
public <R> R accept(ExpressionVisitor<R> visitor) {
return visitor.visitParameter(this);
}
}
|
if (column != null) {
return column.isNullable() ? Column.NULLABLE : Column.NOT_NULLABLE;
}
return super.getNullable();
| 814
| 45
| 859
|
<methods>public non-sealed void <init>() ,public R accept(ExpressionVisitor<R>) ,public void addFilterConditions(com.lealone.sql.optimizer.TableFilter, boolean) ,public void createIndexConditions(com.lealone.db.session.ServerSession, com.lealone.sql.optimizer.TableFilter) ,public java.lang.String getAlias() ,public boolean getBooleanValue(com.lealone.db.session.ServerSession) ,public java.lang.String getColumnName() ,public void getColumns(Set<?>) ,public abstract int getCost() ,public void getDependencies(Set<?>) ,public abstract int getDisplaySize() ,public com.lealone.sql.expression.Expression[] getExpressionColumns(com.lealone.db.session.ServerSession) ,public static com.lealone.sql.expression.Expression[] getExpressionColumns(com.lealone.db.session.ServerSession, com.lealone.db.value.ValueArray) ,public static com.lealone.sql.expression.Expression[] getExpressionColumns(com.lealone.db.session.ServerSession, java.sql.ResultSet) ,public com.lealone.sql.expression.Expression getNonAliasExpression() ,public com.lealone.sql.expression.Expression getNotIfPossible(com.lealone.db.session.ServerSession) ,public int getNullable() ,public abstract long getPrecision() ,public abstract java.lang.String getSQL() ,public abstract int getScale() ,public java.lang.String getSchemaName() ,public java.lang.String getTableName() ,public abstract int getType() ,public com.lealone.db.value.Value getValue(com.lealone.db.session.Session) ,public abstract com.lealone.db.value.Value getValue(com.lealone.db.session.ServerSession) ,public boolean isAutoIncrement() ,public boolean isConstant() ,public boolean isEvaluatable() ,public boolean isValueSet() ,public boolean isWildcard() ,public void mapColumns(com.lealone.sql.optimizer.ColumnResolver, int) ,public abstract com.lealone.sql.expression.Expression optimize(com.lealone.db.session.ServerSession) ,public com.lealone.sql.expression.Expression optimize(com.lealone.db.session.Session) ,public java.lang.String toString() ,public void updateAggregate(com.lealone.db.session.ServerSession) <variables>private boolean addedToFilter
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/expression/SelectOrderBy.java
|
SelectOrderBy
|
getSQL
|
class SelectOrderBy {
/**
* The order by expression.
*/
public Expression expression;
/**
* The column index expression. This can be a column index number (1 meaning
* the first column of the select list) or a parameter (the parameter is a
* number representing the column index number).
*/
public Expression columnIndexExpr;
/**
* If the column should be sorted descending.
*/
public boolean descending;
/**
* If NULL should be appear first.
*/
public boolean nullsFirst;
/**
* If NULL should be appear at the end.
*/
public boolean nullsLast;
public String getSQL() {<FILL_FUNCTION_BODY>}
}
|
StringBuilder buff = new StringBuilder();
if (expression != null) {
buff.append(expression.getSQL());
} else {
buff.append(columnIndexExpr.getSQL());
}
if (descending) {
buff.append(" DESC");
}
if (nullsFirst) {
buff.append(" NULLS FIRST");
} else if (nullsLast) {
buff.append(" NULLS LAST");
}
return buff.toString();
| 192
| 127
| 319
|
<no_super_class>
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/expression/ValueExpression.java
|
ValueExpression
|
getExpressionColumns
|
class ValueExpression extends Expression {
/**
* The expression represents ValueNull.INSTANCE.
*/
private static final Object NULL = new ValueExpression(ValueNull.INSTANCE);
/**
* This special expression represents the default value. It is used for
* UPDATE statements of the form SET COLUMN = DEFAULT. The value is
* ValueNull.INSTANCE, but should never be accessed.
*/
private static final Object DEFAULT = new ValueExpression(ValueNull.INSTANCE);
private final Value value;
private ValueExpression(Value value) {
this.value = value;
}
/**
* Get the NULL expression.
*
* @return the NULL expression
*/
public static ValueExpression getNull() {
return (ValueExpression) NULL;
}
/**
* Get the DEFAULT expression.
*
* @return the DEFAULT expression
*/
public static ValueExpression getDefault() {
return (ValueExpression) DEFAULT;
}
/**
* Create a new expression with the given value.
*
* @param value the value
* @return the expression
*/
public static ValueExpression get(Value value) {
if (value == ValueNull.INSTANCE) {
return getNull();
}
return new ValueExpression(value);
}
@Override
public Value getValue(ServerSession session) {
return value;
}
@Override
public int getType() {
return value.getType();
}
@Override
public void createIndexConditions(ServerSession session, TableFilter filter) {
if (value.getType() == Value.BOOLEAN && !value.getBoolean()) {
filter.addIndexCondition(IndexCondition.get(Comparison.FALSE, null, this));
}
}
@Override
public Expression getNotIfPossible(ServerSession session) {
return new Comparison(session, Comparison.EQUAL, this,
ValueExpression.get(ValueBoolean.get(false)));
}
@Override
public Expression optimize(ServerSession session) {
return this;
}
@Override
public boolean isConstant() {
return true;
}
@Override
public boolean isValueSet() {
return true;
}
@Override
public int getScale() {
return value.getScale();
}
@Override
public long getPrecision() {
return value.getPrecision();
}
@Override
public int getDisplaySize() {
return value.getDisplaySize();
}
@Override
public String getSQL() {
if (this == DEFAULT) {
return "DEFAULT";
}
return value.getSQL();
}
@Override
public int getCost() {
return 0;
}
@Override
public Expression[] getExpressionColumns(ServerSession session) {<FILL_FUNCTION_BODY>}
@Override
public <R> R accept(ExpressionVisitor<R> visitor) {
return visitor.visitValueExpression(this);
}
}
|
if (getType() == Value.ARRAY) {
return getExpressionColumns(session, (ValueArray) getValue(session));
}
return super.getExpressionColumns(session);
| 786
| 49
| 835
|
<methods>public non-sealed void <init>() ,public R accept(ExpressionVisitor<R>) ,public void addFilterConditions(com.lealone.sql.optimizer.TableFilter, boolean) ,public void createIndexConditions(com.lealone.db.session.ServerSession, com.lealone.sql.optimizer.TableFilter) ,public java.lang.String getAlias() ,public boolean getBooleanValue(com.lealone.db.session.ServerSession) ,public java.lang.String getColumnName() ,public void getColumns(Set<?>) ,public abstract int getCost() ,public void getDependencies(Set<?>) ,public abstract int getDisplaySize() ,public com.lealone.sql.expression.Expression[] getExpressionColumns(com.lealone.db.session.ServerSession) ,public static com.lealone.sql.expression.Expression[] getExpressionColumns(com.lealone.db.session.ServerSession, com.lealone.db.value.ValueArray) ,public static com.lealone.sql.expression.Expression[] getExpressionColumns(com.lealone.db.session.ServerSession, java.sql.ResultSet) ,public com.lealone.sql.expression.Expression getNonAliasExpression() ,public com.lealone.sql.expression.Expression getNotIfPossible(com.lealone.db.session.ServerSession) ,public int getNullable() ,public abstract long getPrecision() ,public abstract java.lang.String getSQL() ,public abstract int getScale() ,public java.lang.String getSchemaName() ,public java.lang.String getTableName() ,public abstract int getType() ,public com.lealone.db.value.Value getValue(com.lealone.db.session.Session) ,public abstract com.lealone.db.value.Value getValue(com.lealone.db.session.ServerSession) ,public boolean isAutoIncrement() ,public boolean isConstant() ,public boolean isEvaluatable() ,public boolean isValueSet() ,public boolean isWildcard() ,public void mapColumns(com.lealone.sql.optimizer.ColumnResolver, int) ,public abstract com.lealone.sql.expression.Expression optimize(com.lealone.db.session.ServerSession) ,public com.lealone.sql.expression.Expression optimize(com.lealone.db.session.Session) ,public java.lang.String toString() ,public void updateAggregate(com.lealone.db.session.ServerSession) <variables>private boolean addedToFilter
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/expression/Wildcard.java
|
Wildcard
|
getSQL
|
class Wildcard extends Expression {
private final String schema;
private final String table;
public Wildcard(String schema, String table) {
this.schema = schema;
this.table = table;
}
@Override
public boolean isWildcard() {
return true;
}
@Override
public Value getValue(ServerSession session) {
throw DbException.getInternalError();
}
@Override
public int getType() {
throw DbException.getInternalError();
}
@Override
public void mapColumns(ColumnResolver resolver, int level) {
throw DbException.get(ErrorCode.SYNTAX_ERROR_1, table);
}
@Override
public Expression optimize(ServerSession session) {
throw DbException.get(ErrorCode.SYNTAX_ERROR_1, table);
}
@Override
public int getScale() {
throw DbException.getInternalError();
}
@Override
public long getPrecision() {
throw DbException.getInternalError();
}
@Override
public int getDisplaySize() {
throw DbException.getInternalError();
}
@Override
public String getSchemaName() {
return schema;
}
@Override
public String getTableName() {
return table;
}
@Override
public String getSQL() {<FILL_FUNCTION_BODY>}
@Override
public void updateAggregate(ServerSession session) {
DbException.throwInternalError();
}
@Override
public int getCost() {
throw DbException.getInternalError();
}
@Override
public <R> R accept(ExpressionVisitor<R> visitor) {
return visitor.visitWildcard(this);
}
}
|
if (table == null) {
return "*";
}
return StringUtils.quoteIdentifier(table) + ".*";
| 478
| 36
| 514
|
<methods>public non-sealed void <init>() ,public R accept(ExpressionVisitor<R>) ,public void addFilterConditions(com.lealone.sql.optimizer.TableFilter, boolean) ,public void createIndexConditions(com.lealone.db.session.ServerSession, com.lealone.sql.optimizer.TableFilter) ,public java.lang.String getAlias() ,public boolean getBooleanValue(com.lealone.db.session.ServerSession) ,public java.lang.String getColumnName() ,public void getColumns(Set<?>) ,public abstract int getCost() ,public void getDependencies(Set<?>) ,public abstract int getDisplaySize() ,public com.lealone.sql.expression.Expression[] getExpressionColumns(com.lealone.db.session.ServerSession) ,public static com.lealone.sql.expression.Expression[] getExpressionColumns(com.lealone.db.session.ServerSession, com.lealone.db.value.ValueArray) ,public static com.lealone.sql.expression.Expression[] getExpressionColumns(com.lealone.db.session.ServerSession, java.sql.ResultSet) ,public com.lealone.sql.expression.Expression getNonAliasExpression() ,public com.lealone.sql.expression.Expression getNotIfPossible(com.lealone.db.session.ServerSession) ,public int getNullable() ,public abstract long getPrecision() ,public abstract java.lang.String getSQL() ,public abstract int getScale() ,public java.lang.String getSchemaName() ,public java.lang.String getTableName() ,public abstract int getType() ,public com.lealone.db.value.Value getValue(com.lealone.db.session.Session) ,public abstract com.lealone.db.value.Value getValue(com.lealone.db.session.ServerSession) ,public boolean isAutoIncrement() ,public boolean isConstant() ,public boolean isEvaluatable() ,public boolean isValueSet() ,public boolean isWildcard() ,public void mapColumns(com.lealone.sql.optimizer.ColumnResolver, int) ,public abstract com.lealone.sql.expression.Expression optimize(com.lealone.db.session.ServerSession) ,public com.lealone.sql.expression.Expression optimize(com.lealone.db.session.Session) ,public java.lang.String toString() ,public void updateAggregate(com.lealone.db.session.ServerSession) <variables>private boolean addedToFilter
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/expression/aggregate/ACount.java
|
ACount
|
optimize
|
class ACount extends BuiltInAggregate {
public ACount(int type, Expression on, Select select, boolean distinct) {
super(type, on, select, distinct);
}
@Override
public Expression optimize(ServerSession session) {<FILL_FUNCTION_BODY>}
@Override
protected AggregateData createAggregateData() {
return new AggregateDataCount();
}
@Override
public String getSQL() {
return getSQL("COUNT");
}
public class AggregateDataCount extends AggregateData {
private long count;
private ValueHashMap<AggregateDataCount> distinctValues;
public long getCount() {
return count;
}
public void setCount(long count) {
this.count = count;
}
public ValueHashMap<AggregateDataCount> getDistinctValues() {
return distinctValues;
}
public void setDistinctValues(ValueHashMap<AggregateDataCount> distinctValues) {
this.distinctValues = distinctValues;
}
public boolean isDistinct() {
return distinct;
}
@Override
public void add(ServerSession session, Value v) {
if (v == ValueNull.INSTANCE) {
return;
}
count++;
if (distinct) {
if (distinctValues == null) {
distinctValues = ValueHashMap.newInstance();
}
distinctValues.put(v, this);
}
}
@Override
Value getValue(ServerSession session) {
if (distinct) {
if (distinctValues != null) {
count = distinctValues.size();
} else {
count = 0;
}
}
return ValueLong.get(count);
}
}
}
|
super.optimize(session);
dataType = Value.LONG;
scale = 0;
precision = ValueLong.PRECISION;
displaySize = ValueLong.DISPLAY_SIZE;
return this;
| 467
| 59
| 526
|
<methods>public void <init>(int, com.lealone.sql.expression.Expression, com.lealone.sql.query.Select, boolean) ,public R accept(ExpressionVisitor<R>) ,public int getAType() ,public com.lealone.sql.expression.aggregate.AggregateData getAggregateData() ,public int getCost() ,public int getDisplaySize() ,public com.lealone.sql.expression.Expression getOn() ,public long getPrecision() ,public int getScale() ,public com.lealone.db.value.Value getValue(com.lealone.db.session.ServerSession) ,public boolean isOptimizable(com.lealone.db.table.Table) ,public com.lealone.sql.expression.Expression optimize(com.lealone.db.session.ServerSession) ,public void updateAggregate(com.lealone.db.session.ServerSession) <variables>protected int displaySize,protected final non-sealed boolean distinct,protected com.lealone.sql.expression.Expression on,protected long precision,protected int scale,protected final non-sealed int type
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/expression/aggregate/ACountAll.java
|
ACountAll
|
optimize
|
class ACountAll extends BuiltInAggregate {
public ACountAll(int type, Expression on, Select select, boolean distinct) {
super(type, on, select, distinct);
// 在Parser.readAggregate那里确保使用COUNT_ALL时distinct是false
if (distinct) {
throw DbException.getInternalError();
}
}
@Override
public Expression optimize(ServerSession session) {<FILL_FUNCTION_BODY>}
@Override
protected AggregateData createAggregateData() {
return new AggregateDataCountAll();
}
@Override
public String getSQL() {
return "COUNT(*)";
}
public class AggregateDataCountAll extends AggregateData {
private long count;
public long getCount() {
return count;
}
public void setCount(long count) {
this.count = count;
}
public Select getSelect() {
return select;
}
@Override
public void add(ServerSession session, Value v) {
count++;
}
@Override
Value getValue(ServerSession session) {
return ValueLong.get(count);
}
}
}
|
super.optimize(session);
dataType = Value.LONG;
scale = 0;
precision = ValueLong.PRECISION;
displaySize = ValueLong.DISPLAY_SIZE;
return this;
| 319
| 59
| 378
|
<methods>public void <init>(int, com.lealone.sql.expression.Expression, com.lealone.sql.query.Select, boolean) ,public R accept(ExpressionVisitor<R>) ,public int getAType() ,public com.lealone.sql.expression.aggregate.AggregateData getAggregateData() ,public int getCost() ,public int getDisplaySize() ,public com.lealone.sql.expression.Expression getOn() ,public long getPrecision() ,public int getScale() ,public com.lealone.db.value.Value getValue(com.lealone.db.session.ServerSession) ,public boolean isOptimizable(com.lealone.db.table.Table) ,public com.lealone.sql.expression.Expression optimize(com.lealone.db.session.ServerSession) ,public void updateAggregate(com.lealone.db.session.ServerSession) <variables>protected int displaySize,protected final non-sealed boolean distinct,protected com.lealone.sql.expression.Expression on,protected long precision,protected int scale,protected final non-sealed int type
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/expression/aggregate/AGroupConcat.java
|
AGroupConcat
|
initOrder
|
class AGroupConcat extends BuiltInAggregate {
private Expression groupConcatSeparator;
private ArrayList<SelectOrderBy> groupConcatOrderList;
private SortOrder groupConcatSort;
public AGroupConcat(int type, Expression on, Select select, boolean distinct) {
super(type, on, select, distinct);
}
public Expression getGroupConcatSeparator() {
return groupConcatSeparator;
}
public ArrayList<SelectOrderBy> getGroupConcatOrderList() {
return groupConcatOrderList;
}
/**
* Set the order for GROUP_CONCAT() aggregate.
*
* @param orderBy the order by list
*/
public void setGroupConcatOrder(ArrayList<SelectOrderBy> orderBy) {
this.groupConcatOrderList = orderBy;
}
/**
* Set the separator for the GROUP_CONCAT() aggregate.
*
* @param separator the separator expression
*/
public void setGroupConcatSeparator(Expression separator) {
this.groupConcatSeparator = separator;
}
private SortOrder initOrder(ServerSession session) {<FILL_FUNCTION_BODY>}
@Override
public Expression optimize(ServerSession session) {
super.optimize(session);
if (groupConcatOrderList != null) {
for (SelectOrderBy o : groupConcatOrderList) {
o.expression = o.expression.optimize(session);
}
groupConcatSort = initOrder(session);
}
if (groupConcatSeparator != null) {
groupConcatSeparator = groupConcatSeparator.optimize(session);
}
dataType = Value.STRING;
scale = 0;
precision = displaySize = Integer.MAX_VALUE;
return this;
}
@Override
protected AggregateData createAggregateData() {
return new AggregateDataGroupConcat();
}
@Override
public String getSQL() {
StatementBuilder buff = new StatementBuilder("GROUP_CONCAT(");
if (distinct) {
buff.append("DISTINCT ");
}
buff.append(on.getSQL());
if (groupConcatOrderList != null) {
buff.append(" ORDER BY ");
for (SelectOrderBy o : groupConcatOrderList) {
buff.appendExceptFirst(", ");
buff.append(o.expression.getSQL());
if (o.descending) {
buff.append(" DESC");
}
}
}
if (groupConcatSeparator != null) {
buff.append(" SEPARATOR ").append(groupConcatSeparator.getSQL());
}
return buff.append(')').toString();
}
@Override
public <R> R accept(ExpressionVisitor<R> visitor) {
return visitor.visitAGroupConcat(this);
}
public class AggregateDataGroupConcat extends AggregateData {
private ArrayList<Value> list;
private ValueHashMap<AggregateDataGroupConcat> distinctValues;
@Override
public void add(ServerSession session, Value v) {
if (v != ValueNull.INSTANCE) {
v = v.convertTo(Value.STRING);
if (groupConcatOrderList != null) {
int size = groupConcatOrderList.size();
Value[] array = new Value[1 + size];
array[0] = v;
for (int i = 0; i < size; i++) {
SelectOrderBy o = groupConcatOrderList.get(i);
array[i + 1] = o.expression.getValue(session);
}
v = ValueArray.get(array);
}
}
add(session, v, distinct);
}
private void add(ServerSession session, Value v, boolean distinct) {
if (v == ValueNull.INSTANCE) {
return;
}
if (distinct) {
if (distinctValues == null) {
distinctValues = ValueHashMap.newInstance();
}
distinctValues.put(v, this);
return;
}
if (list == null) {
list = new ArrayList<>();
}
list.add(v);
}
@Override
Value getValue(ServerSession session) {
if (distinct) {
groupDistinct(session, dataType);
}
if (list == null || list.isEmpty()) {
return ValueNull.INSTANCE;
}
if (groupConcatOrderList != null) {
final SortOrder sortOrder = groupConcatSort;
Collections.sort(list, new Comparator<Value>() {
@Override
public int compare(Value v1, Value v2) {
Value[] a1 = ((ValueArray) v1).getList();
Value[] a2 = ((ValueArray) v2).getList();
return sortOrder.compare(a1, a2);
}
});
}
StatementBuilder buff = new StatementBuilder();
String sep = groupConcatSeparator == null ? ","
: groupConcatSeparator.getValue(session).getString();
for (Value val : list) {
String s;
if (val.getType() == Value.ARRAY) {
s = ((ValueArray) val).getList()[0].getString();
} else {
s = val.getString();
}
if (s == null) {
continue;
}
if (sep != null) {
buff.appendExceptFirst(sep);
}
buff.append(s);
}
return ValueString.get(buff.toString());
}
private void groupDistinct(ServerSession session, int dataType) {
if (distinctValues == null) {
return;
}
for (Value v : distinctValues.keys()) {
add(session, v, false);
}
}
}
}
|
int size = groupConcatOrderList.size();
int[] index = new int[size];
int[] sortType = new int[size];
for (int i = 0; i < size; i++) {
SelectOrderBy o = groupConcatOrderList.get(i);
index[i] = i + 1;
int order = o.descending ? SortOrder.DESCENDING : SortOrder.ASCENDING;
sortType[i] = order;
}
return new SortOrder(session.getDatabase(), index, sortType, null);
| 1,524
| 142
| 1,666
|
<methods>public void <init>(int, com.lealone.sql.expression.Expression, com.lealone.sql.query.Select, boolean) ,public R accept(ExpressionVisitor<R>) ,public int getAType() ,public com.lealone.sql.expression.aggregate.AggregateData getAggregateData() ,public int getCost() ,public int getDisplaySize() ,public com.lealone.sql.expression.Expression getOn() ,public long getPrecision() ,public int getScale() ,public com.lealone.db.value.Value getValue(com.lealone.db.session.ServerSession) ,public boolean isOptimizable(com.lealone.db.table.Table) ,public com.lealone.sql.expression.Expression optimize(com.lealone.db.session.ServerSession) ,public void updateAggregate(com.lealone.db.session.ServerSession) <variables>protected int displaySize,protected final non-sealed boolean distinct,protected com.lealone.sql.expression.Expression on,protected long precision,protected int scale,protected final non-sealed int type
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/expression/aggregate/AHistogram.java
|
AggregateDataHistogram
|
getValue
|
class AggregateDataHistogram extends AggregateData {
private long count;
private ValueHashMap<AggregateDataHistogram> distinctValues;
@Override
public void add(ServerSession session, Value v) {
if (distinctValues == null) {
distinctValues = ValueHashMap.newInstance();
}
AggregateDataHistogram a = distinctValues.get(v);
if (a == null) {
if (distinctValues.size() < Constants.SELECTIVITY_DISTINCT_COUNT) {
a = new AggregateDataHistogram();
distinctValues.put(v, a);
}
}
if (a != null) {
a.count++;
}
}
@Override
Value getValue(ServerSession session) {<FILL_FUNCTION_BODY>}
}
|
ValueArray[] values = new ValueArray[distinctValues.size()];
int i = 0;
for (Value dv : distinctValues.keys()) {
AggregateDataHistogram d = distinctValues.get(dv);
values[i] = ValueArray.get(new Value[] { dv, ValueLong.get(d.count) });
i++;
}
final CompareMode compareMode = session.getDatabase().getCompareMode();
Arrays.sort(values, new Comparator<ValueArray>() {
@Override
public int compare(ValueArray v1, ValueArray v2) {
Value a1 = v1.getList()[0];
Value a2 = v2.getList()[0];
return a1.compareTo(a2, compareMode);
}
});
Value v = ValueArray.get(values);
return v.convertTo(dataType);
| 217
| 228
| 445
|
<methods>public void <init>(int, com.lealone.sql.expression.Expression, com.lealone.sql.query.Select, boolean) ,public R accept(ExpressionVisitor<R>) ,public int getAType() ,public com.lealone.sql.expression.aggregate.AggregateData getAggregateData() ,public int getCost() ,public int getDisplaySize() ,public com.lealone.sql.expression.Expression getOn() ,public long getPrecision() ,public int getScale() ,public com.lealone.db.value.Value getValue(com.lealone.db.session.ServerSession) ,public boolean isOptimizable(com.lealone.db.table.Table) ,public com.lealone.sql.expression.Expression optimize(com.lealone.db.session.ServerSession) ,public void updateAggregate(com.lealone.db.session.ServerSession) <variables>protected int displaySize,protected final non-sealed boolean distinct,protected com.lealone.sql.expression.Expression on,protected long precision,protected int scale,protected final non-sealed int type
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/expression/aggregate/ASelectivity.java
|
ASelectivity
|
optimize
|
class ASelectivity extends BuiltInAggregate {
public ASelectivity(int type, Expression on, Select select, boolean distinct) {
super(type, on, select, distinct);
}
@Override
public Expression optimize(ServerSession session) {<FILL_FUNCTION_BODY>}
@Override
protected AggregateData createAggregateData() {
return new AggregateDataSelectivity();
}
@Override
public String getSQL() {
return getSQL("SELECTIVITY");
}
// 会忽略distinct
// 返回(100 * distinctCount/rowCount)
public class AggregateDataSelectivity extends AggregateData {
private long count;
private IntIntHashMap distinctHashes;
private double m2;
@Override
public void add(ServerSession session, Value v) {
// 是基于某个表达式(多数是单个字段)算不重复的记录数所占总记录数的百分比
// Constants.SELECTIVITY_DISTINCT_COUNT默认是1万,这个值不能改,
// 对统计值影响很大。通常这个值越大,统计越精确,但是会使用更多内存。
// SELECTIVITY越大,说明重复的记录越少,在选择索引时更有利。
count++;
if (distinctHashes == null) {
distinctHashes = new IntIntHashMap();
}
int size = distinctHashes.size();
if (size > Constants.SELECTIVITY_DISTINCT_COUNT) {
distinctHashes = new IntIntHashMap();
m2 += size;
}
int hash = v.hashCode();
// the value -1 is not supported
distinctHashes.put(hash, 1);
}
@Override
Value getValue(ServerSession session) {
if (distinctHashes == null)
return ValueInt.get(Constants.SELECTIVITY_DEFAULT);
m2 += distinctHashes.size();
m2 = 100 * m2 / count;
int s = (int) m2;
s = s <= 0 ? 1 : s > 100 ? 100 : s;
Value v = ValueInt.get(s);
return v.convertTo(dataType);
}
}
}
|
super.optimize(session);
dataType = Value.INT;
scale = 0;
precision = ValueInt.PRECISION;
displaySize = ValueInt.DISPLAY_SIZE;
return this;
| 592
| 58
| 650
|
<methods>public void <init>(int, com.lealone.sql.expression.Expression, com.lealone.sql.query.Select, boolean) ,public R accept(ExpressionVisitor<R>) ,public int getAType() ,public com.lealone.sql.expression.aggregate.AggregateData getAggregateData() ,public int getCost() ,public int getDisplaySize() ,public com.lealone.sql.expression.Expression getOn() ,public long getPrecision() ,public int getScale() ,public com.lealone.db.value.Value getValue(com.lealone.db.session.ServerSession) ,public boolean isOptimizable(com.lealone.db.table.Table) ,public com.lealone.sql.expression.Expression optimize(com.lealone.db.session.ServerSession) ,public void updateAggregate(com.lealone.db.session.ServerSession) <variables>protected int displaySize,protected final non-sealed boolean distinct,protected com.lealone.sql.expression.Expression on,protected long precision,protected int scale,protected final non-sealed int type
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/expression/aggregate/Aggregate.java
|
Aggregate
|
create
|
class Aggregate extends Expression {
/**
* The aggregate type for COUNT(*).
*/
public static final int COUNT_ALL = 0;
/**
* The aggregate type for COUNT(expression).
*/
public static final int COUNT = 1;
/**
* The aggregate type for GROUP_CONCAT(...).
*/
public static final int GROUP_CONCAT = 2;
/**
* The aggregate type for SUM(expression).
*/
public static final int SUM = 3;
/**
* The aggregate type for MIN(expression).
*/
public static final int MIN = 4;
/**
* The aggregate type for MAX(expression).
*/
public static final int MAX = 5;
/**
* The aggregate type for AVG(expression).
*/
public static final int AVG = 6;
/**
* The aggregate type for STDDEV_POP(expression).
*/
public static final int STDDEV_POP = 7;
/**
* The aggregate type for STDDEV_SAMP(expression).
*/
public static final int STDDEV_SAMP = 8;
/**
* The aggregate type for VAR_POP(expression).
*/
public static final int VAR_POP = 9;
/**
* The aggregate type for VAR_SAMP(expression).
*/
public static final int VAR_SAMP = 10;
/**
* The aggregate type for BOOL_OR(expression).
*/
public static final int BOOL_OR = 11;
/**
* The aggregate type for BOOL_AND(expression).
*/
public static final int BOOL_AND = 12;
/**
* The aggregate type for BIT_OR(expression).
*/
public static final int BIT_OR = 13;
/**
* The aggregate type for BIT_AND(expression).
*/
public static final int BIT_AND = 14;
/**
* The aggregate type for SELECTIVITY(expression).
*/
public static final int SELECTIVITY = 15;
/**
* The aggregate type for HISTOGRAM(expression).
*/
public static final int HISTOGRAM = 16;
private static final HashMap<String, Integer> AGGREGATES = new HashMap<>();
static {
addAggregate("COUNT", COUNT);
addAggregate("SUM", SUM);
addAggregate("MIN", MIN);
addAggregate("MAX", MAX);
addAggregate("AVG", AVG);
addAggregate("GROUP_CONCAT", GROUP_CONCAT);
// PostgreSQL compatibility: string_agg(expression, delimiter)
addAggregate("STRING_AGG", GROUP_CONCAT);
addAggregate("STDDEV_SAMP", STDDEV_SAMP);
addAggregate("STDDEV", STDDEV_SAMP);
addAggregate("STDDEV_POP", STDDEV_POP);
addAggregate("STDDEVP", STDDEV_POP);
addAggregate("VAR_POP", VAR_POP);
addAggregate("VARP", VAR_POP);
addAggregate("VAR_SAMP", VAR_SAMP);
addAggregate("VAR", VAR_SAMP);
addAggregate("VARIANCE", VAR_SAMP);
addAggregate("BOOL_OR", BOOL_OR);
addAggregate("BOOL_AND", BOOL_AND);
// HSQLDB compatibility, but conflicts with x > SOME(...)
addAggregate("SOME", BOOL_OR);
// HSQLDB compatibility, but conflicts with x > EVERY(...)
addAggregate("EVERY", BOOL_AND);
addAggregate("SELECTIVITY", SELECTIVITY);
addAggregate("HISTOGRAM", HISTOGRAM);
addAggregate("BIT_OR", BIT_OR);
addAggregate("BIT_AND", BIT_AND);
}
private static void addAggregate(String name, int type) {
AGGREGATES.put(name, type);
}
/**
* Get the aggregate type for this name, or -1 if no aggregate has been found.
*
* @param name the aggregate function name
* @return -1 if no aggregate function has been found, or the aggregate type
*/
public static int getAggregateType(String name) {
Integer type = AGGREGATES.get(name);
return type == null ? -1 : type.intValue();
}
public static Aggregate create(int type, Expression on, Select select, boolean distinct) {<FILL_FUNCTION_BODY>}
protected final Select select;
protected int dataType;
protected int lastGroupRowId;
public Aggregate(Select select) {
this.select = select;
}
@Override
public int getType() {
return dataType;
}
@Override
public <R> R accept(ExpressionVisitor<R> visitor) {
return visitor.visitAggregate(this);
}
public Expression getOn() {
return null;
}
}
|
switch (type) {
case Aggregate.COUNT:
return new ACount(type, on, select, distinct);
case Aggregate.COUNT_ALL:
return new ACountAll(type, on, select, distinct);
case Aggregate.GROUP_CONCAT:
return new AGroupConcat(type, on, select, distinct);
case Aggregate.HISTOGRAM:
return new AHistogram(type, on, select, distinct);
case Aggregate.SELECTIVITY:
return new ASelectivity(type, on, select, distinct);
default:
return new ADefault(type, on, select, distinct);
}
| 1,324
| 168
| 1,492
|
<methods>public non-sealed void <init>() ,public R accept(ExpressionVisitor<R>) ,public void addFilterConditions(com.lealone.sql.optimizer.TableFilter, boolean) ,public void createIndexConditions(com.lealone.db.session.ServerSession, com.lealone.sql.optimizer.TableFilter) ,public java.lang.String getAlias() ,public boolean getBooleanValue(com.lealone.db.session.ServerSession) ,public java.lang.String getColumnName() ,public void getColumns(Set<?>) ,public abstract int getCost() ,public void getDependencies(Set<?>) ,public abstract int getDisplaySize() ,public com.lealone.sql.expression.Expression[] getExpressionColumns(com.lealone.db.session.ServerSession) ,public static com.lealone.sql.expression.Expression[] getExpressionColumns(com.lealone.db.session.ServerSession, com.lealone.db.value.ValueArray) ,public static com.lealone.sql.expression.Expression[] getExpressionColumns(com.lealone.db.session.ServerSession, java.sql.ResultSet) ,public com.lealone.sql.expression.Expression getNonAliasExpression() ,public com.lealone.sql.expression.Expression getNotIfPossible(com.lealone.db.session.ServerSession) ,public int getNullable() ,public abstract long getPrecision() ,public abstract java.lang.String getSQL() ,public abstract int getScale() ,public java.lang.String getSchemaName() ,public java.lang.String getTableName() ,public abstract int getType() ,public com.lealone.db.value.Value getValue(com.lealone.db.session.Session) ,public abstract com.lealone.db.value.Value getValue(com.lealone.db.session.ServerSession) ,public boolean isAutoIncrement() ,public boolean isConstant() ,public boolean isEvaluatable() ,public boolean isValueSet() ,public boolean isWildcard() ,public void mapColumns(com.lealone.sql.optimizer.ColumnResolver, int) ,public abstract com.lealone.sql.expression.Expression optimize(com.lealone.db.session.ServerSession) ,public com.lealone.sql.expression.Expression optimize(com.lealone.db.session.Session) ,public java.lang.String toString() ,public void updateAggregate(com.lealone.db.session.ServerSession) <variables>private boolean addedToFilter
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/expression/aggregate/BuiltInAggregate.java
|
BuiltInAggregate
|
getSQL
|
class BuiltInAggregate extends Aggregate {
protected final int type;
protected final boolean distinct;
protected Expression on;
protected int scale;
protected long precision;
protected int displaySize;
/**
* Create a new aggregate object.
*
* @param type the aggregate type
* @param on the aggregated expression
* @param select the select statement
* @param distinct if distinct is used
*/
public BuiltInAggregate(int type, Expression on, Select select, boolean distinct) {
super(select);
this.type = type;
this.on = on;
this.distinct = distinct;
}
public int getAType() {
return type;
}
@Override
public Expression getOn() {
return on;
}
@Override
public int getScale() {
return scale;
}
@Override
public long getPrecision() {
return precision;
}
@Override
public int getDisplaySize() {
return displaySize;
}
@Override
public int getCost() {
return (on == null) ? 1 : on.getCost() + 1;
}
@Override
public Expression optimize(ServerSession session) {
if (on != null) {
on = on.optimize(session);
dataType = on.getType();
scale = on.getScale();
precision = on.getPrecision();
displaySize = on.getDisplaySize();
}
return this;
}
protected abstract AggregateData createAggregateData();
public AggregateData getAggregateData() {
HashMap<Expression, Object> group = select.getCurrentGroup();
if (group == null) {
// this is a different level (the enclosing query)
return null;
}
int groupRowId = select.getCurrentGroupRowId();
if (lastGroupRowId == groupRowId) {
// already visited
return null;
}
lastGroupRowId = groupRowId;
AggregateData data = (AggregateData) group.get(this);
if (data == null) {
data = createAggregateData();
group.put(this, data);
}
return data;
}
@Override
public void updateAggregate(ServerSession session) {
AggregateData data = getAggregateData();
if (data == null) {
return;
}
Value v = on == null ? null : on.getValue(session);
data.add(session, v);
}
@Override
public Value getValue(ServerSession session) {
if (select.isQuickAggregateQuery()) {
switch (type) {
case COUNT:
case COUNT_ALL:
Table table = select.getTopTableFilter().getTable();
return ValueLong.get(table.getRowCount(session));
case MIN:
case MAX:
boolean first = type == MIN;
Index index = getColumnIndex();
int sortType = index.getIndexColumns()[0].sortType;
if ((sortType & SortOrder.DESCENDING) != 0) {
first = !first;
}
SearchRow row = index.findFirstOrLast(session, first);
Value v;
if (row == null) {
v = ValueNull.INSTANCE;
} else {
v = row.getValue(index.getColumns()[0].getColumnId());
}
return v;
default:
DbException.throwInternalError("type=" + type);
}
}
return getFinalAggregateData().getValue(session);
}
private AggregateData getFinalAggregateData() {
HashMap<Expression, Object> group = select.getCurrentGroup();
if (group == null) {
throw DbException.get(ErrorCode.INVALID_USE_OF_AGGREGATE_FUNCTION_1, getSQL());
}
AggregateData data = (AggregateData) group.get(this);
if (data == null) {
data = createAggregateData();
}
return data;
}
private Index getColumnIndex() {
if (on instanceof ExpressionColumn) {
ExpressionColumn col = (ExpressionColumn) on;
Column column = col.getColumn();
TableFilter filter = col.getTableFilter();
if (filter != null) {
Table table = filter.getTable();
Index index = table.getIndexForColumn(column);
return index;
}
}
return null;
}
public boolean isOptimizable(Table table) {
switch (type) {
case COUNT:
if (!distinct && on.getNullable() == Column.NOT_NULLABLE) {
return table.canGetRowCount();
}
return false;
case COUNT_ALL:
return table.canGetRowCount();
case MIN:
case MAX:
Index index = getColumnIndex();
return index != null;
default:
return false;
}
}
static Value divide(Value a, long by) {
if (by == 0) {
return ValueNull.INSTANCE;
}
int type = Value.getHigherOrder(a.getType(), Value.LONG);
Value b = ValueLong.get(by).convertTo(type);
a = a.convertTo(type).divide(b);
return a;
}
protected String getSQL(String text) {<FILL_FUNCTION_BODY>}
@Override
public <R> R accept(ExpressionVisitor<R> visitor) {
return visitor.visitAggregate(this);
}
}
|
if (distinct) {
return text + "(DISTINCT " + on.getSQL() + ")";
}
return text + StringUtils.enclose(on.getSQL());
| 1,458
| 51
| 1,509
|
<methods>public void <init>(com.lealone.sql.query.Select) ,public R accept(ExpressionVisitor<R>) ,public static com.lealone.sql.expression.aggregate.Aggregate create(int, com.lealone.sql.expression.Expression, com.lealone.sql.query.Select, boolean) ,public static int getAggregateType(java.lang.String) ,public com.lealone.sql.expression.Expression getOn() ,public int getType() <variables>private static final HashMap<java.lang.String,java.lang.Integer> AGGREGATES,public static final int AVG,public static final int BIT_AND,public static final int BIT_OR,public static final int BOOL_AND,public static final int BOOL_OR,public static final int COUNT,public static final int COUNT_ALL,public static final int GROUP_CONCAT,public static final int HISTOGRAM,public static final int MAX,public static final int MIN,public static final int SELECTIVITY,public static final int STDDEV_POP,public static final int STDDEV_SAMP,public static final int SUM,public static final int VAR_POP,public static final int VAR_SAMP,protected int dataType,protected int lastGroupRowId,protected final non-sealed com.lealone.sql.query.Select select
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/expression/aggregate/JavaAggregate.java
|
JavaAggregate
|
updateAggregate
|
class JavaAggregate extends com.lealone.sql.expression.aggregate.Aggregate {
private final UserAggregate userAggregate;
private final Expression[] args;
private int[] argTypes;
private Connection userConnection;
private Aggregate aggregate;
public JavaAggregate(UserAggregate userAggregate, Expression[] args, Select select) {
super(select);
this.userAggregate = userAggregate;
this.args = args;
}
public UserAggregate getUserAggregate() {
return userAggregate;
}
public Expression[] getArgs() {
return args;
}
@Override
public int getScale() {
return DataType.getDataType(dataType).defaultScale;
}
@Override
public long getPrecision() {
return Integer.MAX_VALUE;
}
@Override
public int getDisplaySize() {
return Integer.MAX_VALUE;
}
@Override
public int getCost() {
int cost = 5;
for (Expression e : args) {
cost += e.getCost();
}
return cost;
}
@Override
public Expression optimize(ServerSession session) {
userConnection = session.createNestedConnection(false);
int len = args.length;
argTypes = new int[len];
for (int i = 0; i < len; i++) {
Expression expr = args[i];
args[i] = expr.optimize(session);
int type = expr.getType();
argTypes[i] = type;
}
try {
Aggregate aggregate = getInstance();
dataType = aggregate.getInternalType(argTypes);
} catch (SQLException e) {
throw DbException.convert(e);
}
return this;
}
@Override
public String getSQL() {
StatementBuilder buff = new StatementBuilder();
buff.append(LealoneSQLParser.quoteIdentifier(userAggregate.getName())).append('(');
for (Expression e : args) {
buff.appendExceptFirst(", ");
buff.append(e.getSQL());
}
return buff.append(')').toString();
}
private Aggregate getInstance() throws SQLException {
if (aggregate == null) {
aggregate = userAggregate.getInstance();
aggregate.init(userConnection);
}
return aggregate;
}
@Override
public Value getValue(ServerSession session) {
HashMap<Expression, Object> group = select.getCurrentGroup();
if (group == null) {
throw DbException.get(ErrorCode.INVALID_USE_OF_AGGREGATE_FUNCTION_1, getSQL());
}
try {
Aggregate agg = (Aggregate) group.get(this);
if (agg == null) {
agg = getInstance();
}
Object obj = agg.getResult();
if (obj == null) {
return ValueNull.INSTANCE;
}
return DataType.convertToValue(session, obj, dataType);
} catch (SQLException e) {
throw DbException.convert(e);
}
}
@Override
public void updateAggregate(ServerSession session) {<FILL_FUNCTION_BODY>}
@Override
public <R> R accept(ExpressionVisitor<R> visitor) {
return visitor.visitJavaAggregate(this);
}
}
|
HashMap<Expression, Object> group = select.getCurrentGroup();
if (group == null) {
// this is a different level (the enclosing query)
return;
}
int groupRowId = select.getCurrentGroupRowId();
if (lastGroupRowId == groupRowId) {
// already visited
return;
}
lastGroupRowId = groupRowId;
Aggregate agg = (Aggregate) group.get(this);
try {
if (agg == null) {
agg = getInstance();
group.put(this, agg);
}
Object[] argValues = new Object[args.length];
Object arg = null;
for (int i = 0, len = args.length; i < len; i++) {
Value v = args[i].getValue(session);
v = v.convertTo(argTypes[i]);
arg = v.getObject();
argValues[i] = arg;
}
if (args.length == 1) {
agg.add(arg);
} else {
agg.add(argValues);
}
} catch (SQLException e) {
throw DbException.convert(e);
}
| 894
| 313
| 1,207
|
<methods>public void <init>(com.lealone.sql.query.Select) ,public R accept(ExpressionVisitor<R>) ,public static com.lealone.sql.expression.aggregate.Aggregate create(int, com.lealone.sql.expression.Expression, com.lealone.sql.query.Select, boolean) ,public static int getAggregateType(java.lang.String) ,public com.lealone.sql.expression.Expression getOn() ,public int getType() <variables>private static final HashMap<java.lang.String,java.lang.Integer> AGGREGATES,public static final int AVG,public static final int BIT_AND,public static final int BIT_OR,public static final int BOOL_AND,public static final int BOOL_OR,public static final int COUNT,public static final int COUNT_ALL,public static final int GROUP_CONCAT,public static final int HISTOGRAM,public static final int MAX,public static final int MIN,public static final int SELECTIVITY,public static final int STDDEV_POP,public static final int STDDEV_SAMP,public static final int SUM,public static final int VAR_POP,public static final int VAR_SAMP,protected int dataType,protected int lastGroupRowId,protected final non-sealed com.lealone.sql.query.Select select
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/expression/condition/ConditionExists.java
|
ConditionExists
|
updateAggregate
|
class ConditionExists extends Condition {
private final Query query;
public ConditionExists(Query query) {
this.query = query;
}
public Query getQuery() {
return query;
}
@Override
public Value getValue(ServerSession session) {
query.setSession(session);
Result result = query.query(1);
session.addTemporaryResult(result);
boolean r = result.getRowCount() > 0;
return ValueBoolean.get(r);
}
@Override
public Expression optimize(ServerSession session) {
query.prepare();
return this;
}
@Override
public String getSQL() {
return "EXISTS(\n" + StringUtils.indent(query.getPlanSQL(), 4, false) + ")";
}
@Override
public void updateAggregate(ServerSession session) {<FILL_FUNCTION_BODY>}
@Override
public int getCost() {
return query.getCostAsExpression();
}
@Override
public <R> R accept(ExpressionVisitor<R> visitor) {
return visitor.visitConditionExists(this);
}
}
|
// TODO exists: is it allowed that the subquery contains aggregates?
// probably not
// select id from test group by id having exists (select * from test2
// where id=count(test.id))
| 301
| 55
| 356
|
<methods>public int getDisplaySize() ,public long getPrecision() ,public int getScale() ,public int getType() <variables>
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/expression/condition/ConditionIn.java
|
ConditionIn
|
optimize
|
class ConditionIn extends Condition {
private final Database database;
private Expression left;
private final ArrayList<Expression> valueList;
private int queryLevel;
/**
* Create a new IN(..) condition.
*
* @param database the database
* @param left the expression before IN
* @param values the value list (at least one element)
*/
public ConditionIn(Database database, Expression left, ArrayList<Expression> values) {
this.database = database;
this.left = left;
this.valueList = values;
}
public Expression getLeft() {
return left;
}
public ArrayList<Expression> getValueList() {
return valueList;
}
public void setQueryLevel(int level) {
this.queryLevel = Math.max(level, this.queryLevel);
}
@Override
public Value getValue(ServerSession session) {
Value l = left.getValue(session);
if (l == ValueNull.INSTANCE) {
return l;
}
boolean result = false;
boolean hasNull = false;
for (Expression e : valueList) {
Value r = e.getValue(session);
if (r == ValueNull.INSTANCE) {
hasNull = true;
} else {
r = r.convertTo(l.getType());
result = Comparison.compareNotNull(database, l, r, Comparison.EQUAL);
if (result) {
break;
}
}
}
if (!result && hasNull) {
return ValueNull.INSTANCE;
}
return ValueBoolean.get(result);
}
@Override
public Expression optimize(ServerSession session) {<FILL_FUNCTION_BODY>}
@Override
public void createIndexConditions(ServerSession session, TableFilter filter) {
if (!(left instanceof ExpressionColumn)) {
return;
}
ExpressionColumn l = (ExpressionColumn) left;
if (filter != l.getTableFilter()) {
return;
}
if (session.getDatabase().getSettings().optimizeInList) {
NotFromResolverVisitor visitor = ExpressionVisitorFactory.getNotFromResolverVisitor(filter);
for (Expression e : valueList) {
if (!e.accept(visitor)) {
return;
}
}
filter.addIndexCondition(IndexCondition.getInList(l, valueList));
return;
}
}
@Override
public String getSQL() {
StatementBuilder buff = new StatementBuilder("(");
buff.append(left.getSQL()).append(" IN(");
for (Expression e : valueList) {
buff.appendExceptFirst(", ");
buff.append(e.getSQL());
}
return buff.append("))").toString();
}
@Override
public int getCost() {
int cost = left.getCost();
for (Expression e : valueList) {
cost += e.getCost();
}
return cost;
}
/**
* Add an additional element if possible. Example: given two conditions
* A IN(1, 2) OR A=3, the constant 3 is added: A IN(1, 2, 3).
*
* @param other the second condition
* @return null if the condition was not added, or the new condition
*/
Expression getAdditional(Comparison other) {
Expression add = other.getIfEquals(left);
if (add != null) {
valueList.add(add);
return this;
}
return null;
}
@Override
public <R> R accept(ExpressionVisitor<R> visitor) {
return visitor.visitConditionIn(this);
}
}
|
left = left.optimize(session);
boolean constant = left.isConstant();
if (constant && left == ValueExpression.getNull()) {
return left;
}
boolean allValuesConstant = true;
boolean allValuesNull = true;
int size = valueList.size();
for (int i = 0; i < size; i++) {
Expression e = valueList.get(i);
e = e.optimize(session);
if (e.isConstant() && e.getValue(session) != ValueNull.INSTANCE) {
allValuesNull = false;
}
if (allValuesConstant && !e.isConstant()) {
allValuesConstant = false;
}
valueList.set(i, e);
}
if (constant && allValuesConstant) {
return ValueExpression.get(getValue(session));
}
if (size == 1) {
Expression right = valueList.get(0);
Expression expr = new Comparison(session, Comparison.EQUAL, left, right);
expr = expr.optimize(session);
return expr;
}
if (allValuesConstant && !allValuesNull) {
int leftType = left.getType();
if (leftType == Value.UNKNOWN) {
return this;
}
Expression expr = new ConditionInConstantSet(session, left, valueList);
expr = expr.optimize(session);
return expr;
}
return this;
| 962
| 381
| 1,343
|
<methods>public int getDisplaySize() ,public long getPrecision() ,public int getScale() ,public int getType() <variables>
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/expression/condition/ConditionInConstantSet.java
|
ConditionInConstantSet
|
getValue
|
class ConditionInConstantSet extends Condition {
private Expression left;
private int queryLevel;
private final ArrayList<Expression> valueList;
private final HashSet<Value> valueSet;
/**
* Create a new IN(..) condition.
*
* @param session the session
* @param left the expression before IN
* @param valueList the value list (at least two elements)
*/
public ConditionInConstantSet(ServerSession session, Expression left,
ArrayList<Expression> valueList) {
this.left = left;
this.valueList = valueList;
this.valueSet = new HashSet<Value>(valueList.size());
int type = left.getType();
for (Expression expression : valueList) {
valueSet.add(expression.getValue(session).convertTo(type));
}
}
public Expression getLeft() {
return left;
}
public HashSet<Value> getValueSet() {
return valueSet;
}
public void setQueryLevel(int level) {
this.queryLevel = Math.max(level, this.queryLevel);
}
@Override
public Value getValue(ServerSession session) {<FILL_FUNCTION_BODY>}
@Override
public Expression optimize(ServerSession session) {
left = left.optimize(session);
return this;
}
@Override
public void createIndexConditions(ServerSession session, TableFilter filter) {
if (!(left instanceof ExpressionColumn)) {
return;
}
ExpressionColumn l = (ExpressionColumn) left;
if (filter != l.getTableFilter()) {
return;
}
if (session.getDatabase().getSettings().optimizeInList) {
filter.addIndexCondition(IndexCondition.getInList(l, valueList));
return;
}
}
@Override
public String getSQL() {
StatementBuilder buff = new StatementBuilder("(");
buff.append(left.getSQL()).append(" IN(");
for (Expression e : valueList) {
buff.appendExceptFirst(", ");
buff.append(e.getSQL());
}
return buff.append("))").toString();
}
@Override
public int getCost() {
int cost = left.getCost();
return cost;
}
/**
* Add an additional element if possible. Example: given two conditions
* A IN(1, 2) OR A=3, the constant 3 is added: A IN(1, 2, 3).
*
* @param other the second condition
* @return null if the condition was not added, or the new condition
*/
Expression getAdditional(ServerSession session, Comparison other) {
Expression add = other.getIfEquals(left);
if (add != null) {
if (add.isConstant()) {
valueList.add(add);
valueSet.add(add.getValue(session).convertTo(left.getType()));
return this;
}
}
return null;
}
@Override
public <R> R accept(ExpressionVisitor<R> visitor) {
return visitor.visitConditionInConstantSet(this);
}
}
|
Value x = left.getValue(session);
if (x == ValueNull.INSTANCE) {
return x;
}
boolean result = valueSet.contains(x);
if (!result) {
boolean setHasNull = valueSet.contains(ValueNull.INSTANCE);
if (setHasNull) {
return ValueNull.INSTANCE;
}
}
return ValueBoolean.get(result);
| 825
| 106
| 931
|
<methods>public int getDisplaySize() ,public long getPrecision() ,public int getScale() ,public int getType() <variables>
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/expression/condition/ConditionInSelect.java
|
ConditionInSelect
|
getValue
|
class ConditionInSelect extends Condition {
private final Database database;
private Expression left;
private final Query query;
private final boolean all;
private final int compareType;
private SubQueryResult rows;
public ConditionInSelect(Database database, Expression left, Query query, boolean all,
int compareType) {
this.database = database;
this.left = left;
this.query = query;
this.all = all;
this.compareType = compareType;
}
public Expression getLeft() {
return left;
}
public Query getQuery() {
return query;
}
@Override
public Value getValue(ServerSession session) {<FILL_FUNCTION_BODY>}
private Value getValueSlow(SubQueryResult rows, Value l) {
// this only returns the correct result if the result has at least one
// row, and if l is not null
boolean hasNull = false;
boolean result = all;
while (rows.next()) {
boolean value;
Value r = rows.currentRow()[0];
if (r == ValueNull.INSTANCE) {
value = false;
hasNull = true;
} else {
value = Comparison.compareNotNull(database, l, r, compareType);
}
if (!value && all) {
result = false;
break;
} else if (value && !all) {
result = true;
break;
}
}
if (!result && hasNull) {
return ValueNull.INSTANCE;
}
return ValueBoolean.get(result);
}
@Override
public Expression optimize(ServerSession session) {
left = left.optimize(session);
query.prepare();
if (query.getColumnCount() != 1) {
throw DbException.get(ErrorCode.SUBQUERY_IS_NOT_SINGLE_COLUMN);
}
// Can not optimize: the data may change
return this;
}
@Override
public String getSQL() {
StringBuilder buff = new StringBuilder();
buff.append('(').append(left.getSQL()).append(' ');
if (all) {
buff.append(Comparison.getCompareOperator(compareType)).append(" ALL");
} else {
if (compareType != Comparison.EQUAL)
buff.append(Comparison.getCompareOperator(compareType)).append(" SOME");
else
buff.append("IN");
}
buff.append("(\n").append(StringUtils.indent(query.getPlanSQL(), 4, false)).append("))");
return buff.toString();
}
@Override
public int getCost() {
return left.getCost() + query.getCostAsExpression();
}
@Override
public void createIndexConditions(ServerSession session, TableFilter filter) {
if (!session.getDatabase().getSettings().optimizeInList) {
return;
}
if (!(left instanceof ExpressionColumn)) {
return;
}
ExpressionColumn l = (ExpressionColumn) left;
if (filter != l.getTableFilter()) {
return;
}
NotFromResolverVisitor visitor = ExpressionVisitorFactory.getNotFromResolverVisitor(filter);
if (!query.accept(visitor)) {
return;
}
filter.addIndexCondition(IndexCondition.getInQuery(l, query));
}
@Override
public <R> R accept(ExpressionVisitor<R> visitor) {
return visitor.visitConditionInSelect(this);
}
}
|
if (rows == null) {
query.setSession(session);
rows = new SubQueryResult(query, 0);
session.addTemporaryResult(rows);
} else {
rows.reset();
}
Value l = left.getValue(session);
if (rows.getRowCount() == 0) {
return ValueBoolean.get(all);
} else if (l == ValueNull.INSTANCE) {
return l;
}
if (!session.getDatabase().getSettings().optimizeInSelect) {
return getValueSlow(rows, l);
}
if (all || (compareType != Comparison.EQUAL && compareType != Comparison.EQUAL_NULL_SAFE)) {
return getValueSlow(rows, l);
}
int dataType = rows.getColumnType(0);
if (dataType == Value.NULL) {
return ValueBoolean.get(false);
}
l = l.convertTo(dataType);
if (rows.containsDistinct(new Value[] { l })) {
return ValueBoolean.get(true);
}
if (rows.containsDistinct(new Value[] { ValueNull.INSTANCE })) {
return ValueNull.INSTANCE;
}
return ValueBoolean.get(false);
| 914
| 327
| 1,241
|
<methods>public int getDisplaySize() ,public long getPrecision() ,public int getScale() ,public int getType() <variables>
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/expression/condition/ConditionNot.java
|
ConditionNot
|
optimize
|
class ConditionNot extends Condition {
private Expression condition;
public ConditionNot(Expression condition) {
this.condition = condition;
}
public Expression getCondition() {
return condition;
}
@Override
public Expression getNotIfPossible(ServerSession session) {
return condition;
}
@Override
public Value getValue(ServerSession session) {
Value v = condition.getValue(session);
if (v == ValueNull.INSTANCE) {
return v;
}
return v.convertTo(Value.BOOLEAN).negate();
}
@Override
public Expression optimize(ServerSession session) {<FILL_FUNCTION_BODY>}
@Override
public String getSQL() {
return "(NOT " + condition.getSQL() + ")";
}
@Override
public void addFilterConditions(TableFilter filter, boolean outerJoin) {
if (outerJoin) {
// can not optimize:
// select * from test t1 left join test t2 on t1.id = t2.id where
// not t2.id is not null
// to
// select * from test t1 left join test t2 on t1.id = t2.id and
// t2.id is not null
return;
}
super.addFilterConditions(filter, outerJoin);
}
@Override
public int getCost() {
return condition.getCost();
}
@Override
public <R> R accept(ExpressionVisitor<R> visitor) {
return visitor.visitConditionNot(this);
}
}
|
Expression e2 = condition.getNotIfPossible(session);
if (e2 != null) {
return e2.optimize(session);
}
Expression expr = condition.optimize(session);
if (expr.isConstant()) {
Value v = expr.getValue(session);
if (v == ValueNull.INSTANCE) {
return ValueExpression.getNull();
}
return ValueExpression.get(v.convertTo(Value.BOOLEAN).negate());
}
condition = expr;
return this;
| 416
| 144
| 560
|
<methods>public int getDisplaySize() ,public long getPrecision() ,public int getScale() ,public int getType() <variables>
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/expression/function/BuiltInFunction.java
|
BuiltInFunction
|
getNullOrValue
|
class BuiltInFunction extends Function {
protected final Database database;
protected final FunctionInfo info;
private ArrayList<Expression> varArgs;
protected int dataType, scale;
protected long precision = PRECISION_UNKNOWN;
protected int displaySize;
protected BuiltInFunction(Database database, FunctionInfo info) {
this.database = database;
this.info = info;
if (info.parameterCount == VAR_ARGS) {
varArgs = new ArrayList<>(4);
} else {
args = new Expression[info.parameterCount];
}
}
/**
* Set the parameter expression at the given index.
*
* @param index the index (0, 1,...)
* @param param the expression
*/
@Override
public void setParameter(int index, Expression param) {
if (varArgs != null) {
varArgs.add(param);
} else {
if (index >= args.length) {
throw DbException.get(ErrorCode.INVALID_PARAMETER_COUNT_2, info.name, "" + args.length);
}
args[index] = param;
}
}
@Override
public Value getValue(ServerSession session) {
return getValueWithArgs(session, args);
}
@Override
public ValueResultSet getValueForColumnList(ServerSession session, Expression[] args) {
return (ValueResultSet) getValueWithArgs(session, args);
}
private Value getValueWithArgs(ServerSession session, Expression[] args) {
Value[] values = new Value[args.length];
// 如果函数要求所有的参数非null,那么只要有一个参数是null,函数就直接返回null
if (info.nullIfParameterIsNull) {
for (int i = 0; i < args.length; i++) {
Expression e = args[i];
Value v = e.getValue(session);
if (v == ValueNull.INSTANCE) {
return ValueNull.INSTANCE;
}
values[i] = v;
}
}
// 大多数函数只有一个参数,所以if放在最前面
if (info.parameterCount == 1) {
Value v = getNullOrValue(session, args, values, 0);
return getValue1(session, v);
}
if (info.parameterCount == 0) {
return getValue0(session);
}
// info.parameterCount > 1 || info.parameterCount == VAR_ARGS
return getValueN(session, args, values);
}
protected Value getValue0(ServerSession session) {
return null;
}
protected Value getValue1(ServerSession session, Value v) {
return null;
}
protected Value getValueN(ServerSession session, Expression[] args, Value[] values) {
return null;
}
protected static Value getNullOrValue(ServerSession session, Expression[] args, Value[] values,
int i) {<FILL_FUNCTION_BODY>}
protected DbException getUnsupportedException() {
return DbException
.getUnsupportedException("function name: " + info.name + ", type=" + info.type);
}
@Override
public int getType() {
return dataType;
}
/**
* Check if the parameter count is correct.
*
* @param len the number of parameters set
* @throws DbException if the parameter count is incorrect
*/
protected abstract void checkParameterCount(int len);
protected void checkParameterCount(int len, int min, int max) {
boolean ok = (len >= min) && (len <= max);
if (!ok) {
throw DbException.get(ErrorCode.INVALID_PARAMETER_COUNT_2, info.name, min + ".." + max);
}
}
/**
* This method is called after all the parameters have been set.
* It checks if the parameter count is correct.
*
* @throws DbException if the parameter count is incorrect.
*/
@Override
public void doneWithParameters() {
if (info.parameterCount == VAR_ARGS) {
int len = varArgs.size();
checkParameterCount(len);
args = new Expression[len];
varArgs.toArray(args);
varArgs = null;
} else {
int len = args.length;
if (len > 0 && args[len - 1] == null) {
throw DbException.get(ErrorCode.INVALID_PARAMETER_COUNT_2, info.name, "" + len);
}
}
}
@Override
public void setDataType(Column col) {
dataType = col.getType();
precision = col.getPrecision();
displaySize = col.getDisplaySize();
scale = col.getScale();
}
@Override
public Expression optimize(ServerSession session) {
boolean allConst = optimizeArgs(session);
dataType = info.dataType;
DataType type = DataType.getDataType(dataType);
precision = PRECISION_UNKNOWN;
scale = 0;
displaySize = type.defaultScale;
if (allConst) {
Value v = getValue(session);
return ValueExpression.get(v);
}
return this;
}
@Override
public int getScale() {
return scale;
}
@Override
public long getPrecision() {
if (precision == PRECISION_UNKNOWN) {
calculatePrecisionAndDisplaySize();
}
return precision;
}
@Override
public int getDisplaySize() {
if (precision == PRECISION_UNKNOWN) {
calculatePrecisionAndDisplaySize();
}
return displaySize;
}
protected void calculatePrecisionAndDisplaySize() {
DataType type = DataType.getDataType(dataType);
precision = type.defaultPrecision;
displaySize = type.defaultDisplaySize;
}
@Override
public String getSQL() {
StatementBuilder buff = new StatementBuilder(info.name);
buff.append('(');
appendArgs(buff);
return buff.append(')').toString();
}
@Override
public int getFunctionType() {
return info.type;
}
@Override
public String getName() {
return info.name;
}
@Override
public int getCost() {
int cost = 3;
for (Expression e : args) {
cost += e.getCost();
}
return cost;
}
@Override
public boolean isDeterministic() {
return info.deterministic;
}
@Override
boolean isBufferResultSetToLocalTemp() {
return false;
}
@Override
public <R> R accept(ExpressionVisitor<R> visitor) {
return visitor.visitFunction(this);
}
}
|
if (i >= args.length) {
return null;
}
Value v = values[i];
if (v == null && args[i] != null) {
v = values[i] = args[i].getValue(session);
}
return v;
| 1,798
| 73
| 1,871
|
<methods>public non-sealed void <init>() ,public static void deregisterFunctionFactory(com.lealone.sql.expression.function.FunctionFactory) ,public void doneWithParameters() ,public com.lealone.sql.expression.Expression[] getArgs() ,public static com.lealone.sql.expression.function.Function getFunction(com.lealone.db.Database, java.lang.String) ,public static com.lealone.sql.expression.function.FunctionInfo getFunctionInfo(java.lang.String) ,public abstract int getFunctionType() ,public abstract java.lang.String getSQL() ,public abstract int getType() ,public abstract boolean isDeterministic() ,public abstract com.lealone.sql.expression.Expression optimize(com.lealone.db.session.ServerSession) ,public static void registerFunctionFactory(com.lealone.sql.expression.function.FunctionFactory) ,public void setDataType(com.lealone.db.table.Column) ,public void setParameter(int, com.lealone.sql.expression.Expression) <variables>private static final CopyOnWriteArrayList<com.lealone.sql.expression.function.FunctionFactory> FACTORIES,private static final HashMap<java.lang.String,com.lealone.sql.expression.function.FunctionInfo> FUNCTIONS,protected static final long PRECISION_UNKNOWN,protected static final int VAR_ARGS,protected com.lealone.sql.expression.Expression[] args,private static boolean inited
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/expression/function/BuiltInFunctionFactory.java
|
BuiltInFunctionFactory
|
createFunction
|
class BuiltInFunctionFactory implements FunctionFactory {
public static final BuiltInFunctionFactory INSTANCE = new BuiltInFunctionFactory();
public static void register() {
Function.registerFunctionFactory(INSTANCE);
}
@Override
public void init() {
DateTimeFunction.init();
NumericFunction.init();
StringFunction.init();
SystemFunction.init();
TableFunction.init();
}
@Override
public Function createFunction(Database database, FunctionInfo info) {<FILL_FUNCTION_BODY>}
}
|
if (info.type < StringFunction.ASCII)
return new NumericFunction(database, info);
if (info.type < DateTimeFunction.CURDATE)
return new StringFunction(database, info);
if (info.type < SystemFunction.DATABASE)
return new DateTimeFunction(database, info);
if (info.type < TableFunction.TABLE)
return new SystemFunction(database, info);
return new TableFunction(database, info);
| 142
| 117
| 259
|
<no_super_class>
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/expression/function/Function.java
|
Function
|
addFunction
|
class Function extends Expression {
protected static final int VAR_ARGS = -1;
protected static final long PRECISION_UNKNOWN = -1;
private static final HashMap<String, FunctionInfo> FUNCTIONS = new HashMap<>();
private static final CopyOnWriteArrayList<FunctionFactory> FACTORIES = new CopyOnWriteArrayList<>();
private static boolean inited;
// 放在FACTORIES字段之后,否则FACTORIES为null
static {
BuiltInFunctionFactory.register();
}
public static void registerFunctionFactory(FunctionFactory factory) {
FACTORIES.add(factory);
}
public static void deregisterFunctionFactory(FunctionFactory factory) {
FACTORIES.remove(factory);
}
private synchronized static void initFunctionFactories() {
if (inited)
return;
for (FunctionFactory factory : FACTORIES) {
factory.init();
}
inited = true;
}
protected static FunctionInfo addFunction(String name, int type, int parameterCount, int dataType,
boolean nullIfParameterIsNull, boolean deterministic) {<FILL_FUNCTION_BODY>}
protected static FunctionInfo addFunctionNotDeterministic(String name, int type, int parameterCount,
int dataType) {
return addFunction(name, type, parameterCount, dataType, true, false);
}
protected static FunctionInfo addFunction(String name, int type, int parameterCount, int dataType) {
return addFunction(name, type, parameterCount, dataType, true, true);
}
protected static FunctionInfo addFunctionWithNull(String name, int type, int parameterCount,
int dataType) {
return addFunction(name, type, parameterCount, dataType, false, true);
}
// 允许一个函数有多个别名
protected static FunctionInfo addFunction(String name, FunctionInfo info) {
FUNCTIONS.put(name, info);
return info;
}
/**
* Get the function info object for this function, or null if there is no
* such function.
*
* @param name the function name
* @return the function info
*/
public static FunctionInfo getFunctionInfo(String name) {
FunctionInfo info = FUNCTIONS.get(name);
if (info == null && !inited) {
initFunctionFactories();
info = FUNCTIONS.get(name);
}
return info;
}
/**
* Get an instance of the given function for this database.
* If no function with this name is found, null is returned.
*
* @param database the database
* @param name the function name
* @return the function object or null
*/
public static Function getFunction(Database database, String name) {
if (!database.getSettings().databaseToUpper) {
// if not yet converted to uppercase, do it now
name = StringUtils.toUpperEnglish(name);
}
FunctionInfo info = getFunctionInfo(name);
if (info == null) {
return null;
}
if (info.factory != null)
return info.factory.createFunction(database, info);
else
return BuiltInFunctionFactory.INSTANCE.createFunction(database, info);
}
protected Expression[] args;
/**
* Get the function arguments.
*
* @return argument list
*/
public Expression[] getArgs() {
return args;
}
protected boolean optimizeArgs(ServerSession session) {
boolean allConst = isDeterministic();
for (int i = 0; i < args.length; i++) {
Expression e = args[i];
if (e == null) {
continue;
}
e = e.optimize(session);
args[i] = e;
if (!e.isConstant()) {
allConst = false;
}
}
return allConst;
}
protected void appendArgs(StatementBuilder buff) {
for (Expression e : args) {
buff.appendExceptFirst(", ");
buff.append(e.getSQL());
}
}
/**
* Get the name of the function.
*
* @return the name
*/
abstract String getName();
/**
* Get an empty result set with the column names set.
*
* @param session the session
* @param args the argument list (some arguments may be null)
* @return the empty result set
*/
abstract ValueResultSet getValueForColumnList(ServerSession session, Expression[] args);
/**
* Get the data type.
*
* @return the data type
*/
@Override
public abstract int getType();
/**
* Optimize the function if possible.
*
* @param session the session
* @return the optimized expression
*/
@Override
public abstract Expression optimize(ServerSession session);
/**
* Get the SQL snippet of the function (including arguments).
*
* @return the SQL snippet.
*/
@Override
public abstract String getSQL();
public void setParameter(int index, Expression param) {
}
public void doneWithParameters() {
}
public void setDataType(Column col) {
}
public abstract int getFunctionType();
/**
* Whether the function always returns the same result for the same
* parameters.
*
* @return true if it does
*/
public abstract boolean isDeterministic();
/**
* Should the return value ResultSet be buffered in a local temporary file?
*
* @return true if it should be.
*/
abstract boolean isBufferResultSetToLocalTemp();
}
|
FunctionInfo info = new FunctionInfo();
info.name = name;
info.type = type;
info.parameterCount = parameterCount;
info.dataType = dataType;
info.nullIfParameterIsNull = nullIfParameterIsNull;
info.deterministic = deterministic;
FUNCTIONS.put(name, info);
return info;
| 1,478
| 94
| 1,572
|
<methods>public non-sealed void <init>() ,public R accept(ExpressionVisitor<R>) ,public void addFilterConditions(com.lealone.sql.optimizer.TableFilter, boolean) ,public void createIndexConditions(com.lealone.db.session.ServerSession, com.lealone.sql.optimizer.TableFilter) ,public java.lang.String getAlias() ,public boolean getBooleanValue(com.lealone.db.session.ServerSession) ,public java.lang.String getColumnName() ,public void getColumns(Set<?>) ,public abstract int getCost() ,public void getDependencies(Set<?>) ,public abstract int getDisplaySize() ,public com.lealone.sql.expression.Expression[] getExpressionColumns(com.lealone.db.session.ServerSession) ,public static com.lealone.sql.expression.Expression[] getExpressionColumns(com.lealone.db.session.ServerSession, com.lealone.db.value.ValueArray) ,public static com.lealone.sql.expression.Expression[] getExpressionColumns(com.lealone.db.session.ServerSession, java.sql.ResultSet) ,public com.lealone.sql.expression.Expression getNonAliasExpression() ,public com.lealone.sql.expression.Expression getNotIfPossible(com.lealone.db.session.ServerSession) ,public int getNullable() ,public abstract long getPrecision() ,public abstract java.lang.String getSQL() ,public abstract int getScale() ,public java.lang.String getSchemaName() ,public java.lang.String getTableName() ,public abstract int getType() ,public com.lealone.db.value.Value getValue(com.lealone.db.session.Session) ,public abstract com.lealone.db.value.Value getValue(com.lealone.db.session.ServerSession) ,public boolean isAutoIncrement() ,public boolean isConstant() ,public boolean isEvaluatable() ,public boolean isValueSet() ,public boolean isWildcard() ,public void mapColumns(com.lealone.sql.optimizer.ColumnResolver, int) ,public abstract com.lealone.sql.expression.Expression optimize(com.lealone.db.session.ServerSession) ,public com.lealone.sql.expression.Expression optimize(com.lealone.db.session.Session) ,public java.lang.String toString() ,public void updateAggregate(com.lealone.db.session.ServerSession) <variables>private boolean addedToFilter
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/expression/function/FunctionIndex.java
|
FunctionCursor
|
get
|
class FunctionCursor implements Cursor {
private final Result result;
private Value[] values;
private Row row;
FunctionCursor(Result result) {
this.result = result;
}
@Override
public Row get() {<FILL_FUNCTION_BODY>}
@Override
public boolean next() {
row = null;
if (result != null && result.next()) {
values = result.currentRow();
} else {
values = null;
}
return values != null;
}
}
|
if (values == null) {
return null;
}
if (row == null) {
row = new Row(values, 1);
}
return row;
| 143
| 49
| 192
|
<methods>public boolean canGetFirstOrLast() ,public boolean canScan() ,public void checkRename() ,public void close(com.lealone.db.session.ServerSession) ,public int compareRows(com.lealone.db.result.SearchRow, com.lealone.db.result.SearchRow) ,public com.lealone.db.index.Cursor find(com.lealone.db.session.ServerSession, CursorParameters<com.lealone.db.result.SearchRow>) ,public com.lealone.db.index.Cursor findDistinct(com.lealone.db.session.ServerSession) ,public com.lealone.db.result.SearchRow findFirstOrLast(com.lealone.db.session.ServerSession, boolean) ,public int[] getColumnIds() ,public int getColumnIndex(com.lealone.db.table.Column) ,public com.lealone.db.table.Column[] getColumns() ,public java.lang.String getCreateSQL() ,public long getDiskSpaceUsed() ,public com.lealone.db.index.IndexColumn[] getIndexColumns() ,public com.lealone.db.index.IndexType getIndexType() ,public long getMemorySpaceUsed() ,public java.lang.String getPlanSQL() ,public com.lealone.db.result.Row getRow(com.lealone.db.session.ServerSession, long) ,public com.lealone.db.table.Table getTable() ,public com.lealone.db.DbObjectType getType() ,public boolean isHidden() ,public boolean isInMemory() ,public boolean isRowIdIndex() ,public boolean needRebuild() ,public void remove(com.lealone.db.session.ServerSession) ,public void removeChildrenAndResources(com.lealone.db.session.ServerSession, com.lealone.db.lock.DbObjectLock) ,public boolean supportsDistinctQuery() ,public void truncate(com.lealone.db.session.ServerSession) <variables>protected int[] columnIds,protected com.lealone.db.table.Column[] columns,protected com.lealone.db.index.IndexColumn[] indexColumns,protected final non-sealed com.lealone.db.index.IndexType indexType,protected final non-sealed com.lealone.db.table.Table table
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/expression/function/FunctionTable.java
|
FunctionTable
|
getResult
|
class FunctionTable extends Table {
private final Function function;
private final Expression functionExpr;
private LocalResult cachedResult;
private Value cachedValue;
public FunctionTable(Schema schema, ServerSession session, Function function) {
super(schema, 0, function.getName(), false, true);
this.function = function;
functionExpr = function.optimize(session);
int type = function.getType();
if (type != Value.RESULT_SET) {
throw DbException.get(ErrorCode.FUNCTION_MUST_RETURN_RESULT_SET_1, function.getName());
}
ValueResultSet template = function.getValueForColumnList(session, function.getArgs());
if (template == null) {
throw DbException.get(ErrorCode.FUNCTION_MUST_RETURN_RESULT_SET_1, function.getName());
}
ResultSet rs = template.getResultSet();
try {
ResultSetMetaData meta = rs.getMetaData();
int columnCount = meta.getColumnCount();
Column[] cols = new Column[columnCount];
for (int i = 0; i < columnCount; i++) {
cols[i] = new Column(meta.getColumnName(i + 1),
DataType.getValueTypeFromResultSet(meta, i + 1), meta.getPrecision(i + 1),
meta.getScale(i + 1), meta.getColumnDisplaySize(i + 1));
}
setColumns(cols);
} catch (SQLException e) {
throw DbException.convert(e);
}
}
@Override
public TableType getTableType() {
return TableType.FUNCTION_TABLE;
}
@Override
public Index getScanIndex(ServerSession session) {
return new FunctionIndex(this, IndexColumn.wrap(columns));
}
@Override
public long getMaxDataModificationId() {
return database.getModificationDataId();
}
@Override
public boolean isDeterministic() {
return function.isDeterministic();
}
@Override
public boolean canReference() {
return false;
}
@Override
public boolean canDrop() {
throw DbException.getInternalError();
}
@Override
public boolean canGetRowCount() {
return false;
}
@Override
public long getRowCount(ServerSession session) {
return Long.MAX_VALUE;
}
@Override
public long getRowCountApproximation() {
return Long.MAX_VALUE;
}
@Override
public String getCreateSQL() {
return null;
}
@Override
public String getDropSQL() {
return null;
}
@Override
public String getSQL() {
return function.getSQL();
}
/**
* Read the result from the function. This method buffers the result in a
* temporary file.
*
* @param session the session
* @return the result
*/
public Result getResult(ServerSession session) {<FILL_FUNCTION_BODY>}
/**
* Read the result set from the function. This method doesn't cache.
*
* @param session the session
* @return the result set
*/
public ResultSet getResultSet(ServerSession session) {
ValueResultSet v = getValueResultSet(session);
return v == null ? null : v.getResultSet();
}
private ValueResultSet getValueResultSet(ServerSession session) {
Value v = functionExpr.getValue(session);
if (v == ValueNull.INSTANCE) {
return null;
}
return (ValueResultSet) v;
}
boolean isBufferResultSetToLocalTemp() {
return function.isBufferResultSetToLocalTemp();
}
}
|
ValueResultSet v = getValueResultSet(session);
if (v == null) {
return null;
}
if (cachedResult != null && cachedValue == v) {
cachedResult.reset();
return cachedResult;
}
ResultSet rs = v.getResultSet();
LocalResult result = LocalResult.read(session, Expression.getExpressionColumns(session, rs), rs,
0);
if (function.isDeterministic()) {
cachedResult = result;
cachedValue = v;
}
return result;
| 982
| 147
| 1,129
|
<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-sql/src/main/java/com/lealone/sql/expression/function/TableFunction.java
|
TableFunction
|
getSimpleResultSet
|
class TableFunction extends BuiltInFunction {
public static final int TABLE = 300, TABLE_DISTINCT = 301;
public static void init() {
addFunctionWithNull("TABLE", TABLE, VAR_ARGS, Value.RESULT_SET);
addFunctionWithNull("TABLE_DISTINCT", TABLE_DISTINCT, VAR_ARGS, Value.RESULT_SET);
}
private final boolean distinct;
private Column[] columnList;
TableFunction(Database database, FunctionInfo info) {
super(database, info);
distinct = info.type == TABLE_DISTINCT;
}
@Override
public Value getValue(ServerSession session) {
return getTable(session, args, false, distinct);
}
@Override
protected void checkParameterCount(int len) {
if (len < 1) {
throw DbException.get(ErrorCode.INVALID_PARAMETER_COUNT_2, getName(), ">0");
}
}
@Override
public String getSQL() {
StatementBuilder buff = new StatementBuilder(getName());
buff.append('(');
int i = 0;
for (Expression e : args) {
buff.appendExceptFirst(", ");
buff.append(columnList[i++].getCreateSQL()).append('=').append(e.getSQL());
}
return buff.append(')').toString();
}
@Override
public String getName() {
return distinct ? "TABLE_DISTINCT" : "TABLE";
}
@Override
public ValueResultSet getValueForColumnList(ServerSession session, Expression[] args) {
return getTable(session, args, true, false);
}
public void setColumns(ArrayList<Column> columns) {
this.columnList = new Column[columns.size()];
columns.toArray(columnList);
}
private ValueResultSet getTable(ServerSession session, Expression[] argList, boolean onlyColumnList,
boolean distinctRows) {
int len = columnList.length;
Expression[] header = new Expression[len];
Database db = session.getDatabase();
for (int i = 0; i < len; i++) {
Column c = columnList[i];
ExpressionColumn col = new ExpressionColumn(db, c);
header[i] = col;
}
LocalResult result = new LocalResult(session, header, len);
if (distinctRows) {
result.setDistinct();
}
if (!onlyColumnList) {
Value[][] list = new Value[len][];
int rows = 0;
for (int i = 0; i < len; i++) {
Value v = argList[i].getValue(session);
if (v == ValueNull.INSTANCE) {
list[i] = new Value[0];
} else {
ValueArray array = (ValueArray) v.convertTo(Value.ARRAY);
Value[] l = array.getList();
list[i] = l;
rows = Math.max(rows, l.length);
}
}
for (int row = 0; row < rows; row++) {
Value[] r = new Value[len];
for (int j = 0; j < len; j++) {
Value[] l = list[j];
Value v;
if (l.length <= row) {
v = ValueNull.INSTANCE;
} else {
Column c = columnList[j];
v = l[row];
v = c.convert(v);
v = v.convertPrecision(c.getPrecision(), false);
v = v.convertScale(true, c.getScale());
}
r[j] = v;
}
result.addRow(r);
}
}
result.done();
ValueResultSet vr = ValueResultSet.get(getSimpleResultSet(result, Integer.MAX_VALUE));
return vr;
}
private static SimpleResultSet getSimpleResultSet(Result rs, int maxRows) {<FILL_FUNCTION_BODY>}
@Override
public Expression[] getExpressionColumns(ServerSession session) {
return getExpressionColumns(session, getTable(session, getArgs(), true, false).getResultSet());
}
@Override
public <R> R accept(ExpressionVisitor<R> visitor) {
return visitor.visitTableFunction(this);
}
}
|
int columnCount = rs.getVisibleColumnCount();
SimpleResultSet simple = new SimpleResultSet();
for (int i = 0; i < columnCount; i++) {
String name = rs.getColumnName(i);
int sqlType = DataType.convertTypeToSQLType(rs.getColumnType(i));
int precision = MathUtils.convertLongToInt(rs.getColumnPrecision(i));
int scale = rs.getColumnScale(i);
simple.addColumn(name, sqlType, precision, scale);
}
rs.reset();
for (int i = 0; i < maxRows && rs.next(); i++) {
Object[] list = new Object[columnCount];
for (int j = 0; j < columnCount; j++) {
list[j] = rs.currentRow()[j].getObject();
}
simple.addRow(list);
}
return simple;
| 1,127
| 238
| 1,365
|
<methods>public R accept(ExpressionVisitor<R>) ,public void doneWithParameters() ,public int getCost() ,public int getDisplaySize() ,public int getFunctionType() ,public java.lang.String getName() ,public long getPrecision() ,public java.lang.String getSQL() ,public int getScale() ,public int getType() ,public com.lealone.db.value.Value getValue(com.lealone.db.session.ServerSession) ,public com.lealone.db.value.ValueResultSet getValueForColumnList(com.lealone.db.session.ServerSession, com.lealone.sql.expression.Expression[]) ,public boolean isDeterministic() ,public com.lealone.sql.expression.Expression optimize(com.lealone.db.session.ServerSession) ,public void setDataType(com.lealone.db.table.Column) ,public void setParameter(int, com.lealone.sql.expression.Expression) <variables>protected int dataType,protected final non-sealed com.lealone.db.Database database,protected int displaySize,protected final non-sealed com.lealone.sql.expression.function.FunctionInfo info,protected long precision,protected int scale,private ArrayList<com.lealone.sql.expression.Expression> varArgs
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/expression/subquery/SubQuery.java
|
SubQuery
|
getExpression
|
class SubQuery extends Expression {
private final Query query;
private Expression expression;
public SubQuery(Query query) {
this.query = query;
}
@Override
public Value getValue(ServerSession session) {
query.setSession(session);
Result result = query.query(2);
try {
int rowcount = result.getRowCount();
if (rowcount > 1) {
throw DbException.get(ErrorCode.SCALAR_SUBQUERY_CONTAINS_MORE_THAN_ONE_ROW);
}
Value v;
if (rowcount <= 0) {
v = ValueNull.INSTANCE;
} else {
result.next();
Value[] values = result.currentRow();
if (result.getVisibleColumnCount() == 1) {
v = values[0];
} else {
v = ValueArray.get(values);
}
}
return v;
} finally {
result.close();
}
}
@Override
public int getType() {
return getExpression().getType();
}
@Override
public Expression optimize(ServerSession session) {
query.prepare();
return this;
}
@Override
public int getScale() {
return getExpression().getScale();
}
@Override
public long getPrecision() {
return getExpression().getPrecision();
}
@Override
public int getDisplaySize() {
return getExpression().getDisplaySize();
}
@Override
public String getSQL() {
return "(" + query.getPlanSQL() + ")";
}
private Expression getExpression() {<FILL_FUNCTION_BODY>}
public Query getQuery() {
return query;
}
@Override
public int getCost() {
return query.getCostAsExpression();
}
@Override
public Expression[] getExpressionColumns(ServerSession session) {
return getExpression().getExpressionColumns(session);
}
@Override
public <R> R accept(ExpressionVisitor<R> visitor) {
return visitor.visitSubQuery(this);
}
}
|
if (expression == null) {
ArrayList<Expression> expressions = query.getExpressions();
int columnCount = query.getColumnCount();
if (columnCount == 1) {
expression = expressions.get(0);
} else {
Expression[] list = new Expression[columnCount];
for (int i = 0; i < columnCount; i++) {
list[i] = expressions.get(i);
}
expression = new ExpressionList(list);
}
}
return expression;
| 565
| 134
| 699
|
<methods>public non-sealed void <init>() ,public R accept(ExpressionVisitor<R>) ,public void addFilterConditions(com.lealone.sql.optimizer.TableFilter, boolean) ,public void createIndexConditions(com.lealone.db.session.ServerSession, com.lealone.sql.optimizer.TableFilter) ,public java.lang.String getAlias() ,public boolean getBooleanValue(com.lealone.db.session.ServerSession) ,public java.lang.String getColumnName() ,public void getColumns(Set<?>) ,public abstract int getCost() ,public void getDependencies(Set<?>) ,public abstract int getDisplaySize() ,public com.lealone.sql.expression.Expression[] getExpressionColumns(com.lealone.db.session.ServerSession) ,public static com.lealone.sql.expression.Expression[] getExpressionColumns(com.lealone.db.session.ServerSession, com.lealone.db.value.ValueArray) ,public static com.lealone.sql.expression.Expression[] getExpressionColumns(com.lealone.db.session.ServerSession, java.sql.ResultSet) ,public com.lealone.sql.expression.Expression getNonAliasExpression() ,public com.lealone.sql.expression.Expression getNotIfPossible(com.lealone.db.session.ServerSession) ,public int getNullable() ,public abstract long getPrecision() ,public abstract java.lang.String getSQL() ,public abstract int getScale() ,public java.lang.String getSchemaName() ,public java.lang.String getTableName() ,public abstract int getType() ,public com.lealone.db.value.Value getValue(com.lealone.db.session.Session) ,public abstract com.lealone.db.value.Value getValue(com.lealone.db.session.ServerSession) ,public boolean isAutoIncrement() ,public boolean isConstant() ,public boolean isEvaluatable() ,public boolean isValueSet() ,public boolean isWildcard() ,public void mapColumns(com.lealone.sql.optimizer.ColumnResolver, int) ,public abstract com.lealone.sql.expression.Expression optimize(com.lealone.db.session.ServerSession) ,public com.lealone.sql.expression.Expression optimize(com.lealone.db.session.Session) ,public java.lang.String toString() ,public void updateAggregate(com.lealone.db.session.ServerSession) <variables>private boolean addedToFilter
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/expression/subquery/SubQueryResult.java
|
SubQueryResult
|
initDistinctRows
|
class SubQueryResult extends DelegatedResult {
protected ValueHashMap<Value[]> distinctRows;
protected int rowCount = -1;
public SubQueryResult(Query query, int maxRows) {
result = query.query(maxRows);
}
public boolean containsDistinct(Value[] values) {
if (result instanceof LocalResult)
return ((LocalResult) result).containsDistinct(values);
if (distinctRows == null) {
initDistinctRows();
}
ValueArray array = ValueArray.get(values);
return distinctRows.get(array) != null;
}
private int initDistinctRows() {<FILL_FUNCTION_BODY>}
@Override
public int getRowCount() {
int rowCount = result.getRowCount();
if (rowCount == -1) {
initDistinctRows();
return this.rowCount;
}
return rowCount;
}
}
|
if (distinctRows == null) {
rowCount = 0;
distinctRows = ValueHashMap.newInstance();
int visibleColumnCount = getVisibleColumnCount();
ArrayList<Value[]> rowList = new ArrayList<>();
while (next()) {
rowCount++;
Value[] row = currentRow();
if (row.length > visibleColumnCount) {
Value[] r2 = new Value[visibleColumnCount];
System.arraycopy(row, 0, r2, 0, visibleColumnCount);
row = r2;
}
ValueArray array = ValueArray.get(row);
distinctRows.put(array, row);
rowList.add(row);
}
result = new SubQueryRowList(rowList, result);
}
return rowCount;
| 246
| 203
| 449
|
<methods>public non-sealed void <init>() ,public void close() ,public com.lealone.db.value.Value[] currentRow() ,public java.lang.String getAlias(int) ,public java.lang.String getColumnName(int) ,public long getColumnPrecision(int) ,public int getColumnScale(int) ,public int getColumnType(int) ,public int getDisplaySize(int) ,public int getFetchSize() ,public int getNullable(int) ,public int getRowCount() ,public int getRowId() ,public java.lang.String getSchemaName(int) ,public java.lang.String getTableName(int) ,public int getVisibleColumnCount() ,public boolean isAutoIncrement(int) ,public boolean needToClose() ,public boolean next() ,public void reset() ,public void setFetchSize(int) <variables>protected com.lealone.db.result.Result result
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/expression/visitor/BooleanExpressionVisitor.java
|
BooleanExpressionVisitor
|
visitAGroupConcat
|
class BooleanExpressionVisitor extends ExpressionVisitorBase<Boolean> {
@Override
public Boolean visitExpression(Expression e) {
return true;
}
@Override
public Boolean visitAlias(Alias e) {
return e.getNonAliasExpression().accept(this);
}
@Override
public Boolean visitExpressionColumn(ExpressionColumn e) {
return true;
}
@Override
public Boolean visitExpressionList(ExpressionList e) {
for (Expression e2 : e.getList()) {
if (!e2.accept(this))
return false;
}
return true;
}
@Override
public Boolean visitOperation(Operation e) {
return e.getLeft().accept(this) && (e.getRight() == null || e.getRight().accept(this));
}
@Override
public Boolean visitParameter(Parameter e) {
return true;
}
@Override
public Boolean visitRownum(Rownum e) {
return true;
}
@Override
public Boolean visitSequenceValue(SequenceValue e) {
return true;
}
@Override
public Boolean visitSubQuery(SubQuery e) {
return visitQuery(e.getQuery());
}
protected Boolean visitQuery(Query query) {
return query.accept(this);
}
@Override
public Boolean visitValueExpression(ValueExpression e) {
return true;
}
@Override
public Boolean visitVariable(Variable e) {
return true;
}
@Override
public Boolean visitWildcard(Wildcard e) {
return true;
}
@Override
public Boolean visitCompareLike(CompareLike e) {
return e.getLeft().accept(this) && e.getRight().accept(this)
&& (e.getEscape() == null || e.getEscape().accept(this));
}
@Override
public Boolean visitComparison(Comparison e) {
return e.getLeft().accept(this) && (e.getRight() == null || e.getRight().accept(this));
}
@Override
public Boolean visitConditionAndOr(ConditionAndOr e) {
return e.getLeft().accept(this) && e.getRight().accept(this);
}
@Override
public Boolean visitConditionExists(ConditionExists e) {
return visitQuery(e.getQuery());
}
@Override
public Boolean visitConditionIn(ConditionIn e) {
if (!e.getLeft().accept(this)) {
return false;
}
for (Expression e2 : e.getValueList()) {
if (!e2.accept(this)) {
return false;
}
}
return true;
}
@Override
public Boolean visitConditionInConstantSet(ConditionInConstantSet e) {
return e.getLeft().accept(this);
}
@Override
public Boolean visitConditionInSelect(ConditionInSelect e) {
if (!e.getLeft().accept(this)) {
return false;
}
return visitQuery(e.getQuery());
}
@Override
public Boolean visitConditionNot(ConditionNot e) {
return e.getCondition().accept(this);
}
@Override
public Boolean visitAggregate(Aggregate e) {
return e.getOn() == null || e.getOn().accept(this);
}
@Override
public Boolean visitAGroupConcat(AGroupConcat e) {<FILL_FUNCTION_BODY>}
@Override
public Boolean visitJavaAggregate(JavaAggregate e) {
for (Expression e2 : e.getArgs()) {
if (e != null && !e2.accept(this)) {
return false;
}
}
return true;
}
@Override
public Boolean visitFunction(Function e) {
for (Expression e2 : e.getArgs()) {
if (e2 != null && !e2.accept(this)) {
return false;
}
}
return true;
}
@Override
public Boolean visitJavaFunction(JavaFunction e) {
return visitFunction(e);
}
@Override
public Boolean visitTableFunction(TableFunction e) {
return visitFunction(e);
}
@Override
public Boolean visitSelect(Select s) {
ExpressionVisitor<Boolean> v2 = incrementQueryLevel(1);
ArrayList<Expression> expressions = s.getExpressions();
for (int i = 0, size = expressions.size(); i < size; i++) {
Expression e = expressions.get(i);
if (!e.accept(v2))
return false;
}
if (s.getCondition() != null) {
if (!s.getCondition().accept(v2))
return false;
}
if (s.getHaving() != null) {
if (!s.getHaving().accept(v2))
return false;
}
return true;
}
@Override
public Boolean visitSelectUnion(SelectUnion su) {
return su.getLeft().accept(this) && su.getRight().accept(this);
}
}
|
if (!visitAggregate(e)) {
return false;
}
if (e.getGroupConcatSeparator() != null && !e.getGroupConcatSeparator().accept(this)) {
return false;
}
if (e.getGroupConcatOrderList() != null) {
for (int i = 0, size = e.getGroupConcatOrderList().size(); i < size; i++) {
SelectOrderBy o = e.getGroupConcatOrderList().get(i);
if (!o.expression.accept(this)) {
return false;
}
}
}
return true;
| 1,329
| 163
| 1,492
|
<methods>public non-sealed void <init>() ,public int getQueryLevel() ,public ExpressionVisitorBase<java.lang.Boolean> incrementQueryLevel(int) ,public void setQueryLevel(int) <variables>private int queryLevel
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/expression/visitor/DependenciesVisitor.java
|
DependenciesVisitor
|
visitQuery
|
class DependenciesVisitor extends VoidExpressionVisitor {
private Set<DbObject> dependencies;
public DependenciesVisitor(Set<DbObject> dependencies) {
this.dependencies = dependencies;
}
public void addDependency(DbObject obj) {
dependencies.add(obj);
}
public Set<DbObject> getDependencies() {
return dependencies;
}
@Override
public Void visitExpressionColumn(ExpressionColumn e) {
if (e.getColumn() != null)
addDependency(e.getColumn().getTable());
return null;
}
@Override
public Void visitSequenceValue(SequenceValue e) {
addDependency(e.getSequence());
return null;
}
@Override
public Void visitJavaAggregate(JavaAggregate e) {
addDependency(e.getUserAggregate());
super.visitJavaAggregate(e);
return null;
}
@Override
public Void visitJavaFunction(JavaFunction e) {
addDependency(e.getFunctionAlias());
super.visitJavaFunction(e);
return null;
}
@Override
protected Void visitQuery(Query query) {<FILL_FUNCTION_BODY>}
}
|
super.visitQuery(query);
for (int i = 0, size = query.getFilters().size(); i < size; i++) {
TableFilter f = query.getFilters().get(i);
Table table = f.getTable();
addDependency(table);
table.addDependencies(dependencies);
}
return null;
| 325
| 92
| 417
|
<methods>public non-sealed void <init>() ,public java.lang.Void visitAGroupConcat(com.lealone.sql.expression.aggregate.AGroupConcat) ,public java.lang.Void visitAggregate(com.lealone.sql.expression.aggregate.Aggregate) ,public java.lang.Void visitAlias(com.lealone.sql.expression.Alias) ,public java.lang.Void visitCompareLike(com.lealone.sql.expression.condition.CompareLike) ,public java.lang.Void visitComparison(com.lealone.sql.expression.condition.Comparison) ,public java.lang.Void visitConditionAndOr(com.lealone.sql.expression.condition.ConditionAndOr) ,public java.lang.Void visitConditionExists(com.lealone.sql.expression.condition.ConditionExists) ,public java.lang.Void visitConditionIn(com.lealone.sql.expression.condition.ConditionIn) ,public java.lang.Void visitConditionInConstantSet(com.lealone.sql.expression.condition.ConditionInConstantSet) ,public java.lang.Void visitConditionInSelect(com.lealone.sql.expression.condition.ConditionInSelect) ,public java.lang.Void visitConditionNot(com.lealone.sql.expression.condition.ConditionNot) ,public java.lang.Void visitExpression(com.lealone.sql.expression.Expression) ,public java.lang.Void visitExpressionColumn(com.lealone.sql.expression.ExpressionColumn) ,public java.lang.Void visitExpressionList(com.lealone.sql.expression.ExpressionList) ,public java.lang.Void visitFunction(com.lealone.sql.expression.function.Function) ,public java.lang.Void visitJavaAggregate(com.lealone.sql.expression.aggregate.JavaAggregate) ,public java.lang.Void visitJavaFunction(com.lealone.sql.expression.function.JavaFunction) ,public java.lang.Void visitOperation(com.lealone.sql.expression.Operation) ,public java.lang.Void visitParameter(com.lealone.sql.expression.Parameter) ,public java.lang.Void visitRownum(com.lealone.sql.expression.Rownum) ,public java.lang.Void visitSelect(com.lealone.sql.query.Select) ,public java.lang.Void visitSelectUnion(com.lealone.sql.query.SelectUnion) ,public java.lang.Void visitSequenceValue(com.lealone.sql.expression.SequenceValue) ,public java.lang.Void visitSubQuery(com.lealone.sql.expression.subquery.SubQuery) ,public java.lang.Void visitTableFunction(com.lealone.sql.expression.function.TableFunction) ,public java.lang.Void visitValueExpression(com.lealone.sql.expression.ValueExpression) ,public java.lang.Void visitVariable(com.lealone.sql.expression.Variable) ,public java.lang.Void visitWildcard(com.lealone.sql.expression.Wildcard) <variables>
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/expression/visitor/DeterministicVisitor.java
|
DeterministicVisitor
|
visitJavaAggregate
|
class DeterministicVisitor extends BooleanExpressionVisitor {
@Override
public Boolean visitRownum(Rownum e) {
return false;
}
@Override
public Boolean visitSequenceValue(SequenceValue e) {
return false;
}
@Override
public Boolean visitVariable(Variable e) {
return false;
}
@Override
public Boolean visitJavaAggregate(JavaAggregate e) {<FILL_FUNCTION_BODY>}
@Override
public Boolean visitFunction(Function e) {
return super.visitFunction(e) && e.isDeterministic();
}
@Override
public Boolean visitSelect(Select s) {
return s.isDeterministic() && super.visitSelect(s);
}
@Override
protected ExpressionVisitorBase<Boolean> copy() {
return new DeterministicVisitor();
}
}
|
// TODO optimization: some functions are deterministic, but we don't
// know (no setting for that)
return false;
| 235
| 35
| 270
|
<methods>public non-sealed void <init>() ,public java.lang.Boolean visitAGroupConcat(com.lealone.sql.expression.aggregate.AGroupConcat) ,public java.lang.Boolean visitAggregate(com.lealone.sql.expression.aggregate.Aggregate) ,public java.lang.Boolean visitAlias(com.lealone.sql.expression.Alias) ,public java.lang.Boolean visitCompareLike(com.lealone.sql.expression.condition.CompareLike) ,public java.lang.Boolean visitComparison(com.lealone.sql.expression.condition.Comparison) ,public java.lang.Boolean visitConditionAndOr(com.lealone.sql.expression.condition.ConditionAndOr) ,public java.lang.Boolean visitConditionExists(com.lealone.sql.expression.condition.ConditionExists) ,public java.lang.Boolean visitConditionIn(com.lealone.sql.expression.condition.ConditionIn) ,public java.lang.Boolean visitConditionInConstantSet(com.lealone.sql.expression.condition.ConditionInConstantSet) ,public java.lang.Boolean visitConditionInSelect(com.lealone.sql.expression.condition.ConditionInSelect) ,public java.lang.Boolean visitConditionNot(com.lealone.sql.expression.condition.ConditionNot) ,public java.lang.Boolean visitExpression(com.lealone.sql.expression.Expression) ,public java.lang.Boolean visitExpressionColumn(com.lealone.sql.expression.ExpressionColumn) ,public java.lang.Boolean visitExpressionList(com.lealone.sql.expression.ExpressionList) ,public java.lang.Boolean visitFunction(com.lealone.sql.expression.function.Function) ,public java.lang.Boolean visitJavaAggregate(com.lealone.sql.expression.aggregate.JavaAggregate) ,public java.lang.Boolean visitJavaFunction(com.lealone.sql.expression.function.JavaFunction) ,public java.lang.Boolean visitOperation(com.lealone.sql.expression.Operation) ,public java.lang.Boolean visitParameter(com.lealone.sql.expression.Parameter) ,public java.lang.Boolean visitRownum(com.lealone.sql.expression.Rownum) ,public java.lang.Boolean visitSelect(com.lealone.sql.query.Select) ,public java.lang.Boolean visitSelectUnion(com.lealone.sql.query.SelectUnion) ,public java.lang.Boolean visitSequenceValue(com.lealone.sql.expression.SequenceValue) ,public java.lang.Boolean visitSubQuery(com.lealone.sql.expression.subquery.SubQuery) ,public java.lang.Boolean visitTableFunction(com.lealone.sql.expression.function.TableFunction) ,public java.lang.Boolean visitValueExpression(com.lealone.sql.expression.ValueExpression) ,public java.lang.Boolean visitVariable(com.lealone.sql.expression.Variable) ,public java.lang.Boolean visitWildcard(com.lealone.sql.expression.Wildcard) <variables>
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/expression/visitor/ExpressionVisitorBase.java
|
ExpressionVisitorBase
|
incrementQueryLevel
|
class ExpressionVisitorBase<R> implements ExpressionVisitor<R> {
private int queryLevel;
@Override
public ExpressionVisitorBase<R> incrementQueryLevel(int offset) {<FILL_FUNCTION_BODY>}
public void setQueryLevel(int queryLevel) {
this.queryLevel = queryLevel;
}
@Override
public int getQueryLevel() {
return queryLevel;
}
protected ExpressionVisitorBase<R> copy() {
return this;
}
}
|
ExpressionVisitorBase<R> c = copy();
c.setQueryLevel(getQueryLevel() + offset);
return c;
| 138
| 37
| 175
|
<no_super_class>
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/expression/visitor/MapColumnsVisitor.java
|
MapColumnsVisitor
|
visitJavaAggregate
|
class MapColumnsVisitor extends VoidExpressionVisitor {
private ColumnResolver resolver;
private int level;
public MapColumnsVisitor(ColumnResolver resolver, int level) {
this.resolver = resolver;
this.level = level;
}
@Override
public Void visitExpressionColumn(ExpressionColumn e) {
e.mapColumns(resolver, level);
return null;
}
@Override
public Void visitSubQuery(SubQuery e) {
level++;
super.visitSubQuery(e);
level--;
return null;
}
@Override
public Void visitConditionExists(ConditionExists e) {
level++;
super.visitConditionExists(e);
level--;
return null;
}
@Override
public Void visitConditionIn(ConditionIn e) {
int level = this.level;
super.visitConditionIn(e);
e.setQueryLevel(level);
return null;
}
@Override
public Void visitConditionInConstantSet(ConditionInConstantSet e) {
int level = this.level;
super.visitConditionInConstantSet(e);
e.setQueryLevel(level);
return null;
}
@Override
public Void visitConditionInSelect(ConditionInSelect e) {
e.getLeft().accept(this);
level++;
visitQuery(e.getQuery());
level--;
return null;
}
@Override
public Void visitAggregate(Aggregate e) {
// 聚合函数不能嵌套
if (resolver.getState() == ColumnResolver.STATE_IN_AGGREGATE) {
throw DbException.get(ErrorCode.INVALID_USE_OF_AGGREGATE_FUNCTION_1, e.getSQL());
}
if (e.getOn() != null) {
int state = resolver.getState();
resolver.setState(ColumnResolver.STATE_IN_AGGREGATE);
try {
super.visitAggregate(e);
} finally {
resolver.setState(state);
}
}
return null;
}
@Override
public Void visitAGroupConcat(AGroupConcat e) {
// 聚合函数不能嵌套
if (resolver.getState() == ColumnResolver.STATE_IN_AGGREGATE) {
throw DbException.get(ErrorCode.INVALID_USE_OF_AGGREGATE_FUNCTION_1, e.getSQL());
}
int state = resolver.getState();
resolver.setState(ColumnResolver.STATE_IN_AGGREGATE);
try {
super.visitAGroupConcat(e);
} finally {
resolver.setState(state);
}
return null;
}
@Override
public Void visitJavaAggregate(JavaAggregate e) {<FILL_FUNCTION_BODY>}
}
|
// 聚合函数不能嵌套
if (resolver.getState() == ColumnResolver.STATE_IN_AGGREGATE) {
throw DbException.get(ErrorCode.INVALID_USE_OF_AGGREGATE_FUNCTION_1, e.getSQL());
}
int state = resolver.getState();
resolver.setState(ColumnResolver.STATE_IN_AGGREGATE);
try {
super.visitJavaAggregate(e);
} finally {
resolver.setState(state);
}
return null;
| 772
| 148
| 920
|
<methods>public non-sealed void <init>() ,public java.lang.Void visitAGroupConcat(com.lealone.sql.expression.aggregate.AGroupConcat) ,public java.lang.Void visitAggregate(com.lealone.sql.expression.aggregate.Aggregate) ,public java.lang.Void visitAlias(com.lealone.sql.expression.Alias) ,public java.lang.Void visitCompareLike(com.lealone.sql.expression.condition.CompareLike) ,public java.lang.Void visitComparison(com.lealone.sql.expression.condition.Comparison) ,public java.lang.Void visitConditionAndOr(com.lealone.sql.expression.condition.ConditionAndOr) ,public java.lang.Void visitConditionExists(com.lealone.sql.expression.condition.ConditionExists) ,public java.lang.Void visitConditionIn(com.lealone.sql.expression.condition.ConditionIn) ,public java.lang.Void visitConditionInConstantSet(com.lealone.sql.expression.condition.ConditionInConstantSet) ,public java.lang.Void visitConditionInSelect(com.lealone.sql.expression.condition.ConditionInSelect) ,public java.lang.Void visitConditionNot(com.lealone.sql.expression.condition.ConditionNot) ,public java.lang.Void visitExpression(com.lealone.sql.expression.Expression) ,public java.lang.Void visitExpressionColumn(com.lealone.sql.expression.ExpressionColumn) ,public java.lang.Void visitExpressionList(com.lealone.sql.expression.ExpressionList) ,public java.lang.Void visitFunction(com.lealone.sql.expression.function.Function) ,public java.lang.Void visitJavaAggregate(com.lealone.sql.expression.aggregate.JavaAggregate) ,public java.lang.Void visitJavaFunction(com.lealone.sql.expression.function.JavaFunction) ,public java.lang.Void visitOperation(com.lealone.sql.expression.Operation) ,public java.lang.Void visitParameter(com.lealone.sql.expression.Parameter) ,public java.lang.Void visitRownum(com.lealone.sql.expression.Rownum) ,public java.lang.Void visitSelect(com.lealone.sql.query.Select) ,public java.lang.Void visitSelectUnion(com.lealone.sql.query.SelectUnion) ,public java.lang.Void visitSequenceValue(com.lealone.sql.expression.SequenceValue) ,public java.lang.Void visitSubQuery(com.lealone.sql.expression.subquery.SubQuery) ,public java.lang.Void visitTableFunction(com.lealone.sql.expression.function.TableFunction) ,public java.lang.Void visitValueExpression(com.lealone.sql.expression.ValueExpression) ,public java.lang.Void visitVariable(com.lealone.sql.expression.Variable) ,public java.lang.Void visitWildcard(com.lealone.sql.expression.Wildcard) <variables>
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/expression/visitor/MaxModificationIdVisitor.java
|
MaxModificationIdVisitor
|
visitQuery
|
class MaxModificationIdVisitor extends VoidExpressionVisitor {
private long maxDataModificationId;
public long getMaxDataModificationId() {
return maxDataModificationId;
}
public void setMaxDataModificationId(long maxDataModificationId) {
if (maxDataModificationId > this.maxDataModificationId) {
this.maxDataModificationId = maxDataModificationId;
}
}
@Override
public Void visitExpressionColumn(ExpressionColumn e) {
setMaxDataModificationId(e.getColumn().getTable().getMaxDataModificationId());
return null;
}
@Override
public Void visitSequenceValue(SequenceValue e) {
setMaxDataModificationId(e.getSequence().getModificationId());
return null;
}
@Override
protected Void visitQuery(Query query) {<FILL_FUNCTION_BODY>}
}
|
super.visitQuery(query);
for (int i = 0, size = query.getFilters().size(); i < size; i++) {
TableFilter f = query.getFilters().get(i);
long m = f.getTable().getMaxDataModificationId();
setMaxDataModificationId(m);
}
return null;
| 240
| 92
| 332
|
<methods>public non-sealed void <init>() ,public java.lang.Void visitAGroupConcat(com.lealone.sql.expression.aggregate.AGroupConcat) ,public java.lang.Void visitAggregate(com.lealone.sql.expression.aggregate.Aggregate) ,public java.lang.Void visitAlias(com.lealone.sql.expression.Alias) ,public java.lang.Void visitCompareLike(com.lealone.sql.expression.condition.CompareLike) ,public java.lang.Void visitComparison(com.lealone.sql.expression.condition.Comparison) ,public java.lang.Void visitConditionAndOr(com.lealone.sql.expression.condition.ConditionAndOr) ,public java.lang.Void visitConditionExists(com.lealone.sql.expression.condition.ConditionExists) ,public java.lang.Void visitConditionIn(com.lealone.sql.expression.condition.ConditionIn) ,public java.lang.Void visitConditionInConstantSet(com.lealone.sql.expression.condition.ConditionInConstantSet) ,public java.lang.Void visitConditionInSelect(com.lealone.sql.expression.condition.ConditionInSelect) ,public java.lang.Void visitConditionNot(com.lealone.sql.expression.condition.ConditionNot) ,public java.lang.Void visitExpression(com.lealone.sql.expression.Expression) ,public java.lang.Void visitExpressionColumn(com.lealone.sql.expression.ExpressionColumn) ,public java.lang.Void visitExpressionList(com.lealone.sql.expression.ExpressionList) ,public java.lang.Void visitFunction(com.lealone.sql.expression.function.Function) ,public java.lang.Void visitJavaAggregate(com.lealone.sql.expression.aggregate.JavaAggregate) ,public java.lang.Void visitJavaFunction(com.lealone.sql.expression.function.JavaFunction) ,public java.lang.Void visitOperation(com.lealone.sql.expression.Operation) ,public java.lang.Void visitParameter(com.lealone.sql.expression.Parameter) ,public java.lang.Void visitRownum(com.lealone.sql.expression.Rownum) ,public java.lang.Void visitSelect(com.lealone.sql.query.Select) ,public java.lang.Void visitSelectUnion(com.lealone.sql.query.SelectUnion) ,public java.lang.Void visitSequenceValue(com.lealone.sql.expression.SequenceValue) ,public java.lang.Void visitSubQuery(com.lealone.sql.expression.subquery.SubQuery) ,public java.lang.Void visitTableFunction(com.lealone.sql.expression.function.TableFunction) ,public java.lang.Void visitValueExpression(com.lealone.sql.expression.ValueExpression) ,public java.lang.Void visitVariable(com.lealone.sql.expression.Variable) ,public java.lang.Void visitWildcard(com.lealone.sql.expression.Wildcard) <variables>
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/expression/visitor/OptimizableVisitor.java
|
OptimizableVisitor
|
visitJavaAggregate
|
class OptimizableVisitor extends BooleanExpressionVisitor {
private final Table table;
public OptimizableVisitor(Table table) {
this.table = table;
}
@Override
public Boolean visitRownum(Rownum e) {
return false;
}
@Override
public Boolean visitExpressionColumn(ExpressionColumn e) {
return true;
}
@Override
public Boolean visitJavaAggregate(JavaAggregate e) {<FILL_FUNCTION_BODY>}
@Override
public Boolean visitAggregate(Aggregate e) {
return ((BuiltInAggregate) e).isOptimizable(table) && super.visitAggregate(e);
}
}
|
// user defined aggregate functions can not be optimized
return false;
| 182
| 19
| 201
|
<methods>public non-sealed void <init>() ,public java.lang.Boolean visitAGroupConcat(com.lealone.sql.expression.aggregate.AGroupConcat) ,public java.lang.Boolean visitAggregate(com.lealone.sql.expression.aggregate.Aggregate) ,public java.lang.Boolean visitAlias(com.lealone.sql.expression.Alias) ,public java.lang.Boolean visitCompareLike(com.lealone.sql.expression.condition.CompareLike) ,public java.lang.Boolean visitComparison(com.lealone.sql.expression.condition.Comparison) ,public java.lang.Boolean visitConditionAndOr(com.lealone.sql.expression.condition.ConditionAndOr) ,public java.lang.Boolean visitConditionExists(com.lealone.sql.expression.condition.ConditionExists) ,public java.lang.Boolean visitConditionIn(com.lealone.sql.expression.condition.ConditionIn) ,public java.lang.Boolean visitConditionInConstantSet(com.lealone.sql.expression.condition.ConditionInConstantSet) ,public java.lang.Boolean visitConditionInSelect(com.lealone.sql.expression.condition.ConditionInSelect) ,public java.lang.Boolean visitConditionNot(com.lealone.sql.expression.condition.ConditionNot) ,public java.lang.Boolean visitExpression(com.lealone.sql.expression.Expression) ,public java.lang.Boolean visitExpressionColumn(com.lealone.sql.expression.ExpressionColumn) ,public java.lang.Boolean visitExpressionList(com.lealone.sql.expression.ExpressionList) ,public java.lang.Boolean visitFunction(com.lealone.sql.expression.function.Function) ,public java.lang.Boolean visitJavaAggregate(com.lealone.sql.expression.aggregate.JavaAggregate) ,public java.lang.Boolean visitJavaFunction(com.lealone.sql.expression.function.JavaFunction) ,public java.lang.Boolean visitOperation(com.lealone.sql.expression.Operation) ,public java.lang.Boolean visitParameter(com.lealone.sql.expression.Parameter) ,public java.lang.Boolean visitRownum(com.lealone.sql.expression.Rownum) ,public java.lang.Boolean visitSelect(com.lealone.sql.query.Select) ,public java.lang.Boolean visitSelectUnion(com.lealone.sql.query.SelectUnion) ,public java.lang.Boolean visitSequenceValue(com.lealone.sql.expression.SequenceValue) ,public java.lang.Boolean visitSubQuery(com.lealone.sql.expression.subquery.SubQuery) ,public java.lang.Boolean visitTableFunction(com.lealone.sql.expression.function.TableFunction) ,public java.lang.Boolean visitValueExpression(com.lealone.sql.expression.ValueExpression) ,public java.lang.Boolean visitVariable(com.lealone.sql.expression.Variable) ,public java.lang.Boolean visitWildcard(com.lealone.sql.expression.Wildcard) <variables>
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/expression/visitor/VoidExpressionVisitor.java
|
VoidExpressionVisitor
|
visitFunction
|
class VoidExpressionVisitor extends ExpressionVisitorBase<Void> {
@Override
public Void visitExpression(Expression e) {
return null;
}
@Override
public Void visitAlias(Alias e) {
return e.getNonAliasExpression().accept(this);
}
@Override
public Void visitExpressionColumn(ExpressionColumn e) {
return null;
}
@Override
public Void visitExpressionList(ExpressionList e) {
for (Expression e2 : e.getList()) {
e2.accept(this);
}
return null;
}
@Override
public Void visitOperation(Operation e) {
e.getLeft().accept(this);
if (e.getRight() != null)
e.getRight().accept(this);
return null;
}
@Override
public Void visitParameter(Parameter e) {
return null;
}
@Override
public Void visitRownum(Rownum e) {
return null;
}
@Override
public Void visitSequenceValue(SequenceValue e) {
return null;
}
@Override
public Void visitSubQuery(SubQuery e) {
visitQuery(e.getQuery());
return null;
}
protected Void visitQuery(Query query) {
query.accept(this);
return null;
}
@Override
public Void visitValueExpression(ValueExpression e) {
return null;
}
@Override
public Void visitVariable(Variable e) {
return null;
}
@Override
public Void visitWildcard(Wildcard e) {
return null;
}
@Override
public Void visitCompareLike(CompareLike e) {
e.getLeft().accept(this);
e.getRight().accept(this);
if (e.getEscape() != null)
e.getEscape().accept(this);
return null;
}
@Override
public Void visitComparison(Comparison e) {
e.getLeft().accept(this);
if (e.getRight() != null)
e.getRight().accept(this);
return null;
}
@Override
public Void visitConditionAndOr(ConditionAndOr e) {
e.getLeft().accept(this);
e.getRight().accept(this);
return null;
}
@Override
public Void visitConditionExists(ConditionExists e) {
visitQuery(e.getQuery());
return null;
}
@Override
public Void visitConditionIn(ConditionIn e) {
e.getLeft().accept(this);
for (Expression e2 : e.getValueList()) {
e2.accept(this);
}
return null;
}
@Override
public Void visitConditionInConstantSet(ConditionInConstantSet e) {
e.getLeft().accept(this);
return null;
}
@Override
public Void visitConditionInSelect(ConditionInSelect e) {
e.getLeft().accept(this);
visitQuery(e.getQuery());
return null;
}
@Override
public Void visitConditionNot(ConditionNot e) {
e.getCondition().accept(this);
return null;
}
@Override
public Void visitAggregate(Aggregate e) {
if (e.getOn() != null)
e.getOn().accept(this);
return null;
}
@Override
public Void visitAGroupConcat(AGroupConcat e) {
if (e.getOn() != null)
e.getOn().accept(this);
if (e.getGroupConcatSeparator() != null)
e.getGroupConcatSeparator().accept(this);
if (e.getGroupConcatOrderList() != null) {
for (SelectOrderBy o : e.getGroupConcatOrderList()) {
o.expression.accept(this);
}
}
return null;
}
@Override
public Void visitJavaAggregate(JavaAggregate e) {
for (Expression e2 : e.getArgs()) {
if (e2 != null)
e2.accept(this);
}
return null;
}
@Override
public Void visitFunction(Function e) {<FILL_FUNCTION_BODY>}
@Override
public Void visitJavaFunction(JavaFunction e) {
for (Expression e2 : e.getArgs()) {
if (e2 != null)
e2.accept(this);
}
return null;
}
@Override
public Void visitTableFunction(TableFunction e) {
for (Expression e2 : e.getArgs()) {
if (e2 != null)
e2.accept(this);
}
return null;
}
@Override
public Void visitSelect(Select s) {
ExpressionVisitor<Void> v2 = incrementQueryLevel(1);
ArrayList<Expression> expressions = s.getExpressions();
for (int i = 0, size = expressions.size(); i < size; i++) {
Expression e = expressions.get(i);
e.accept(v2);
}
if (s.getCondition() != null) {
s.getCondition().accept(v2);
}
if (s.getHaving() != null) {
s.getHaving().accept(v2);
}
return null;
}
@Override
public Void visitSelectUnion(SelectUnion su) {
su.getLeft().accept(this);
su.getRight().accept(this);
return null;
}
}
|
for (Expression e2 : e.getArgs()) {
if (e2 != null)
e2.accept(this);
}
return null;
| 1,493
| 44
| 1,537
|
<methods>public non-sealed void <init>() ,public int getQueryLevel() ,public ExpressionVisitorBase<java.lang.Void> incrementQueryLevel(int) ,public void setQueryLevel(int) <variables>private int queryLevel
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/optimizer/Permutations.java
|
Permutations
|
moveIndex
|
class Permutations<T> {
private final T[] in;
private final T[] out;
private final int n, m;
private final int[] index;
private boolean hasNext = true;
private Permutations(T[] in, T[] out, int m) {
this.n = in.length;
this.m = m;
if (n < m || m < 0) {
DbException.throwInternalError("n < m or m < 0");
}
this.in = in;
this.out = out;
index = new int[n];
for (int i = 0; i < n; i++) {
index[i] = i;
}
// The elements from m to n are always kept ascending right to left.
// This keeps the dip in the interesting region.
reverseAfter(m - 1);
}
/**
* Create a new permutations object.
*
* @param <T> the type
* @param in the source array
* @param out the target array
* @return the generated permutations object
*/
public static <T> Permutations<T> create(T[] in, T[] out) {
return new Permutations<T>(in, out, in.length);
}
/**
* Create a new permutations object.
*
* @param <T> the type
* @param in the source array
* @param out the target array
* @param m the number of output elements to generate
* @return the generated permutations object
*/
public static <T> Permutations<T> create(T[] in, T[] out, int m) {
return new Permutations<T>(in, out, m);
}
/**
* Move the index forward a notch. The algorithm first finds the rightmost
* index that is less than its neighbor to the right. This is the dip point.
* The algorithm next finds the least element to the right of the dip that
* is greater than the dip. That element is switched with the dip. Finally,
* the list of elements to the right of the dip is reversed.
* For example, in a permutation of 5 items, the index may be {1, 2, 4, 3,
* 0}. The dip is 2 the rightmost element less than its neighbor on its
* right. The least element to the right of 2 that is greater than 2 is 3.
* These elements are swapped, yielding {1, 3, 4, 2, 0}, and the list right
* of the dip point is reversed, yielding {1, 3, 0, 2, 4}.
*/
private void moveIndex() {<FILL_FUNCTION_BODY>}
/**
* Get the index of the first element from the right that is less
* than its neighbor on the right.
*
* @return the index or -1 if non is found
*/
private int rightmostDip() {
for (int i = n - 2; i >= 0; i--) {
if (index[i] < index[i + 1]) {
return i;
}
}
return -1;
}
/**
* Reverse the elements to the right of the specified index.
*
* @param i the index
*/
private void reverseAfter(int i) {
int start = i + 1;
int end = n - 1;
while (start < end) {
int t = index[start];
index[start] = index[end];
index[end] = t;
start++;
end--;
}
}
/**
* Go to the next lineup, and if available, fill the target array.
*
* @return if a new lineup is available
*/
public boolean next() {
if (!hasNext) {
return false;
}
for (int i = 0; i < m; i++) {
out[i] = in[index[i]];
}
moveIndex();
return true;
}
}
|
// find the index of the first element that dips
int i = rightmostDip();
if (i < 0) {
hasNext = false;
return;
}
// find the least greater element to the right of the dip
int leastToRightIndex = i + 1;
for (int j = i + 2; j < n; j++) {
if (index[j] < index[leastToRightIndex] && index[j] > index[i]) {
leastToRightIndex = j;
}
}
// switch dip element with least greater element to its right
int t = index[i];
index[i] = index[leastToRightIndex];
index[leastToRightIndex] = t;
if (m - 1 > i) {
// reverse the elements to the right of the dip
reverseAfter(i);
// reverse the elements to the right of m - 1
reverseAfter(m - 1);
}
| 1,043
| 246
| 1,289
|
<no_super_class>
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/optimizer/Plan.java
|
Plan
|
calculateCost
|
class Plan {
private final TableFilter[] filters;
private final HashMap<TableFilter, PlanItem> planItems = new HashMap<>();
private final TableFilter[] allFilters;
/**
* Create a query plan with the given order.
*
* @param filters the tables of the query
* @param count the number of table items
*/
public Plan(TableFilter[] filters, int count) {
this.filters = new TableFilter[count];
System.arraycopy(filters, 0, this.filters, 0, count);
final ArrayList<TableFilter> all = new ArrayList<>();
for (int i = 0; i < count; i++) {
filters[i].visit(f -> all.add(f));
}
allFilters = all.toArray(new TableFilter[0]);
}
/**
* Get the plan item for the given table.
*
* @param filter the table
* @return the plan item
*/
public PlanItem getItem(TableFilter filter) {
return planItems.get(filter);
}
/**
* The the list of tables.
*
* @return the list of tables
*/
public TableFilter[] getFilters() {
return filters;
}
/**
* Optimize full conditions and remove all index conditions that can not be used.
*/
public void optimizeConditions() {
for (int i = 0; i < allFilters.length; i++) {
TableFilter f = allFilters[i];
setEvaluatable(f, true);
if (i < allFilters.length - 1) {
// the last table doesn't need the optimization,
// otherwise the expression is calculated twice unnecessarily
// (not that bad but not optimal)
f.optimizeFullCondition();
}
f.removeUnusableIndexConditions();
}
for (TableFilter f : allFilters) {
setEvaluatable(f, false);
}
}
/**
* Calculate the cost of this query plan.
*
* @param session the session
* @return the cost
*/
public double calculateCost(ServerSession session) {<FILL_FUNCTION_BODY>}
private void setEvaluatable(TableFilter filter, boolean b) {
filter.setEvaluatable(filter, b);
}
}
|
double cost = 1;
boolean invalidPlan = false;
int level = 1;
for (TableFilter tableFilter : allFilters) {
PlanItem item = tableFilter.getBestPlanItem(session, level++);
planItems.put(tableFilter, item);
cost += cost * item.cost;
setEvaluatable(tableFilter, true);
Expression on = tableFilter.getJoinCondition();
if (on != null && !on.isEvaluatable()) {
invalidPlan = true;
break;
}
}
if (invalidPlan) {
cost = Double.POSITIVE_INFINITY;
}
for (TableFilter f : allFilters) {
setEvaluatable(f, false);
}
return cost;
| 607
| 198
| 805
|
<no_super_class>
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/optimizer/TableIterator.java
|
TableIterator
|
tryLockRow
|
class TableIterator {
private final ServerSession session;
private final TableFilter tableFilter;
private final Table table;
private Row oldRow;
private Cursor cursor;
public TableIterator(ServerSession session, TableFilter tableFilter) {
this.session = session;
this.tableFilter = tableFilter;
this.table = tableFilter.getTable();
}
public void setCursor(Cursor cursor) {
this.cursor = cursor;
}
public void start() {
tableFilter.startQuery(session);
reset();
}
public void reset() {
tableFilter.reset();
}
public boolean next() {
if (oldRow != null) {
Row r = oldRow;
oldRow = null;
// 当发生行锁时可以直接用tableFilter的当前值重试
if (tableFilter.rebuildSearchRow(session, r) != null)
return true;
}
if (cursor == null) {
return tableFilter.next();
} else {
return cursor.next();
}
}
public Row getRow() {
if (cursor == null) {
return tableFilter.get();
} else {
SearchRow found = cursor.getSearchRow();
return tableFilter.getTable().getRow(session, found.getKey());
}
}
public int tryLockRow(int[] lockColumns) {<FILL_FUNCTION_BODY>}
public void onLockedException() {
oldRow = getRow();
}
}
|
Row oldRow = getRow();
if (oldRow == null) { // 已经删除了
return -1;
}
int ret = table.tryLockRow(session, oldRow, lockColumns);
if (ret < 0) { // 已经删除了
return -1;
} else if (ret == 0) { // 被其他事务锁住了
this.oldRow = oldRow;
return 0;
}
if (table.isRowChanged(oldRow)) {
this.oldRow = oldRow;
return -1;
}
return 1;
| 395
| 153
| 548
|
<no_super_class>
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/query/QAggregate.java
|
QAggregate
|
run
|
class QAggregate extends QOperator {
QAggregate(Select select) {
super(select);
select.currentGroup = new HashMap<>();
}
@Override
public void run() {<FILL_FUNCTION_BODY>}
}
|
while (next()) {
boolean yield = yieldIfNeeded(++loopCount);
if (conditionEvaluator.getBooleanValue()) {
if (select.isForUpdate && !tryLockRow()) {
return; // 锁记录失败
}
rowCount++;
select.currentGroupRowId++;
for (int i = 0; i < columnCount; i++) {
Expression expr = select.expressions.get(i);
expr.updateAggregate(session);
}
if (sampleSize > 0 && rowCount >= sampleSize) {
break;
}
}
if (yield)
return;
}
// 最后把聚合后的结果增加到结果集中
Value[] row = createRow();
row = QGroup.toResultRow(row, columnCount, select.resultColumnCount);
result.addRow(row);
loopEnd = true;
| 67
| 231
| 298
|
<methods>public void <init>(com.lealone.sql.query.Select) ,public boolean canBreakLoop() ,public void copyStatusTo(com.lealone.sql.query.QOperator) ,public com.lealone.sql.expression.evaluator.ExpressionEvaluator createConditionEvaluator(com.lealone.sql.expression.Expression) ,public com.lealone.db.value.Value[] createRow() ,public com.lealone.db.result.LocalResult getLocalResult() ,public boolean isStopped() ,public void onLockedException() ,public void run() ,public void start() ,public void stop() ,public boolean yieldIfNeeded(int) <variables>protected int columnCount,protected final non-sealed com.lealone.sql.expression.evaluator.ExpressionEvaluator conditionEvaluator,protected long limitRows,protected com.lealone.db.result.LocalResult localResult,protected int loopCount,protected boolean loopEnd,protected int maxRows,protected com.lealone.db.result.ResultTarget result,protected int rowCount,protected int sampleSize,protected final non-sealed com.lealone.sql.query.Select select,protected final non-sealed com.lealone.db.session.ServerSession session,protected final non-sealed com.lealone.sql.optimizer.TableIterator tableIterator,protected com.lealone.db.result.ResultTarget target,protected com.lealone.sql.query.YieldableSelect yieldableSelect
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/query/QAggregateQuick.java
|
QAggregateQuick
|
run
|
class QAggregateQuick extends QOperator {
QAggregateQuick(Select select) {
super(select);
}
@Override
public void start() {
// 什么都不需要做
}
@Override
public void run() {<FILL_FUNCTION_BODY>}
}
|
Value[] row = createRow();
result.addRow(row);
rowCount = 1;
loopEnd = true;
| 80
| 35
| 115
|
<methods>public void <init>(com.lealone.sql.query.Select) ,public boolean canBreakLoop() ,public void copyStatusTo(com.lealone.sql.query.QOperator) ,public com.lealone.sql.expression.evaluator.ExpressionEvaluator createConditionEvaluator(com.lealone.sql.expression.Expression) ,public com.lealone.db.value.Value[] createRow() ,public com.lealone.db.result.LocalResult getLocalResult() ,public boolean isStopped() ,public void onLockedException() ,public void run() ,public void start() ,public void stop() ,public boolean yieldIfNeeded(int) <variables>protected int columnCount,protected final non-sealed com.lealone.sql.expression.evaluator.ExpressionEvaluator conditionEvaluator,protected long limitRows,protected com.lealone.db.result.LocalResult localResult,protected int loopCount,protected boolean loopEnd,protected int maxRows,protected com.lealone.db.result.ResultTarget result,protected int rowCount,protected int sampleSize,protected final non-sealed com.lealone.sql.query.Select select,protected final non-sealed com.lealone.db.session.ServerSession session,protected final non-sealed com.lealone.sql.optimizer.TableIterator tableIterator,protected com.lealone.db.result.ResultTarget target,protected com.lealone.sql.query.YieldableSelect yieldableSelect
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/query/QDistinct.java
|
QDistinct
|
run
|
class QDistinct extends QOperator {
private final Index index;
private final int[] columnIds;
private final int size;
private Cursor cursor;
QDistinct(Select select) {
super(select);
index = select.getTopTableFilter().getIndex();
columnIds = index.getColumnIds();
size = columnIds.length;
}
@Override
public void start() {
cursor = index.findDistinct(session);
yieldableSelect.disableOlap(); // 无需从oltp转到olap
tableIterator.setCursor(cursor);
super.start();
}
@Override
public void run() {<FILL_FUNCTION_BODY>}
}
|
while (next()) {
if (select.isForUpdate && !tryLockRow()) {
return; // 锁记录失败
}
boolean yield = yieldIfNeeded(++loopCount);
SearchRow found = cursor.getSearchRow();
Value[] row = new Value[size];
for (int i = 0; i < size; i++) {
row[i] = found.getValue(columnIds[i]);
}
result.addRow(row);
rowCount++;
if (canBreakLoop()) {
break;
}
if (yield)
return;
}
loopEnd = true;
| 184
| 163
| 347
|
<methods>public void <init>(com.lealone.sql.query.Select) ,public boolean canBreakLoop() ,public void copyStatusTo(com.lealone.sql.query.QOperator) ,public com.lealone.sql.expression.evaluator.ExpressionEvaluator createConditionEvaluator(com.lealone.sql.expression.Expression) ,public com.lealone.db.value.Value[] createRow() ,public com.lealone.db.result.LocalResult getLocalResult() ,public boolean isStopped() ,public void onLockedException() ,public void run() ,public void start() ,public void stop() ,public boolean yieldIfNeeded(int) <variables>protected int columnCount,protected final non-sealed com.lealone.sql.expression.evaluator.ExpressionEvaluator conditionEvaluator,protected long limitRows,protected com.lealone.db.result.LocalResult localResult,protected int loopCount,protected boolean loopEnd,protected int maxRows,protected com.lealone.db.result.ResultTarget result,protected int rowCount,protected int sampleSize,protected final non-sealed com.lealone.sql.query.Select select,protected final non-sealed com.lealone.db.session.ServerSession session,protected final non-sealed com.lealone.sql.optimizer.TableIterator tableIterator,protected com.lealone.db.result.ResultTarget target,protected com.lealone.sql.query.YieldableSelect yieldableSelect
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/query/QFlat.java
|
QFlat
|
run
|
class QFlat extends QOperator {
QFlat(Select select) {
super(select);
}
@Override
public void run() {<FILL_FUNCTION_BODY>}
}
|
while (next()) {
boolean yield = yieldIfNeeded(++loopCount);
if (conditionEvaluator.getBooleanValue()) {
if (select.isForUpdate && !tryLockRow()) {
return; // 锁记录失败
}
Value[] row = createRow();
result.addRow(row);
rowCount++;
if (canBreakLoop()) {
break;
}
}
if (yield)
return;
}
loopEnd = true;
| 55
| 130
| 185
|
<methods>public void <init>(com.lealone.sql.query.Select) ,public boolean canBreakLoop() ,public void copyStatusTo(com.lealone.sql.query.QOperator) ,public com.lealone.sql.expression.evaluator.ExpressionEvaluator createConditionEvaluator(com.lealone.sql.expression.Expression) ,public com.lealone.db.value.Value[] createRow() ,public com.lealone.db.result.LocalResult getLocalResult() ,public boolean isStopped() ,public void onLockedException() ,public void run() ,public void start() ,public void stop() ,public boolean yieldIfNeeded(int) <variables>protected int columnCount,protected final non-sealed com.lealone.sql.expression.evaluator.ExpressionEvaluator conditionEvaluator,protected long limitRows,protected com.lealone.db.result.LocalResult localResult,protected int loopCount,protected boolean loopEnd,protected int maxRows,protected com.lealone.db.result.ResultTarget result,protected int rowCount,protected int sampleSize,protected final non-sealed com.lealone.sql.query.Select select,protected final non-sealed com.lealone.db.session.ServerSession session,protected final non-sealed com.lealone.sql.optimizer.TableIterator tableIterator,protected com.lealone.db.result.ResultTarget target,protected com.lealone.sql.query.YieldableSelect yieldableSelect
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/query/QGroup.java
|
QGroup
|
addGroupRow
|
class QGroup extends QOperator {
private final ValueHashMap<HashMap<Expression, Object>> groups;
QGroup(Select select) {
super(select);
select.currentGroup = null;
groups = ValueHashMap.newInstance();
}
public ValueHashMap<HashMap<Expression, Object>> getGroups() {
return groups;
}
@Override
public void run() {
while (next()) {
boolean yield = yieldIfNeeded(++loopCount);
if (conditionEvaluator.getBooleanValue()) {
if (select.isForUpdate && !tryLockRow()) {
return; // 锁记录失败
}
rowCount++;
Value key = getKey(select);
select.currentGroup = getOrCreateGroup(groups, key);
select.currentGroupRowId++;
updateAggregate(select, columnCount);
if (sampleSize > 0 && rowCount >= sampleSize) {
break;
}
}
if (yield)
return;
}
// 把分组后的记录放到result中
addGroupRows(groups, select, columnCount, result);
loopEnd = true;
}
public static Value getKey(Select select) {
// 避免在ExpressionColumn.getValue中取到旧值
// 例如SELECT id/3 AS A, COUNT(*) FROM mytable GROUP BY A HAVING A>=0
select.currentGroup = null;
return ValueArray.get(getKeyValues(select));
}
// 分组key,包括一到多个字段
public static Value[] getKeyValues(Select select) {
Value[] keyValues = new Value[select.groupIndex.length];
for (int i = 0; i < select.groupIndex.length; i++) {
int idx = select.groupIndex[i];
Expression expr = select.expressions.get(idx);
keyValues[i] = expr.getValue(select.getSession());
}
return keyValues;
}
public static HashMap<Expression, Object> getOrCreateGroup(
ValueHashMap<HashMap<Expression, Object>> groups, Value key) {
HashMap<Expression, Object> values = groups.get(key);
if (values == null) {
values = new HashMap<>();
groups.put(key, values);
}
return values;
}
public static void addGroupRows(ValueHashMap<HashMap<Expression, Object>> groups, Select select,
int columnCount, ResultTarget result) {
for (Value v : groups.keys()) {
ValueArray key = (ValueArray) v;
select.currentGroup = groups.get(key);
Value[] keyValues = key.getList();
addGroupRow(select, keyValues, columnCount, result);
}
}
public static void addGroupRow(Select select, Value[] keyValues, int columnCount,
ResultTarget result) {<FILL_FUNCTION_BODY>}
private static boolean isHavingNullOrFalse(Value[] row, int havingIndex) {
if (havingIndex >= 0) {
Value v = row[havingIndex];
if (v == ValueNull.INSTANCE)
return true;
return !v.getBoolean();
}
return false;
}
// 不包含having和group by中加入的列
public static Value[] toResultRow(Value[] row, int columnCount, int resultColumnCount) {
if (columnCount == resultColumnCount) {
return row;
}
return Arrays.copyOf(row, resultColumnCount);
}
static void updateAggregate(Select select, int columnCount) {
for (int i = 0; i < columnCount; i++) {
if (select.groupByExpression == null || !select.groupByExpression[i]) {
Expression expr = select.expressions.get(i);
expr.updateAggregate(select.getSession());
}
}
}
}
|
Value[] row = new Value[columnCount];
for (int i = 0; select.groupIndex != null && i < select.groupIndex.length; i++) {
row[select.groupIndex[i]] = keyValues[i];
}
for (int i = 0; i < columnCount; i++) {
if (select.groupByExpression != null && select.groupByExpression[i]) {
continue;
}
Expression expr = select.expressions.get(i);
row[i] = expr.getValue(select.getSession());
}
if (isHavingNullOrFalse(row, select.havingIndex)) {
return;
}
row = toResultRow(row, columnCount, select.resultColumnCount);
result.addRow(row);
| 999
| 201
| 1,200
|
<methods>public void <init>(com.lealone.sql.query.Select) ,public boolean canBreakLoop() ,public void copyStatusTo(com.lealone.sql.query.QOperator) ,public com.lealone.sql.expression.evaluator.ExpressionEvaluator createConditionEvaluator(com.lealone.sql.expression.Expression) ,public com.lealone.db.value.Value[] createRow() ,public com.lealone.db.result.LocalResult getLocalResult() ,public boolean isStopped() ,public void onLockedException() ,public void run() ,public void start() ,public void stop() ,public boolean yieldIfNeeded(int) <variables>protected int columnCount,protected final non-sealed com.lealone.sql.expression.evaluator.ExpressionEvaluator conditionEvaluator,protected long limitRows,protected com.lealone.db.result.LocalResult localResult,protected int loopCount,protected boolean loopEnd,protected int maxRows,protected com.lealone.db.result.ResultTarget result,protected int rowCount,protected int sampleSize,protected final non-sealed com.lealone.sql.query.Select select,protected final non-sealed com.lealone.db.session.ServerSession session,protected final non-sealed com.lealone.sql.optimizer.TableIterator tableIterator,protected com.lealone.db.result.ResultTarget target,protected com.lealone.sql.query.YieldableSelect yieldableSelect
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/query/QGroupSorted.java
|
QGroupSorted
|
run
|
class QGroupSorted extends QOperator {
private Value[] previousKeyValues;
QGroupSorted(Select select) {
super(select);
select.currentGroup = null;
}
public Value[] getPreviousKeyValues() {
return previousKeyValues;
}
@Override
public void run() {<FILL_FUNCTION_BODY>}
}
|
while (next()) {
boolean yield = yieldIfNeeded(++loopCount);
if (conditionEvaluator.getBooleanValue()) {
if (select.isForUpdate && !tryLockRow()) {
return; // 锁记录失败
}
rowCount++;
Value[] keyValues = QGroup.getKeyValues(select);
if (previousKeyValues == null) {
previousKeyValues = keyValues;
select.currentGroup = new HashMap<>();
} else if (!Arrays.equals(previousKeyValues, keyValues)) {
QGroup.addGroupRow(select, previousKeyValues, columnCount, result);
previousKeyValues = keyValues;
select.currentGroup = new HashMap<>();
}
select.currentGroupRowId++;
QGroup.updateAggregate(select, columnCount);
if (yield)
return;
}
}
if (previousKeyValues != null) {
QGroup.addGroupRow(select, previousKeyValues, columnCount, result);
}
loopEnd = true;
| 98
| 266
| 364
|
<methods>public void <init>(com.lealone.sql.query.Select) ,public boolean canBreakLoop() ,public void copyStatusTo(com.lealone.sql.query.QOperator) ,public com.lealone.sql.expression.evaluator.ExpressionEvaluator createConditionEvaluator(com.lealone.sql.expression.Expression) ,public com.lealone.db.value.Value[] createRow() ,public com.lealone.db.result.LocalResult getLocalResult() ,public boolean isStopped() ,public void onLockedException() ,public void run() ,public void start() ,public void stop() ,public boolean yieldIfNeeded(int) <variables>protected int columnCount,protected final non-sealed com.lealone.sql.expression.evaluator.ExpressionEvaluator conditionEvaluator,protected long limitRows,protected com.lealone.db.result.LocalResult localResult,protected int loopCount,protected boolean loopEnd,protected int maxRows,protected com.lealone.db.result.ResultTarget result,protected int rowCount,protected int sampleSize,protected final non-sealed com.lealone.sql.query.Select select,protected final non-sealed com.lealone.db.session.ServerSession session,protected final non-sealed com.lealone.sql.optimizer.TableIterator tableIterator,protected com.lealone.db.result.ResultTarget target,protected com.lealone.sql.query.YieldableSelect yieldableSelect
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/query/QOperator.java
|
QOperator
|
start
|
class QOperator implements Operator {
protected final Select select;
protected final ServerSession session;
protected final ExpressionEvaluator conditionEvaluator;
protected final TableIterator tableIterator;
protected int columnCount;
protected ResultTarget target;
protected ResultTarget result;
protected LocalResult localResult;
protected int maxRows; // 实际返回的最大行数
protected long limitRows; // 有可能超过maxRows
protected int sampleSize;
protected int rowCount; // 满足条件的记录数
protected int loopCount; // 循环次数,有可能大于rowCount
protected boolean loopEnd;
protected YieldableSelect yieldableSelect;
public QOperator(Select select) {
this.select = select;
session = select.getSession();
tableIterator = new TableIterator(session, select.getTopTableFilter());
Expression c = select.condition;
// 没有查询条件或者查询条件是常量时看看是否能演算为true,false在IndexCursor.isAlwaysFalse()中已经处理了
if (c == null || (c instanceof ValueExpression && c.getValue(session).getBoolean())) {
conditionEvaluator = new AlwaysTrueEvaluator();
} else {
conditionEvaluator = createConditionEvaluator(c);
}
}
// 允许子类覆盖
public ExpressionEvaluator createConditionEvaluator(Expression c) {
return new ExpressionInterpreter(session, c);
}
public boolean yieldIfNeeded(int rowNumber) {
return yieldableSelect.yieldIfNeeded(rowNumber);
}
public boolean canBreakLoop() {
// 不需要排序时,如果超过行数限制了可以退出循环
if ((select.sort == null || select.sortUsingIndex) && limitRows > 0 && rowCount >= limitRows) {
return true;
}
// 超过采样数也可以退出循环
if (sampleSize > 0 && rowCount >= sampleSize) {
return true;
}
return false;
}
protected boolean next() {
return tableIterator.next();
}
protected boolean tryLockRow() {
return tableIterator.tryLockRow(null) > 0;
}
@Override
public void start() {<FILL_FUNCTION_BODY>}
@Override
public void run() {
}
@Override
public void stop() {
if (select.offsetExpr != null) {
localResult.setOffset(select.offsetExpr.getValue(session).getInt());
}
if (maxRows >= 0) {
localResult.setLimit(maxRows);
}
handleLocalResult();
}
void handleLocalResult() {
if (localResult != null) {
localResult.done();
if (target != null) {
while (localResult.next()) {
target.addRow(localResult.currentRow());
}
localResult.close();
}
}
}
@Override
public boolean isStopped() {
return loopEnd;
}
@Override
public LocalResult getLocalResult() {
return localResult;
}
public Value[] createRow() {
Value[] row = new Value[columnCount];
for (int i = 0; i < columnCount; i++) {
Expression expr = select.expressions.get(i);
row[i] = expr.getValue(session);
}
return row;
}
@Override
public void onLockedException() {
tableIterator.onLockedException();
}
public void copyStatusTo(QOperator o) {
o.columnCount = columnCount;
o.target = target;
o.result = result;
o.localResult = localResult;
o.maxRows = maxRows;
o.limitRows = limitRows;
o.sampleSize = sampleSize;
o.rowCount = rowCount;
o.loopCount = loopCount;
o.yieldableSelect = yieldableSelect;
}
}
|
limitRows = maxRows;
// 并不会按offset先跳过前面的行数,而是limitRows加上offset,读够limitRows+offset行,然后再从result中跳
// 因为可能需要排序,offset是相对于最后的结果来说的,而不是排序前的结果
// limitRows must be long, otherwise we get an int overflow
// if limitRows is at or near Integer.MAX_VALUE
// limitRows is never 0 here
if (limitRows > 0 && select.offsetExpr != null) {
int offset = select.offsetExpr.getValue(session).getInt();
if (offset > 0) {
limitRows += offset;
}
if (limitRows < 0) {
// Overflow
limitRows = Long.MAX_VALUE;
}
}
rowCount = 0;
select.setCurrentRowNumber(0);
sampleSize = select.getSampleSizeValue(session);
tableIterator.start();
| 1,030
| 237
| 1,267
|
<no_super_class>
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/query/QueryResultCache.java
|
QueryResultCache
|
sameParamsAsLast
|
class QueryResultCache {
private final Select select;
private final ServerSession session;
private boolean noCache;
private int lastLimit;
private long lastEvaluated;
private Value[] lastParameters;
private LocalResult lastResult;
private boolean cacheableChecked;
QueryResultCache(Select select) {
this.select = select;
session = select.getSession();
}
void disable() {
noCache = true;
}
boolean isNotCachable() {
return noCache || !session.getDatabase().getOptimizeReuseResults();
}
void setResult(LocalResult r) {
if (isNotCachable())
return;
if (!isDeterministic())
disable();
else
lastResult = r;
}
LocalResult getResult(int limit) {
if (isNotCachable()) {
return null;
} else {
Value[] params = getParameterValues();
long now = session.getDatabase().getModificationDataId();
// 当lastEvaluated != now时,说明数据已经有变化,缓存的结果不能用了
if (lastEvaluated == now && lastResult != null && !lastResult.isClosed()
&& limit == lastLimit) {
if (sameResultAsLast(params)) {
lastResult = lastResult.createShallowCopy(session);
if (lastResult != null) {
lastResult.reset();
return lastResult;
}
}
}
lastLimit = limit;
lastEvaluated = now;
lastParameters = params;
if (lastResult != null) {
lastResult.close();
lastResult = null;
}
return null;
}
}
private boolean isDeterministic() {
return select.accept(ExpressionVisitorFactory.getDeterministicVisitor());
}
private Value[] getParameterValues() {
ArrayList<Parameter> list = select.getParameters();
if (list == null || list.isEmpty()) {
return null;
}
int size = list.size();
Value[] params = new Value[size];
for (int i = 0; i < size; i++) {
params[i] = list.get(i).getValue();
}
return params;
}
private boolean sameResultAsLast(Value[] params) {
if (!cacheableChecked) {
long max = select.getMaxDataModificationId();
noCache = max == Long.MAX_VALUE;
cacheableChecked = true;
}
if (noCache) {
return false;
}
Database db = session.getDatabase();
if (!sameParamsAsLast(db, params))
return false;
if (!select.accept(ExpressionVisitorFactory.getIndependentVisitor())) {
return false;
}
if (db.getModificationDataId() > lastEvaluated
&& select.getMaxDataModificationId() > lastEvaluated) {
return false;
}
return true;
}
private boolean sameParamsAsLast(Database db, Value[] params) {<FILL_FUNCTION_BODY>}
}
|
if (params == null && lastParameters == null)
return true;
if (params != null && lastParameters != null) {
if (params.length != lastParameters.length)
return false;
for (int i = 0; i < params.length; i++) {
Value a = lastParameters[i], b = params[i];
if (a.getType() != b.getType() || !db.areEqual(a, b)) {
return false;
}
}
return true;
}
return false;
| 810
| 143
| 953
|
<no_super_class>
|
lealone_Lealone
|
Lealone/lealone-sql/src/main/java/com/lealone/sql/query/YieldableSelect.java
|
YieldableSelect
|
executeInternal
|
class YieldableSelect extends YieldableQueryBase {
private final Select select;
private final ResultTarget target;
private final int olapThreshold;
private boolean olapDisabled;
private Operator queryOperator;
public YieldableSelect(Select select, int maxRows, boolean scrollable,
AsyncHandler<AsyncResult<Result>> asyncHandler, ResultTarget target) {
super(select, maxRows, scrollable, asyncHandler);
this.select = select;
this.target = target;
this.olapThreshold = session.getOlapThreshold();
}
@Override
public boolean yieldIfNeeded(int rowNumber) {
if (!olapDisabled && olapThreshold > 0 && rowNumber > olapThreshold) {
olapDisabled = true;
boolean yield = super.yieldIfNeeded(rowNumber);
Operator olapOperator = createOlapOperator();
if (olapOperator != null) {
queryOperator = olapOperator;
yield = true; // olapOperator创建成功后让出执行权
session.setStatus(SessionStatus.STATEMENT_YIELDED);
}
return yield;
}
return super.yieldIfNeeded(rowNumber);
}
// 一些像QDistinct这样的Operator无需从oltp转到olap,可以禁用olap
public void disableOlap() {
olapDisabled = true;
}
private Operator createOlapOperator() {
Operator olapOperator = null;
String olapOperatorFactoryName = session.getOlapOperatorFactoryName();
if (olapOperatorFactoryName == null) {
olapOperatorFactoryName = "olap";
}
OperatorFactory operatorFactory = PluginManager.getPlugin(OperatorFactory.class,
olapOperatorFactoryName);
if (operatorFactory != null) {
olapOperator = operatorFactory.createOperator(select, queryOperator.getLocalResult());
olapOperator.start();
olapOperator.copyStatus(queryOperator);
}
return olapOperator;
}
@Override
protected boolean startInternal() {
// select.getTopTableFilter().lock(session, select.isForUpdate);
select.fireBeforeSelectTriggers();
queryOperator = createQueryOperator();
queryOperator.start();
return false;
}
@Override
protected void stopInternal() {
// 执行startInternal抛异常时queryOperator可能为null
if (queryOperator != null)
queryOperator.stop();
}
@Override
protected void executeInternal() {<FILL_FUNCTION_BODY>}
private QOperator createQueryOperator() {
LocalResult result;
ResultTarget to;
QOperator queryOperator;
int limitRows = getLimitRows(maxRows);
LocalResult cachedResult = select.resultCache.getResult(maxRows); // 不直接用limitRows
if (cachedResult != null) {
result = cachedResult;
to = cachedResult;
queryOperator = new QCache(select, cachedResult);
} else {
result = createLocalResultIfNeeded(limitRows);
to = result != null ? result : target;
if (limitRows != 0) {
if (select.isQuickAggregateQuery) {
queryOperator = new QAggregateQuick(select);
} else if (select.isGroupQuery) {
if (select.isGroupSortedQuery) {
queryOperator = new QGroupSorted(select);
} else {
if (select.groupIndex == null) { // 忽视select.havingIndex
queryOperator = new QAggregate(select);
} else {
queryOperator = new QGroup(select);
}
}
} else if (select.isDistinctQuery) {
queryOperator = new QDistinct(select);
} else {
queryOperator = new QFlat(select);
}
} else {
queryOperator = new QEmpty(select);
}
}
queryOperator.columnCount = select.expressions.size();
queryOperator.maxRows = limitRows;
queryOperator.target = target;
queryOperator.result = to;
queryOperator.localResult = result;
queryOperator.yieldableSelect = this;
return queryOperator;
}
private int getLimitRows(int maxRows) {
// 按JDBC规范的要求,当调用java.sql.Statement.setMaxRows时,
// 如果maxRows是0,表示不限制行数,相当于没有调用过setMaxRows一样,
// 如果小余0,已经在客户端抛了无效参数异常,所以这里统一处理: 当limitRows小于0时表示不限制行数。
int limitRows = maxRows == 0 ? -1 : maxRows;
if (select.limitExpr != null) {
// 如果在select语句中又指定了limit子句,那么用它覆盖maxRows
// 注意limit 0表示不取任何记录,跟maxRows为0时刚好相反
Value v = select.limitExpr.getValue(session);
int l = v == ValueNull.INSTANCE ? -1 : v.getInt();
if (limitRows < 0) {
limitRows = l;
} else if (l >= 0) {
limitRows = Math.min(l, limitRows);
}
}
return limitRows;
}
private LocalResult createLocalResultIfNeeded(int limitRows) {
LocalResult result = null;
if (target == null || !session.getDatabase().getSettings().optimizeInsertFromSelect) {
result = createLocalResult(result);
}
if (select.sort != null && (!select.sortUsingIndex || select.distinct)) {
result = createLocalResult(result);
result.setSortOrder(select.sort);
}
if (select.distinct && !select.isDistinctQuery) {
result = createLocalResult(result);
result.setDistinct();
}
if (select.isGroupQuery && !select.isGroupSortedQuery) {
result = createLocalResult(result);
}
if (limitRows >= 0 || select.offsetExpr != null) {
result = createLocalResult(result);
}
return result;
}
private LocalResult createLocalResult(LocalResult old) {
return old != null ? old
: new LocalResult(session, select.expressionArray, select.visibleColumnCount,
select.rawExpressionInfoList);
}
}
|
while (true) {
session.setStatus(SessionStatus.STATEMENT_RUNNING);
try {
queryOperator.run();
} catch (RuntimeException e) {
if (DbObjectLock.LOCKED_EXCEPTION == e) {
queryOperator.onLockedException();
} else {
throw e;
}
}
if (queryOperator.isStopped()) {
// 查询结果已经增加到target了
if (target != null) {
session.setStatus(SessionStatus.STATEMENT_COMPLETED);
} else if (queryOperator.getLocalResult() != null) {
LocalResult r = queryOperator.getLocalResult();
setResult(r, r.getRowCount());
select.resultCache.setResult(r);
session.setStatus(SessionStatus.STATEMENT_COMPLETED);
}
break;
}
if (session.getStatus() == SessionStatus.STATEMENT_YIELDED
|| session.getStatus() == SessionStatus.WAITING) {
return;
}
}
| 1,636
| 273
| 1,909
|
<methods>public void <init>(com.lealone.sql.StatementBase, int, boolean, AsyncHandler<AsyncResult<com.lealone.db.result.Result>>) <variables>protected final non-sealed int maxRows,protected final non-sealed boolean scrollable
|
pagehelper_Mybatis-PageHelper
|
Mybatis-PageHelper/src/main/java/com/github/pagehelper/BoundSqlInterceptorChain.java
|
BoundSqlInterceptorChain
|
_doBoundSql
|
class BoundSqlInterceptorChain implements BoundSqlInterceptor.Chain {
private final BoundSqlInterceptor.Chain original;
private final List<BoundSqlInterceptor> interceptors;
private int index = 0;
private boolean executable;
public BoundSqlInterceptorChain(BoundSqlInterceptor.Chain original, List<BoundSqlInterceptor> interceptors) {
this(original, interceptors, false);
}
private BoundSqlInterceptorChain(BoundSqlInterceptor.Chain original, List<BoundSqlInterceptor> interceptors, boolean executable) {
this.original = original;
this.interceptors = interceptors;
this.executable = executable;
}
@Override
public BoundSql doBoundSql(BoundSqlInterceptor.Type type, BoundSql boundSql, CacheKey cacheKey) {
if(executable) {
return _doBoundSql(type, boundSql, cacheKey);
} else {
return new BoundSqlInterceptorChain(original, interceptors, true).doBoundSql(type, boundSql, cacheKey);
}
}
private BoundSql _doBoundSql(BoundSqlInterceptor.Type type, BoundSql boundSql, CacheKey cacheKey) {<FILL_FUNCTION_BODY>}
}
|
if (this.interceptors == null || this.interceptors.size() == this.index) {
return this.original != null ? this.original.doBoundSql(type, boundSql, cacheKey) : boundSql;
} else {
return this.interceptors.get(this.index++).boundSql(type, boundSql, cacheKey, this);
}
| 334
| 96
| 430
|
<no_super_class>
|
pagehelper_Mybatis-PageHelper
|
Mybatis-PageHelper/src/main/java/com/github/pagehelper/PageHelper.java
|
PageHelper
|
setProperties
|
class PageHelper extends PageMethod implements Dialect, BoundSqlInterceptor.Chain {
private PageParams pageParams;
private PageAutoDialect autoDialect;
private PageBoundSqlInterceptors pageBoundSqlInterceptors;
private ForkJoinPool asyncCountService;
@Override
public boolean skip(MappedStatement ms, Object parameterObject, RowBounds rowBounds) {
Page page = pageParams.getPage(parameterObject, rowBounds);
if (page == null) {
return true;
} else {
//设置默认的 count 列
if (StringUtil.isEmpty(page.getCountColumn())) {
page.setCountColumn(pageParams.getCountColumn());
}
//设置默认的异步 count 设置
if (page.getAsyncCount() == null) {
page.setAsyncCount(pageParams.isAsyncCount());
}
autoDialect.initDelegateDialect(ms, page.getDialectClass());
return false;
}
}
@Override
public boolean isAsyncCount() {
return getLocalPage().asyncCount();
}
@Override
public <T> Future<T> asyncCountTask(Callable<T> task) {
//异步执行时需要将ThreadLocal值传递,否则会找不到
AbstractHelperDialect dialectThreadLocal = autoDialect.getDialectThreadLocal();
Page<Object> localPage = getLocalPage();
String countId = UUID.randomUUID().toString();
return asyncCountService.submit(() -> {
try {
//设置 ThreadLocal
autoDialect.setDialectThreadLocal(dialectThreadLocal);
setLocalPage(localPage);
return task.call();
} finally {
autoDialect.clearDelegate();
clearPage();
}
});
}
@Override
public boolean beforeCount(MappedStatement ms, Object parameterObject, RowBounds rowBounds) {
return autoDialect.getDelegate().beforeCount(ms, parameterObject, rowBounds);
}
@Override
public String getCountSql(MappedStatement ms, BoundSql boundSql, Object parameterObject, RowBounds rowBounds, CacheKey countKey) {
return autoDialect.getDelegate().getCountSql(ms, boundSql, parameterObject, rowBounds, countKey);
}
@Override
public boolean afterCount(long count, Object parameterObject, RowBounds rowBounds) {
return autoDialect.getDelegate().afterCount(count, parameterObject, rowBounds);
}
@Override
public Object processParameterObject(MappedStatement ms, Object parameterObject, BoundSql boundSql, CacheKey pageKey) {
return autoDialect.getDelegate().processParameterObject(ms, parameterObject, boundSql, pageKey);
}
@Override
public boolean beforePage(MappedStatement ms, Object parameterObject, RowBounds rowBounds) {
return autoDialect.getDelegate().beforePage(ms, parameterObject, rowBounds);
}
@Override
public String getPageSql(MappedStatement ms, BoundSql boundSql, Object parameterObject, RowBounds rowBounds, CacheKey pageKey) {
return autoDialect.getDelegate().getPageSql(ms, boundSql, parameterObject, rowBounds, pageKey);
}
public String getPageSql(String sql, Page page, RowBounds rowBounds, CacheKey pageKey) {
return autoDialect.getDelegate().getPageSql(sql, page, pageKey);
}
@Override
public Object afterPage(List pageList, Object parameterObject, RowBounds rowBounds) {
//这个方法即使不分页也会被执行,所以要判断 null
AbstractHelperDialect delegate = autoDialect.getDelegate();
if (delegate != null) {
return delegate.afterPage(pageList, parameterObject, rowBounds);
}
return pageList;
}
@Override
public void afterAll() {
//这个方法即使不分页也会被执行,所以要判断 null
AbstractHelperDialect delegate = autoDialect.getDelegate();
if (delegate != null) {
delegate.afterAll();
autoDialect.clearDelegate();
}
clearPage();
}
@Override
public BoundSql doBoundSql(BoundSqlInterceptor.Type type, BoundSql boundSql, CacheKey cacheKey) {
Page<Object> localPage = getLocalPage();
BoundSqlInterceptor.Chain chain = localPage != null ? localPage.getChain() : null;
if (chain == null) {
BoundSqlInterceptor boundSqlInterceptor = localPage != null ? localPage.getBoundSqlInterceptor() : null;
BoundSqlInterceptor.Chain defaultChain = pageBoundSqlInterceptors != null ? pageBoundSqlInterceptors.getChain() : null;
if (boundSqlInterceptor != null) {
chain = new BoundSqlInterceptorChain(defaultChain, Arrays.asList(boundSqlInterceptor));
} else if (defaultChain != null) {
chain = defaultChain;
}
if (chain == null) {
chain = DO_NOTHING;
}
if (localPage != null) {
localPage.setChain(chain);
}
}
return chain.doBoundSql(type, boundSql, cacheKey);
}
@Override
public void setProperties(Properties properties) {<FILL_FUNCTION_BODY>}
}
|
setStaticProperties(properties);
pageParams = new PageParams();
autoDialect = new PageAutoDialect();
pageBoundSqlInterceptors = new PageBoundSqlInterceptors();
pageParams.setProperties(properties);
autoDialect.setProperties(properties);
pageBoundSqlInterceptors.setProperties(properties);
//20180902新增 aggregateFunctions, 允许手动添加聚合函数(影响行数)
CountSqlParser.addAggregateFunctions(properties.getProperty("aggregateFunctions"));
// 异步 asyncCountService 并发度设置,这里默认为应用可用的处理器核心数 * 2,更合理的值应该综合考虑数据库服务器的处理能力
int asyncCountParallelism = Integer.parseInt(properties.getProperty("asyncCountParallelism",
"" + (Runtime.getRuntime().availableProcessors() * 2)));
asyncCountService = new ForkJoinPool(asyncCountParallelism,
pool -> {
final ForkJoinWorkerThread worker = ForkJoinPool.defaultForkJoinWorkerThreadFactory.newThread(pool);
worker.setName("pagehelper-async-count-" + worker.getPoolIndex());
return worker;
}, null, true);
| 1,381
| 316
| 1,697
|
<methods>public non-sealed void <init>() ,public static void clearPage() ,public static long count(com.github.pagehelper.ISelect) ,public static Page<T> getLocalPage() ,public static Page<E> offsetPage(int, int) ,public static Page<E> offsetPage(int, int, boolean) ,public static void orderBy(java.lang.String) ,public static void setLocalPage(Page#RAW) ,public static Page<E> startPage(java.lang.Object) ,public static Page<E> startPage(int, int) ,public static Page<E> startPage(int, int, boolean) ,public static Page<E> startPage(int, int, java.lang.String) ,public static Page<E> startPage(int, int, boolean, java.lang.Boolean, java.lang.Boolean) <variables>protected static boolean DEFAULT_COUNT,protected static final ThreadLocal<Page#RAW> LOCAL_PAGE
|
pagehelper_Mybatis-PageHelper
|
Mybatis-PageHelper/src/main/java/com/github/pagehelper/PageSerializable.java
|
PageSerializable
|
toString
|
class PageSerializable<T> implements Serializable {
private static final long serialVersionUID = 1L;
//总记录数
protected long total;
//结果集
protected List<T> list;
public PageSerializable() {
}
@SuppressWarnings("unchecked")
public PageSerializable(List<? extends T> list) {
this.list = (List<T>) list;
if(list instanceof Page){
this.total = ((Page<?>)list).getTotal();
} else {
this.total = list.size();
}
}
public static <T> PageSerializable<T> of(List<? extends T> list){
return new PageSerializable<T>(list);
}
public long getTotal() {
return total;
}
public void setTotal(long total) {
this.total = total;
}
public List<T> getList() {
return list;
}
public void setList(List<T> list) {
this.list = list;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "PageSerializable{" +
"total=" + total +
", list=" + list +
'}';
| 306
| 35
| 341
|
<no_super_class>
|
pagehelper_Mybatis-PageHelper
|
Mybatis-PageHelper/src/main/java/com/github/pagehelper/QueryInterceptor.java
|
QueryInterceptor
|
intercept
|
class QueryInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {<FILL_FUNCTION_BODY>}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
}
}
|
Object[] args = invocation.getArgs();
MappedStatement ms = (MappedStatement) args[0];
Object parameter = args[1];
RowBounds rowBounds = (RowBounds) args[2];
ResultHandler resultHandler = (ResultHandler) args[3];
Executor executor = (Executor) invocation.getTarget();
CacheKey cacheKey;
BoundSql boundSql;
//由于逻辑关系,只会进入一次
if(args.length == 4){
//4 个参数时
boundSql = ms.getBoundSql(parameter);
cacheKey = executor.createCacheKey(ms, parameter, rowBounds, boundSql);
} else {
//6 个参数时
cacheKey = (CacheKey) args[4];
boundSql = (BoundSql) args[5];
}
//TODO 自己要进行的各种处理
//注:下面的方法可以根据自己的逻辑调用多次,在分页插件中,count 和 page 各调用了一次
return executor.query(ms, parameter, rowBounds, resultHandler, cacheKey, boundSql);
| 97
| 277
| 374
|
<no_super_class>
|
pagehelper_Mybatis-PageHelper
|
Mybatis-PageHelper/src/main/java/com/github/pagehelper/cache/CacheFactory.java
|
CacheFactory
|
createCache
|
class CacheFactory {
/**
* 创建 SQL 缓存
*
* @param sqlCacheClass
* @return
*/
public static <K, V> Cache<K, V> createCache(String sqlCacheClass, String prefix, Properties properties) {<FILL_FUNCTION_BODY>}
}
|
if (StringUtil.isEmpty(sqlCacheClass)) {
try {
Class.forName("com.google.common.cache.Cache");
return new GuavaCache<K, V>(properties, prefix);
} catch (Throwable t) {
return new SimpleCache<K, V>(properties, prefix);
}
} else {
try {
Class<? extends Cache> clazz = (Class<? extends Cache>) Class.forName(sqlCacheClass);
try {
Constructor<? extends Cache> constructor = clazz.getConstructor(Properties.class, String.class);
return constructor.newInstance(properties, prefix);
} catch (Exception e) {
Cache cache = clazz.newInstance();
if (cache instanceof PageProperties) {
((PageProperties) cache).setProperties(properties);
}
return cache;
}
} catch (Throwable t) {
throw new PageException("Created Sql Cache [" + sqlCacheClass + "] Error", t);
}
}
| 82
| 254
| 336
|
<no_super_class>
|
pagehelper_Mybatis-PageHelper
|
Mybatis-PageHelper/src/main/java/com/github/pagehelper/cache/SimpleCache.java
|
SimpleCache
|
get
|
class SimpleCache<K, V> implements Cache<K, V> {
private final org.apache.ibatis.cache.Cache CACHE;
public SimpleCache(Properties properties, String prefix) {
CacheBuilder cacheBuilder = new CacheBuilder("SQL_CACHE");
String typeClass = properties.getProperty(prefix + ".typeClass");
if (StringUtil.isNotEmpty(typeClass)) {
try {
cacheBuilder.implementation((Class<? extends org.apache.ibatis.cache.Cache>) Class.forName(typeClass));
} catch (ClassNotFoundException e) {
cacheBuilder.implementation(PerpetualCache.class);
}
} else {
cacheBuilder.implementation(PerpetualCache.class);
}
String evictionClass = properties.getProperty(prefix + ".evictionClass");
if (StringUtil.isNotEmpty(evictionClass)) {
try {
cacheBuilder.addDecorator((Class<? extends org.apache.ibatis.cache.Cache>) Class.forName(evictionClass));
} catch (ClassNotFoundException e) {
cacheBuilder.addDecorator(FifoCache.class);
}
} else {
cacheBuilder.addDecorator(FifoCache.class);
}
String flushInterval = properties.getProperty(prefix + ".flushInterval");
if (StringUtil.isNotEmpty(flushInterval)) {
cacheBuilder.clearInterval(Long.parseLong(flushInterval));
}
String size = properties.getProperty(prefix + ".size");
if (StringUtil.isNotEmpty(size)) {
cacheBuilder.size(Integer.parseInt(size));
}
cacheBuilder.properties(properties);
CACHE = cacheBuilder.build();
}
@Override
public V get(K key) {<FILL_FUNCTION_BODY>}
@Override
public void put(K key, V value) {
CACHE.putObject(key, value);
}
}
|
Object value = CACHE.getObject(key);
if (value != null) {
return (V) value;
}
return null;
| 503
| 43
| 546
|
<no_super_class>
|
pagehelper_Mybatis-PageHelper
|
Mybatis-PageHelper/src/main/java/com/github/pagehelper/dialect/AbstractRowBoundsDialect.java
|
AbstractRowBoundsDialect
|
beforeCount
|
class AbstractRowBoundsDialect extends AbstractDialect {
@Override
public boolean skip(MappedStatement ms, Object parameterObject, RowBounds rowBounds) {
return rowBounds == RowBounds.DEFAULT;
}
@Override
public boolean beforeCount(MappedStatement ms, Object parameterObject, RowBounds rowBounds) {<FILL_FUNCTION_BODY>}
@Override
public boolean afterCount(long count, Object parameterObject, RowBounds rowBounds) {
//由于 beforeCount 校验,这里一定是 PageRowBounds
((PageRowBounds) rowBounds).setTotal(count);
return count > 0;
}
@Override
public Object processParameterObject(MappedStatement ms, Object parameterObject, BoundSql boundSql, CacheKey pageKey) {
return parameterObject;
}
@Override
public boolean beforePage(MappedStatement ms, Object parameterObject, RowBounds rowBounds) {
return true;
}
@Override
public String getPageSql(MappedStatement ms, BoundSql boundSql, Object parameterObject, RowBounds rowBounds, CacheKey pageKey) {
String sql = boundSql.getSql();
return getPageSql(sql, rowBounds, pageKey);
}
public abstract String getPageSql(String sql, RowBounds rowBounds, CacheKey pageKey);
@Override
public Object afterPage(List pageList, Object parameterObject, RowBounds rowBounds) {
return pageList;
}
@Override
public void afterAll() {
}
@Override
public void setProperties(Properties properties) {
super.setProperties(properties);
}
}
|
if(rowBounds instanceof PageRowBounds){
PageRowBounds pageRowBounds = (PageRowBounds)rowBounds;
return pageRowBounds.getCount() == null || pageRowBounds.getCount();
}
return false;
| 410
| 59
| 469
|
<methods>public non-sealed void <init>() ,public java.lang.String getCountSql(org.apache.ibatis.mapping.MappedStatement, org.apache.ibatis.mapping.BoundSql, java.lang.Object, org.apache.ibatis.session.RowBounds, org.apache.ibatis.cache.CacheKey) ,public void setProperties(java.util.Properties) <variables>protected com.github.pagehelper.parser.CountSqlParser countSqlParser,protected com.github.pagehelper.parser.OrderBySqlParser orderBySqlParser
|
pagehelper_Mybatis-PageHelper
|
Mybatis-PageHelper/src/main/java/com/github/pagehelper/dialect/auto/DataSourceAutoDialect.java
|
DataSourceAutoDialect
|
extractDialectKey
|
class DataSourceAutoDialect<Ds extends DataSource> implements AutoDialect<String> {
protected Class dataSourceClass;
public DataSourceAutoDialect() {
Type genericSuperclass = getClass().getGenericSuperclass();
dataSourceClass = (Class) ((ParameterizedType) genericSuperclass).getActualTypeArguments()[0];
}
public abstract String getJdbcUrl(Ds ds);
@Override
public String extractDialectKey(MappedStatement ms, DataSource dataSource, Properties properties) {<FILL_FUNCTION_BODY>}
@Override
public AbstractHelperDialect extractDialect(String dialectKey, MappedStatement ms, DataSource dataSource, Properties properties) {
String dialect = PageAutoDialect.fromJdbcUrl(dialectKey);
return PageAutoDialect.instanceDialect(dialect, properties);
}
}
|
if (dataSourceClass.isInstance(dataSource)) {
return getJdbcUrl((Ds) dataSource);
}
return null;
| 227
| 40
| 267
|
<no_super_class>
|
pagehelper_Mybatis-PageHelper
|
Mybatis-PageHelper/src/main/java/com/github/pagehelper/dialect/auto/DataSourceNegotiationAutoDialect.java
|
DataSourceNegotiationAutoDialect
|
extractDialectKey
|
class DataSourceNegotiationAutoDialect implements AutoDialect<String> {
private static final List<DataSourceAutoDialect> AUTO_DIALECTS = new ArrayList<DataSourceAutoDialect>();
private Map<String, DataSourceAutoDialect> urlMap = new ConcurrentHashMap<String, DataSourceAutoDialect>();
static {
//创建时,初始化所有实现,当依赖的连接池不存在时,这里不会添加成功,所以理论上这里包含的内容不会多,执行时不会迭代多次
try {
AUTO_DIALECTS.add(new HikariAutoDialect());
} catch (Exception ignore) {
}
try {
AUTO_DIALECTS.add(new DruidAutoDialect());
} catch (Exception ignore) {
}
try {
AUTO_DIALECTS.add(new TomcatAutoDialect());
} catch (Exception ignore) {
}
try {
AUTO_DIALECTS.add(new C3P0AutoDialect());
} catch (Exception ignore) {
}
try {
AUTO_DIALECTS.add(new DbcpAutoDialect());
} catch (Exception ignore) {
}
}
/**
* 允许手工添加额外的实现,实际上没有必要
*
* @param autoDialect
*/
public static void registerAutoDialect(DataSourceAutoDialect autoDialect) {
AUTO_DIALECTS.add(autoDialect);
}
@Override
public String extractDialectKey(MappedStatement ms, DataSource dataSource, Properties properties) {<FILL_FUNCTION_BODY>}
@Override
public AbstractHelperDialect extractDialect(String dialectKey, MappedStatement ms, DataSource dataSource, Properties properties) {
if (dialectKey != null && urlMap.containsKey(dialectKey)) {
return urlMap.get(dialectKey).extractDialect(dialectKey, ms, dataSource, properties);
}
//都不匹配的时候使用默认方式
return DefaultAutoDialect.DEFAULT.extractDialect(dialectKey, ms, dataSource, properties);
}
}
|
for (DataSourceAutoDialect autoDialect : AUTO_DIALECTS) {
String dialectKey = autoDialect.extractDialectKey(ms, dataSource, properties);
if (dialectKey != null) {
if (!urlMap.containsKey(dialectKey)) {
urlMap.put(dialectKey, autoDialect);
}
return dialectKey;
}
}
//都不匹配的时候使用默认方式
return DefaultAutoDialect.DEFAULT.extractDialectKey(ms, dataSource, properties);
| 583
| 149
| 732
|
<no_super_class>
|
pagehelper_Mybatis-PageHelper
|
Mybatis-PageHelper/src/main/java/com/github/pagehelper/dialect/auto/DefaultAutoDialect.java
|
DefaultAutoDialect
|
extractDialectKey
|
class DefaultAutoDialect implements AutoDialect<String> {
public static final AutoDialect<String> DEFAULT = new DefaultAutoDialect();
@Override
public String extractDialectKey(MappedStatement ms, DataSource dataSource, Properties properties) {<FILL_FUNCTION_BODY>}
@Override
public AbstractHelperDialect extractDialect(String dialectKey, MappedStatement ms, DataSource dataSource, Properties properties) {
String dialectStr = PageAutoDialect.fromJdbcUrl(dialectKey);
if (dialectStr == null) {
throw new PageException("The database type cannot be obtained automatically, please specify it via the helperDialect parameter!");
}
return PageAutoDialect.instanceDialect(dialectStr, properties);
}
}
|
Connection conn = null;
try {
conn = dataSource.getConnection();
return conn.getMetaData().getURL();
} catch (SQLException e) {
throw new PageException(e);
} finally {
if (conn != null) {
try {
String closeConn = properties.getProperty("closeConn");
if (StringUtil.isEmpty(closeConn) || Boolean.parseBoolean(closeConn)) {
conn.close();
}
} catch (SQLException e) {
//ignore
}
}
}
| 205
| 146
| 351
|
<no_super_class>
|
pagehelper_Mybatis-PageHelper
|
Mybatis-PageHelper/src/main/java/com/github/pagehelper/dialect/helper/AS400Dialect.java
|
AS400Dialect
|
processPageParameter
|
class AS400Dialect extends AbstractHelperDialect {
@Override
public Object processPageParameter(MappedStatement ms, Map<String, Object> paramMap,
Page page, BoundSql boundSql, CacheKey pageKey) {<FILL_FUNCTION_BODY>}
@Override
public String getPageSql(String sql, Page page, CacheKey pageKey) {
return sql + " OFFSET ? ROWS FETCH FIRST ? ROWS ONLY";
}
}
|
paramMap.put(PAGEPARAMETER_FIRST, page.getStartRow());
paramMap.put(PAGEPARAMETER_SECOND, page.getPageSize());
pageKey.update(page.getStartRow());
pageKey.update(page.getPageSize());
handleParameter(boundSql, ms, long.class, int.class);
return paramMap;
| 121
| 103
| 224
|
<methods>public non-sealed void <init>() ,public void afterAll() ,public boolean afterCount(long, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public java.lang.Object afterPage(List#RAW, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public boolean beforeCount(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public boolean beforePage(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public java.lang.String getCountSql(org.apache.ibatis.mapping.MappedStatement, org.apache.ibatis.mapping.BoundSql, java.lang.Object, org.apache.ibatis.session.RowBounds, org.apache.ibatis.cache.CacheKey) ,public Page<T> getLocalPage() ,public java.lang.String getPageSql(org.apache.ibatis.mapping.MappedStatement, org.apache.ibatis.mapping.BoundSql, java.lang.Object, org.apache.ibatis.session.RowBounds, org.apache.ibatis.cache.CacheKey) ,public abstract java.lang.String getPageSql(java.lang.String, Page#RAW, org.apache.ibatis.cache.CacheKey) ,public abstract java.lang.Object processPageParameter(org.apache.ibatis.mapping.MappedStatement, Map<java.lang.String,java.lang.Object>, Page#RAW, org.apache.ibatis.mapping.BoundSql, org.apache.ibatis.cache.CacheKey) ,public java.lang.Object processParameterObject(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.mapping.BoundSql, org.apache.ibatis.cache.CacheKey) ,public void setProperties(java.util.Properties) ,public final boolean skip(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) <variables>
|
pagehelper_Mybatis-PageHelper
|
Mybatis-PageHelper/src/main/java/com/github/pagehelper/dialect/helper/CirroDataDialect.java
|
CirroDataDialect
|
getPageSql
|
class CirroDataDialect extends AbstractHelperDialect {
@Override
public Object processPageParameter(MappedStatement ms, Map<String, Object> paramMap, Page page, BoundSql boundSql, CacheKey pageKey) {
paramMap.put(PAGEPARAMETER_FIRST, page.getStartRow() + 1);
paramMap.put(PAGEPARAMETER_SECOND, page.getEndRow());
//处理pageKey
pageKey.update(page.getStartRow() + 1);
pageKey.update(page.getEndRow());
//处理参数配置
handleParameter(boundSql, ms, long.class, long.class);
return paramMap;
}
@Override
public String getPageSql(String sql, Page page, CacheKey pageKey) {<FILL_FUNCTION_BODY>}
}
|
StringBuilder sqlBuilder = new StringBuilder(sql.length() + 16);
sqlBuilder.append(sql);
sqlBuilder.append("\n LIMIT ( ?, ? )");
return sqlBuilder.toString();
| 213
| 54
| 267
|
<methods>public non-sealed void <init>() ,public void afterAll() ,public boolean afterCount(long, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public java.lang.Object afterPage(List#RAW, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public boolean beforeCount(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public boolean beforePage(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public java.lang.String getCountSql(org.apache.ibatis.mapping.MappedStatement, org.apache.ibatis.mapping.BoundSql, java.lang.Object, org.apache.ibatis.session.RowBounds, org.apache.ibatis.cache.CacheKey) ,public Page<T> getLocalPage() ,public java.lang.String getPageSql(org.apache.ibatis.mapping.MappedStatement, org.apache.ibatis.mapping.BoundSql, java.lang.Object, org.apache.ibatis.session.RowBounds, org.apache.ibatis.cache.CacheKey) ,public abstract java.lang.String getPageSql(java.lang.String, Page#RAW, org.apache.ibatis.cache.CacheKey) ,public abstract java.lang.Object processPageParameter(org.apache.ibatis.mapping.MappedStatement, Map<java.lang.String,java.lang.Object>, Page#RAW, org.apache.ibatis.mapping.BoundSql, org.apache.ibatis.cache.CacheKey) ,public java.lang.Object processParameterObject(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.mapping.BoundSql, org.apache.ibatis.cache.CacheKey) ,public void setProperties(java.util.Properties) ,public final boolean skip(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) <variables>
|
pagehelper_Mybatis-PageHelper
|
Mybatis-PageHelper/src/main/java/com/github/pagehelper/dialect/helper/Db2Dialect.java
|
Db2Dialect
|
getPageSql
|
class Db2Dialect extends AbstractHelperDialect {
@Override
public Object processPageParameter(MappedStatement ms, Map<String, Object> paramMap, Page page, BoundSql boundSql, CacheKey pageKey) {
paramMap.put(PAGEPARAMETER_FIRST, page.getStartRow() + 1);
paramMap.put(PAGEPARAMETER_SECOND, page.getEndRow());
//处理pageKey
pageKey.update(page.getStartRow() + 1);
pageKey.update(page.getEndRow());
//处理参数配置
handleParameter(boundSql, ms, long.class, long.class);
return paramMap;
}
@Override
public String getPageSql(String sql, Page page, CacheKey pageKey) {<FILL_FUNCTION_BODY>}
}
|
StringBuilder sqlBuilder = new StringBuilder(sql.length() + 140);
sqlBuilder.append("SELECT * FROM (SELECT TMP_PAGE.*,ROWNUMBER() OVER() AS PAGEHELPER_ROW_ID FROM ( \n");
sqlBuilder.append(sql);
sqlBuilder.append("\n ) AS TMP_PAGE) TMP_PAGE WHERE PAGEHELPER_ROW_ID BETWEEN ? AND ?");
return sqlBuilder.toString();
| 213
| 120
| 333
|
<methods>public non-sealed void <init>() ,public void afterAll() ,public boolean afterCount(long, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public java.lang.Object afterPage(List#RAW, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public boolean beforeCount(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public boolean beforePage(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public java.lang.String getCountSql(org.apache.ibatis.mapping.MappedStatement, org.apache.ibatis.mapping.BoundSql, java.lang.Object, org.apache.ibatis.session.RowBounds, org.apache.ibatis.cache.CacheKey) ,public Page<T> getLocalPage() ,public java.lang.String getPageSql(org.apache.ibatis.mapping.MappedStatement, org.apache.ibatis.mapping.BoundSql, java.lang.Object, org.apache.ibatis.session.RowBounds, org.apache.ibatis.cache.CacheKey) ,public abstract java.lang.String getPageSql(java.lang.String, Page#RAW, org.apache.ibatis.cache.CacheKey) ,public abstract java.lang.Object processPageParameter(org.apache.ibatis.mapping.MappedStatement, Map<java.lang.String,java.lang.Object>, Page#RAW, org.apache.ibatis.mapping.BoundSql, org.apache.ibatis.cache.CacheKey) ,public java.lang.Object processParameterObject(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.mapping.BoundSql, org.apache.ibatis.cache.CacheKey) ,public void setProperties(java.util.Properties) ,public final boolean skip(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) <variables>
|
pagehelper_Mybatis-PageHelper
|
Mybatis-PageHelper/src/main/java/com/github/pagehelper/dialect/helper/FirebirdDialect.java
|
FirebirdDialect
|
getPageSql
|
class FirebirdDialect extends AbstractHelperDialect {
@Override
public Object processPageParameter(MappedStatement ms, Map<String, Object> paramMap, Page page, BoundSql boundSql, CacheKey pageKey) {
paramMap.put(PAGEPARAMETER_FIRST, page.getStartRow());
paramMap.put(PAGEPARAMETER_SECOND, page.getPageSize());
//处理pageKey
pageKey.update(page.getStartRow());
pageKey.update(page.getPageSize());
//处理参数配置
handleParameter(boundSql, ms, long.class, int.class);
return paramMap;
}
@Override
public String getPageSql(String sql, Page page, CacheKey pageKey) {<FILL_FUNCTION_BODY>}
}
|
StringBuilder sqlBuilder = new StringBuilder(sql.length() + 64);
sqlBuilder.append(sql);
sqlBuilder.append("\n OFFSET ? ROWS FETCH NEXT ? ROWS ONLY ");
pageKey.update(page.getPageSize());
return sqlBuilder.toString();
| 206
| 77
| 283
|
<methods>public non-sealed void <init>() ,public void afterAll() ,public boolean afterCount(long, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public java.lang.Object afterPage(List#RAW, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public boolean beforeCount(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public boolean beforePage(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public java.lang.String getCountSql(org.apache.ibatis.mapping.MappedStatement, org.apache.ibatis.mapping.BoundSql, java.lang.Object, org.apache.ibatis.session.RowBounds, org.apache.ibatis.cache.CacheKey) ,public Page<T> getLocalPage() ,public java.lang.String getPageSql(org.apache.ibatis.mapping.MappedStatement, org.apache.ibatis.mapping.BoundSql, java.lang.Object, org.apache.ibatis.session.RowBounds, org.apache.ibatis.cache.CacheKey) ,public abstract java.lang.String getPageSql(java.lang.String, Page#RAW, org.apache.ibatis.cache.CacheKey) ,public abstract java.lang.Object processPageParameter(org.apache.ibatis.mapping.MappedStatement, Map<java.lang.String,java.lang.Object>, Page#RAW, org.apache.ibatis.mapping.BoundSql, org.apache.ibatis.cache.CacheKey) ,public java.lang.Object processParameterObject(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.mapping.BoundSql, org.apache.ibatis.cache.CacheKey) ,public void setProperties(java.util.Properties) ,public final boolean skip(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) <variables>
|
pagehelper_Mybatis-PageHelper
|
Mybatis-PageHelper/src/main/java/com/github/pagehelper/dialect/helper/HerdDBDialect.java
|
HerdDBDialect
|
getPageSql
|
class HerdDBDialect extends AbstractHelperDialect {
@Override
public Object processPageParameter(MappedStatement ms, Map<String, Object> paramMap, Page page, BoundSql boundSql, CacheKey pageKey) {
paramMap.put(PAGEPARAMETER_FIRST, page.getStartRow());
paramMap.put(PAGEPARAMETER_SECOND, page.getPageSize());
pageKey.update(page.getStartRow());
pageKey.update(page.getPageSize());
if (boundSql.getParameterMappings() != null) {
List<ParameterMapping> newParameterMappings = new ArrayList<ParameterMapping>(boundSql.getParameterMappings());
if (page.getStartRow() == 0) {
newParameterMappings.add(new ParameterMapping.Builder(ms.getConfiguration(), PAGEPARAMETER_SECOND, int.class).build());
} else {
newParameterMappings.add(new ParameterMapping.Builder(ms.getConfiguration(), PAGEPARAMETER_FIRST, long.class).build());
newParameterMappings.add(new ParameterMapping.Builder(ms.getConfiguration(), PAGEPARAMETER_SECOND, int.class).build());
}
MetaObject metaObject = MetaObjectUtil.forObject(boundSql);
metaObject.setValue("parameterMappings", newParameterMappings);
}
return paramMap;
}
@Override
public String getPageSql(String sql, Page page, CacheKey pageKey) {<FILL_FUNCTION_BODY>}
}
|
StringBuilder sqlBuilder = new StringBuilder(sql.length() + 14);
sqlBuilder.append(sql);
if (page.getStartRow() == 0) {
sqlBuilder.append("\n LIMIT ? ");
} else {
sqlBuilder.append("\n LIMIT ?, ? ");
}
return sqlBuilder.toString();
| 392
| 85
| 477
|
<methods>public non-sealed void <init>() ,public void afterAll() ,public boolean afterCount(long, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public java.lang.Object afterPage(List#RAW, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public boolean beforeCount(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public boolean beforePage(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public java.lang.String getCountSql(org.apache.ibatis.mapping.MappedStatement, org.apache.ibatis.mapping.BoundSql, java.lang.Object, org.apache.ibatis.session.RowBounds, org.apache.ibatis.cache.CacheKey) ,public Page<T> getLocalPage() ,public java.lang.String getPageSql(org.apache.ibatis.mapping.MappedStatement, org.apache.ibatis.mapping.BoundSql, java.lang.Object, org.apache.ibatis.session.RowBounds, org.apache.ibatis.cache.CacheKey) ,public abstract java.lang.String getPageSql(java.lang.String, Page#RAW, org.apache.ibatis.cache.CacheKey) ,public abstract java.lang.Object processPageParameter(org.apache.ibatis.mapping.MappedStatement, Map<java.lang.String,java.lang.Object>, Page#RAW, org.apache.ibatis.mapping.BoundSql, org.apache.ibatis.cache.CacheKey) ,public java.lang.Object processParameterObject(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.mapping.BoundSql, org.apache.ibatis.cache.CacheKey) ,public void setProperties(java.util.Properties) ,public final boolean skip(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) <variables>
|
pagehelper_Mybatis-PageHelper
|
Mybatis-PageHelper/src/main/java/com/github/pagehelper/dialect/helper/HsqldbDialect.java
|
HsqldbDialect
|
processPageParameter
|
class HsqldbDialect extends AbstractHelperDialect {
@Override
public Object processPageParameter(MappedStatement ms, Map<String, Object> paramMap, Page page, BoundSql boundSql, CacheKey pageKey) {<FILL_FUNCTION_BODY>}
@Override
public String getPageSql(String sql, Page page, CacheKey pageKey) {
StringBuilder sqlBuilder = new StringBuilder(sql.length() + 20);
sqlBuilder.append(sql);
if (page.getPageSize() > 0) {
sqlBuilder.append("\n LIMIT ? ");
}
if (page.getStartRow() > 0) {
sqlBuilder.append("\n OFFSET ? ");
}
return sqlBuilder.toString();
}
}
|
paramMap.put(PAGEPARAMETER_FIRST, page.getPageSize());
paramMap.put(PAGEPARAMETER_SECOND, page.getStartRow());
//处理pageKey
pageKey.update(page.getPageSize());
pageKey.update(page.getStartRow());
//处理参数配置
if (boundSql.getParameterMappings() != null) {
List<ParameterMapping> newParameterMappings = new ArrayList<ParameterMapping>(boundSql.getParameterMappings());
if (page.getPageSize() > 0) {
newParameterMappings.add(new ParameterMapping.Builder(ms.getConfiguration(), PAGEPARAMETER_FIRST, int.class).build());
}
if (page.getStartRow() > 0) {
newParameterMappings.add(new ParameterMapping.Builder(ms.getConfiguration(), PAGEPARAMETER_SECOND, long.class).build());
}
MetaObject metaObject = MetaObjectUtil.forObject(boundSql);
metaObject.setValue("parameterMappings", newParameterMappings);
}
return paramMap;
| 193
| 282
| 475
|
<methods>public non-sealed void <init>() ,public void afterAll() ,public boolean afterCount(long, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public java.lang.Object afterPage(List#RAW, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public boolean beforeCount(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public boolean beforePage(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public java.lang.String getCountSql(org.apache.ibatis.mapping.MappedStatement, org.apache.ibatis.mapping.BoundSql, java.lang.Object, org.apache.ibatis.session.RowBounds, org.apache.ibatis.cache.CacheKey) ,public Page<T> getLocalPage() ,public java.lang.String getPageSql(org.apache.ibatis.mapping.MappedStatement, org.apache.ibatis.mapping.BoundSql, java.lang.Object, org.apache.ibatis.session.RowBounds, org.apache.ibatis.cache.CacheKey) ,public abstract java.lang.String getPageSql(java.lang.String, Page#RAW, org.apache.ibatis.cache.CacheKey) ,public abstract java.lang.Object processPageParameter(org.apache.ibatis.mapping.MappedStatement, Map<java.lang.String,java.lang.Object>, Page#RAW, org.apache.ibatis.mapping.BoundSql, org.apache.ibatis.cache.CacheKey) ,public java.lang.Object processParameterObject(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.mapping.BoundSql, org.apache.ibatis.cache.CacheKey) ,public void setProperties(java.util.Properties) ,public final boolean skip(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) <variables>
|
pagehelper_Mybatis-PageHelper
|
Mybatis-PageHelper/src/main/java/com/github/pagehelper/dialect/helper/InformixDialect.java
|
InformixDialect
|
processPageParameter
|
class InformixDialect extends AbstractHelperDialect {
@Override
public Object processPageParameter(MappedStatement ms, Map<String, Object> paramMap, Page page, BoundSql boundSql, CacheKey pageKey) {<FILL_FUNCTION_BODY>}
@Override
public String getPageSql(String sql, Page page, CacheKey pageKey) {
StringBuilder sqlBuilder = new StringBuilder(sql.length() + 40);
sqlBuilder.append("SELECT ");
if (page.getStartRow() > 0) {
sqlBuilder.append(" SKIP ? ");
}
if (page.getPageSize() > 0) {
sqlBuilder.append(" FIRST ? ");
}
sqlBuilder.append(" * FROM ( \n");
sqlBuilder.append(sql);
sqlBuilder.append("\n ) TEMP_T ");
return sqlBuilder.toString();
}
}
|
paramMap.put(PAGEPARAMETER_FIRST, page.getStartRow());
paramMap.put(PAGEPARAMETER_SECOND, page.getPageSize());
//处理pageKey
pageKey.update(page.getStartRow());
pageKey.update(page.getPageSize());
//处理参数配置
if (boundSql.getParameterMappings() != null) {
List<ParameterMapping> newParameterMappings = new ArrayList<ParameterMapping>();
if (page.getStartRow() > 0) {
newParameterMappings.add(new ParameterMapping.Builder(ms.getConfiguration(), PAGEPARAMETER_FIRST, long.class).build());
}
if (page.getPageSize() > 0) {
newParameterMappings.add(new ParameterMapping.Builder(ms.getConfiguration(), PAGEPARAMETER_SECOND, int.class).build());
}
newParameterMappings.addAll(boundSql.getParameterMappings());
MetaObject metaObject = MetaObjectUtil.forObject(boundSql);
metaObject.setValue("parameterMappings", newParameterMappings);
}
return paramMap;
| 227
| 292
| 519
|
<methods>public non-sealed void <init>() ,public void afterAll() ,public boolean afterCount(long, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public java.lang.Object afterPage(List#RAW, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public boolean beforeCount(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public boolean beforePage(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public java.lang.String getCountSql(org.apache.ibatis.mapping.MappedStatement, org.apache.ibatis.mapping.BoundSql, java.lang.Object, org.apache.ibatis.session.RowBounds, org.apache.ibatis.cache.CacheKey) ,public Page<T> getLocalPage() ,public java.lang.String getPageSql(org.apache.ibatis.mapping.MappedStatement, org.apache.ibatis.mapping.BoundSql, java.lang.Object, org.apache.ibatis.session.RowBounds, org.apache.ibatis.cache.CacheKey) ,public abstract java.lang.String getPageSql(java.lang.String, Page#RAW, org.apache.ibatis.cache.CacheKey) ,public abstract java.lang.Object processPageParameter(org.apache.ibatis.mapping.MappedStatement, Map<java.lang.String,java.lang.Object>, Page#RAW, org.apache.ibatis.mapping.BoundSql, org.apache.ibatis.cache.CacheKey) ,public java.lang.Object processParameterObject(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.mapping.BoundSql, org.apache.ibatis.cache.CacheKey) ,public void setProperties(java.util.Properties) ,public final boolean skip(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) <variables>
|
pagehelper_Mybatis-PageHelper
|
Mybatis-PageHelper/src/main/java/com/github/pagehelper/dialect/helper/MySqlDialect.java
|
MySqlDialect
|
getPageSql
|
class MySqlDialect extends AbstractHelperDialect {
@Override
public Object processPageParameter(MappedStatement ms, Map<String, Object> paramMap, Page page, BoundSql boundSql, CacheKey pageKey) {
paramMap.put(PAGEPARAMETER_FIRST, page.getStartRow());
paramMap.put(PAGEPARAMETER_SECOND, page.getPageSize());
//处理pageKey
pageKey.update(page.getStartRow());
pageKey.update(page.getPageSize());
//处理参数配置
if (boundSql.getParameterMappings() != null) {
List<ParameterMapping> newParameterMappings = new ArrayList<ParameterMapping>(boundSql.getParameterMappings());
if (page.getStartRow() == 0) {
newParameterMappings.add(new ParameterMapping.Builder(ms.getConfiguration(), PAGEPARAMETER_SECOND, int.class).build());
} else {
newParameterMappings.add(new ParameterMapping.Builder(ms.getConfiguration(), PAGEPARAMETER_FIRST, long.class).build());
newParameterMappings.add(new ParameterMapping.Builder(ms.getConfiguration(), PAGEPARAMETER_SECOND, int.class).build());
}
MetaObject metaObject = MetaObjectUtil.forObject(boundSql);
metaObject.setValue("parameterMappings", newParameterMappings);
}
return paramMap;
}
@Override
public String getPageSql(String sql, Page page, CacheKey pageKey) {<FILL_FUNCTION_BODY>}
}
|
StringBuilder sqlBuilder = new StringBuilder(sql.length() + 14);
sqlBuilder.append(sql);
if (page.getStartRow() == 0) {
sqlBuilder.append("\n LIMIT ? ");
} else {
sqlBuilder.append("\n LIMIT ?, ? ");
}
return sqlBuilder.toString();
| 403
| 85
| 488
|
<methods>public non-sealed void <init>() ,public void afterAll() ,public boolean afterCount(long, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public java.lang.Object afterPage(List#RAW, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public boolean beforeCount(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public boolean beforePage(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public java.lang.String getCountSql(org.apache.ibatis.mapping.MappedStatement, org.apache.ibatis.mapping.BoundSql, java.lang.Object, org.apache.ibatis.session.RowBounds, org.apache.ibatis.cache.CacheKey) ,public Page<T> getLocalPage() ,public java.lang.String getPageSql(org.apache.ibatis.mapping.MappedStatement, org.apache.ibatis.mapping.BoundSql, java.lang.Object, org.apache.ibatis.session.RowBounds, org.apache.ibatis.cache.CacheKey) ,public abstract java.lang.String getPageSql(java.lang.String, Page#RAW, org.apache.ibatis.cache.CacheKey) ,public abstract java.lang.Object processPageParameter(org.apache.ibatis.mapping.MappedStatement, Map<java.lang.String,java.lang.Object>, Page#RAW, org.apache.ibatis.mapping.BoundSql, org.apache.ibatis.cache.CacheKey) ,public java.lang.Object processParameterObject(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.mapping.BoundSql, org.apache.ibatis.cache.CacheKey) ,public void setProperties(java.util.Properties) ,public final boolean skip(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) <variables>
|
pagehelper_Mybatis-PageHelper
|
Mybatis-PageHelper/src/main/java/com/github/pagehelper/dialect/helper/Oracle9iDialect.java
|
Oracle9iDialect
|
getPageSql
|
class Oracle9iDialect extends AbstractHelperDialect {
@Override
public Object processPageParameter(MappedStatement ms, Map<String, Object> paramMap, Page page, BoundSql boundSql, CacheKey pageKey) {
paramMap.put(PAGEPARAMETER_FIRST, page.getEndRow());
paramMap.put(PAGEPARAMETER_SECOND, page.getStartRow());
//处理pageKey
pageKey.update(page.getEndRow());
pageKey.update(page.getStartRow());
//处理参数配置
handleParameter(boundSql, ms, long.class, long.class);
return paramMap;
}
@Override
public String getPageSql(String sql, Page page, CacheKey pageKey) {<FILL_FUNCTION_BODY>}
}
|
StringBuilder sqlBuilder = new StringBuilder(sql.length() + 120);
sqlBuilder.append("SELECT * FROM ( ");
sqlBuilder.append(" SELECT TMP_PAGE.*, ROWNUM PAGEHELPER_ROW_ID FROM ( \n");
sqlBuilder.append(sql);
sqlBuilder.append("\n ) TMP_PAGE WHERE ROWNUM <= ? ");
sqlBuilder.append(" ) WHERE PAGEHELPER_ROW_ID > ? ");
return sqlBuilder.toString();
| 207
| 126
| 333
|
<methods>public non-sealed void <init>() ,public void afterAll() ,public boolean afterCount(long, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public java.lang.Object afterPage(List#RAW, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public boolean beforeCount(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public boolean beforePage(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public java.lang.String getCountSql(org.apache.ibatis.mapping.MappedStatement, org.apache.ibatis.mapping.BoundSql, java.lang.Object, org.apache.ibatis.session.RowBounds, org.apache.ibatis.cache.CacheKey) ,public Page<T> getLocalPage() ,public java.lang.String getPageSql(org.apache.ibatis.mapping.MappedStatement, org.apache.ibatis.mapping.BoundSql, java.lang.Object, org.apache.ibatis.session.RowBounds, org.apache.ibatis.cache.CacheKey) ,public abstract java.lang.String getPageSql(java.lang.String, Page#RAW, org.apache.ibatis.cache.CacheKey) ,public abstract java.lang.Object processPageParameter(org.apache.ibatis.mapping.MappedStatement, Map<java.lang.String,java.lang.Object>, Page#RAW, org.apache.ibatis.mapping.BoundSql, org.apache.ibatis.cache.CacheKey) ,public java.lang.Object processParameterObject(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.mapping.BoundSql, org.apache.ibatis.cache.CacheKey) ,public void setProperties(java.util.Properties) ,public final boolean skip(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) <variables>
|
pagehelper_Mybatis-PageHelper
|
Mybatis-PageHelper/src/main/java/com/github/pagehelper/dialect/helper/OracleDialect.java
|
OracleDialect
|
processPageParameter
|
class OracleDialect extends AbstractHelperDialect {
@Override
public Object processPageParameter(MappedStatement ms, Map<String, Object> paramMap, Page page, BoundSql boundSql, CacheKey pageKey) {<FILL_FUNCTION_BODY>}
@Override
public String getPageSql(String sql, Page page, CacheKey pageKey) {
StringBuilder sqlBuilder = new StringBuilder(sql.length() + 120);
sqlBuilder.append("SELECT * FROM ( ");
sqlBuilder.append(" SELECT TMP_PAGE.*, ROWNUM PAGEHELPER_ROW_ID FROM ( \n");
sqlBuilder.append(sql);
sqlBuilder.append("\n ) TMP_PAGE)");
sqlBuilder.append(" WHERE PAGEHELPER_ROW_ID <= ? AND PAGEHELPER_ROW_ID > ?");
return sqlBuilder.toString();
}
}
|
paramMap.put(PAGEPARAMETER_FIRST, page.getEndRow());
paramMap.put(PAGEPARAMETER_SECOND, page.getStartRow());
//处理pageKey
pageKey.update(page.getEndRow());
pageKey.update(page.getStartRow());
//处理参数配置
handleParameter(boundSql, ms, long.class, long.class);
return paramMap;
| 228
| 110
| 338
|
<methods>public non-sealed void <init>() ,public void afterAll() ,public boolean afterCount(long, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public java.lang.Object afterPage(List#RAW, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public boolean beforeCount(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public boolean beforePage(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public java.lang.String getCountSql(org.apache.ibatis.mapping.MappedStatement, org.apache.ibatis.mapping.BoundSql, java.lang.Object, org.apache.ibatis.session.RowBounds, org.apache.ibatis.cache.CacheKey) ,public Page<T> getLocalPage() ,public java.lang.String getPageSql(org.apache.ibatis.mapping.MappedStatement, org.apache.ibatis.mapping.BoundSql, java.lang.Object, org.apache.ibatis.session.RowBounds, org.apache.ibatis.cache.CacheKey) ,public abstract java.lang.String getPageSql(java.lang.String, Page#RAW, org.apache.ibatis.cache.CacheKey) ,public abstract java.lang.Object processPageParameter(org.apache.ibatis.mapping.MappedStatement, Map<java.lang.String,java.lang.Object>, Page#RAW, org.apache.ibatis.mapping.BoundSql, org.apache.ibatis.cache.CacheKey) ,public java.lang.Object processParameterObject(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.mapping.BoundSql, org.apache.ibatis.cache.CacheKey) ,public void setProperties(java.util.Properties) ,public final boolean skip(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) <variables>
|
pagehelper_Mybatis-PageHelper
|
Mybatis-PageHelper/src/main/java/com/github/pagehelper/dialect/helper/OscarDialect.java
|
OscarDialect
|
processPageParameter
|
class OscarDialect extends AbstractHelperDialect {
@Override
public Object processPageParameter(MappedStatement ms, Map<String, Object> paramMap, Page page, BoundSql boundSql, CacheKey pageKey) {<FILL_FUNCTION_BODY>}
@Override
public String getPageSql(String sql, Page page, CacheKey pageKey) {
StringBuilder sqlBuilder = new StringBuilder(sql.length() + 14);
sqlBuilder.append(sql);
if (page.getStartRow() == 0) {
sqlBuilder.append("\n LIMIT ? ");
} else {
sqlBuilder.append("\n LIMIT ? OFFSET ? ");
}
return sqlBuilder.toString();
}
}
|
paramMap.put(PAGEPARAMETER_FIRST, page.getPageSize() );
paramMap.put(PAGEPARAMETER_SECOND, (int) page.getStartRow() );
//处理pageKey
pageKey.update(page.getStartRow());
pageKey.update(page.getPageSize());
//处理参数配置
if (boundSql.getParameterMappings() != null) {
List<ParameterMapping> newParameterMappings = new ArrayList<ParameterMapping>(boundSql.getParameterMappings());
if (page.getStartRow() == 0) {
newParameterMappings.add(new ParameterMapping.Builder(ms.getConfiguration(), PAGEPARAMETER_FIRST, int.class).build());
} else {
newParameterMappings.add(new ParameterMapping.Builder(ms.getConfiguration(), PAGEPARAMETER_FIRST, int.class).build());
newParameterMappings.add(new ParameterMapping.Builder(ms.getConfiguration(), PAGEPARAMETER_SECOND, int.class).build());
}
MetaObject metaObject = MetaObjectUtil.forObject(boundSql);
metaObject.setValue("parameterMappings", newParameterMappings);
}
return paramMap;
| 181
| 311
| 492
|
<methods>public non-sealed void <init>() ,public void afterAll() ,public boolean afterCount(long, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public java.lang.Object afterPage(List#RAW, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public boolean beforeCount(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public boolean beforePage(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public java.lang.String getCountSql(org.apache.ibatis.mapping.MappedStatement, org.apache.ibatis.mapping.BoundSql, java.lang.Object, org.apache.ibatis.session.RowBounds, org.apache.ibatis.cache.CacheKey) ,public Page<T> getLocalPage() ,public java.lang.String getPageSql(org.apache.ibatis.mapping.MappedStatement, org.apache.ibatis.mapping.BoundSql, java.lang.Object, org.apache.ibatis.session.RowBounds, org.apache.ibatis.cache.CacheKey) ,public abstract java.lang.String getPageSql(java.lang.String, Page#RAW, org.apache.ibatis.cache.CacheKey) ,public abstract java.lang.Object processPageParameter(org.apache.ibatis.mapping.MappedStatement, Map<java.lang.String,java.lang.Object>, Page#RAW, org.apache.ibatis.mapping.BoundSql, org.apache.ibatis.cache.CacheKey) ,public java.lang.Object processParameterObject(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.mapping.BoundSql, org.apache.ibatis.cache.CacheKey) ,public void setProperties(java.util.Properties) ,public final boolean skip(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) <variables>
|
pagehelper_Mybatis-PageHelper
|
Mybatis-PageHelper/src/main/java/com/github/pagehelper/dialect/helper/PostgreSqlDialect.java
|
PostgreSqlDialect
|
getPageSql
|
class PostgreSqlDialect extends AbstractHelperDialect {
@Override
public Object processPageParameter(MappedStatement ms, Map<String, Object> paramMap, Page page, BoundSql boundSql, CacheKey pageKey) {
paramMap.put(PAGEPARAMETER_SECOND, page.getPageSize());
paramMap.put(PAGEPARAMETER_FIRST, page.getStartRow());
//处理pageKey
pageKey.update(page.getPageSize());
pageKey.update(page.getStartRow());
//处理参数配置
if (boundSql.getParameterMappings() != null) {
List<ParameterMapping> newParameterMappings = new ArrayList<ParameterMapping>(boundSql.getParameterMappings());
if (page.getStartRow() == 0) {
newParameterMappings.add(new ParameterMapping.Builder(ms.getConfiguration(), PAGEPARAMETER_SECOND, int.class).build());
} else {
newParameterMappings.add(new ParameterMapping.Builder(ms.getConfiguration(), PAGEPARAMETER_SECOND, int.class).build());
newParameterMappings.add(new ParameterMapping.Builder(ms.getConfiguration(), PAGEPARAMETER_FIRST, long.class).build());
}
MetaObject metaObject = MetaObjectUtil.forObject(boundSql);
metaObject.setValue("parameterMappings", newParameterMappings);
}
return paramMap;
}
/**
* 构建 <a href="https://www.postgresql.org/docs/current/queries-limit.html">PostgreSQL</a>分页查询语句
*/
@Override
public String getPageSql(String sql, Page page, CacheKey pageKey) {<FILL_FUNCTION_BODY>}
}
|
StringBuilder sqlStr = new StringBuilder(sql.length() + 17);
sqlStr.append(sql);
if (page.getStartRow() == 0) {
sqlStr.append(" LIMIT ?");
} else {
sqlStr.append(" LIMIT ? OFFSET ?");
}
return sqlStr.toString();
| 454
| 86
| 540
|
<methods>public non-sealed void <init>() ,public void afterAll() ,public boolean afterCount(long, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public java.lang.Object afterPage(List#RAW, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public boolean beforeCount(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public boolean beforePage(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public java.lang.String getCountSql(org.apache.ibatis.mapping.MappedStatement, org.apache.ibatis.mapping.BoundSql, java.lang.Object, org.apache.ibatis.session.RowBounds, org.apache.ibatis.cache.CacheKey) ,public Page<T> getLocalPage() ,public java.lang.String getPageSql(org.apache.ibatis.mapping.MappedStatement, org.apache.ibatis.mapping.BoundSql, java.lang.Object, org.apache.ibatis.session.RowBounds, org.apache.ibatis.cache.CacheKey) ,public abstract java.lang.String getPageSql(java.lang.String, Page#RAW, org.apache.ibatis.cache.CacheKey) ,public abstract java.lang.Object processPageParameter(org.apache.ibatis.mapping.MappedStatement, Map<java.lang.String,java.lang.Object>, Page#RAW, org.apache.ibatis.mapping.BoundSql, org.apache.ibatis.cache.CacheKey) ,public java.lang.Object processParameterObject(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.mapping.BoundSql, org.apache.ibatis.cache.CacheKey) ,public void setProperties(java.util.Properties) ,public final boolean skip(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) <variables>
|
pagehelper_Mybatis-PageHelper
|
Mybatis-PageHelper/src/main/java/com/github/pagehelper/dialect/helper/SqlServer2012Dialect.java
|
SqlServer2012Dialect
|
getPageSql
|
class SqlServer2012Dialect extends SqlServerDialect {
@Override
public Object processPageParameter(MappedStatement ms, Map<String, Object> paramMap, Page page, BoundSql boundSql, CacheKey pageKey) {
paramMap.put(PAGEPARAMETER_FIRST, page.getStartRow());
paramMap.put(PAGEPARAMETER_SECOND, page.getPageSize());
//处理pageKey
pageKey.update(page.getStartRow());
pageKey.update(page.getPageSize());
//处理参数配置
handleParameter(boundSql, ms, long.class, int.class);
return paramMap;
}
@Override
public String getPageSql(String sql, Page page, CacheKey pageKey) {<FILL_FUNCTION_BODY>}
}
|
StringBuilder sqlBuilder = new StringBuilder(sql.length() + 64);
sqlBuilder.append(sql);
sqlBuilder.append("\n OFFSET ? ROWS FETCH NEXT ? ROWS ONLY ");
pageKey.update(page.getPageSize());
return sqlBuilder.toString();
| 210
| 77
| 287
|
<methods>public non-sealed void <init>() ,public java.lang.String getCountSql(org.apache.ibatis.mapping.MappedStatement, org.apache.ibatis.mapping.BoundSql, java.lang.Object, org.apache.ibatis.session.RowBounds, org.apache.ibatis.cache.CacheKey) ,public java.lang.String getPageSql(java.lang.String, Page#RAW, org.apache.ibatis.cache.CacheKey) ,public java.lang.String getPageSql(org.apache.ibatis.mapping.MappedStatement, org.apache.ibatis.mapping.BoundSql, java.lang.Object, org.apache.ibatis.session.RowBounds, org.apache.ibatis.cache.CacheKey) ,public java.lang.Object processPageParameter(org.apache.ibatis.mapping.MappedStatement, Map<java.lang.String,java.lang.Object>, Page#RAW, org.apache.ibatis.mapping.BoundSql, org.apache.ibatis.cache.CacheKey) ,public void setProperties(java.util.Properties) <variables>protected Cache<java.lang.String,java.lang.String> CACHE_COUNTSQL,protected Cache<java.lang.String,java.lang.String> CACHE_PAGESQL,protected com.github.pagehelper.dialect.ReplaceSql replaceSql,protected com.github.pagehelper.parser.SqlServerSqlParser sqlServerSqlParser
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.