New splash.bmp with version 1.36.0
[simantics/platform.git] / bundles / org.simantics.db.impl / src / org / simantics / db / impl / query / AssertedStatements.java
1 /*******************************************************************************
2  * Copyright (c) 2007, 2010 Association for Decentralized Information Management
3  * in Industry THTH ry.
4  * All rights reserved. This program and the accompanying materials
5  * are made available under the terms of the Eclipse Public License v1.0
6  * which accompanies this distribution, and is available at
7  * http://www.eclipse.org/legal/epl-v10.html
8  *
9  * Contributors:
10  *     VTT Technical Research Centre of Finland - initial API and implementation
11  *******************************************************************************/
12 package org.simantics.db.impl.query;
13
14 import java.util.concurrent.Semaphore;
15 import java.util.concurrent.atomic.AtomicInteger;
16
17 import org.simantics.db.RelationInfo;
18 import org.simantics.db.exception.ManyObjectsForFunctionalRelationException;
19 import org.simantics.db.impl.graph.ReadGraphImpl;
20 import org.simantics.db.impl.procedure.InternalProcedure;
21 import org.simantics.db.impl.procedure.TripleIntProcedureAdapter;
22 import org.simantics.db.procedure.ListenerBase;
23 import org.simantics.db.request.RequestFlags;
24
25
26 final public class AssertedStatements extends CollectionBinaryQuery<TripleIntProcedure> {
27     
28 //    public ArrayList<TripleIntProcedure> procs;
29     
30     public AssertedStatements(final int r1, final int r2) {
31         super(r1, r2);
32     }
33
34     public static AssertedStatements newInstance(final int r1, final int r2) {
35         return new AssertedStatements(r1, r2);
36     }
37     
38     final static AssertedStatements runner(ReadGraphImpl graph, final int r1, final int r2, final QueryProcessor provider, final AssertedStatements cached, final CacheEntry parent, final ListenerBase listener, final TripleIntProcedure procedure) {
39         
40         AssertedStatements entry = cached != null ? cached : (AssertedStatements)provider.assertedStatementsMap.get(id(r1,r2)); 
41         if(entry == null) {
42                 
43                 entry = new AssertedStatements(r1, r2);
44                 entry.setPending();
45                 entry.clearResult(provider.querySupport);
46                 entry.putEntry(provider);
47                 
48             provider.performForEach(graph, entry, parent, listener, procedure);
49             
50             return entry;
51             
52         } else {
53                 
54             if(entry.isPending()) {
55                 synchronized(entry) {
56                     if(entry.isPending()) {
57                         throw new IllegalStateException();
58 //                      if(entry.procs == null) entry.procs = new ArrayList<TripleIntProcedure>();
59 //                        entry.procs.add(procedure);
60 //                        provider.registerDependencies(graph, entry, parent, listener, procedure, false);
61 //                        return entry;
62                     }
63                 }
64             }
65             provider.performForEach(graph, entry, parent, listener, procedure);
66         }
67         
68         return entry;
69         
70     }
71     
72     final public static AssertedStatements queryEach(ReadGraphImpl graph, final int r1, final int r2, final QueryProcessor provider, final CacheEntry parent, final ListenerBase listener, final TripleIntProcedure procedure) {
73         
74         assert(r1 != 0);
75         assert(r2 != 0);
76         
77         final AssertedStatements entry = (AssertedStatements)provider.assertedStatementsMap.get(id(r1,r2));
78         
79         if(parent == null && !(listener != null)) {
80             if(entry != null && entry.isReady()) { 
81                 entry.performFromCache(graph, provider, procedure);
82                 return entry;
83             }
84         }
85
86         return runner(graph, r1, r2, provider, entry, parent, listener, procedure);
87          
88     }
89
90     @Override
91     public BinaryQuery<TripleIntProcedure> getEntry(QueryProcessor provider) {
92         return provider.assertedStatementsMap.get(id);
93     }
94         
95         @Override
96         public void putEntry(QueryProcessor provider) {
97         provider.assertedStatementsMap.put(id, this);
98         }
99
100         @Override
101         final public void removeEntry(QueryProcessor provider) {
102             provider.assertedStatementsMap.remove(id);
103         }
104         
105         void computeInheritedAssertions(ReadGraphImpl graph, int type, final int predicate, final RelationInfo ri, final QueryProcessor queryProvider, final TripleIntProcedure proc) {
106             
107 //        final AtomicBoolean found = new AtomicBoolean(0);
108
109             DirectObjects.queryEach(graph, type, queryProvider.getInherits(), queryProvider, this, null, new SyncIntProcedure() {
110
111             @Override
112             public void run(ReadGraphImpl graph) {
113
114 //                if(ri.isFunctional && found.get() == 1) {
115 //
116 //                    ManyObjectsForFunctionalRelationException exception = new ManyObjectsForFunctionalRelationException("Functional relation has assertions from multiple inherited types.");
117 //                    except(exception);
118 //                    proc.exception(graph, exception);
119 //                    return;
120 //                    
121 //                }
122
123                 finish(graph, queryProvider);
124                 proc.finished(graph);
125                 
126             }
127
128             @Override
129             public void execute(ReadGraphImpl graph, int inh) {
130                 
131 //                if(ri.isFunctional && found.get() == 1) return;
132
133                 inc();
134                 
135                 AssertedStatements.queryEach(graph, inh, predicate, queryProvider, AssertedStatements.this, null, new TripleIntProcedureAdapter() {
136
137                     @Override
138                     public void execute(ReadGraphImpl graph, int s, int p, int o) {
139
140 //                        if(ri.isFunctional) {
141 //                            
142 ////                            if(found.get() == 1) return;
143 //
144 //                            if(found.compareAndSet(0, o)) {
145                                 if(addOrSet(s,p,o))
146                                         proc.execute(graph, s, p, o);
147 //                            }
148 //                            // If this was a duplicate, we can ignore this
149 //                            else if (found.compareAndSet(o, o)) {
150 //                                //System.err.println("duplicates!");
151 //                            }
152 //                            // Otherwise we have error
153 //                            else {
154 //                                found.set(1);
155 //                            }
156 //                            
157 //                        } else {
158 //                            
159 //                            addOrSet(s, p, o);
160 //                            proc.execute(graph, s, p, o);
161 //                            
162 //                        }
163                         
164                     }
165
166                     @Override
167                     public void finished(ReadGraphImpl graph) {
168                         dec(graph);
169                     }
170                                 
171                                 @Override
172                                 public void exception(ReadGraphImpl graph, Throwable t) {
173                                         proc.exception(graph, t);
174                                         dec(graph);
175                     }
176                     
177                 });
178                 
179             }
180
181             @Override
182             public void finished(ReadGraphImpl graph) {
183                 dec(graph);
184             }
185             
186         });
187
188         }
189
190     void computeLocalAssertions(ReadGraphImpl graph, final int type, final int predicate, final RelationInfo ri, final QueryProcessor queryProvider, final TripleIntProcedure proc) {
191         
192         final AtomicInteger found = new AtomicInteger(0);
193
194         DirectObjects.queryEach(graph, type, queryProvider.getAsserts(), queryProvider, this, null, new SyncIntProcedure() {
195
196             @Override
197             public void run(ReadGraphImpl graph) {
198                 
199                 if(ri.isFunctional && found.get() > 1) {
200
201                     ManyObjectsForFunctionalRelationException exception = new ManyObjectsForFunctionalRelationException("Functional relation has more than one asserted statement.");
202                     except(exception);
203                     proc.exception(graph, exception);
204                     return;
205                     
206                 }
207
208                 if(ri.isFunctional && found.get() == 1) {
209                                         
210                     finish(graph, queryProvider);
211                     proc.finished(graph);
212                     return;
213                     
214                 }
215
216                 computeInheritedAssertions(graph, type, predicate, ri, queryProvider, proc);
217                 
218             }
219
220             @Override
221             public void execute(ReadGraphImpl graph, final int ass) {
222                 
223                 if(ri.isFunctional && found.get() > 1) return;
224                 
225                 inc();
226                 
227                 DirectObjects.queryEach(graph, ass, queryProvider.getHasPredicate(), queryProvider, AssertedStatements.this, null, new IntProcedure() {
228
229                     @Override
230                     public void execute(ReadGraphImpl graph, final int pred) {
231                         
232                         if(ri.isFunctional) {
233                             
234                             if(found.get() > 1) return;
235
236                             inc();
237
238                             DirectObjects.queryEach(graph, ass, queryProvider.getHasObject(), queryProvider, AssertedStatements.this, null, new IntProcedure() {
239
240                                 @Override
241                                 public void execute(ReadGraphImpl graph, final int object) {
242                                     
243                                     if(found.get() > 1) return;
244
245                                     if(pred == predicate) {
246
247                                         if(found.getAndIncrement() == 0) {
248                                                 if(addOrSet(type, pred, object))
249                                                         proc.execute(graph, type, pred, object);
250                                         }
251                                         
252                                         return;
253                                         
254                                     }
255                                     
256                                     if ( !ri.isFinal ) {
257
258                                         inc();
259
260                                         SuperRelations.queryEach(graph, pred, queryProvider, AssertedStatements.this, null, new InternalProcedure<IntSet>() {
261                                             
262                                             @Override
263                                             public void execute(ReadGraphImpl graph, IntSet result) {
264                                                 
265                                                 if(found.get() > 1) {
266                                                     dec(graph);
267                                                     return;
268                                                 }
269
270                                                 if(result.contains(predicate)) {
271                     
272                                                     if(found.getAndIncrement() == 0) {
273                                                                 if(addOrSet(type, pred, object))
274                                                                         proc.execute(graph, type, pred, object);
275                                                         }
276                                                     
277                                                 }
278                                                 
279                                                 dec(graph);
280                                                 
281                                             }
282                                                         
283                                                         @Override
284                                                         public void exception(ReadGraphImpl graph, Throwable t) {
285                                                             
286                                                                 proc.exception(graph, t);
287                                                 dec(graph);
288                                                                 
289                                             }
290
291                                         });
292
293                                     }
294
295                                 }
296                                 
297                                 @Override
298                                 public void finished(ReadGraphImpl graph) {
299                                     dec(graph);
300                                 }
301                                         
302                                         @Override
303                                         public void exception(ReadGraphImpl graph, Throwable t) {
304                                                 proc.exception(graph, t);
305                                     dec(graph);
306                                 }
307
308                             });
309                             
310                         } else {
311
312                             inc();
313
314                             DirectObjects.queryEach(graph, ass, queryProvider.getHasObject(), queryProvider, AssertedStatements.this, null, new IntProcedure() {
315
316                                 @Override
317                                 public void execute(ReadGraphImpl graph, final int object) {
318                                     
319                                     if(pred == predicate) {
320
321                                         addOrSet(type, pred, object);
322                                         proc.execute(graph, type, pred, object);
323                                         return;
324                                         
325                                     }
326                                     
327                                     if ( !ri.isFinal ) {
328
329                                         inc();
330
331                                         SuperRelations.queryEach(graph, pred, queryProvider, AssertedStatements.this, null, new InternalProcedure<IntSet>() {
332                                             
333                                             @Override
334                                             public void execute(ReadGraphImpl graph, IntSet result) {
335                                                 
336                                                 if(result.contains(predicate)) {
337                     
338                                                     addOrSet(type, pred, object);
339                                                     proc.execute(graph, type, pred, object);
340
341                                                 }
342                                                 
343                                                 dec(graph);
344                                                 
345                                             }
346                                                         
347                                                         @Override
348                                                         public void exception(ReadGraphImpl graph, Throwable t) {
349                                                                 proc.exception(graph, t);
350                                                 dec(graph);
351                                             }
352  
353                                         });
354
355                                     }
356
357                                 }
358                                 
359                                 @Override
360                                 public void finished(ReadGraphImpl graph) {
361                                     dec(graph);
362                                 }
363                                         
364                                         @Override
365                                         public void exception(ReadGraphImpl graph, Throwable t) {
366                                                 proc.exception(graph, t);
367                                     dec(graph);
368                                 }
369
370                             });
371
372                         }
373
374                     }
375
376                     @Override
377                     public void finished(ReadGraphImpl graph) {
378                         dec(graph);
379                     }
380                                 
381                                 @Override
382                                 public void exception(ReadGraphImpl graph, Throwable t) {
383                                         proc.exception(graph, t);
384                         dec(graph);
385                     }
386
387                 });
388                 
389             }
390
391             @Override
392             public void finished(ReadGraphImpl graph) {
393                 dec(graph);
394             }
395             
396         });
397         
398     }
399
400         @Override
401     public void computeForEach(ReadGraphImpl graph, final QueryProcessor provider, final TripleIntProcedure procedure, boolean store) {
402         
403         RelationInfoQuery.queryEach(graph, r2(), provider, this, null, new InternalProcedure<RelationInfo>() {
404
405             @Override
406             public void execute(ReadGraphImpl graph, RelationInfo ri) {
407                 
408                 computeLocalAssertions(graph, r1(), r2(), ri, provider, procedure);
409                 
410             }
411                         
412                         @Override
413                         public void exception(ReadGraphImpl graph, Throwable t) {
414                                 procedure.exception(graph, t);
415             }
416  
417         });
418         
419     }
420     
421     @Override
422     public String toString() {
423         return "AssertedStatements2[" + r1() + " - " + r2() + "]";
424     }
425
426     private boolean addOrSet(int s, int p, int o) {
427         
428         assert(isPending());
429         
430         IntArray value = (IntArray)getResult();
431         if(value.data != null) {
432                         for(int i = 0;i < value.sizeOrData ; i+=3) {
433                                 int existingP = value.data[i+1];
434                                 if(p == existingP) {
435                                         int existingO = value.data[i+2];
436                                         if(existingO == o) return false;
437                                 }
438                         }
439                 value.add(s);
440                 value.add(p);
441                 value.add(o);
442         } else {
443                 value.add(s);
444                 value.add(p);
445                 value.add(o);
446         }
447         
448         return true;
449         
450     }
451     
452     final private void finish(ReadGraphImpl graph, QueryProcessor provider) {
453         
454         assert(isPending());
455
456 //        ArrayList<TripleIntProcedure> p = null;
457
458         synchronized(this) {
459                 
460                 setReady();
461 //            p = procs;
462 //            procs = null; 
463         
464         }
465         
466 //        if(p != null) {
467 //              final IntArray value = (IntArray)getResult();
468 //              for(TripleIntProcedure proc : p) {
469 //                      for(int i=0;i<value.size();i+=3) {
470 //                              proc.execute(graph, value.data[i], value.data[i+1], value.data[i+2]);
471 //                      }
472 //              }
473 //
474 //              for(TripleIntProcedure proc : p) proc.finished(graph);
475 //        }
476
477     }
478
479     @Override
480     public void performFromCache(ReadGraphImpl graph, QueryProcessor provider, final TripleIntProcedure procedure) {
481         
482         assert(isReady());
483         
484         if(handleException(graph, procedure)) return;
485         
486         final IntArray value = (IntArray)getResult();
487         for(int i=0;i<value.size();i+=3) {
488                 procedure.execute(graph, value.data[i], value.data[i+1], value.data[i+2]);
489         }
490
491         procedure.finished(graph);
492         
493     }
494     
495     @Override
496     public void recompute(ReadGraphImpl graph, QueryProcessor provider) {
497         
498         final Semaphore s = new Semaphore(0);
499
500         computeForEach(graph, provider, new TripleIntProcedureAdapter() {
501
502             @Override
503             public void finished(ReadGraphImpl graph) {
504                 s.release();
505             }
506                         
507                         @Override
508                         public void exception(ReadGraphImpl graph, Throwable t) {
509                                 throw new Error("Error in recompute", t);
510             }
511     
512         }, true);
513         
514         try {
515             s.acquire();
516         } catch (InterruptedException e) {
517             throw new Error(e);
518         }
519         
520     }
521     
522     @Override
523     public int type() {
524         return RequestFlags.IMMEDIATE_UPDATE;
525     }
526     
527
528     @Override
529     boolean isImmutable(ReadGraphImpl graph) {
530         return graph.processor.isImmutable(r1());
531     }
532     
533 }