diff --git a/.gitignore b/.gitignore index 0cbb97cb70..33272b5ff7 100644 --- a/.gitignore +++ b/.gitignore @@ -24,6 +24,7 @@ framework/jetty/build/ framework/minilang/build/ framework/security/build/ framework/service/build/ +framework/sql/build/ framework/start/build/ framework/testtools/build/ framework/webapp/build/ diff --git a/framework/base/src/org/ofbiz/base/util/Appender.java b/framework/base/src/org/ofbiz/base/util/Appender.java new file mode 100644 index 0000000000..7a28cec1df --- /dev/null +++ b/framework/base/src/org/ofbiz/base/util/Appender.java @@ -0,0 +1,23 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.ofbiz.base.util; + +public interface Appender { + T appendTo(T target); +} diff --git a/framework/base/src/org/ofbiz/base/util/StringUtil.java b/framework/base/src/org/ofbiz/base/util/StringUtil.java index 6f52238e38..6c03058246 100644 --- a/framework/base/src/org/ofbiz/base/util/StringUtil.java +++ b/framework/base/src/org/ofbiz/base/util/StringUtil.java @@ -685,6 +685,28 @@ public class StringUtil { return new StringWrapper(theString); } + public static StringBuilder appendTo(StringBuilder sb, Iterable> iterable, String prefix, String suffix, String sep) { + Iterator> it = iterable.iterator(); + while (it.hasNext()) { + if (prefix != null) sb.append(prefix); + it.next().appendTo(sb); + if (suffix != null) sb.append(suffix); + if (it.hasNext() && sep != null) sb.append(sep); + } + return sb; + } + + public static StringBuilder append(StringBuilder sb, Iterable iterable, String prefix, String suffix, String sep) { + Iterator it = iterable.iterator(); + while (it.hasNext()) { + if (prefix != null) sb.append(prefix); + sb.append(it.next()); + if (suffix != null) sb.append(suffix); + if (it.hasNext() && sep != null) sb.append(sep); + } + return sb; + } + /** * A super-lightweight object to wrap a String object. Mainly used with FTL templates * to avoid the general HTML auto-encoding that is now done through the Screen Widget. diff --git a/framework/component-load.xml b/framework/component-load.xml index 5328768b18..9dd4edcd25 100644 --- a/framework/component-load.xml +++ b/framework/component-load.xml @@ -21,6 +21,7 @@ under the License. + diff --git a/framework/entity/build.xml b/framework/entity/build.xml index d0b5953349..639aa974e3 100644 --- a/framework/entity/build.xml +++ b/framework/entity/build.xml @@ -37,10 +37,7 @@ under the License. - - - - + @@ -52,11 +49,7 @@ under the License. - - - - - + diff --git a/framework/entity/src/org/ofbiz/entity/sql/EntityDeletePlan.java b/framework/entity/src/org/ofbiz/entity/sql/EntityDeletePlan.java new file mode 100644 index 0000000000..e08725a0df --- /dev/null +++ b/framework/entity/src/org/ofbiz/entity/sql/EntityDeletePlan.java @@ -0,0 +1,24 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.ofbiz.entity.sql; + +import org.ofbiz.sql.DeletePlan; + +public class EntityDeletePlan extends DeletePlan { +} diff --git a/framework/entity/src/org/ofbiz/entity/sql/EntityInsertPlan.java b/framework/entity/src/org/ofbiz/entity/sql/EntityInsertPlan.java new file mode 100644 index 0000000000..431acd3221 --- /dev/null +++ b/framework/entity/src/org/ofbiz/entity/sql/EntityInsertPlan.java @@ -0,0 +1,24 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.ofbiz.entity.sql; + +import org.ofbiz.sql.InsertPlan; + +public class EntityInsertPlan extends InsertPlan { +} diff --git a/framework/entity/src/org/ofbiz/entity/sql/EntityPlanner.java b/framework/entity/src/org/ofbiz/entity/sql/EntityPlanner.java new file mode 100644 index 0000000000..bb6ce6e444 --- /dev/null +++ b/framework/entity/src/org/ofbiz/entity/sql/EntityPlanner.java @@ -0,0 +1,253 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.ofbiz.entity.sql; + +import java.util.Collections; +import java.util.Iterator; +import java.util.List; + +import javolution.util.FastList; + +import org.ofbiz.entity.GenericValue; +import org.ofbiz.entity.condition.EntityFieldValue; +import org.ofbiz.entity.condition.EntityCondition; +import org.ofbiz.entity.condition.EntityConditionValue; +import org.ofbiz.entity.condition.EntityOperator; +import org.ofbiz.entity.model.DynamicViewEntity; +import org.ofbiz.entity.model.ModelViewEntity.ComplexAlias; +import org.ofbiz.entity.model.ModelViewEntity.ComplexAliasField; +import org.ofbiz.entity.model.ModelViewEntity.ComplexAliasMember; +import org.ofbiz.entity.model.ModelKeyMap; + +import org.ofbiz.sql.BooleanCondition; +import org.ofbiz.sql.Condition; +import org.ofbiz.sql.ConditionList; +import org.ofbiz.sql.FieldAll; +import org.ofbiz.sql.FieldDef; +import org.ofbiz.sql.FieldDefFieldValue; +import org.ofbiz.sql.FieldDefValue; +import org.ofbiz.sql.FieldValue; +import org.ofbiz.sql.FunctionCall; +import org.ofbiz.sql.Joined; +import org.ofbiz.sql.Joiner; +import org.ofbiz.sql.KeyMap; +import org.ofbiz.sql.MathValue; +import org.ofbiz.sql.NumberValue; +import org.ofbiz.sql.Planner; +import org.ofbiz.sql.MathValue; +import org.ofbiz.sql.Relation; +import org.ofbiz.sql.SQLDelete; +import org.ofbiz.sql.SQLInsert; +import org.ofbiz.sql.SQLSelect; +import org.ofbiz.sql.SQLUpdate; +import org.ofbiz.sql.SQLView; +import org.ofbiz.sql.StaticValue; +import org.ofbiz.sql.StringValue; +import org.ofbiz.sql.Table; +import org.ofbiz.sql.TableName; +import org.ofbiz.sql.Value; + +public class EntityPlanner implements Planner { + public EntityDeletePlan plan(SQLDelete deleteStatement) { + return null; + } + + public EntityInsertPlan plan(SQLInsert insertStatement) { + return null; + } + + public EntitySelectPlan plan(SQLSelect selectStatement) { + DynamicViewEntity dve = new DynamicViewEntity(); + Table table = selectStatement.getTable(); + addMember(dve, table.getTableName()); + addJoined(dve, table.getTableName().getAlias(), table.getJoined()); + for (FieldAll fieldAll: selectStatement.getFieldAlls()) { + dve.addAliasAll(fieldAll.getAlias(), null); + } + for (Relation relation: selectStatement.getRelations()) { + dve.addRelation(relation.getType(), relation.getTitle(), relation.getEntityName(), buildKeyMaps(relation)); + } + List groupBy = selectStatement.getGroupBy(); + if (groupBy == null) { + groupBy = Collections.emptyList(); + } + for (FieldDef fieldDef: selectStatement.getFieldDefs()) { + addFieldDef(dve, groupBy, fieldDef.getAlias(), fieldDef); + } + return new EntitySelectPlan(dve, buildCondition(selectStatement.getWhereCondition()), buildCondition(selectStatement.getHavingCondition()), selectStatement.getOrderBy()); + } + + public EntityUpdatePlan plan(SQLUpdate updateStatement) { + return null; + } + + public EntityViewPlan plan(SQLView viewStatement) { + return null; + } + + private static void addFieldDef(DynamicViewEntity dve, List groupBy, String alias, FieldDef fieldDef) { + if (fieldDef instanceof FieldDefFieldValue) { + addFieldDef(dve, groupBy, fieldDef.getAlias(), ((FieldDefFieldValue) fieldDef).getFieldValue(), null); + } else if (fieldDef instanceof FieldDefValue) { + addFieldDef(dve, groupBy, fieldDef.getAlias(), ((FieldDefValue) fieldDef).getValue()); + } else { + throw new UnsupportedOperationException(alias + "[" + fieldDef + "]:" + fieldDef.getClass()); + } + } + + private static void addFieldDef(DynamicViewEntity dve, List groupBy, String alias, FieldValue fieldValue, String function) { + dve.addAlias(fieldValue.getTableName(), alias, fieldValue.getFieldName(), null, null, groupBy.contains(alias), function); + } + + private static void addFieldDef(DynamicViewEntity dve, List groupBy, String alias, ComplexAliasMember member) { + dve.addAlias(null, alias, null, null, null, groupBy.contains(alias), null, member); + } + + private static void addFieldDef(DynamicViewEntity dve, List groupBy, String alias, StaticValue value) { + ComplexAliasMember complexMember; + if (value instanceof FieldValue) { + addFieldDef(dve, groupBy, alias, (FieldValue) value, null); + return; + } else if (value instanceof FunctionCall) { + FunctionCall fc = (FunctionCall) value; + String name = fc.getName().toLowerCase(); + Iterator it = fc.iterator(); + if (it.hasNext()) { + Value firstValue = it.next(); + if (!it.hasNext()) { + if (firstValue instanceof FieldValue) { + addFieldDef(dve, groupBy, alias, (FieldValue) firstValue, name); + return; + } + } + } + } + addFieldDef(dve, groupBy, alias, buildComplexMember(value)); + } + + private static ComplexAliasMember buildComplexMember(Value value) { + if (value instanceof FieldValue) { + FieldValue fv = (FieldValue) value; + return new ComplexAliasField(fv.getTableName(), fv.getFieldName(), null, null); + } else if (value instanceof FunctionCall) { + FunctionCall fc = (FunctionCall) value; + String name = fc.getName().toLowerCase(); + if (fc.getArgCount() == 1) { + Value firstValue = fc.iterator().next(); + if (firstValue instanceof FieldValue) { + FieldValue fv = (FieldValue) firstValue; + return new ComplexAliasField(fv.getTableName(), fv.getFieldName(), null, name); + } else if (firstValue instanceof FunctionCall) { + FunctionCall fc2 = (FunctionCall) firstValue; + if (fc2.getName().equalsIgnoreCase("coalesce") && fc2.getArgCount() == 2) { + Iterator it = fc2.iterator(); + Value f1 = it.next(), f2 = it.next(); + if (f1 instanceof FieldValue) { + FieldValue fv = (FieldValue) f1; + if (f2 instanceof NumberValue) { + return new ComplexAliasField(fv.getTableName(), fv.getFieldName(), ((NumberValue) f2).getNumber().toString(), name); + } else if (f2 instanceof StringValue) { + return new ComplexAliasField(fv.getTableName(), fv.getFieldName(), "'" + ((StringValue) f2).getString() + "'", name); + } + } + } + } + } else if (fc.getName().equalsIgnoreCase("coalesce") && fc.getArgCount() == 2) { + Iterator it = fc.iterator(); + Value f1 = it.next(), f2 = it.next(); + if (f1 instanceof FieldValue) { + FieldValue fv = (FieldValue) f1; + if (f2 instanceof NumberValue) { + return new ComplexAliasField(fv.getTableName(), fv.getFieldName(), ((NumberValue) f2).getNumber().toString(), null); + } else if (f2 instanceof StringValue) { + return new ComplexAliasField(fv.getTableName(), fv.getFieldName(), "'" + ((StringValue) f2).getString() + "'", null); + } + } + } + } else if (value instanceof MathValue) { + MathValue mv = (MathValue) value; + List members = FastList.newInstance(); + ComplexAlias complexAlias = new ComplexAlias(mv.getOp()); + for (StaticValue staticValue: mv) { + complexAlias.addComplexAliasMember(buildComplexMember(value)); + } + return complexAlias; + } + throw new UnsupportedOperationException(value + ":" + value.getClass()); + } + + private static void addMember(DynamicViewEntity dve, TableName member) { + dve.addMemberEntity(member.getAlias(), member.getTableName()); + } + + private static void addJoined(DynamicViewEntity dve, String leftAlias, Joined joined) { + if (joined == null) return; + addMember(dve, joined.getTableName()); + dve.addViewLink(leftAlias, joined.getTableName().getAlias(), joined.isOptional(), buildKeyMaps(joined)); + addJoined(dve, joined.getTableName().getAlias(), joined.getJoined()); + } + + private static List buildKeyMaps(Iterable keyMaps) { + List entityKeyMaps = FastList.newInstance(); + for (KeyMap keyMap: keyMaps) { + entityKeyMaps.add(new ModelKeyMap(keyMap.getLeftFieldName(), keyMap.getRightFieldName())); + } + return entityKeyMaps; + } + + private static EntityCondition buildCondition(Condition condition) { + if (condition == null) return null; + if (condition instanceof BooleanCondition) { + BooleanCondition bc = (BooleanCondition) condition; + return EntityCondition.makeCondition(buildFieldValue(bc.getLeft()), EntityOperator.lookupComparison(bc.getOp()), buildValue(bc.getRight())); + } else if (condition instanceof ConditionList) { + ConditionList cl = (ConditionList) condition; + List conditions = FastList.newInstance(); + for (Condition subCondition: cl) { + conditions.add(buildCondition(subCondition)); + } + return EntityCondition.makeCondition(conditions, cl.getJoiner() == Joiner.AND ? EntityOperator.AND : EntityOperator.OR); + } else { + throw new UnsupportedOperationException(condition.toString()); + } + } + + private static EntityFieldValue buildFieldValue(Value value) { + if (value instanceof FieldValue) { + FieldValue fv = (FieldValue) value; + return EntityFieldValue.makeFieldValue(fv.getFieldName(), fv.getTableName(), null, null); + } + throw new UnsupportedOperationException(value.toString()); + } + + private static Object buildValue(Object value) { + if (value instanceof NumberValue) { + return ((NumberValue) value).getNumber(); + } else if (value instanceof StringValue) { + return ((StringValue) value).getString(); + } else if (value instanceof List) { + List values = FastList.newInstance(); + for (Object sqlValue: (List) value) { + values.add(buildValue(sqlValue)); + } + return values; + } + throw new UnsupportedOperationException(value.toString()); + } +} diff --git a/framework/entity/src/org/ofbiz/entity/sql/SQLSelect.java b/framework/entity/src/org/ofbiz/entity/sql/EntitySelectPlan.java similarity index 78% rename from framework/entity/src/org/ofbiz/entity/sql/SQLSelect.java rename to framework/entity/src/org/ofbiz/entity/sql/EntitySelectPlan.java index 9f1d21530b..a4658bd8b6 100644 --- a/framework/entity/src/org/ofbiz/entity/sql/SQLSelect.java +++ b/framework/entity/src/org/ofbiz/entity/sql/EntitySelectPlan.java @@ -19,74 +19,67 @@ package org.ofbiz.entity.sql; import java.util.List; +import java.util.ListIterator; import java.util.Map; import javolution.util.FastList; import javolution.util.FastMap; +import org.ofbiz.entity.condition.EntityCondition; +import org.ofbiz.entity.condition.EntityOperator; +import org.ofbiz.entity.model.DynamicViewEntity; + import org.ofbiz.entity.Delegator; import org.ofbiz.entity.GenericEntityException; +import org.ofbiz.entity.GenericValue; import org.ofbiz.entity.condition.EntityCondition; import org.ofbiz.entity.model.DynamicViewEntity; import org.ofbiz.entity.model.ModelKeyMap; import org.ofbiz.entity.util.EntityListIterator; -public class SQLSelect { - private DynamicViewEntity dve; - private EntityCondition whereCondition; - private EntityCondition havingCondition; - private int offset = -1; - private int limit = -1; - private List orderBy; +import org.ofbiz.sql.SelectPlan; + +public final class EntitySelectPlan extends SelectPlan { + private final DynamicViewEntity dve; + private final EntityCondition whereCondition; + private final EntityCondition havingCondition; + private final List orderBy; + private final int offset = -1; + private final int limit = -1; + + public EntitySelectPlan(DynamicViewEntity dve, EntityCondition whereCondition, EntityCondition havingCondition, List orderBy) { + this.dve = dve; + this.whereCondition = whereCondition; + this.havingCondition = havingCondition; + this.orderBy = orderBy; + //this.offset = offset; + //this.limit = limit; + } public EntityListIterator getEntityListIterator(Delegator delegator) throws GenericEntityException { return delegator.findListIteratorByCondition(dve, whereCondition, havingCondition, null, orderBy, null); } - void setDynamicViewEntity(DynamicViewEntity dve) { - this.dve = dve; - } - public DynamicViewEntity getDynamicViewEntity() { return dve; } - void setWhereCondition(EntityCondition whereCondition) { - this.whereCondition = whereCondition; - } - public EntityCondition getWhereCondition() { return whereCondition; } - void setHavingCondition(EntityCondition havingCondition) { - this.havingCondition = havingCondition; - } - public EntityCondition getHavingCondition() { return havingCondition; } - void setOrderBy(List orderBy) { - this.orderBy = orderBy; - } - public List getOrderBy() { return orderBy; } - void setOffset(int offset) { - this.offset = offset; - } - public int getOffset() { return offset; } - void setLimit(int limit) { - this.limit = limit; - } - public int getLimit() { return limit; } @@ -115,4 +108,3 @@ public class SQLSelect { return sb.toString(); } } -/* JavaCC - OriginalChecksum=49309c1a721b16d029f160d2568a03bc (do not edit this line) */ diff --git a/framework/entity/src/org/ofbiz/entity/sql/EntityUpdatePlan.java b/framework/entity/src/org/ofbiz/entity/sql/EntityUpdatePlan.java new file mode 100644 index 0000000000..13f6dab682 --- /dev/null +++ b/framework/entity/src/org/ofbiz/entity/sql/EntityUpdatePlan.java @@ -0,0 +1,24 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.ofbiz.entity.sql; + +import org.ofbiz.sql.UpdatePlan; + +public class EntityUpdatePlan extends UpdatePlan { +} diff --git a/framework/entity/src/org/ofbiz/entity/sql/EntityViewPlan.java b/framework/entity/src/org/ofbiz/entity/sql/EntityViewPlan.java new file mode 100644 index 0000000000..57ded02763 --- /dev/null +++ b/framework/entity/src/org/ofbiz/entity/sql/EntityViewPlan.java @@ -0,0 +1,24 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.ofbiz.entity.sql; + +import org.ofbiz.sql.ViewPlan; + +public final class EntityViewPlan extends ViewPlan { +} diff --git a/framework/entity/src/org/ofbiz/entity/sql/Parser.jj b/framework/entity/src/org/ofbiz/entity/sql/Parser.jj deleted file mode 100644 index 243fd8301f..0000000000 --- a/framework/entity/src/org/ofbiz/entity/sql/Parser.jj +++ /dev/null @@ -1,588 +0,0 @@ -options { - JAVA_UNICODE_ESCAPE = false; - ERROR_REPORTING = true; - STATIC = false; -// MULTI = true; - JDK_VERSION = "1.5"; -// VISITOR = true; -// BUILD_NODE_FILES = true; -// NODE_FACTORY = false; -// NODE_USES_PARSER = true; -// NODE_SCOPE_HOOK = true; -// NODE_PREFIX = "SQL"; -// DEBUG_PARSER = true; -// DEBUG_LOOKAHEAD = true; -// DEBUG_TOKEN_MANAGER = true; - LOOKAHEAD = 1; -// CHOICE_AMBIGUITY_CHECK = 3; -// OTHER_AMBIGUITY_CHECK = 3; - IGNORE_CASE = true; -} -PARSER_BEGIN(Parser) - -package org.ofbiz.entity.sql; - -import java.io.*; -import java.util.List; -import java.util.LinkedList; -import java.util.Set; - -import javolution.util.FastList; -import javolution.util.FastSet; - -import org.ofbiz.base.conversion.ConversionException; -import org.ofbiz.base.conversion.Converter; -import org.ofbiz.base.conversion.Converters; -import org.ofbiz.entity.condition.EntityComparisonOperator; -import org.ofbiz.entity.condition.EntityCondition; -import org.ofbiz.entity.condition.EntityConditionValue; -import org.ofbiz.entity.condition.EntityFieldValue; -import org.ofbiz.entity.condition.EntityOperator; -import org.ofbiz.entity.condition.OrderByItem; -import org.ofbiz.entity.condition.OrderByList; -import org.ofbiz.entity.model.DynamicViewEntity; -import org.ofbiz.entity.model.ModelKeyMap; -import org.ofbiz.entity.model.ModelViewEntity.ComplexAlias; -import org.ofbiz.entity.model.ModelViewEntity.ComplexAliasField; -import org.ofbiz.entity.model.ModelViewEntity.ComplexAliasMember; -import org.ofbiz.entity.model.ModelViewEntity.ModelAlias; - -public class Parser { -} - -PARSER_END(Parser) -TOKEN_MGR_DECLS: { - private final LinkedList stack = new LinkedList(); - - void pushState(int newState) { - stack.add(curLexState); - SwitchTo(newState); - } - - void popState() { - SwitchTo(stack.removeLast()); - } -} - -TOKEN: { - -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| -| { pushState(IN_DQUOTE); } -| { pushState(IN_SQUOTE); } -| -| -//| -} - - -SKIP: { - -} - -<*> -MORE: { - { if (curLexState != IN_COMMENT) pushState(IN_COMMENT); } -} - - -MORE: { - <(~[])> -| { popState(); } -} - - -TOKEN: { - -} - - -TOKEN: { - { popState(); } -} - - -TOKEN: { - -| { popState(); } -} - - -TOKEN: { - -} - -// ------------------- - - -SQLSelect Select(): -{ - EntityCondition condition; - int i; - DynamicViewEntity dve = new DynamicViewEntity(); - SQLSelect sqlSelect = new SQLSelect(); - sqlSelect.setDynamicViewEntity(dve); - List fieldList; - List orderBy; -} -{ - ( + FieldDef(fieldDefs, fieldAlls) + ( FieldDef(fieldDefs, fieldAlls) )* + ) + table=Table() + ( relation=Relation() { relations.add(relation); } )* + ( whereCondition=ConditionExpression() )? + ( havingCondition=ConditionExpression() )? + ( groupBy=FieldList() )? + ( orderBy=OrderByList() )? + ( offset=Integer() )? + ( limit=Integer() )? + { return new SQLSelect(fieldAlls, fieldDefs, table, relations, whereCondition, havingCondition, groupBy, orderBy, offset, limit); } +} + +private Relation Relation(): +{ + String type = null, title = null, entityName; + List keyMaps; +} +{ + ( type=NamePart() )? + ( title=NamePart() )? + <NAME> { entityName = getToken(0).image; } + keyMaps=KeyMaps("cur", "other") + { return new Relation(type, title, entityName, keyMaps); } +} + + +private SQLUpdate Update(): +{ + TableName tableName; + List<Table> tableList = null; + Condition whereCondition = null; + List<SetField> allSetFields = FastList.newInstance(); + List<SetField> setFields; + Joined joined = null; +} +{ + <UPDATE> tableName=TableName() + <SET> + setFields=SetField() { allSetFields.addAll(setFields); } + ( <COMMA> setFields=SetField() { allSetFields.addAll(setFields); } )* + ( <FROM> joined=JoinedRest(false, tableName) )? + ( <WHERE> whereCondition=ConditionExpression() )? + { return new SQLUpdate(new Table(tableName, joined), allSetFields, whereCondition); } +} + +private SQLDelete Delete(): +{ + TableName tableName; + List<Table> tableList = null; + Condition whereCondition = null; + Joined joined = null; +} +{ + <DELETE> <FROM> tableName=TableName() + ( <USING> joined=JoinedRest(false, tableName) )? + ( <WHERE> whereCondition=ConditionExpression() )? + { return new SQLDelete(new Table(tableName, joined), whereCondition); } +} + +private SQLInsert Insert(): +{ + TableName tableName; + List<String> columns = FastList.newInstance(); + String n; + InsertSource source; +} +{ + <INSERT> <INTO> tableName=TableName() ( + <OPEN_PAREN> + n=NamePart() { columns.add(n); } + ( <COMMA> n=NamePart() { columns.add(n); } )* + <CLOSE_PAREN> + )? + ( source=InsertValues() | source=Select() ) + { return new SQLInsert(tableName, source, columns); } +} + +private InsertValues InsertValues(): +{ + List<InsertRow> list = FastList.newInstance(); + InsertRow row; +} +{ + <VALUES> + row=InsertRow() { list.add(row); } + ( <COMMA> row=InsertRow() { list.add(row); } )* + { return new InsertValues(list); } +} + +private InsertRow InsertRow(): +{ + List<Value> list = FastList.newInstance(); + Value v; +} +{ + <OPEN_PAREN> + v=InsertValue() { list.add(v); } + ( <COMMA> v=InsertValue() { list.add(v); } )* + <CLOSE_PAREN> + { return new InsertRow(list); } +} + +private Value InsertValue(): +{ + Value v; + Integer i; + String s; +} +{ + v=ParameterValue() { return v; } +| i=Integer() { return new NumberValue<Integer>(i); } +| s=SQuoted() { return new StringValue(s); } +} + +private List<SetField> SetField(): +{ + List<SetField> setFields = FastList.newInstance(); + String n; + Value v; + List<String> columnList = FastList.newInstance(); + List<Value> valueList = FastList.newInstance(); +} +{ + ( + n=NamePart() <EQUALS> v=Value() { setFields.add(new SetField(n, v)); } + | <OPEN_PAREN> + n=NamePart() { columnList.add(n); } + ( <COMMA> n=NamePart() { columnList.add(n); } )* + <CLOSE_PAREN> + <EQUALS> + <OPEN_PAREN> + v=Value() { valueList.add(v); } + ( <COMMA> v=Value() { valueList.add(v); } )* + <CLOSE_PAREN> + ) + { return setFields; } +} + +private Table Table(): +{ + TableName tableName; + Joined joined = null; +} +{ + tableName=TableName() + ( joined=Joined(tableName) )? + { return new Table(tableName, joined); } +} + +private Joined Joined(TableName leftTableName): +{ + Boolean isOptional; + Joined joined = null; +} +{ + isOptional=Joiner() joined=JoinedRest(isOptional, leftTableName) + { return joined; } +} + +private Joined JoinedRest(boolean isOptional, TableName leftTableName): +{ + TableName rightTableName; + List<KeyMap> keyMaps; + Joined joined = null; +} +{ + rightTableName=TableName() + keyMaps=KeyMaps(leftTableName.getAlias(), rightTableName.getAlias()) + ( joined=Joined(rightTableName) )? + { return new Joined(isOptional, rightTableName, keyMaps, joined); } +} + +private List<KeyMap> KeyMaps(String leftAlias, String rightAlias): +{ + List<KeyMap> keyMaps = FastList.newInstance(); + String n; +} +{ + ( + <ON> + KeyMap(keyMaps, leftAlias, rightAlias) + ( <AND> KeyMap(keyMaps, leftAlias, rightAlias) )* + | + <USING> + n=NamePart() { keyMaps.add(new KeyMap(n, n)); } + ( <COMMA> n=NamePart() { keyMaps.add(new KeyMap(n, n)); } )* + ) + { return keyMaps; } +} + +private void KeyMap(List<KeyMap> keyMaps, String leftAlias, String rightAlias): +{ + String alias1, field1; + String alias2, field2; +} +{ + alias1=NamePart() <PERIOD> field1=NamePart() + <EQUALS> + alias2=NamePart() <PERIOD> field2=NamePart() + { + if (alias1.equals(leftAlias)) { + if (!alias2.equals(rightAlias)) throw new IllegalArgumentException("invalid right alias(" + alias2 + "), expected(" + rightAlias + ")"); + keyMaps.add(new KeyMap(field1, field2)); + } else if (alias1.equals(rightAlias)) { + if (!alias2.equals(leftAlias)) throw new IllegalArgumentException("invalid left alias(" + alias2 + "), expected(" + leftAlias + ")"); + keyMaps.add(new KeyMap(field2, field1)); + } else { + throw new IllegalArgumentException("invalid aliases, expected(" + leftAlias + " or " + rightAlias + ")"); + } + } +} + +private TableName TableName(): +{ + String tableName, alias = null; +} +{ + tableName=NamePart() + ( (<AS>)? alias=NamePart() )? + { return new TableName(tableName, alias); } +} + +private Boolean Joiner(): +{} +{ + <LEFT> <JOIN> { return Boolean.TRUE; } +| <JOIN> { return Boolean.FALSE; } +} + +private void FieldDef(Map<String, FieldDef> fieldDefs, List<FieldAll> fieldAlls): +{ + StaticValue v; + String n, fieldAlias = null, fieldName, exc; + FieldDef def; + List<String> excludeList = FastList.newInstance(); +} +{ + ( + n=NamePart() ( + <PERIOD> ( + <STAR> + ( + <EXCLUDE> <OPEN_PAREN> + exc=NamePart() { excludeList.add(exc); } + ( <COMMA> exc=NamePart() { excludeList.add(exc); } )* + <CLOSE_PAREN> + )? + { fieldAlls.add(new FieldAll(n, excludeList)); return; } + | fieldName=NamePart() ( <AS> fieldAlias=NamePart() )? { def = new FieldDefValue(new FieldValue(n, fieldName), fieldAlias); } + ) + | v=FunctionCallRest(n) <AS> fieldAlias=NamePart() { def = new FieldDefValue(v, fieldAlias); } + | ( <AS> fieldAlias=NamePart() )? { def = new FieldDefFieldValue(new FieldValue(null, n), fieldAlias); } + ) + | v=MathValue() <AS> fieldAlias=NamePart() { def = new FieldDefValue(v, fieldAlias); } + ) { + if (fieldDefs.containsKey(def.getAlias())) throw new IllegalArgumentException("duplicate alias(" + def.getAlias() + ")"); + fieldDefs.put(def.getAlias(), def); + } +} + +private StaticValue MathValue(): +{ + StaticValue v; + List<StaticValue> values = FastList.newInstance(); + String operator = null, newOperator; +} +{ + <OPEN_PAREN> + v=StaticValue() { values.add(v); } + ( + newOperator=MathOperator() + v=StaticValue() { + if (operator == null) { + operator = newOperator; + } else if (!newOperator.equals(operator)) { + throw new IllegalArgumentException("Different operators in complex alias(" + operator + ":" + newOperator + ")"); + } + values.add(v); + } + )* + <CLOSE_PAREN> + { + if (values.size() == 1) return values.get(0); + return new MathValue(operator, values); + } +} + +private FunctionCall FunctionCallRest(String name): +{ + Value arg; + List<Value> args = FastList.newInstance(); +} +{ + <OPEN_PAREN> + ( + arg=Value() { args.add(arg); } + ( <COMMA> arg=Value() { args.add(arg); } )* + ) ? + <CLOSE_PAREN> + { return new FunctionCall(name, args); } +} + +private StaticValue StaticValue(): +{ + String n; + StaticValue v; +} +{ + n=NamePart() ( + v=FunctionCallRest(n) { return v; } + | v=FieldValue(n) { return v; } + ) +| v=MathValue() { return v; } +} + +private String NamePart(): +{} +{ + <NAME> { return getToken(0).image; } +| <TYPE> { return getToken(0).image; } +} + +private String DQuoted(): +{ StringBuilder sb = new StringBuilder(); } +{ + <START_DQUOTE> (<TEXT> { sb.append(getToken(0).image); } | <ESCAPED> { sb.append(getToken(0).image); })* <END_DQUOTE> + { return sb.toString(); } +} + +private String SQuoted(): +{ StringBuilder sb = new StringBuilder(); } +{ + <START_SQUOTE> ( + <TEXT> { sb.append(getToken(0).image); } + | <ESCAPED> { sb.append(getToken(0).image); } + | <ESCAPE_SQUOTE> { sb.append("'"); } + )* <END_SQUOTE> + { return sb.toString(); } +} + +private List<String> FieldList(): +{ + List<String> list = FastList.newInstance(); + String n; +} +{ + n=NamePart() { list.add(n); } + ( <COMMA> n=NamePart() { list.add(n); } )* + { return list; } +} + +private FieldValue FieldValue(String fieldName): +{ + String tableAlias = null, s; +} +{ + ( <PERIOD> s=NamePart() { tableAlias = fieldName; fieldName = s; } )? + { + return new FieldValue(tableAlias, fieldName); + } +} + +private List<String> OrderByList(): +{ + List<String> orderBy = FastList.newInstance(); + String obi; +} +{ + obi=OrderByItem() { orderBy.add(obi); } + ( <COMMA> obi=OrderByItem() { orderBy.add(obi); } )* + { return orderBy; } +} + +private String OrderByItem(): +{ + StringBuilder sb = new StringBuilder(); + String n; +} +{ + n=NamePart() { sb.append(n); } + ( + <DESC> { sb.append(" DESC"); } + | <ASC> { sb.append(" ASC"); } + )? + { return sb.toString(); } +} + +private Integer Integer(): +{} +{ + <INTEGER> { + try { + Converter<String, Integer> converter = Converters.getConverter(String.class, Integer.class); + return converter.convert(getToken(0).image); + } catch (ClassNotFoundException e) { + return null; + } catch (ConversionException e) { + return null; + } + } +} + +private Value Value(): +{ + String n; + Value v; + int i; + String s; +} +{ + n=NamePart() ( + v=FunctionCallRest(n) { return v; } + | v=FieldValue(n) { return v; } + ) +| i=Integer() { return new NumberValue<Integer>(i); } +| s=SQuoted() { return new StringValue(s); } +} + +private Condition ConditionExpression(): +{ Condition c; } +{ + c=OrExpression() { return c; } +} + +private Condition AndExpression(): +{ + List<Condition> list = FastList.newInstance(); + Condition c; +} +{ + c=BooleanExpression() { list.add(c); } + ( <AND> c=BooleanExpression() { list.add(c); } )* + { return list.size() == 1 ? list.get(0) : new ConditionList(Joiner.AND, list); } +} + +private Condition OrExpression(): +{ + List<Condition> list = FastList.newInstance(); + Condition c; +} +{ + c=AndExpression() { list.add(c); } + ( <OR> c=AndExpression() { list.add(c); } )* + { return list.size() == 1 ? list.get(0) : new ConditionList(Joiner.OR, list); } +} + +private Value RightValue(): +{ + Value v; +} +{ + v=Value() { return v; } +| v=ParameterValue() { return v; } +} + +private ParameterValue ParameterValue(): +{} +{ + <PARAMETER> { return new ParameterValue(getToken(0).image.substring(1)); } +} + +private Condition BooleanExpression(): +{ + Value v1, v2, v; + String op; + Condition c; + List<Value> list = FastList.newInstance(); +} +{ + v1=Value() ( + <BETWEEN> + v=RightValue() { list.add(v); } + <AND> + v=RightValue() { list.add(v); } + { v2 = new ListValue(list); op = "between"; } + | op=ComparisonOperator() ( + v2=RightValue() + | <OPEN_PAREN> + v=RightValue() { list.add(v); } + ( <COMMA> v=RightValue() { list.add(v); } )* + <CLOSE_PAREN> + { v2 = new ListValue(list); } + ) + ) + { return new BooleanCondition(v1, op, v2); } +| <OPEN_PAREN> c=ConditionExpression() <CLOSE_PAREN> { return c; } +} + +private String ComparisonOperator(): +{} +{ + ( <TEXT> )+ { return getToken(0).image; } +| <NAME> { return getToken(0).image; } +| <EQUALS> { return getToken(0).image.toLowerCase(); } +} + +private String MathOperator(): +{} +{ + ( <TEXT> )+ { return getToken(0).image.toLowerCase(); } +| <NAME> { return getToken(0).image.toLowerCase(); } +} diff --git a/framework/sql/src/org/ofbiz/sql/Planner.java b/framework/sql/src/org/ofbiz/sql/Planner.java new file mode 100644 index 0000000000..70cb9b831d --- /dev/null +++ b/framework/sql/src/org/ofbiz/sql/Planner.java @@ -0,0 +1,27 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.ofbiz.sql; + +public interface Planner<P extends Planner<P, D, I, S, U, V>, D extends DeletePlan<D>, I extends InsertPlan<I>, S extends SelectPlan<S>, U extends UpdatePlan<U>, V extends ViewPlan<V>> { + D plan(SQLDelete<?> deleteStatement); + I plan(SQLInsert<?> insertStatement); + S plan(SQLSelect<?> selectStatement); + U plan(SQLUpdate<?> updateStatement); + V plan(SQLView<?> viewStatement); +} diff --git a/framework/sql/src/org/ofbiz/sql/Relation.java b/framework/sql/src/org/ofbiz/sql/Relation.java new file mode 100644 index 0000000000..8fd45b623d --- /dev/null +++ b/framework/sql/src/org/ofbiz/sql/Relation.java @@ -0,0 +1,71 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.ofbiz.sql; + +import java.util.Iterator; +import java.util.List; + +import org.ofbiz.base.util.Appender; + +public final class Relation implements Appender<StringBuilder>, Iterable<KeyMap> { + private final String type; + private final String title; + private final String entityName; + private final List<KeyMap> keyMaps; + + public Relation(String type, String title, String entityName, List<KeyMap> keyMaps) { + this.type = type; + this.title = title; + this.entityName = entityName; + this.keyMaps = keyMaps; + } + + public String getType() { + return type; + } + + public String getTitle() { + return title; + } + + public String getEntityName() { + return entityName; + } + + public Iterator<KeyMap> iterator() { + return keyMaps.iterator(); + } + + public StringBuilder appendTo(StringBuilder sb) { + sb.append("RELATION"); + if (type != null) { + sb.append(' ').append(type); + } + if (title != null) { + sb.append(' ').append(title); + } + sb.append(' ').append(entityName); + sb.append(" ON"); + for (int i = 0; i < keyMaps.size(); i++) { + sb.append(' '); + keyMaps.get(i).appendTo("cur", "other", sb); + } + return sb; + } +} diff --git a/framework/sql/src/org/ofbiz/sql/SQLDelete.java b/framework/sql/src/org/ofbiz/sql/SQLDelete.java new file mode 100644 index 0000000000..9768bee80b --- /dev/null +++ b/framework/sql/src/org/ofbiz/sql/SQLDelete.java @@ -0,0 +1,57 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.ofbiz.sql; + +public final class SQLDelete<P extends DeletePlan<P>> extends SQLStatement<SQLDelete<P>, P> { + private final Table table; + private final Condition whereCondition; + + public SQLDelete(Table table, Condition whereCondition) { + this.table = table; + this.whereCondition = whereCondition; + } + + @SuppressWarnings("unchecked") + public <PP extends P> PP plan(Planner<?, ?, ?, ?, ?, ?> planner) { + return (PP) planner.plan(this); + } + + public Table getTable() { + return table; + } + + public Condition getWhereCondition() { + return whereCondition; + } + + public StringBuilder appendTo(StringBuilder sb) { + sb.append("DELETE FROM "); + table.getTableName().appendTo(sb); + if (table.getJoined() != null) { + sb.append(" USING"); + table.getJoined().appendToRest(table.getTableName().getAlias(), sb); + } + if (whereCondition != null) { + sb.append(" WHERE "); + whereCondition.appendTo(sb); + } + sb.append(';'); + return sb; + } +} diff --git a/framework/sql/src/org/ofbiz/sql/SQLInsert.java b/framework/sql/src/org/ofbiz/sql/SQLInsert.java new file mode 100644 index 0000000000..8a2c520c43 --- /dev/null +++ b/framework/sql/src/org/ofbiz/sql/SQLInsert.java @@ -0,0 +1,54 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.ofbiz.sql; + +import java.util.List; + +import org.ofbiz.base.util.StringUtil; +import org.ofbiz.base.util.UtilGenerics; + +public final class SQLInsert<P extends InsertPlan<P>> extends SQLStatement<SQLInsert<P>, P> { + private final TableName tableName; + private final InsertSource source; + private final List<String> columns; + + public SQLInsert(TableName tableName, InsertSource source, List<String> columns) { + this.tableName = tableName; + this.source = source; + this.columns = columns; + } + + @SuppressWarnings("unchecked") + public <PP extends P> PP plan(Planner<?, ?, ?, ?, ?, ?> planner) { + return (PP) planner.plan(this); + } + + public StringBuilder appendTo(StringBuilder sb) { + sb.append("INSERT INTO "); + tableName.appendTo(sb); + if (columns != null && !columns.isEmpty()) { + sb.append(" ("); + StringUtil.append(sb, columns, null, null, ", "); + sb.append(')'); + } + sb.append(' '); + source.appendTo(sb); + return sb; + } +} diff --git a/framework/sql/src/org/ofbiz/sql/SQLPlan.java b/framework/sql/src/org/ofbiz/sql/SQLPlan.java new file mode 100644 index 0000000000..1e85dc8ce5 --- /dev/null +++ b/framework/sql/src/org/ofbiz/sql/SQLPlan.java @@ -0,0 +1,24 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.ofbiz.sql; + +import java.util.Map; + +public abstract class SQLPlan<P extends SQLPlan<P>> { +} diff --git a/framework/sql/src/org/ofbiz/sql/SQLSelect.java b/framework/sql/src/org/ofbiz/sql/SQLSelect.java new file mode 100644 index 0000000000..f252ed99b0 --- /dev/null +++ b/framework/sql/src/org/ofbiz/sql/SQLSelect.java @@ -0,0 +1,136 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.ofbiz.sql; + +import java.util.Collection; +import java.util.Iterator; +import java.util.List; +import java.util.ListIterator; +import java.util.Map; + +import org.ofbiz.base.util.StringUtil; + +public final class SQLSelect<P extends SelectPlan<P>> extends SQLStatement<SQLSelect<P>, P> implements InsertSource { + private final List<FieldAll> fieldAlls; + private final Map<String, FieldDef> fieldDefs; + private final Table table; + private final List<Relation> relations; + private final Condition whereCondition; + private final Condition havingCondition; + private final int offset; + private final int limit; + private final List<String> orderBy; + private final List<String> groupBy; + + public SQLSelect(List<FieldAll> fieldAlls, Map<String, FieldDef> fieldDefs, Table table, List<Relation> relations, Condition whereCondition, Condition havingCondition, List<String> groupBy, List<String> orderBy, int offset, int limit) { + this.fieldAlls = fieldAlls; + this.fieldDefs = fieldDefs; + this.table = table; + this.relations = relations; + this.whereCondition = whereCondition; + this.havingCondition = havingCondition; + this.groupBy = groupBy; + this.orderBy = orderBy; + this.offset = offset; + this.limit = limit; + } + + @SuppressWarnings("unchecked") + public <PP extends P> PP plan(Planner<?, ?, ?, ?, ?, ?> planner) { + return (PP) planner.plan(this); + } + + public Collection<FieldAll> getFieldAlls() { + return fieldAlls; + } + + public Collection<FieldDef> getFieldDefs() { + return fieldDefs.values(); + } + + public Table getTable() { + return table; + } + + public List<Relation> getRelations() { + return relations; + } + + public Condition getWhereCondition() { + return whereCondition; + } + + public Condition getHavingCondition() { + return havingCondition; + } + + public List<String> getGroupBy() { + return groupBy; + } + + public List<String> getOrderBy() { + return orderBy; + } + + public int getOffset() { + return offset; + } + + public int getLimit() { + return limit; + } + + public StringBuilder appendTo(StringBuilder sb) { + sb.append("SELECT"); + StringUtil.appendTo(sb, fieldAlls, " ", null, ","); + if (!fieldAlls.isEmpty() && !fieldDefs.isEmpty()) { + sb.append(','); + } + StringUtil.appendTo(sb, fieldDefs.values(), " ", null, ","); + sb.append(" FROM "); + table.appendTo(sb); + if (!relations.isEmpty()) { + StringUtil.appendTo(sb, relations, " ", null, ","); + } + if (whereCondition != null) { + sb.append(" WHERE "); + whereCondition.appendTo(sb); + } + if (havingCondition != null) { + sb.append(" HAVING "); + havingCondition.appendTo(sb); + } + if (offset != -1) { + sb.append(" OFFSET ").append(offset); + } + if (limit != -1) { + sb.append(" LIMIT ").append(limit); + } + if (groupBy != null) { + sb.append(" GROUP BY "); + StringUtil.append(sb, groupBy, null, null, ", "); + } + if (orderBy != null) { + sb.append(" ORDER BY "); + StringUtil.append(sb, orderBy, null, null, ", "); + } + sb.append(';'); + return sb; + } +} diff --git a/framework/sql/src/org/ofbiz/sql/SQLStatement.java b/framework/sql/src/org/ofbiz/sql/SQLStatement.java new file mode 100644 index 0000000000..a9f4fff5f5 --- /dev/null +++ b/framework/sql/src/org/ofbiz/sql/SQLStatement.java @@ -0,0 +1,29 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.ofbiz.sql; + +import org.ofbiz.base.util.Appender; + +public abstract class SQLStatement<S extends SQLStatement<S, P>, P extends SQLPlan<P>> implements Appender<StringBuilder> { + public abstract <PP extends P> PP plan(Planner<?, ?, ?, ?, ?, ?> planner); + + public String toString() { + return appendTo(new StringBuilder()).toString(); + } +} diff --git a/framework/sql/src/org/ofbiz/sql/SQLUpdate.java b/framework/sql/src/org/ofbiz/sql/SQLUpdate.java new file mode 100644 index 0000000000..db9951a87d --- /dev/null +++ b/framework/sql/src/org/ofbiz/sql/SQLUpdate.java @@ -0,0 +1,96 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.ofbiz.sql; + +import java.util.Iterator; +import java.util.List; + +import org.ofbiz.base.util.StringUtil; + +public final class SQLUpdate<P extends UpdatePlan<P>> extends SQLStatement<SQLUpdate<P>, P> { + private final Table table; + private final List<SetField> setFields; + private final Condition whereCondition; + + public SQLUpdate(Table table, List<SetField> setFields, Condition whereCondition) { + this.table = table; + this.setFields = setFields; + this.whereCondition = whereCondition; + } + + @SuppressWarnings("unchecked") + public <PP extends P> PP plan(Planner<?, ?, ?, ?, ?, ?> planner) { + return (PP) planner.plan(this); + } + + public Table getTable() { + return table; + } + + public List<SetField> getSetFields() { + return setFields; + } + + public Condition getWhereCondition() { + return whereCondition; + } + + public StringBuilder appendTo(StringBuilder sb) { + sb.append("UPDATE "); + table.getTableName().appendTo(sb); + // n=4;1+(n-1)*2+3+(n-1)*2+1;3*n+(n-1)*2 + // 17 + // 18 + sb.append(" SET "); + if (setFields.size() <= 3) { + StringUtil.appendTo(sb, setFields, null, null, ", "); + } else { + Iterator<SetField> it = setFields.iterator(); + sb.append('('); + while (it.hasNext()) { + SetField setField = it.next(); + sb.append(setField.getName()); + if (it.hasNext()) { + sb.append(", "); + } + } + sb.append(") = ("); + it = setFields.iterator(); + while (it.hasNext()) { + SetField setField = it.next(); + setField.getValue().appendTo(sb); + if (it.hasNext()) { + sb.append(", "); + } + } + sb.append(')'); + it = setFields.iterator(); + } + if (table.getJoined() != null) { + sb.append(" FROM "); + table.getJoined().appendToRest(table.getTableName().getAlias(), sb); + } + if (whereCondition != null) { + sb.append(" WHERE "); + whereCondition.appendTo(sb); + } + sb.append(';'); + return sb; + } +} diff --git a/framework/sql/src/org/ofbiz/sql/SQLView.java b/framework/sql/src/org/ofbiz/sql/SQLView.java new file mode 100644 index 0000000000..d5ec1e84e7 --- /dev/null +++ b/framework/sql/src/org/ofbiz/sql/SQLView.java @@ -0,0 +1,50 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.ofbiz.sql; + +import java.util.ListIterator; + +public final class SQLView<P extends ViewPlan<P>> extends SQLStatement<SQLView<P>, P> { + private final String name; + private final SQLSelect sqlSelect; + + public SQLView(String name, SQLSelect sqlSelect) { + this.name = name; + this.sqlSelect = sqlSelect; + } + + @SuppressWarnings("unchecked") + public <PP extends P> PP plan(Planner<?, ?, ?, ?, ?, ?> planner) { + return (PP) planner.plan(this); + } + + public String getName() { + return name; + } + + public SQLSelect getSelect() { + return sqlSelect; + } + + public StringBuilder appendTo(StringBuilder sb) { + sb.append("CREATE VIEW ").append(name).append(" AS "); + sqlSelect.appendTo(sb); + return sb; + } +} diff --git a/framework/sql/src/org/ofbiz/sql/SelectPlan.java b/framework/sql/src/org/ofbiz/sql/SelectPlan.java new file mode 100644 index 0000000000..1bab7c479e --- /dev/null +++ b/framework/sql/src/org/ofbiz/sql/SelectPlan.java @@ -0,0 +1,22 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.ofbiz.sql; + +public abstract class SelectPlan<P extends SelectPlan<P>> extends SQLPlan<P> { +} diff --git a/framework/sql/src/org/ofbiz/sql/SetField.java b/framework/sql/src/org/ofbiz/sql/SetField.java new file mode 100644 index 0000000000..d1b8aaa11b --- /dev/null +++ b/framework/sql/src/org/ofbiz/sql/SetField.java @@ -0,0 +1,45 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.ofbiz.sql; + +import org.ofbiz.base.util.Appender; + +public final class SetField implements Appender<StringBuilder> { + private final String name; + private final Value value; + + public SetField(String name, Value value) { + this.name = name; + this.value = value; + } + + public String getName() { + return name; + } + + public Value getValue() { + return value; + } + + public StringBuilder appendTo(StringBuilder sb) { + sb.append(name).append(" = "); + value.appendTo(sb); + return sb; + } +} diff --git a/framework/sql/src/org/ofbiz/sql/StaticValue.java b/framework/sql/src/org/ofbiz/sql/StaticValue.java new file mode 100644 index 0000000000..40dd89f5bc --- /dev/null +++ b/framework/sql/src/org/ofbiz/sql/StaticValue.java @@ -0,0 +1,23 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.ofbiz.sql; + +public abstract class StaticValue extends Value { + public abstract String getDefaultName(); +} diff --git a/framework/sql/src/org/ofbiz/sql/StringValue.java b/framework/sql/src/org/ofbiz/sql/StringValue.java new file mode 100644 index 0000000000..61971cd8d0 --- /dev/null +++ b/framework/sql/src/org/ofbiz/sql/StringValue.java @@ -0,0 +1,36 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.ofbiz.sql; + +public final class StringValue extends ConstantValue { + private final String str; + + public StringValue(String str) { + this.str = str; + } + + public String getString() { + return str; + } + + public StringBuilder appendTo(StringBuilder sb) { + sb.append('\'').append(str.replaceAll("'", "''")).append('\''); + return sb; + } +} diff --git a/framework/sql/src/org/ofbiz/sql/Table.java b/framework/sql/src/org/ofbiz/sql/Table.java new file mode 100644 index 0000000000..bfa03d9bf8 --- /dev/null +++ b/framework/sql/src/org/ofbiz/sql/Table.java @@ -0,0 +1,55 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.ofbiz.sql; + +import org.ofbiz.base.util.Appender; + +public final class Table implements Appender<StringBuilder> { + private final TableName tableName; + private final Joined joined; + + public Table(TableName tableName) { + this(tableName, null); + } + + public Table(TableName tableName, Joined joined) { + this.tableName = tableName; + this.joined = joined; + } + + public TableName getTableName() { + return tableName; + } + + public Joined getJoined() { + return joined; + } + + public String toString() { + return appendTo(new StringBuilder()).toString(); + } + + public StringBuilder appendTo(StringBuilder sb) { + tableName.appendTo(sb); + if (joined != null) { + joined.appendTo(tableName.getAlias(), sb); + } + return sb; + } +} diff --git a/framework/sql/src/org/ofbiz/sql/TableName.java b/framework/sql/src/org/ofbiz/sql/TableName.java new file mode 100644 index 0000000000..598129067a --- /dev/null +++ b/framework/sql/src/org/ofbiz/sql/TableName.java @@ -0,0 +1,51 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.ofbiz.sql; + +import org.ofbiz.base.util.Appender; + +public final class TableName implements Appender<StringBuilder> { + private final String tableName; + private final String alias; + + public TableName(String tableName, String alias) { + this.tableName = tableName; + this.alias = alias != null ? alias : tableName; + } + + public final String getTableName() { + return tableName; + } + + public final String getAlias() { + return alias; + } + + public String toString() { + return appendTo(new StringBuilder()).toString(); + } + + public StringBuilder appendTo(StringBuilder sb) { + sb.append(tableName); + if (!alias.equals(tableName)) { + sb.append(' ').append(alias); + } + return sb; + } +} diff --git a/framework/sql/src/org/ofbiz/sql/UpdatePlan.java b/framework/sql/src/org/ofbiz/sql/UpdatePlan.java new file mode 100644 index 0000000000..81b6e42e9e --- /dev/null +++ b/framework/sql/src/org/ofbiz/sql/UpdatePlan.java @@ -0,0 +1,22 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.ofbiz.sql; + +public abstract class UpdatePlan<P extends UpdatePlan<P>> extends SQLPlan<P> { +} diff --git a/framework/sql/src/org/ofbiz/sql/Value.java b/framework/sql/src/org/ofbiz/sql/Value.java new file mode 100644 index 0000000000..65c9b1c102 --- /dev/null +++ b/framework/sql/src/org/ofbiz/sql/Value.java @@ -0,0 +1,27 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.ofbiz.sql; + +import org.ofbiz.base.util.Appender; + +public abstract class Value implements Appender<StringBuilder> { + public String toString() { + return appendTo(new StringBuilder()).toString(); + } +} diff --git a/framework/sql/src/org/ofbiz/sql/ViewPlan.java b/framework/sql/src/org/ofbiz/sql/ViewPlan.java new file mode 100644 index 0000000000..cd6793bd2e --- /dev/null +++ b/framework/sql/src/org/ofbiz/sql/ViewPlan.java @@ -0,0 +1,22 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.ofbiz.sql; + +public abstract class ViewPlan<P extends ViewPlan<P>> extends SQLPlan<P> { +} diff --git a/framework/webslinger/websites/webslinger/www/TestSQL.groovy b/framework/webslinger/websites/webslinger/www/TestSQL.groovy index 2cc417b049..c33b2c0ab6 100644 --- a/framework/webslinger/websites/webslinger/www/TestSQL.groovy +++ b/framework/webslinger/websites/webslinger/www/TestSQL.groovy @@ -4,28 +4,28 @@ import org.ofbiz.entity.transaction.TransactionUtil response.contentType = 'text/html' def delegator = request.delegator -def ec1 = SQLUtil.parseCondition("partyId = 'foo' AND partyTypeId = 'PARTY_GROUP'") +/* +def ec1 = SQLUtil.parseCondition("partyId = 'foo' AND partyTypeId = 'PARTY_GROUP' OR sequenceNum IN (1, 2) or foo BETWEEN 'a' and 'b'") +println("ec1=$ec1") response.writer.println("ec1=$ec1<br />") def ec2 = SQLUtil.parseCondition(ec1.toString()) +println("ec2=$ec2") response.writer.println("ec2=$ec2<br />") //return +*/ def sql = """ -select +SELECT a.partyId, - a.partyTypeId as type, - b.firstName, - b.lastName, - c.groupName + a.partyTypeId AS type, + COALESCE(b.firstName, '') AS firstName, + COALESCE(b.lastName, '') AS lastName, + COALESCE(c.groupName, '') AS groupName FROM Party a LEFT JOIN Person b USING partyId LEFT JOIN PartyGroup c USING partyId RELATION TYPE one Party USING partyId -RELATION TYPE one Person USING partyId -RELATION TYPE one PartyGroup USING partyId WHERE partyId = 'admin' -ORDER BY - lastName ; """ def sqlSelect = SQLUtil.parseSelect(sql) @@ -37,10 +37,8 @@ TransactionUtil.doNewTransaction("Test", [call: { def gv; while ((gv = eli.next()) != null) { response.writer.println("gv=$gv<br />") - def party = gv.getRelatedOneCache('Party') - def person = gv.getRelatedOneCache('Person') - response.writer.println("\tparty=$party<br />") - response.writer.println("\tperson=$person<br />") + def party = gv.getRelatedOneCache('Party'); response.writer.println("\tparty=$party<br />") + //def person = gv.getRelatedOneCache('Person'); response.writer.println("\tperson=$person<br />") } } finally { if (eli != null) eli.close()