Skip to main content
summaryrefslogtreecommitdiffstats
blob: 74c04b6982a20c843825d5b9726e82df630f2d72 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
/*******************************************************************************
 * Copyright (c) 2012 Boeing.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Boeing - initial API and implementation
 *******************************************************************************/
package org.eclipse.osee.orcs.db.internal.sql;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import org.eclipse.osee.framework.jdk.core.type.Identifiable;
import org.eclipse.osee.framework.jdk.core.type.Identity;
import org.eclipse.osee.framework.jdk.core.type.OseeCoreException;
import org.eclipse.osee.framework.jdk.core.util.Conditions;
import org.eclipse.osee.framework.jdk.core.util.Strings;
import org.eclipse.osee.logger.Log;
import org.eclipse.osee.orcs.core.ds.HasOptions;
import org.eclipse.osee.orcs.core.ds.Options;
import org.eclipse.osee.orcs.db.internal.SqlProvider;
import org.eclipse.osee.orcs.db.internal.sql.join.AbstractJoinQuery;
import org.eclipse.osee.orcs.db.internal.sql.join.CharJoinQuery;
import org.eclipse.osee.orcs.db.internal.sql.join.IdJoinQuery;
import org.eclipse.osee.orcs.db.internal.sql.join.SqlJoinFactory;

/**
 * @author Roberto E. Escobar
 */
public abstract class AbstractSqlWriter implements HasOptions {

   protected static final String AND_WITH_NEWLINES = "\n AND \n";

   private final StringBuilder output = new StringBuilder();
   private final List<String> tableEntries = new ArrayList<String>();
   private final List<WithClause> withClauses = new ArrayList<WithClause>();
   private final SqlAliasManager aliasManager = new SqlAliasManager();

   private final Log logger;
   private final SqlJoinFactory joinFactory;
   private final SqlProvider sqlProvider;
   private final SqlContext context;
   private final QueryType queryType;
   private int level = 0;

   public AbstractSqlWriter(Log logger, SqlJoinFactory joinFactory, SqlProvider sqlProvider, SqlContext context, QueryType queryType) {
      this.logger = logger;
      this.joinFactory = joinFactory;
      this.sqlProvider = sqlProvider;
      this.context = context;
      this.queryType = queryType;
   }

   public void build(SqlHandler<?>... handlers) throws OseeCoreException {
      build(Arrays.asList(handlers));
   }

   public void build(List<SqlHandler<?>> handlers) throws OseeCoreException {
      Conditions.checkNotNullOrEmpty(handlers, "SqlHandlers");
      reset();

      write(handlers);

      String sql = toString();
      context.setSql(sql);

      if (logger.isTraceEnabled()) {
         logger.trace("Sql Writer - [%s]", context);
      }
   }

   protected void reset() {
      output.delete(0, output.length());
      context.getJoins().clear();
      context.getParameters().clear();
      tableEntries.clear();
      withClauses.clear();
      aliasManager.reset();
      level = 0;
   }

   public boolean isCountQueryType() {
      return QueryType.COUNT == queryType;
   }

   protected void write(Iterable<SqlHandler<?>> handlers) throws OseeCoreException {
      computeTables(handlers);
      computeWithClause(handlers);

      writeWithClause();
      writeSelect(handlers);
      write("\n FROM \n");
      writeTables();
      write("\n WHERE \n");
      writePredicates(handlers);
      writeGroupAndOrder();
   }

   private void writeRecursiveWith() throws OseeCoreException {
      String recursiveWith = sqlProvider.getSql(SqlProvider.SQL_RECURSIVE_WITH_KEY);
      if (Strings.isValid(recursiveWith)) {
         write(" ");
         write(recursiveWith);
      }
   }

   protected void writeWithClause() throws OseeCoreException {
      if (Conditions.hasValues(withClauses)) {
         write("WITH");
         int size = withClauses.size();
         for (int i = 0; i < size; i++) {
            WithClause clause = withClauses.get(i);
            if (clause.isRecursive()) {
               writeRecursiveWith();
            }
            write(" ");
            write(clause.getName());
            if (clause.hasParameters()) {
               write(" ");
               write(clause.getParameters());
            }
            write(" AS ( \n");
            write(clause.getBody());
            write("\n )");
            if (i + 1 < size) {
               write(", \n");
            }
         }
         write("\n");
      }
   }

   public void addWithClause(WithClause clause) {
      withClauses.add(clause);
   }

   protected void computeWithClause(Iterable<SqlHandler<?>> handlers) throws OseeCoreException {
      for (SqlHandler<?> handler : handlers) {
         setHandlerLevel(handler);
         handler.addWithTables(this);
      }
   }

   public SqlContext getContext() {
      return context;
   }

   protected abstract void writeSelect(Iterable<SqlHandler<?>> handlers) throws OseeCoreException;

   public abstract String getWithClauseTxBranchFilter(String txsAlias, boolean deletedPredicate) throws OseeCoreException;

   public abstract String getTxBranchFilter(String txsAlias) throws OseeCoreException;

   public abstract String getTxBranchFilter(String txsAlias, boolean allowDeleted) throws OseeCoreException;

   protected abstract void writeGroupAndOrder() throws OseeCoreException;

   protected void writeTables() throws OseeCoreException {
      int size = tableEntries.size();
      for (int i = 0; i < size; i++) {
         write(tableEntries.get(i));
         if (i + 1 < size) {
            write(", ");
         }
      }
   }

   protected void computeTables(Iterable<SqlHandler<?>> handlers) throws OseeCoreException {
      for (SqlHandler<?> handler : handlers) {
         setHandlerLevel(handler);
         handler.addTables(this);
      }
   }

   protected void setHandlerLevel(SqlHandler<?> handler) {
      level = handler.getLevel();
   }

   protected void writePredicates(Iterable<SqlHandler<?>> handlers) throws OseeCoreException {
      Iterator<SqlHandler<?>> iterator = handlers.iterator();
      while (iterator.hasNext()) {
         SqlHandler<?> handler = iterator.next();
         setHandlerLevel(handler);
         boolean modified = handler.addPredicates(this);
         if (modified && iterator.hasNext()) {
            writeAndLn();
         }
      }
      removeDanglingSeparator(AND_WITH_NEWLINES);
   }

   public void writeAndLn() throws OseeCoreException {
      write(AND_WITH_NEWLINES);
   }

   protected void removeDanglingSeparator(String token) {
      int length = output.length();
      int index = output.lastIndexOf(token);
      if (index == length - token.length()) {
         output.delete(index, length);
      }
   }

   protected boolean hasAlias(TableEnum table) {
      ObjectType type = getObjectType(table);
      return getAliasManager().hasAlias(level, table, type);
   }

   public List<String> getAliases(TableEnum table) {
      ObjectType type = getObjectType(table);
      return getAliasManager().getAliases(level, table, type);
   }

   public String getFirstAlias(TableEnum table) {
      ObjectType type = getObjectType(table);
      return getFirstAlias(level, table, type);
   }

   public String getFirstAlias(int level, TableEnum table, ObjectType type) {
      return getAliasManager().getFirstAlias(level, table, type);
   }

   public String getLastAlias(TableEnum table) {
      ObjectType type = getObjectType(table);
      return getLastAlias(table, type);
   }

   public String getLastAlias(TableEnum table, ObjectType type) {
      int level = getAliasManager().getLevel();
      return getAliasManager().getLastAlias(level, table, type);
   }

   public String getNextAlias(AliasEntry table) {
      ObjectType type = getObjectType(table);
      return getNextAlias(table, type);
   }

   private String getNextAlias(AliasEntry table, ObjectType type) {
      int level = getAliasManager().getLevel();
      return getAliasManager().getNextAlias(level, table, type);
   }

   private ObjectType getObjectType(AliasEntry entry) {
      ObjectType toReturn = ObjectType.UNKNOWN;
      if (entry instanceof TableEnum) {
         TableEnum table = (TableEnum) entry;
         switch (table) {
            case BRANCH_TABLE:
               toReturn = ObjectType.BRANCH;
               break;
            case TX_DETAILS_TABLE:
               toReturn = ObjectType.TX;
               break;
            case ARTIFACT_TABLE:
               toReturn = ObjectType.ARTIFACT;
               break;
            case ATTRIBUTE_TABLE:
               toReturn = ObjectType.ATTRIBUTE;
               break;
            case RELATION_TABLE:
               toReturn = ObjectType.RELATION;
               break;
            default:
               break;
         }
      }
      return toReturn;
   }

   public void nextAliasLevel() {
      getAliasManager().nextLevel();
   }

   protected SqlAliasManager getAliasManager() {
      return aliasManager;
   }

   public void addTable(String table) {
      tableEntries.add(table);
   }

   public String addTable(AliasEntry table) {
      String alias = getNextAlias(table);
      tableEntries.add(String.format("%s %s", table.getName(), alias));
      return alias;
   }

   public String addTable(AliasEntry table, ObjectType objectType) {
      String alias = getNextAlias(table, objectType);
      tableEntries.add(String.format("%s %s", table.getName(), alias));
      return alias;
   }

   public void write(String data, Object... params) throws OseeCoreException {
      if (params != null && params.length > 0) {
         output.append(String.format(data, params));
      } else {
         output.append(data);
      }
   }

   public void writeEquals(String table1, String table2, String column) {
      write("%s.%s = %s.%s", table1, column, table2, column);
   }

   public void addParameter(Object data) {
      getContext().getParameters().add(data);
   }

   private void addJoin(AbstractJoinQuery join) {
      getContext().getJoins().add(join);
   }

   public CharJoinQuery writeCharJoin(Collection<String> ids) {
      CharJoinQuery joinQuery = joinFactory.createCharJoinQuery();
      for (String id : ids) {
         joinQuery.add(id);
      }
      addJoin(joinQuery);
      return joinQuery;
   }

   public IdJoinQuery writeIdJoin(Collection<? extends Number> ids) {
      IdJoinQuery joinQuery = joinFactory.createIdJoinQuery();
      for (Number id : ids) {
         joinQuery.add(id.longValue());
      }
      addJoin(joinQuery);
      return joinQuery;
   }

   public IdJoinQuery writeIdentifiableJoin(Collection<? extends Identifiable<Long>> ids) {
      IdJoinQuery joinQuery = joinFactory.createIdJoinQuery();
      for (Identity<Long> id : ids) {
         joinQuery.add(id.getGuid());
      }
      addJoin(joinQuery);
      return joinQuery;
   }

   @Override
   public Options getOptions() {
      return getContext().getOptions();
   }

   protected String getSqlHint() throws OseeCoreException {
      String hint = Strings.EMPTY_STRING;
      if (!Conditions.hasValues(withClauses)) {
         hint = sqlProvider.getSql(OseeSql.QUERY_BUILDER);
      }
      return hint;
   }

   @Override
   public String toString() {
      return output.toString();
   }

   public void writePatternMatch(String field, String expression) throws OseeCoreException {
      String pattern = sqlProvider.getSql(SqlProvider.SQL_REG_EXP_PATTERN_KEY);
      write(pattern, field, expression);
   }

}

Back to the top