]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/CodeGen.java
First step to enable reading of cache when not writing
[simantics/platform.git] / bundles / org.simantics.db.impl / src / org / simantics / db / impl / query / CodeGen.java
1 package org.simantics.db.impl.query;
2
3 import java.io.File;
4 import java.io.IOException;
5 import java.io.UnsupportedEncodingException;
6 import java.net.MalformedURLException;
7 import java.net.URL;
8 import java.net.URLDecoder;
9
10 import org.simantics.utils.FileUtils;
11
12 public class CodeGen {
13
14     int indent = 4;
15
16     class GenerationInfo {
17         String p1;
18         String keyName;
19         String keyToId;
20         String procedure;
21         boolean useNeedsToBlock;
22         String entryCreationArguments;
23         GenerationInfo(String p1, String keyName, String keyToId, String p4, String procedure, String entryCreationArguments, boolean useNeedsToBlock) {
24             this.p1 = p1;
25             this.keyName = keyName;
26             this.keyToId = keyToId;
27             this.procedure = procedure;
28             this.useNeedsToBlock = useNeedsToBlock;
29             this.entryCreationArguments = entryCreationArguments;
30         }
31     }
32
33     GenerationInfo signatureR1RelationInfo = new GenerationInfo  ( "int r", "r", "keyR", "long", "InternalProcedure<RelationInfo>", "", false );
34     GenerationInfo signatureR1Bytes = new GenerationInfo  ( "int r", "r", "keyR", "long", "InternalProcedure<byte[]>", "", false );
35     GenerationInfo signatureR1IntSet = new GenerationInfo  ( "int r", "r", "keyR", "long", "InternalProcedure<IntSet>", "", false );
36     GenerationInfo signatureR1IP = new GenerationInfo  ( "int r", "r", "keyR", "long", "IntProcedure", "", false );
37     GenerationInfo signatureR2IP = new GenerationInfo  ( "int r1, int r2", "r1,r2", "keyR2", "long", "IntProcedure", "", false );
38     GenerationInfo signatureR2TIP = new GenerationInfo  ( "int r1, int r2", "r1,r2", "keyR2", "long", "TripleIntProcedure", "", false );
39     GenerationInfo signatureID1 = new GenerationInfo  ( "String id", "id", "keyID", "String", "InternalProcedure<Integer>", "", false );
40     GenerationInfo signatureID2 = new GenerationInfo  ( "String id", "id", "keyID", "String", "InternalProcedure<TObjectIntHashMap<String>>", "", false );
41     GenerationInfo signatureChildMap = new GenerationInfo  ( "int r", "r", "keyR", "long", "InternalProcedure<ObjectResourceIdMap<String>>", "", false );
42     GenerationInfo signatureRead = new GenerationInfo  ( "Read<?> r", "r", "id", "long", "AsyncProcedure", "", true );
43     GenerationInfo signatureAsyncRead = new GenerationInfo  ( "AsyncRead<?> r", "r", "id", "long", "AsyncProcedure", "", true );
44     GenerationInfo signatureMultiRead = new GenerationInfo  ( "MultiRead<?> r", "r", "id", "long", "SyncMultiProcedure", "", false );
45     GenerationInfo signatureAsyncMultiRead = new GenerationInfo  ( "AsyncMultiRead<?> r", "r", "id", "long", "AsyncMultiProcedure", "", false );
46     GenerationInfo signatureExternalRead = new GenerationInfo  ( "ExternalRead<?> r", "r", "id", "long", "AsyncProcedure", ", graph", false );
47
48     private void line(StringBuilder content, String line) {
49         for(int i=0;i<indent;i++)
50             content.append(" ");
51         content.append(line);
52         content.append("\n");
53     }
54
55     public void generateQuery(StringBuilder content, String clazz, GenerationInfo signature, boolean runnerShortcut, boolean genReturn) {
56         generateGetOrCreate(content, clazz, signature);
57         generateRemove(content, clazz, signature);
58         generateRunner(content, clazz, signature, runnerShortcut, genReturn);
59     }
60
61     public void generateRunner(StringBuilder content, String clazz, GenerationInfo signature, boolean shortcut, boolean genReturn) {
62
63         line(content, "public static " + (genReturn ? "Object" : "void") + " runner" + clazz + "(ReadGraphImpl graph, " + signature.p1 + ", CacheEntry parent, ListenerBase listener, final " + signature.procedure + " procedure" + (signature.useNeedsToBlock ? ", boolean needsToBlock" : "") + ") throws DatabaseException {");
64         line(content, "    QueryCache cache  = graph.processor.cache;");
65         if(shortcut) {
66             line(content, "    if(parent == null && listener == null && !cache.shouldCache(graph.processor, " + signature.keyName + ")) {");
67             line(content, "        if (SINGLE) {");
68             line(content, "            " + clazz + " e = cache.peek" + clazz + "(" + signature.keyName + ");");
69             line(content, "            if (e != null && e.isReady()) {");
70             line(content, "                " + (genReturn ? "return " : "") + "e.performFromCache(graph, procedure);");
71             if(!genReturn) line(content, "                return;");
72             line(content, "            }");
73             line(content, "        }");
74             line(content, "        " + (genReturn ? "return " : "") + clazz + ".computeForEach(graph, " + signature.keyName + ", null, procedure" + (signature.useNeedsToBlock ? ", needsToBlock" : "") + ");");
75             if(!genReturn) line(content, "        return;");
76             line(content, "    }");
77         }
78         if(signature.useNeedsToBlock) {
79             line(content, "    " + clazz + " entry = (" + clazz + ")cache.getOrCreate" + clazz + "(graph, " + signature.keyName + ", needsToBlock);");
80             line(content, "    if(entry == null) {");
81             line(content, "      graph.processor.schedule(new SessionTask(graph) {");
82             line(content, "        @Override");
83             line(content, "        public void run0(int thread) {");
84             line(content, "          try {");
85             line(content, "            runner" + clazz + "(graph, r, parent, listener, procedure, needsToBlock);");
86             line(content, "          } catch (DatabaseException e) {");
87             line(content, "            Logger.defaultLogError(e);");
88             line(content, "          }");
89             line(content, "        }");
90             line(content, "      });");
91             line(content, "      return null;");
92             line(content, "    }");
93         } else {
94             line(content, "    " + clazz + " entry = (" + clazz + ")cache.getOrCreate" + clazz + "(graph, " + signature.keyName + ");");
95         }
96         line(content, "    " + signature.procedure + " procedure_ = procedure != null ? procedure : emptyProcedure" + clazz + ";");
97         line(content, "    ListenerEntry listenerEntry = cache.registerDependencies(graph, entry, parent, listener, procedure_, false);");
98         line(content, "    if(entry.isReady()) " + (genReturn ? "return " : "") + "entry.performFromCache(graph, procedure_);");
99         line(content, "    else {");
100         line(content, "      assert(entry.isPending());");
101         if(shortcut) line(content, "      " + (genReturn ? "Object result = " : "") + clazz + ".computeForEach(graph, " + signature.keyName + ", entry, procedure_" + (signature.useNeedsToBlock ? ", needsToBlock" : "") + ");");
102         else line(content, "      entry.compute(graph, procedure_);"); 
103         line(content, "      if(listenerEntry != null) cache.primeListenerEntry(listenerEntry, entry.getResult());");
104         if(genReturn) line(content, "      return result;");
105         line(content, "    }");
106         line(content, "}");
107         line(content, "");
108
109         String lower = Character.toLowerCase(clazz.charAt(0)) + clazz.substring(1);
110
111         line(content, "private " + clazz + " peek" + clazz + "(" + signature.p1 + ") {");
112         line(content, "    synchronized(" + lower +"Map) {");
113         line(content, "        return (" + clazz + ") " + lower + "Map.get(" + signature.keyName + ");");
114         line(content, "    }");
115         line(content, "}");
116         line(content, "");
117     }
118
119     public void generateRemove(StringBuilder content, String clazz, GenerationInfo signature) {
120
121         String lower = Character.toLowerCase(clazz.charAt(0)) + clazz.substring(1);
122
123         line(content, "void remove(" + clazz + " entry) {");
124         line(content, "    synchronized(" + lower + "Map) {");
125         line(content, "        " + lower + "Map.remove(entry.id);");
126         line(content, "    }");
127         line(content, "}");
128         line(content, "");
129
130     }
131
132     public void generateGetOrCreate(StringBuilder content, String clazz, GenerationInfo signature) {
133
134         String lower = Character.toLowerCase(clazz.charAt(0)) + clazz.substring(1);
135
136         line(content, "" + clazz + " getOrCreate" + clazz + "(ReadGraphImpl graph, " + signature.p1 + (signature.useNeedsToBlock ? ", boolean needsToBlock" : "") +  ") throws DatabaseException {");
137         line(content, "    " + clazz + " existing = null;");
138         line(content, "    synchronized(" + lower + "Map) {");
139         line(content, "        existing = (" + clazz + ")" + lower + "Map.get(" + signature.keyName + ");");
140         line(content, "        if(existing == null) {");
141         line(content, "            existing = new " + clazz + "(" + signature.keyName + signature.entryCreationArguments + ");");
142         line(content, "            existing.setPending(querySupport);");
143         line(content, "            " + lower + "Map.put(" + signature.keyToId + "(" + signature.keyName + "), existing);");
144         line(content, "            size++;");
145         line(content, "            return existing;");
146         line(content, "        }");
147         line(content, "        if(existing.requiresComputation()) {");
148         line(content, "            existing.setPending(querySupport);");
149         line(content, "            return existing;");
150         line(content, "        }");
151         line(content, "    }");
152         line(content, "    if(existing.isPending()) {");
153         if(signature.useNeedsToBlock) {
154             line(content, "      if(needsToBlock)");
155             line(content, "        waitPending(graph, existing);");
156             line(content, "      else {");
157             line(content, "        return null;");
158             line(content, "      }");
159         } else {
160             line(content, "      waitPending(graph, existing);");
161         }
162         line(content, "    }");
163         line(content, "    return existing;");
164         line(content, "}");
165         line(content, "");
166
167     }
168
169     public void generate() {
170
171         URL classLocation = CodeGen.class.getResource(".");
172         if (classLocation != null) {
173             if (classLocation.getProtocol().equals("file")) {
174                 try {
175                     URL resource = new URL(classLocation, ".");
176                     File path = new File(URLDecoder.decode(resource.getPath(), "UTF-8"));
177                     String target = path.getAbsolutePath().replace("\\", "/");
178                     target = target.replace("/bin/", "/src/") + "/QueryCache.java";
179                     System.err.println("target=" + target);
180                     File source = new File(target);
181                     StringBuilder content = new StringBuilder();
182                     content.append("package org.simantics.db.impl.query;\n");
183                     content.append("\n");
184
185                     content.append("import org.simantics.db.ObjectResourceIdMap;\n");
186                     content.append("import org.simantics.db.RelationInfo;\n");
187                     content.append("import org.simantics.db.common.utils.Logger;\n");
188                     content.append("import org.simantics.db.exception.DatabaseException;\n");
189                     content.append("import org.simantics.db.impl.graph.ReadGraphImpl;\n");
190                     content.append("import org.simantics.db.impl.procedure.InternalProcedure;\n");
191                     content.append("import org.simantics.db.impl.query.QueryProcessor.SessionTask;\n");
192                     content.append("import org.simantics.db.procedure.AsyncMultiProcedure;\n");
193                     content.append("import org.simantics.db.procedure.AsyncProcedure;\n");
194                     content.append("import org.simantics.db.procedure.ListenerBase;\n");
195                     content.append("import org.simantics.db.procedure.SyncMultiProcedure;\n");
196                     content.append("import org.simantics.db.request.AsyncMultiRead;\n");
197                     content.append("import org.simantics.db.request.AsyncRead;\n");
198                     content.append("import org.simantics.db.request.ExternalRead;\n");
199                     content.append("import org.simantics.db.request.MultiRead;\n");
200                     content.append("import org.simantics.db.request.Read;\n");
201                     content.append("\n");
202
203                     content.append("public class QueryCache extends QueryCacheBase {\n");
204                     content.append("\n");
205
206                     line(content, "private static final boolean SINGLE = false;");
207                     content.append("\n");
208
209                     line(content,"public QueryCache(QuerySupport querySupport, int threads) {");
210                     line(content,"    super(querySupport, threads);");
211                     line(content,"}");
212                     content.append("\n");
213
214                     generateQuery(content, "Objects", signatureR2IP, true, false);
215                     generateQuery(content, "Statements", signatureR2TIP, true, false);
216                     generateQuery(content, "DirectObjects", signatureR2IP, true, false);
217                     generateQuery(content, "RelationInfoQuery", signatureR1RelationInfo, true, false);
218                     generateQuery(content, "URIToResource", signatureID1, true, false);
219                     generateQuery(content, "ValueQuery", signatureR1Bytes, true, false);
220                     generateQuery(content, "OrderedSet", signatureR1IP, true, false);
221                     generateQuery(content, "PrincipalTypes", signatureR1IP, true, false);
222                     generateQuery(content, "DirectPredicates", signatureR1IntSet, true, false);
223                     generateQuery(content, "Predicates", signatureR1IntSet, true, false);
224                     generateQuery(content, "ReadEntry", signatureRead, true, true);
225                     generateQuery(content, "AsyncReadEntry", signatureAsyncRead, true, true);
226                     generateQuery(content, "Types", signatureR1IntSet, true, false);
227                     generateQuery(content, "ChildMap", signatureChildMap, true, false);
228                     generateQuery(content, "TypeHierarchy", signatureR1IntSet, true, false);
229                     generateQuery(content, "SuperTypes", signatureR1IntSet, true, false);
230                     generateQuery(content, "SuperRelations", signatureR1IntSet, true, false);
231
232                     generateQuery(content, "AssertedPredicates", signatureR1IP, false, false);
233                     generateQuery(content, "AssertedStatements", signatureR2TIP, false, false);
234                     generateQuery(content, "DirectSuperRelations", signatureR1IP, false, false);
235                     generateQuery(content, "MultiReadEntry", signatureMultiRead, false, false);
236                     generateQuery(content, "AsyncMultiReadEntry", signatureAsyncMultiRead, false, false);
237                     generateQuery(content, "ExternalReadEntry", signatureExternalRead, false, false);
238                     content.append("}\n");
239                     FileUtils.writeFile(source, content.toString().getBytes());
240                 } catch (MalformedURLException e) {
241                     e.printStackTrace();
242                 } catch (UnsupportedEncodingException e) {
243                     e.printStackTrace();
244                 } catch (IOException e) {
245                     e.printStackTrace();
246                 }
247             }
248         }
249
250     }
251
252     public static void main(String[] args) {
253         new CodeGen().generate();
254     }
255
256 }