Revision 44858

View differences:

trunk/org.gvsig.desktop/org.gvsig.desktop.library/org.gvsig.expressionevaluator/org.gvsig.expressionevaluator.lib/org.gvsig.expressionevaluator.lib.impl/src/main/java/org/gvsig/expressionevaluator/impl/grammars/BasicGrammarFactory.java
27 27
import org.gvsig.expressionevaluator.impl.function.programming.WhileFunction;
28 28
import org.gvsig.expressionevaluator.spi.AbstractGrammarFactory;
29 29
import org.gvsig.expressionevaluator.Code.Callable;
30
import static org.gvsig.expressionevaluator.ExpressionBuilder.FUNCTION_MAP;
30 31

  
31 32
/**
32 33
 *
......
346 347
            stmt.code(FUNCTION_EXTRACT,stmt.args_names("FIELD", "EXP"));
347 348
            theGrammar.addStatement(stmt);
348 349

  
350
            stmt = theGrammar.createStatement("MAP");
351
            stmt.addRule(stmt.require_any_token("MAP"));
352
            stmt.addRule(stmt.require_any_token("("));
353
            stmt.addRule(stmt.repeat()
354
                    .addRule(stmt.require_identifier().capture_as("NAME#"))
355
                    .addRule(stmt.require_any_token("="))
356
                    .addRule(stmt.require_expression().capture_as("VALUE#"))
357
                    .addRule(stmt.optional_any_token(",")
358
                            .addRuleOnFalse(stmt.break_loop())
359
                    )
360
            );      
361
            stmt.addRule(stmt.require_any_token(")"));
362
            stmt.code(FUNCTION_MAP,stmt.args_names("NAME#", "VALUE#"));
363
            theGrammar.addStatement(stmt);
364

  
349 365
            this.grammar = theGrammar;
350 366

  
351 367

  
trunk/org.gvsig.desktop/org.gvsig.desktop.library/org.gvsig.expressionevaluator/org.gvsig.expressionevaluator.lib/org.gvsig.expressionevaluator.lib.impl/src/main/java/org/gvsig/expressionevaluator/impl/symboltable/ProgrammingSymbolTable.java
9 9
import org.gvsig.expressionevaluator.impl.function.programming.CallStaticMethodFunction;
10 10
import org.gvsig.expressionevaluator.impl.function.programming.CodeBlockWithExceptFunction;
11 11
import org.gvsig.expressionevaluator.impl.function.programming.CreateFnFunction;
12
//import org.gvsig.expressionevaluator.impl.function.programming.EvalFunction;
12
import org.gvsig.expressionevaluator.impl.function.programming.EvalFunction;
13 13
import org.gvsig.expressionevaluator.impl.function.programming.FileFunction;
14 14
import org.gvsig.expressionevaluator.impl.function.programming.GetattrFunction;
15 15
import org.gvsig.expressionevaluator.impl.function.programming.GetitemFunction;
......
17 17
import org.gvsig.expressionevaluator.impl.function.programming.LenFunction;
18 18
import org.gvsig.expressionevaluator.impl.function.programming.LetFunction;
19 19
import org.gvsig.expressionevaluator.impl.function.programming.ListFunction;
20
import org.gvsig.expressionevaluator.impl.function.programming.MapFunction;
20 21
import org.gvsig.expressionevaluator.impl.function.programming.PrintFunction;
21 22
import org.gvsig.expressionevaluator.impl.function.programming.RangeFunction;
22 23
import org.gvsig.expressionevaluator.impl.function.programming.ReturnFunction;
......
61 62
        this.addFunction(new LenFunction());
62 63
        this.addFunction(new URLFunction());
63 64
        this.addFunction(new LabeledValueFunction());
64
//        this.addFunction(new EvalFunction());
65
        this.addFunction(new EvalFunction());
65 66
        this.addFunction(new UserFunction());
67
        this.addFunction(new MapFunction());
66 68
    }
67 69

  
68 70
    private void addOperator(Function operator) {
trunk/org.gvsig.desktop/org.gvsig.desktop.library/org.gvsig.expressionevaluator/org.gvsig.expressionevaluator.lib/org.gvsig.expressionevaluator.lib.impl/src/main/java/org/gvsig/expressionevaluator/impl/function/programming/MapFunction.java
1
package org.gvsig.expressionevaluator.impl.function.programming;
2

  
3
import java.util.HashMap;
4
import java.util.Map;
5
import org.apache.commons.lang3.Range;
6
import static org.gvsig.expressionevaluator.ExpressionBuilder.FUNCTION_MAP;
7
import org.gvsig.expressionevaluator.Function;
8
import org.gvsig.expressionevaluator.Interpreter;
9
import org.gvsig.expressionevaluator.spi.AbstractFunction;
10

  
11
public class MapFunction extends AbstractFunction {
12
    
13
    public MapFunction() {
14
        super(Function.GROUP_PROGRAMMING, 
15
                FUNCTION_MAP, 
16
                Range.between(0, Integer.MAX_VALUE),
17
                null,
18
                null,
19
                null,
20
                "MAP",
21
                false
22
        );
23
    }
24

  
25
    @Override
26
    public boolean allowConstantFolding() {
27
        return false;
28
    }
29
    
30
    @Override
31
    public Object call(Interpreter interpreter, Object[] args) throws Exception {
32
      Map<Object,Object> map = new HashMap<>();
33
      for (int i_key = 0, i_val = args.length/2; i_key < args.length/2; i_key++, i_val++) {
34
        Object key = args[i_key];
35
        Object value = args[i_val];
36
        map.put(key, value);
37
      }
38
      return map;
39
    }
40
}
trunk/org.gvsig.desktop/org.gvsig.desktop.library/org.gvsig.expressionevaluator/org.gvsig.expressionevaluator.lib/org.gvsig.expressionevaluator.lib.api/src/main/java/org/gvsig/expressionevaluator/ExpressionBuilder.java
109 109
    public static final String FUNCTION_EVAL = "EVAL";
110 110
    public static final String FUNCTION_LIST = "LIST";
111 111
    public static final String FUNCTION_TUPLE = "TUPLE";
112
    public static final String FUNCTION_MAP = "MAP";
112 113
    
113 114
    public static final String FUNCTION_GETATTR = "GETATTR";
114 115
    
trunk/org.gvsig.desktop/org.gvsig.desktop.compat.cdc/org.gvsig.fmap.dal/org.gvsig.fmap.dal.impl/src/main/java/org/gvsig/expressionevaluator/impl/function/dataaccess/ExistsTableFunction.java
1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2020 gvSIG Association.
5
 *
6
 * This program is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU General Public License
8
 * as published by the Free Software Foundation; either version 3
9
 * of the License, or (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19
 * MA  02110-1301, USA.
20
 *
21
 * For any additional information, do not hesitate to contact us
22
 * at info AT gvsig.com, or visit our website www.gvsig.com.
23
 */
24
package org.gvsig.expressionevaluator.impl.function.dataaccess;
25

  
26
import org.apache.commons.lang3.Range;
27
import org.gvsig.expressionevaluator.Interpreter;
28
import org.gvsig.expressionevaluator.impl.DALFunctions;
29
import org.gvsig.expressionevaluator.spi.AbstractFunction;
30
import org.gvsig.fmap.dal.DALLocator;
31
import org.gvsig.fmap.dal.DataManager;
32
import static org.gvsig.fmap.dal.DataManager.FUNCTION_EXISTS_TABLE;
33
import org.gvsig.fmap.dal.DataStoreParameters;
34

  
35
/**
36
 *
37
 * @author jjdelcerro
38
 */
39
public class ExistsTableFunction extends AbstractFunction {
40

  
41
  public ExistsTableFunction() {
42
    super(DALFunctions.SYMBOLTABLE_NAME,
43
            FUNCTION_EXISTS_TABLE,
44
            Range.is(1),
45
            "Check if a table exists in the applicacion.",
46
            FUNCTION_EXISTS_TABLE,
47
            null,
48
            "Boolean",
49
            false
50
    );
51
  }
52

  
53
  @Override
54
  public boolean allowConstantFolding() {
55
    return false;
56
  }
57

  
58
  @Override
59
  public Object call(Interpreter interpreter, Object[] args) throws Exception {
60
    DataManager dataManager = DALLocator.getDataManager();  
61
    DataStoreParameters p = dataManager.getStoresRepository().get(getStr(args,0));
62
    return p!=null;
63
  }
64
}
trunk/org.gvsig.desktop/org.gvsig.desktop.compat.cdc/org.gvsig.fmap.dal/org.gvsig.fmap.dal.impl/src/main/java/org/gvsig/expressionevaluator/impl/function/dataaccess/CreateInMemoryTableFunction.java
1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2020 gvSIG Association.
5
 *
6
 * This program is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU General Public License
8
 * as published by the Free Software Foundation; either version 3
9
 * of the License, or (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19
 * MA  02110-1301, USA.
20
 *
21
 * For any additional information, do not hesitate to contact us
22
 * at info AT gvsig.com, or visit our website www.gvsig.com.
23
 */
24
package org.gvsig.expressionevaluator.impl.function.dataaccess;
25

  
26
import java.util.Collections;
27
import java.util.HashMap;
28
import java.util.Iterator;
29
import java.util.Map;
30
import java.util.Set;
31
import org.apache.commons.lang3.Range;
32
import org.gvsig.expressionevaluator.ExpressionRuntimeException;
33
import org.gvsig.expressionevaluator.Interpreter;
34
import org.gvsig.expressionevaluator.impl.DALFunctions;
35
import org.gvsig.expressionevaluator.spi.AbstractFunction;
36
import org.gvsig.fmap.dal.AbstractStoresRepository;
37
import org.gvsig.fmap.dal.BaseStoresRepository;
38
import org.gvsig.fmap.dal.DALLocator;
39
import org.gvsig.fmap.dal.DataManager;
40
import static org.gvsig.fmap.dal.DataManager.FUNCTION_CREATE_IN_MEMORY_TABLE;
41
import static org.gvsig.fmap.dal.DataManager.FUNCTION_EXISTS_TABLE;
42
import org.gvsig.fmap.dal.DataStore;
43
import org.gvsig.fmap.dal.DataStoreParameters;
44
import org.gvsig.fmap.dal.StoresRepository;
45
import org.gvsig.fmap.dal.feature.EditableFeatureType;
46
import org.gvsig.fmap.dal.feature.FeatureStore;
47
import org.gvsig.tools.util.UnmodifiableBasicSet;
48
import org.gvsig.tools.util.UnmodifiableBasicSetAdapter;
49

  
50
/**
51
 *
52
 * @author jjdelcerro
53
 */
54
public class CreateInMemoryTableFunction extends AbstractFunction {
55

  
56
  public CreateInMemoryTableFunction() {
57
    super(DALFunctions.SYMBOLTABLE_NAME,
58
            FUNCTION_CREATE_IN_MEMORY_TABLE,
59
            Range.is(2),
60
            "",
61
            FUNCTION_CREATE_IN_MEMORY_TABLE,
62
            null,
63
            "Table",
64
            false
65
    );
66
  }
67

  
68
  @Override
69
  public boolean allowConstantFolding() {
70
    return false;
71
  }
72

  
73
  @Override
74
  public Object call(Interpreter interpreter, Object[] args) throws Exception {
75
    DataManager dataManager = DALLocator.getDataManager();  
76
    StoresRepository storesRepository = dataManager.getStoresRepository();
77
    MemoryStoresRepository repo = (MemoryStoresRepository) storesRepository.getSubrepository("Temporary");
78
    if( repo == null ) {
79
      repo = new MemoryStoresRepository("Temporary");
80
      storesRepository.addRepository(repo);
81
    }
82
    String targetName = getStr(args,0);
83
    String sourceName = getStr(args,1);
84
    FeatureStore source = (FeatureStore) storesRepository.getStore(sourceName);
85
    if( source == null ) {
86
      throw new ExpressionRuntimeException("Can't locate source table '"+sourceName+"'.");    
87
    }
88
    EditableFeatureType featureType = source.getDefaultFeatureType().getEditable();
89
    
90
    FeatureStore target = dataManager.createMemoryStore(null);
91
    target.edit();
92
    target.update(featureType);
93
    target.finishEditing();
94
    repo.add(targetName, target);
95
    return target;
96
  }
97
  
98
  private class MemoryStoresRepository extends AbstractStoresRepository {
99
    private final Map<String,FeatureStore> repository;
100

  
101
    public MemoryStoresRepository(String name) {
102
      super(name);
103
      this.repository = new HashMap<>();
104
    }
105

  
106
    public void add(String name, FeatureStore store) {
107
      this.repository.put(name, store);
108
    }
109
    
110
    @Override
111
    protected DataStoreParameters getMyParameters(String name) {
112
      FeatureStore store = this.repository.get(name);
113
      return store.getParameters();
114
    }
115

  
116
    @Override
117
    protected boolean isEmptyMyRepository() {
118
      return this.repository.isEmpty();
119
    }
120

  
121
    @Override
122
    protected int getMySize() {
123
      return this.repository.size();
124
    }
125

  
126
    @Override
127
    protected UnmodifiableBasicSet<String> getMyKeySet() {
128
        Set<String> keyset = this.repository.keySet();
129
        if( keyset == null || keyset.isEmpty() ) {
130
            return UnmodifiableBasicSet.EMPTY_UNMODIFIABLEBASICSET;
131
        }
132
        return new UnmodifiableBasicSetAdapter<>(keyset);
133
    }
134

  
135
    @Override
136
    public DataStore getStore(String name) {
137
      FeatureStore store = this.repository.get(name);
138
      return store;
139
    }
140

  
141
    @Override
142
    public void add(String name, DataStoreParameters parameters) {
143

  
144
    }
145

  
146
    @Override
147
    public boolean contains(DataStoreParameters parameters) {
148
      return false;
149
    }
150

  
151
    @Override
152
    public boolean containsKey(String key) {
153
      return this.repository.containsKey(key);
154
    }
155

  
156
    @Override
157
    public Iterator<DataStoreParameters> iterator() {
158
      return Collections.EMPTY_LIST.iterator();
159
    }
160

  
161
    @Override
162
    public void remove(String name) {
163
      this.repository.remove(name);
164
    }
165

  
166
  }
167
}
trunk/org.gvsig.desktop/org.gvsig.desktop.compat.cdc/org.gvsig.fmap.dal/org.gvsig.fmap.dal.impl/src/main/java/org/gvsig/expressionevaluator/impl/function/dataaccess/SetRowTagFunction.java
1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2020 gvSIG Association.
5
 *
6
 * This program is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU General Public License
8
 * as published by the Free Software Foundation; either version 3
9
 * of the License, or (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19
 * MA  02110-1301, USA.
20
 *
21
 * For any additional information, do not hesitate to contact us
22
 * at info AT gvsig.com, or visit our website www.gvsig.com.
23
 */
24
package org.gvsig.expressionevaluator.impl.function.dataaccess;
25

  
26
import java.util.Objects;
27
import org.apache.commons.lang3.Range;
28
import org.gvsig.expressionevaluator.Codes;
29
import org.gvsig.expressionevaluator.ExpressionRuntimeException;
30
import org.gvsig.expressionevaluator.Interpreter;
31
import org.gvsig.expressionevaluator.impl.DALFunctions;
32
import static org.gvsig.expressionevaluator.impl.function.programming.FileFunction.NAME;
33
import org.gvsig.fmap.dal.DataManager;
34
import org.gvsig.fmap.dal.feature.Feature;
35

  
36
/**
37
 *
38
 * @author jjdelcerro
39
 */
40
public class SetRowTagFunction extends AbstractFeatureFunction {
41

  
42
  public SetRowTagFunction() {
43
    super(DALFunctions.SYMBOLTABLE_NAME,
44
            DataManager.FUNCTION_SET_ROW_TAG,
45
            Range.is(1),
46
            "Assign a value associated with a label of the current row. This value is not persistent.",
47
            DataManager.FUNCTION_SET_ROW_TAG+"({{name}}, value)",
48
            null,
49
            "Object",
50
            false
51
    );
52
  }
53

  
54
  @Override
55
  public boolean allowConstantFolding() {
56
    return false;
57
  }
58

  
59
  @Override
60
  public boolean useArgumentsInsteadObjects() {
61
    return false;
62
  }
63
  
64
  @Override
65
  public Object call(Interpreter interpreter, Object[] args) throws Exception {
66
    Feature f = this.current_row(interpreter);
67
    if( f!=null ) {
68
      String name = getStr(args,0);
69
      f.setExtraValue(name, args[0]);
70
    }
71
    return args[0];
72
  }
73
}
trunk/org.gvsig.desktop/org.gvsig.desktop.compat.cdc/org.gvsig.fmap.dal/org.gvsig.fmap.dal.impl/src/main/java/org/gvsig/expressionevaluator/impl/function/dataaccess/RowTagFunction.java
1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2020 gvSIG Association.
5
 *
6
 * This program is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU General Public License
8
 * as published by the Free Software Foundation; either version 3
9
 * of the License, or (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19
 * MA  02110-1301, USA.
20
 *
21
 * For any additional information, do not hesitate to contact us
22
 * at info AT gvsig.com, or visit our website www.gvsig.com.
23
 */
24
package org.gvsig.expressionevaluator.impl.function.dataaccess;
25

  
26
import java.util.Map;
27
import java.util.Objects;
28
import org.apache.commons.lang3.Range;
29
import org.gvsig.expressionevaluator.Code;
30
import org.gvsig.expressionevaluator.Codes;
31
import org.gvsig.expressionevaluator.ExpressionRuntimeException;
32
import org.gvsig.expressionevaluator.Interpreter;
33
import org.gvsig.expressionevaluator.impl.DALFunctions;
34
import org.gvsig.fmap.dal.DataManager;
35
import org.gvsig.fmap.dal.feature.Feature;
36
import org.gvsig.tools.util.GetItemByKey;
37

  
38
/**
39
 *
40
 * @author jjdelcerro
41
 */
42
public class RowTagFunction extends AbstractFeatureFunction {
43

  
44
  public RowTagFunction() {
45
    super(DALFunctions.SYMBOLTABLE_NAME,
46
            DataManager.FUNCTION_ROW_TAG,
47
            Range.between(1,2),
48
            "Retrieves a value associated with a tag from the current line.",
49
            DataManager.FUNCTION_ROW_TAG+"({{name}})",
50
            null,
51
            "Object",
52
            false
53
    );
54
  }
55

  
56
  @Override
57
  public boolean allowConstantFolding() {
58
    return false;
59
  }
60

  
61
  @Override
62
  public boolean useArgumentsInsteadObjects() {
63
    return true;
64
  }
65

  
66
  @Override
67
  public Object call(Interpreter interpreter, Object[] args) throws Exception {
68
    return null;
69
  }
70

  
71
  @Override
72
  public Object call(Interpreter interpreter, Codes args) throws Exception {
73
    Feature f = this.current_row(interpreter);
74
    if( f==null ) {
75
      return null;
76
    }
77
    String name = Objects.toString(getObject(interpreter, args, 0),null);
78
    if( name == null ) {
79
      throw new ExpressionRuntimeException("The first argument of '"+DataManager.FUNCTION_SET_ROW_TAG+"' can't be null.");    
80
    }
81
    if( args.size()==2 ) {
82
      if( !f.hasExtraValue(name) ) {
83
        Object map = Objects.toString(getObject(interpreter, args, 1),null);
84
        if( map instanceof Map) {
85
          for (Map.Entry<Object, Object> entry : ((Map<Object,Object>)map).entrySet()) {
86
            String key = Objects.toString(entry.getKey(),null);
87
            Object val = entry.getValue();
88
            if( key!=null ) {
89
              f.setExtraValue(key, val);
90
            }
91
          }
92
  //      } else if( map instanceof GetItemByKey && map instanceof GetKeys ) {
93
  //        for (String key : ((GetKeys<String>)map).getKeys() ) {
94
  //          Object val = ((GetItemByKey<String,Object>)map).get(key);
95
  //          f.setExtraValue(key, val);
96
  //        }
97
        }
98
      }
99
    }
100
   return f.getExtraValue(name);
101
  }
102
}
trunk/org.gvsig.desktop/org.gvsig.desktop.compat.cdc/org.gvsig.fmap.dal/org.gvsig.fmap.dal.impl/src/main/java/org/gvsig/expressionevaluator/impl/function/dataaccess/InsertIntoTableFunction.java
1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2020 gvSIG Association.
5
 *
6
 * This program is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU General Public License
8
 * as published by the Free Software Foundation; either version 3
9
 * of the License, or (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19
 * MA  02110-1301, USA.
20
 *
21
 * For any additional information, do not hesitate to contact us
22
 * at info AT gvsig.com, or visit our website www.gvsig.com.
23
 */
24
package org.gvsig.expressionevaluator.impl.function.dataaccess;
25

  
26
import java.util.ArrayList;
27
import java.util.List;
28
import java.util.Objects;
29
import org.apache.commons.lang3.Range;
30
import org.apache.commons.lang3.StringUtils;
31
import org.apache.commons.lang3.tuple.ImmutablePair;
32
import org.apache.commons.lang3.tuple.Pair;
33
import org.gvsig.expressionevaluator.Code;
34
import org.gvsig.expressionevaluator.CodeBuilder;
35
import org.gvsig.expressionevaluator.Codes;
36
import static org.gvsig.expressionevaluator.ExpressionBuilder.FUNCTION_GETATTR;
37
import static org.gvsig.expressionevaluator.ExpressionBuilder.FUNCTION_TUPLE;
38
import org.gvsig.expressionevaluator.ExpressionRuntimeException;
39
import org.gvsig.expressionevaluator.ExpressionUtils;
40
import org.gvsig.expressionevaluator.Interpreter;
41
import org.gvsig.expressionevaluator.Optimizer;
42
import org.gvsig.expressionevaluator.SymbolTable;
43
import org.gvsig.expressionevaluator.impl.DALFunctions;
44
import org.gvsig.expressionevaluator.spi.AbstractFunction;
45
import org.gvsig.fmap.dal.DALLocator;
46
import org.gvsig.fmap.dal.DataManager;
47
import static org.gvsig.fmap.dal.DataManager.FUNCTION_EXISTS_TABLE;
48
import static org.gvsig.fmap.dal.DataManager.FUNCTION_SELECT;
49
import org.gvsig.fmap.dal.DataStore;
50
import org.gvsig.fmap.dal.expressionevaluator.ExpressionEvaluator;
51
import static org.gvsig.fmap.dal.expressionevaluator.FeatureSymbolTable.SYMBOL_CURRENT_TABLE;
52
import org.gvsig.fmap.dal.expressionevaluator.TableAttributeHandler;
53
import org.gvsig.fmap.dal.feature.EditableFeature;
54
import org.gvsig.fmap.dal.feature.Feature;
55
import org.gvsig.fmap.dal.feature.FeatureQuery;
56
import org.gvsig.fmap.dal.feature.FeatureQueryOrder;
57
import org.gvsig.fmap.dal.feature.FeatureSet;
58
import org.gvsig.fmap.dal.feature.FeatureStore;
59
import org.gvsig.fmap.dal.impl.expressionevaluator.DefaultExpressionEvaluator;
60
import org.gvsig.tools.dispose.DisposeUtils;
61
import org.gvsig.tools.exception.BaseException;
62

  
63
/**
64
 *
65
 * @author jjdelcerro
66
 */
67
public class InsertIntoTableFunction 
68
        extends AbstractFunction 
69
        implements Optimizer.FunctionOptimizer
70
  {
71

  
72
  public InsertIntoTableFunction() {
73
    super(DALFunctions.SYMBOLTABLE_NAME,
74
            DataManager.FUNCTION_INSERT_INTO_TABLE,
75
            Range.is(7),
76
            "",
77
            DataManager.FUNCTION_INSERT_INTO_TABLE,
78
            null,
79
            "Number",
80
            false
81
    );
82
  }
83

  
84
  @Override
85
  public boolean allowConstantFolding() {
86
    return false;
87
  }
88

  
89

  
90
  @Override
91
  public boolean useArgumentsInsteadObjects() {
92
    return true;
93
  }
94
  
95
  @Override
96
  public Object call(Interpreter interpreter, Object[] args) throws Exception {
97
    throw new UnsupportedOperationException();
98
  }
99

  
100
  private static final int COLUMNS = 1;
101
  private static final int TABLE = 2;
102
  private static final int WHERE = 3;
103
  private static final int ORDER = 4;
104
  private static final int ORDER_MODE = 5;
105
  private static final int LIMIT = 6;
106
  
107
  
108
  private Code.Callable getTupleOrNull(Codes args, int argn) {
109
    Code code = args.get(argn);
110
    if( code.code()==Code.CONSTANT ) {
111
      if( ((Code.Constant)code).value()!=null ) {
112
        throw new ExpressionRuntimeException("Tupple or null expected in argument "+argn+ " of function '" + FUNCTION_SELECT + "'.");
113
      }
114
      return null;
115
    }
116
    if( code.code()!=Code.CALLABLE ) {
117
      throw new ExpressionRuntimeException("Tupple or null expected in argument "+argn+ " of function '" + FUNCTION_SELECT + "'.");
118
    }
119
    Code.Callable caller = (Code.Callable) code;
120
    if( !StringUtils.equalsIgnoreCase(FUNCTION_TUPLE, caller.name()) ) {
121
      throw new ExpressionRuntimeException("Tupple or null expected in argument "+argn+ " of function '" + FUNCTION_SELECT + "'.");
122
    }
123
    return caller;
124
  }
125
  
126
  @Override
127
  @SuppressWarnings("UseSpecificCatch")
128
  public Object call(Interpreter interpreter, Codes args) throws Exception {
129
    FeatureStore targetStore = null;
130
    FeatureStore sourceStore = null;
131
    try {
132
      String targetTableName = Objects.toString(getObject(interpreter, args, 0),null);
133
      if( targetTableName == null ) {
134
        throw new ExpressionRuntimeException("Target table name can't be null.");    
135
      }
136
      DataManager dataManager = DALLocator.getDataManager();  
137
      targetStore = (FeatureStore) dataManager.getStoresRepository().getStore(targetTableName);
138
      if( targetStore==null ) {
139
        throw new ExpressionRuntimeException("Can't locate target table '"+targetTableName+"'.");    
140
      }
141

  
142

  
143
      Code.Identifier storeName =  (Code.Identifier) args.get(TABLE);
144
      Code columns = getTupleOrNull(args, COLUMNS);
145
      Code where = args.get(WHERE);
146
      Number limit = (Number) getObject(interpreter, args, LIMIT);
147
      Code.Callable order = getTupleOrNull(args, ORDER);
148
      Code.Callable order_mode = getTupleOrNull(args, ORDER_MODE);
149

  
150
      FeatureQueryOrder queryOrder = null;
151
      if( order!=null || order_mode!=null ) {
152
        for( int n=0 ; n<order.parameters().size(); n++) {
153
          String member = (String) interpreter.run(order.parameters().get(n));
154
          Boolean mode = (Boolean) interpreter.run(order_mode.parameters().get(n));
155
          if( queryOrder == null ) {
156
            queryOrder = new FeatureQueryOrder();
157
          }
158
          queryOrder.add(member, mode);
159
        }
160
      }
161

  
162
      // FIXME: add columns to query.addAttributeName() 
163
      DataStore store = this.getStore(storeName.name());
164
      if (store == null ) {
165
        throw new ExpressionRuntimeException("Cant locate the store '" + storeName + "' in function '" + FUNCTION_SELECT + "'.");
166
      }
167
      if (!(store instanceof FeatureStore)) {
168
        throw new ExpressionRuntimeException("The store'" + storeName + "' is not valid for function '" + FUNCTION_SELECT + "', a FeatureStore is required.");
169
      }
170
      sourceStore = (FeatureStore) store;
171
      FeatureSet features;
172
      if (where == null && queryOrder == null && limit==null ) {
173
        features = sourceStore.getFeatureSet();
174
      } else {
175
        FeatureQuery query = sourceStore.createFeatureQuery();
176
        if (where != null) {
177
          removeOuterTablesReferences(interpreter, where);
178
          ExpressionEvaluator filter = new DefaultExpressionEvaluator(where.toString());
179
          filter.getSymbolTable().addSymbolTable(interpreter.getSymbolTable());
180
          query.addFilter(filter);
181
        }
182
        if (queryOrder != null) {
183
          query.getOrder().copyFrom(queryOrder);
184
        }
185
        if( limit!=null ) {
186
          query.setLimit(limit.longValue());
187
        }
188
        query.retrievesAllAttributes();
189
        features = sourceStore.getFeatureSet(query);
190
      }
191
      
192
      long count = 0;
193
      targetStore.edit(FeatureStore.MODE_APPEND);
194
      for (Feature feature : features) {
195
        EditableFeature f = targetStore.createNewFeature();
196
        f.copyFrom(feature);
197
        targetStore.insert(f);
198
        count++;
199
      }
200
      targetStore.finishEditing();
201
      
202
      return count;
203
    } catch (ExpressionRuntimeException ex) {
204
      throw ex;
205
    } catch (Exception ex) {
206
      if( targetStore!=null && targetStore.isAppending() ) {
207
        targetStore.cancelEditing();
208
      }
209
      DisposeUtils.disposeQuietly(targetStore);
210
      DisposeUtils.disposeQuietly(sourceStore);
211
      throw new ExpressionRuntimeException("Problems calling '" + FUNCTION_SELECT + "' function", ex);
212
    }
213
  }
214

  
215
  protected DataStore getStore(String storeName) {
216
    DataManager dataManager = DALLocator.getDataManager();
217
    DataStore store = dataManager.getStoresRepository().getStore(storeName);
218
    return store;
219
  }
220

  
221
  private void removeOuterTablesReferences(Interpreter interpreter, Code where) {
222
    try {
223
      SymbolTable symbolTable = interpreter.getSymbolTable();
224
      TableAttributeHandler table = (TableAttributeHandler) symbolTable.value(SYMBOL_CURRENT_TABLE);
225
      List<Pair<Code,Code>>replaces = new ArrayList<>();
226
      CodeBuilder codeBuilder = ExpressionUtils.createCodeBuilder();
227
      where.accept((Object o) -> {
228
        Code code = (Code) o;
229
        if( code!=null && code.code() == Code.CALLABLE ) {
230
          Code.Callable caller = (Code.Callable) code;
231
          if( StringUtils.equalsIgnoreCase(caller.name(),FUNCTION_GETATTR) ) {
232
            Codes args = caller.parameters();
233
            Code arg0 = args.get(0);
234
            Code arg1 = args.get(1);
235
            if( arg0 instanceof Code.Identifier && arg1 instanceof Code.Identifier ) {
236
              Object tt = symbolTable.value(((Code.Identifier)arg0).name());
237
              if( tt instanceof TableAttributeHandler && 
238
                  StringUtils.equalsIgnoreCase(((TableAttributeHandler)tt).getName(), table.getName()) ) {
239
                String columnName = Objects.toString(((Code.Identifier)arg1).name(), null);
240
                if( columnName!=null ) {
241
                  Object value = table.get(columnName);
242
                  replaces.add(
243
                          new ImmutablePair<>(
244
                                  caller,
245
                                  codeBuilder.constant(value)
246
                          )
247
                  );
248
                }
249
              }
250
            }
251
          }
252
        }
253
      });
254
      for (Pair<Code, Code> replace : replaces) {
255
        if( replace!=null ) {
256
          where.replace(replace.getLeft(), replace.getRight());
257
        }
258
      }
259
    } catch (BaseException ex) {
260
      throw new ExpressionRuntimeException("Can't remove references to outer tables.", ex);
261
    }
262
                
263
  }
264

  
265
  @Override
266
  public Code optimize(Optimizer optimizer, Code.Callable caller) {
267
    return caller; // Don't optimize SELECT
268
  }
269
}
trunk/org.gvsig.desktop/org.gvsig.desktop.compat.cdc/org.gvsig.fmap.dal/org.gvsig.fmap.dal.impl/src/main/java/org/gvsig/expressionevaluator/impl/grammars/DataAccessGrammarFactory.java
95 95
    @Override
96 96
    public Codes build(StatementContext context) {
97 97
      context.trace(this.toString() + ".build");
98

  
99
      CodeBuilder codeBuilder = context.getCodeBuilder();
100
      BaseCodes args = (BaseCodes) codeBuilder.args();
101
      return build(context,args);
102
    }
103
    
104
    public Codes build(StatementContext context, BaseCodes args) {
98 105
      int n;
99 106
      BaseCodes argsX;
100 107
      
101 108
      CodeBuilder codeBuilder = context.getCodeBuilder();
102
      BaseCodes args = (BaseCodes) codeBuilder.args();
103 109

  
104 110
      Code columns = context.getCode("COLUMNS");
105 111
      args.add(columns);
......
151 157
    }
152 158

  
153 159
  }
160
  private static class InsertIntoArgsBuilder 
161
          extends SelectArgsBuilder
162
          implements ArgsBuilder 
163
  {
154 164

  
165
    public InsertIntoArgsBuilder() {
166
    }
167

  
168
    @Override
169
    public String toString() {
170
      return "insert_into_args()";
171
    }
172

  
173
    @Override
174
    public Codes build(StatementContext context) {
175
      context.trace(this.toString() + ".build");
176

  
177
      CodeBuilder codeBuilder = context.getCodeBuilder();
178
      BaseCodes args = (BaseCodes) codeBuilder.args();
179

  
180
      Code table = context.getCode("TARGETTABLE");
181
      args.add(codeBuilder.identifier((String) ((Code.Constant) table).value()));
182
      
183
      return build(context,args);
184
    }
185
    
186
  }
187
  
155 188
  private static class SelectCountArgsBuilder implements ArgsBuilder {
156 189

  
157 190
    public SelectCountArgsBuilder() {
......
227 260
      );
228 261
      theGrammar.addStatement(stmt);
229 262

  
263
      stmt = theGrammar.createStatement("CREATE_IN_MEMORY_TABLE");
264
      stmt.addRule(stmt.require_any_token("CREATE"));
265
      stmt.addRule(stmt.require_any_token("IN"));
266
      stmt.addRule(stmt.require_any_token("MEMORY"));
267
      stmt.addRule(stmt.require_any_token("TABLE"));
268
      stmt.addRule(stmt.require_identifier().capture_as("NEWTABLE"));
269
      stmt.addRule(stmt.require_any_token("FROM"));
270
      stmt.addRule(stmt.require_identifier().capture_as("SOURCETABLE"));
271
      stmt.code(
272
              FUNCTION_FOREING_VALUE,
273
              stmt.args_names("NEWTABLE","SOURCETABLE")
274
      );
275
      theGrammar.addStatement(stmt);
276

  
230 277
      stmt = theGrammar.createStatement("SELECT");
231 278
      stmt.addRule(stmt.require_any_token("SELECT"));
232 279
      stmt.addRule(stmt.optional_any_token("*")
......
263 310
      );
264 311
      theGrammar.addStatement(stmt);
265 312

  
313
      stmt = theGrammar.createStatement("INSERT_INTO");
314
      stmt.addRule(stmt.require_any_token("INSERT"));
315
      stmt.addRule(stmt.require_any_token("INTO"));
316
      stmt.addRule(stmt.require_identifier().capture_as("TARGETTABLE"));
317
      stmt.addRule(stmt.require_any_token("SELECT"));
318
      stmt.addRule(stmt.optional_any_token("*")
319
              .addRuleOnTrue(stmt.set_expression("COLUMNS", codeBuilder.tuple()))
320
              .addRuleOnFalse(stmt.require_identifiers(",").capture_as("COLUMNS"))
321
      );
322
      stmt.addRule(stmt.require_any_token("FROM"));
323
      stmt.addRule(stmt.require_identifier().capture_as("TABLE"));
324
      stmt.addRule(stmt.optional_any_token("WHERE")
325
              .addRuleOnTrue(stmt.require_expression().capture_as("WHERE"))
326
      );
327

  
328
      stmt.addRule(stmt.optional_any_token("ORDER")
329
              .addRuleOnTrue(stmt.require_any_token("BY"))
330
              .addRuleOnTrue(stmt.repeat()
331
                      .addRule(stmt.require_expression().capture_as("ORDER#"))
332
                      .addRule(stmt.switch_token()
333
                              .addCase("ASC", stmt.set_expression("ORDER_MODE#", true))
334
                              .addCase("DESC", stmt.set_expression("ORDER_MODE#", false))
335
                              .addDefault(stmt.set_expression("ORDER_MODE#", true))
336
                      )
337
                      .addRule(stmt.optional_any_token(",")
338
                              .addRuleOnFalse(stmt.break_loop())
339
                      )
340
              )
341
      );
342
      stmt.addRule(stmt.optional_any_token("LIMIT")
343
              .addRuleOnTrue(stmt.require_expression().capture_as("LIMIT"))
344
      );
345
      stmt.addRule(stmt.optional_any_token(";"));
346
      stmt.code(
347
              FUNCTION_SELECT,
348
              new InsertIntoArgsBuilder()
349
      );
350
      theGrammar.addStatement(stmt);
351

  
266 352
      stmt = theGrammar.createStatement("SELECT_COUNT");
267 353
      stmt.addRule(stmt.require_any_token("SELECT"));
268 354
      stmt.addRule(stmt.require_any_token("COUNT"));
trunk/org.gvsig.desktop/org.gvsig.desktop.compat.cdc/org.gvsig.fmap.dal/org.gvsig.fmap.dal.impl/src/main/java/org/gvsig/expressionevaluator/impl/symboltable/DALSymbolTable.java
24 24
package org.gvsig.expressionevaluator.impl.symboltable;
25 25

  
26 26
import org.gvsig.expressionevaluator.impl.DALFunctions;
27
import org.gvsig.expressionevaluator.impl.function.dataaccess.CreateInMemoryTableFunction;
27 28
import org.gvsig.expressionevaluator.impl.function.dataaccess.CurrentRowFunction;
28 29
import org.gvsig.expressionevaluator.impl.function.dataaccess.CurrentStoreFunction;
29 30
import org.gvsig.expressionevaluator.impl.function.dataaccess.ExistsFunction;
30 31
import org.gvsig.expressionevaluator.impl.function.dataaccess.ForeingValueFunction;
31 32
import org.gvsig.expressionevaluator.impl.function.dataaccess.GeometryFunction;
33
import org.gvsig.expressionevaluator.impl.function.dataaccess.InsertIntoTableFunction;
32 34
import org.gvsig.expressionevaluator.impl.function.dataaccess.IsSelectedCurrentRowFunction;
35
import org.gvsig.expressionevaluator.impl.function.dataaccess.RowTagFunction;
33 36
import org.gvsig.expressionevaluator.impl.function.dataaccess.SelectCountFunction;
34 37
import org.gvsig.expressionevaluator.impl.function.dataaccess.SelectFunction;
38
import org.gvsig.expressionevaluator.impl.function.dataaccess.SetRowTagFunction;
35 39
import org.gvsig.expressionevaluator.spi.AbstractSymbolTable;
36 40

  
37 41
/**
......
57 61
        this.addFunction(new IsSelectedCurrentRowFunction());
58 62
        this.addFunction(new ForeingValueFunction());
59 63
        this.addFunction(new GeometryFunction());
64
        this.addFunction(new CreateInMemoryTableFunction());
65
        this.addFunction(new InsertIntoTableFunction());
66
        this.addFunction(new RowTagFunction());
67
        this.addFunction(new SetRowTagFunction());
60 68
    }    
61 69
}
trunk/org.gvsig.desktop/org.gvsig.desktop.compat.cdc/org.gvsig.fmap.dal/org.gvsig.fmap.dal.impl/src/main/java/org/gvsig/fmap/dal/feature/impl/DefaultFeature.java
28 28
import java.time.format.DateTimeFormatter;
29 29
import java.util.ArrayList;
30 30
import java.util.Date;
31
import java.util.HashMap;
31 32
import java.util.Iterator;
32 33
import java.util.List;
33 34
import java.util.Map;
......
82 83
	private WeakReference storeRef;
83 84

  
84 85
	private boolean inserted = false;
85
        private Object[] extraValuesData;
86
  private Object[] extraValuesData;
87
  private Map<String,Object> extraValues; // not persistent
86 88

  
87 89
    /*
88 90
	 * Usar con mucha precaucion o mejor no usar. Lo precisa el
......
1220 1222
        String label = attrdesc.getLabelOfValue(value);
1221 1223
        return label;
1222 1224
    }
1225
   
1226
    @Override
1227
    public void setExtraValue(String name, Object value) {
1228
      if( this.extraValues==null ) {
1229
        this.extraValues = new HashMap<>();
1230
      }
1231
      this.extraValues.put(name, value);
1232
    }
1223 1233

  
1224
    
1225
      @Override
1234
    @Override
1226 1235
    public Object getExtraValue(String name) {
1227 1236
        Object value;
1237
        if( this.extraValues!=null ) {
1238
          if( this.extraValues.containsKey(name) ) {
1239
            return this.extraValues.get(name);
1240
          }
1241
        }
1228 1242
        FeatureExtraColumns columns = this.getType().getExtraColumns();
1229 1243
        int index = columns.getIndexOf(name);
1230 1244
        if( index >= 0 ) {
......
1249 1263

  
1250 1264
    @Override
1251 1265
    public boolean hasExtraValue(String name) {
1266
        if( this.extraValues!=null ) {
1267
          if( this.extraValues.containsKey(name) ) {
1268
            return true;
1269
          }
1270
        }
1252 1271
        FeatureExtraColumns columns = this.getType().getExtraColumns();
1253 1272
        int index = columns.getIndexOf(name);
1254 1273
        if( index >= 0 ) {
trunk/org.gvsig.desktop/org.gvsig.desktop.compat.cdc/org.gvsig.fmap.dal/org.gvsig.fmap.dal.api/src/main/java/org/gvsig/fmap/dal/DataManager.java
77 77
    public static final String FUNCTION_SELECT = "SELECT";
78 78
    public static final String FUNCTION_SELECT_COUNT = "SELECT_COUNT";
79 79
    public static final String FUNCTION_EXISTS = "EXISTS";
80
    public static final String FUNCTION_EXISTS_TABLE = "EXISTS_TABLE";
81
    public static final String FUNCTION_ROW_TAG = "ROW_TAG";
82
    public static final String FUNCTION_SET_ROW_TAG = "SET_ROW_TAG";
80 83
    public static final String FUNCTION_CURRENT_ROW = "CURRENT_ROW";
81 84
    public static final String FUNCTION_CURRENT_STORE = "CURRENT_STORE";
82 85
    public static final String FUNCTION_ISSELECTED_CURRENT_ROW = "ISSELECTED_CURRENT_ROW";
83 86
    public static final String FUNCTION_GEOMETRY = "GEOMETRY";
87
    public static final String FUNCTION_CREATE_IN_MEMORY_TABLE = "CREATE_IN_MEMORY_TABLE";
88
    public static final String FUNCTION_INSERT_INTO_TABLE = "INSERT_INTO_TABLE";
84 89
    
85 90
    public static final String DAL_PREFERRED_COLUMNS = "DAL.Preferred.Columns";
86 91
    
trunk/org.gvsig.desktop/org.gvsig.desktop.compat.cdc/org.gvsig.fmap.dal/org.gvsig.fmap.dal.api/src/main/java/org/gvsig/fmap/dal/feature/Feature.java
492 492
  public Object getExtraValue(String name);
493 493

  
494 494
  public boolean hasExtraValue(String name);
495
  
496
  public void setExtraValue(String name, Object value);
495 497

  
496 498
//  public Feature getRelatedFeature(String name);
497 499
//  

Also available in: Unified diff