Project

General

Profile

12161a_2_fql_assembly.patch

Stefanel Pezamosca, 11/13/2026 02:39 AM

Download (38.9 KB)

View differences:

new/src/com/goldencode/p2j/persist/FQLExpression.java
2 2
** Module   : FQLExpression.java
3 3
** Abstract : FQL expression with substitution parameters.
4 4
**
5
** Copyright (c) 2014-2024, Golden Code Development Corporation.
5
** Copyright (c) 2014-2026, Golden Code Development Corporation.
6 6
**
7 7
** -#- -I- --Date-- ---------------------------------------Description---------------------------------------
8 8
** 001 SVL 20140210 Created initial version.
......
13 13
** 005 OM  20231115 Added multiplexed property to mark the object as already containing the multiplex and
14 14
**                  this constraint into outer FQL is not needed and even illegal.
15 15
** 006 CA  20240812 Performance improvement - reduce the number of StringBuilder instances.
16
** 007 SP  20261110 Added finalLength() and appendFinalExpression(), which writes into a given StringBuilder.
16 17
*/
17 18

  
18 19
/*
......
253 254
    */
254 255
   public String toFinalExpression(boolean jpaStyle)
255 256
   {
256
      writeLastPart();
257
      StringBuilder sb = new StringBuilder(finalLength(jpaStyle));
258
      appendFinalExpression(sb, jpaStyle);
259
      return sb.toString();
260
   }
261

  
262
   /**
263
    * Appends the final form of the FQL expression, as {@link #toFinalExpression(boolean)} returns it, to
264
    * the given builder, after what it already holds.
265
    *
266
    * @param   sb
267
    *          The builder to append to.
268
    * @param   jpaStyle
269
    *          <code>true</code> to emit JPA-style positional parameter placeholders;
270
    *          <code>false</code> to emit simple placeholders.
271
    */
272
   public void appendFinalExpression(StringBuilder sb, boolean jpaStyle)
273
   {
274
      sb.ensureCapacity(sb.length() + finalLength(jpaStyle));
257 275
      int index = 0;
258 276
      int len = parts.size();
259
      StringBuilder sb = new StringBuilder();
260 277
      for (int i = 0; i < len; i++)
261 278
      {
262 279
         sb.append(parts.get(i));
263 280
         boolean last = (i == len - 1);
264 281
         if (!last || endsWithSubst)
265 282
         {
266
            sb.append("?");
283
            sb.append('?');
267 284
            if (jpaStyle)
268 285
            {
269 286
               sb.append(index++);
270 287
            }
271 288
         }
272 289
      }
273
      return sb.toString();
290
   }
291

  
292
   /**
293
    * Returns the length of the final form of the FQL expression, as {@link #toFinalExpression(boolean)}
294
    * returns it.
295
    *
296
    * @param   jpaStyle
297
    *          <code>true</code> for JPA-style positional parameter placeholders;
298
    *          <code>false</code> for simple placeholders.
299
    *
300
    * @return  The number of characters of the final form.
301
    */
302
   public int finalLength(boolean jpaStyle)
303
   {
304
      writeLastPart();
305
      int len = parts.size();
306
      int placeholders = (len == 0 ? 0 : (endsWithSubst ? len : len - 1));
307
      int total = placeholders;
308
      for (int i = 0; i < len; i++)
309
      {
310
         total += parts.get(i).length();
311
      }
312

  
313
      if (jpaStyle)
314
      {
315
         // decimal digits of the indexes 0 .. placeholders - 1: 1 digit below 10, 2 below 100, ...
316
         int  done   = 0;
317
         int  digits = 1;
318
         long limit  = 10;
319
         while (done < placeholders)
320
         {
321
            int upto = (int) Math.min(placeholders, limit);
322
            total += (upto - done) * digits;
323
            done = upto;
324
            digits++;
325
            limit *= 10;
326
         }
327
      }
328

  
329
      return total;
274 330
   }
275 331

  
276 332
   /**
new/src/com/goldencode/p2j/persist/PreselectQuery.java
759 759
**                           isBetweenRows. A NO-WAIT lock conflict on current() reads NO-LOCK.
760 760
** 253 AL2 20241119          Adapt to the switch from dirty context to transactional changes manager.
761 761
**     AL2 20260930          Restored the text of entry 219 and removed trailing whitespace.
762
** 254 SP  20261110          Build the inverted FQL only when a backward scroll reads it; fewer FQL copies.
762 763
*/
763 764

  
764 765
/*
......
933 934
   /** FQL query string to retrieve primary key ID arrays */
934 935
   private String fql = null;
935 936

  
936
   /** Inverted FQL query string to retrieve primary key ID arrays. */
937
   private String invertedFQL = null;
937
   /** Text of the last assembled FQL statement, and its inverted form on demand. */
938
   private AssembledFql assembled = null;
938 939
   
939 940
   /** Result set for this query */
940 941
   private Results results = null;
......
6548 6549
   }
6549 6550
   
6550 6551
   /**
6551
    * Generates the {@code order by} clause starting from the list of criteria, including the "order by"
6552
    * keyword. Uses the form:
6553
    * <pre>
6554
    *   order by {{dmo.property} {asc/desc}} [, ...]
6555
    * </pre>
6556
    * <p>
6557
    *
6558
    * @param   sortCriteria
6559
    *          The list of criteria to be added.
6560
    * @param   buf
6561
    *          The string builder to add the result.
6562
    * @param   invert
6563
    *          {@code true} only if the order by clause should be inverted. (e.g. 'desc' becomes 'asc'
6564
    *          and 'asc' becomes 'desc').
6565
    */
6566
   private void generateOrderBy(ArrayList<SortCriterion> sortCriteria, StringBuilder buf, boolean invert)
6567
   {
6568
      if (sortCriteria == null)
6569
      {
6570
         return; // quick out
6571
      }
6572
      
6573
      boolean orderBy = true;
6574
      for (int i = 0; i < sortCriteria.size(); i++)
6575
      {
6576
         SortCriterion criterion = sortCriteria.get(i);
6577
         if (orderBy)
6578
         {
6579
            buf.append(" order by ");
6580
            orderBy = false;
6581
         }
6582
         else
6583
         {
6584
            buf.append(", ");
6585
         }
6586
         buf.append(invert ? criterion.toSortExpression(true) : criterion.toString());
6587
      }
6588
   }
6589
   
6590
   /**
6591 6552
    * Assemble the {@code order by} clause for an FQL query.
6592 6553
    * <p>
6593 6554
    * Any text-based sort criteria are augmented with the necessary upper() and rtrim() functions.
......
8105 8066
   }
8106 8067

  
8107 8068
   /**
8108
    * Get the inverted FQL query.
8069
    * Get the inverted FQL query of the last assembled statement. The inverted text is built on the first
8070
    * {@code get()}, so a query which only scrolls forward never builds it.
8109 8071
    *
8110
    * @return  FQL query or {@code null} if the query has not yet been executed.
8072
    * @return  Supplier of the inverted FQL query or {@code null} if the query has not yet been executed.
8111 8073
    */
8112
   protected String getInvertedHQL()
8074
   protected Supplier<String> getInvertedHQL()
8113 8075
   {
8114
      return invertedFQL;
8076
      return assembled;
8115 8077
   }
8116 8078
   
8117 8079
   /**
......
8514 8476
      {
8515 8477
         assembleFQLImpl(buf);
8516 8478
      }
8517
      
8518
      return buf.toString().trim();
8479

  
8480
      return assembled.text().trim();
8519 8481
   }
8520 8482
   
8521 8483
   /**
......
8608 8570
   }
8609 8571

  
8610 8572
   /**
8573
    * Generates the {@code order by} clause starting from the list of criteria, including the "order by"
8574
    * keyword. Uses the form:
8575
    * <pre>
8576
    *   order by {{dmo.property} {asc/desc}} [, ...]
8577
    * </pre>
8578
    * The caller sizes {@code buf}; {@link #orderByLength} gives the length appended.
8579
    *
8580
    * @param   sortCriteria
8581
    *          The list of criteria to be added.
8582
    * @param   buf
8583
    *          The string builder to add the result.
8584
    * @param   invert
8585
    *          {@code true} only if the order by clause should be inverted. (e.g. 'desc' becomes 'asc'
8586
    *          and 'asc' becomes 'desc').
8587
    */
8588
   private static void generateOrderBy(List<SortCriterion> sortCriteria, StringBuilder buf, boolean invert)
8589
   {
8590
      if (sortCriteria == null)
8591
      {
8592
         return; // quick out
8593
      }
8594
      
8595
      for (int i = 0; i < sortCriteria.size(); i++)
8596
      {
8597
         buf.append(i == 0 ? " order by " : ", ");
8598
         buf.append(sortCriteria.get(i).toSortExpression(invert));
8599
      }
8600
   }
8601
   
8602
   /**
8603
    * Get the number of characters {@link #generateOrderBy} appends for the given criteria.
8604
    *
8605
    * @param   sortCriteria
8606
    *          The list of criteria; can be {@code null}.
8607
    * @param   invert
8608
    *          {@code true} for the inverted order by clause.
8609
    *
8610
    * @return  The length of the order by clause, {@code 0} when there are no criteria.
8611
    */
8612
   private static int orderByLength(List<SortCriterion> sortCriteria, boolean invert)
8613
   {
8614
      if (sortCriteria == null || sortCriteria.isEmpty())
8615
      {
8616
         return 0;
8617
      }
8618
      
8619
      int len = " order by ".length() + 2 * (sortCriteria.size() - 1);
8620
      for (int i = 0; i < sortCriteria.size(); i++)
8621
      {
8622
         len += sortCriteria.get(i).toSortExpression(invert).length();
8623
      }
8624
      
8625
      return len;
8626
   }
8627

  
8628
   /**
8611 8629
    * Keep one property of one buffer in both projection maps. A no-op for a buffer this query
8612 8630
    * carries no FIELDS/EXCEPT phrase for, such as the outer buffer of an OF join.
8613 8631
    *
......
8682 8700
    * the database query underlying this object. The FQL generated uses the
8683 8701
    * theta join style and includes a select clause, a from clause, an
8684 8702
    * optional where clause, and an order by clause (mandatory in all cases
8685
    * except a unique find). In addition, the inverted FQL will be computed
8686
    * for optimization purposes.
8703
    * except a unique find). The result, with what is needed to build the
8704
    * inverted FQL on demand, is stored in {@link #assembled}.
8687 8705
    *
8688 8706
    * @param   buf
8689 8707
    *          The buffer where to assemble the FQL.
......
8707 8725
      adjustProjection();
8708 8726

  
8709 8727
      assembleSelectClause(buf);
8710
      buf.append(fromAndWhere.toFinalExpression());
8711 8728

  
8712
      StringBuilder inverted = new StringBuilder(buf);
8713
      if (isOrderByRequired())
8729
      // reads the preprocessors built above; appending the from and where text has no side effects
8730
      boolean orderByRequired = isOrderByRequired();
8731
      buf.ensureCapacity(buf.length() +
8732
                         fromAndWhere.finalLength(true) +
8733
                         (orderByRequired ? orderByLength(sortCriteria, false) : 0));
8734
      fromAndWhere.appendFinalExpression(buf, true);
8735

  
8736
      int orderByStart = buf.length();
8737
      if (orderByRequired)
8714 8738
      {
8715 8739
         generateOrderBy(sortCriteria, buf, false);
8716
         generateOrderBy(sortCriteria, inverted, true);
8717 8740
      }
8718 8741

  
8719
      invertedFQL = inverted.toString();
8742
      assembled = new AssembledFql(buf.toString(), orderByStart, orderByRequired ? sortCriteria : null);
8720 8743
   }
8721 8744
   
8722 8745
   /**
......
9102 9125
         // else cursor is -1 (before), 0 (on single record), 1 (after)
9103 9126
      }
9104 9127
   }
9128

  
9129
   /**
9130
    * Text of one assembled FQL statement, and its inverted form, which is built on the first {@link #get()}.
9131
    * Each assembly creates a new instance, so results which keep it read the inverted text of their own
9132
    * statement.
9133
    */
9134
   private static final class AssembledFql
9135
   implements Supplier<String>
9136
   {
9137
      /** The assembled statement, untrimmed. */
9138
      private final String text;
9139
      
9140
      /** Length of the statement before its order by clause. */
9141
      private final int orderByStart;
9142
      
9143
      /** Sort criteria of the order by clause, or {@code null} when the statement has none. */
9144
      private final List<SortCriterion> sortCriteria;
9145
      
9146
      /** The inverted statement, built on the first {@link #get()}. */
9147
      private String inverted = null;
9148
      
9149
      /**
9150
       * Create the text of an assembled statement.
9151
       *
9152
       * @param   text
9153
       *          The assembled statement, untrimmed.
9154
       * @param   orderByStart
9155
       *          Length of the statement before its order by clause.
9156
       * @param   sortCriteria
9157
       *          Sort criteria of the order by clause, or {@code null} when the statement has none.
9158
       */
9159
      AssembledFql(String text, int orderByStart, List<SortCriterion> sortCriteria)
9160
      {
9161
         this.text = text;
9162
         this.orderByStart = orderByStart;
9163
         this.sortCriteria = sortCriteria;
9164
      }
9165
      
9166
      /**
9167
       * Get the assembled statement.
9168
       *
9169
       * @return  The statement, untrimmed.
9170
       */
9171
      String text()
9172
      {
9173
         return text;
9174
      }
9175
      
9176
      /**
9177
       * Get the inverted statement: the same statement with each sort direction of its order by clause
9178
       * reversed. Without an order by clause it is the statement itself.
9179
       *
9180
       * @return  The inverted statement, untrimmed.
9181
       */
9182
      @Override
9183
      public String get()
9184
      {
9185
         if (inverted == null)
9186
         {
9187
            if (sortCriteria == null)
9188
            {
9189
               inverted = text;
9190
            }
9191
            else
9192
            {
9193
               StringBuilder sb = new StringBuilder(orderByStart + orderByLength(sortCriteria, true));
9194
               sb.append(text, 0, orderByStart);
9195
               generateOrderBy(sortCriteria, sb, true);
9196
               inverted = sb.toString();
9197
            }
9198
         }
9199
         
9200
         return inverted;
9201
      }
9202
   }
9105 9203
}
9106 9204

  
new/src/com/goldencode/p2j/persist/ProgressiveResults.java
171 171
** 056 LS  20260128          Reverted DDF 20241211, 20250120 and RNC 20250912 changes, as they are causing
172 172
**                           performance regression.
173 173
** 057 AL2 20260326          Moved cache to pk-only to avoid large memory consumption.
174
** 058 SP  20261110          The inverted HQL is a Supplier, read only when scrolling backward.
174 175
*/
175 176

  
176 177
/*
......
230 231

  
231 232
import java.sql.*;
232 233
import java.util.*;
234
import java.util.function.*;
233 235
import java.util.logging.*;
234 236
import com.goldencode.p2j.persist.dialect.*;
235 237
import com.goldencode.p2j.persist.event.*;
......
322 324
   /** HQL query string used to select records */
323 325
   private final String hql;
324 326

  
325
   /** Inverted HQL query string used to select records. */
326
   private final String invertedHQL;
327
   /** Supplies the inverted HQL query string; read only when scrolling backward. */
328
   private final Supplier<String> invertedHQL;
327 329
   
328 330
   /** Substitution parameters, if any, to be applied to the query */
329 331
   private final Object[] args;
......
390 392
    * @param   hql
391 393
    *          HQL query string used to select records.
392 394
    * @param   invertedHQL
393
    *          Inverted HQL query string used to select records.
395
    *          Supplies the inverted HQL query string used to select records when scrolling backward.
394 396
    * @param   args
395 397
    *          Substitution parameters, if any, to be applied to the query.
396 398
    * @param   scrolling
......
409 411
    */
410 412
   ProgressiveResults(Persistence persistence,
411 413
                      String hql,
412
                      String invertedHQL,
414
                      Supplier<String> invertedHQL,
413 415
                      Object[] args,
414 416
                      boolean scrolling,
415 417
                      boolean forwardOnly,
......
1317 1319
         int start      = locator.getRow() - locator.getOffset();
1318 1320
         int offset     = start > 0 ? start - 1 : start;
1319 1321
         int maxResults = start > 0 ? locator.getSize() + 1 : locator.getSize();
1320
         String currentHQL = forwardScroll ? hql : invertedHQL;
1322
         String currentHQL = forwardScroll ? hql : invertedHQL.get();
1321 1323

  
1322 1324
         if (bracket == 0 || (bracket <= 3 && projection))
1323 1325
         {
new/src/com/goldencode/p2j/persist/SortCriterion.java
122 122
** 047 TG  20260317          Removed coalesce. The FQL is build now depending of the argument.
123 123
** 048 RNC 20260402          Fixed javadoc warnings.
124 124
** 049 ES  20261015          Added getPropertyName(), for the FIND cursor's reposition check.
125
** 050 SP  20261110          toSortExpression(boolean) builds its text once; the criterion is immutable.
125 126
*/
126 127

  
127 128
/*
......
287 288
   
288 289
   /** SQL dialect which used this sort criterion; used for rtrim calls on character properties */
289 290
   private final Dialect dialect;
290
   
291

  
292
   /** Text of {@link #toSortExpression(boolean)} in the original direction, built on first use. */
293
   private String sortText = null;
294

  
295
   /** Text of {@link #toSortExpression(boolean)} in the inverted direction, built on first use. */
296
   private String invertedSortText = null;
297

  
291 298
   /**
292 299
    * Constructor which parses original sort component text, deriving the property name, sort
293 300
    * direction, getter method for the property, case sensitivity of the property (character type
......
1000 1007
    */
1001 1008
   String toSortExpression(boolean invert)
1002 1009
   {
1003
      return toSortExpression(invert, true, false, true);
1010
      // criteria are shared between sessions through the cache; String is immutable, so a racing reader
1011
      // sees either null (and builds an equal string) or the complete value
1012
      String text = invert ? invertedSortText : sortText;
1013
      if (text == null)
1014
      {
1015
         text = toSortExpression(invert, true, false, true);
1016
         if (invert)
1017
         {
1018
            invertedSortText = text;
1019
         }
1020
         else
1021
         {
1022
            sortText = text;
1023
         }
1024
      }
1025

  
1026
      return text;
1004 1027
   }
1005 1028
   
1006 1029
   /**
new/test/com/goldencode/p2j/persist/FQLExpressionTest.java
1
/*
2
** Module   : FQLExpressionTest.java
3
** Abstract : Tests for the final text of an FQL expression.
4
**
5
** Copyright (c) 2026, Golden Code Development Corporation.
6
**
7
** -#- -I- --Date-- ---------------------------------Description---------------------------------
8
** 001 SP  20261110 Created initial version.
9
*/
10

  
11
/*
12
** This program is free software: you can redistribute it and/or modify
13
** it under the terms of the GNU Affero General Public License as
14
** published by the Free Software Foundation, either version 3 of the
15
** License, or (at your option) any later version.
16
**
17
** This program is distributed in the hope that it will be useful,
18
** but WITHOUT ANY WARRANTY; without even the implied warranty of
19
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
** GNU Affero General Public License for more details.
21
**
22
** You may find a copy of the GNU Affero GPL version 3 at the following
23
** location: https://www.gnu.org/licenses/agpl-3.0.en.html
24
**
25
** Additional terms under GNU Affero GPL version 3 section 7:
26
**
27
**   Under Section 7 of the GNU Affero GPL version 3, the following additional
28
**   terms apply to the works covered under the License.  These additional terms
29
**   are non-permissive additional terms allowed under Section 7 of the GNU
30
**   Affero GPL version 3 and may not be removed by you.
31
**
32
**   0. Attribution Requirement.
33
**
34
**     You must preserve all legal notices or author attributions in the covered
35
**     work or Appropriate Legal Notices displayed by works containing the covered
36
**     work.  You may not remove from the covered work any author or developer
37
**     credit already included within the covered work.
38
**
39
**   1. No License To Use Trademarks.
40
**
41
**     This license does not grant any license or rights to use the trademarks
42
**     Golden Code, FWD, any Golden Code or FWD logo, or any other trademarks
43
**     of Golden Code Development Corporation. You are not authorized to use the
44
**     name Golden Code, FWD, or the names of any author or contributor, for
45
**     publicity purposes without written authorization.
46
**
47
**   2. No Misrepresentation of Affiliation.
48
**
49
**     You may not represent yourself as Golden Code Development Corporation or FWD.
50
**
51
**     You may not represent yourself for publicity purposes as associated with
52
**     Golden Code Development Corporation, FWD, or any author or contributor to
53
**     the covered work, without written authorization.
54
**
55
**   3. No Misrepresentation of Source or Origin.
56
**
57
**     You may not represent the covered work as solely your work.  All modified
58
**     versions of the covered work must be marked in a reasonable way to make it
59
**     clear that the modified work is not originating from Golden Code Development
60
**     Corporation or FWD.  All modified versions must contain the notices of
61
**     attribution required in this license.
62
*/
63

  
64
package com.goldencode.p2j.persist;
65

  
66
import static org.junit.jupiter.api.Assertions.*;
67

  
68
import org.junit.jupiter.api.*;
69

  
70
/**
71
 * Tests for {@link FQLExpression#toFinalExpression(boolean)},
72
 * {@link FQLExpression#appendFinalExpression(StringBuilder, boolean)} and
73
 * {@link FQLExpression#finalLength(boolean)}: the same text through each, with numbered (JPA-style) and
74
 * simple placeholders.
75
 */
76
public class FQLExpressionTest
77
{
78
   /**
79
    * Placeholders are numbered from 0 in JPA style and plain otherwise.
80
    */
81
   @Test
82
   public void finalExpressionNumbersPlaceholders()
83
   {
84
      assertText("a = ?0 and b = ?1 order", twoSubstitutions(), true);
85
      assertText("a = ? and b = ? order", twoSubstitutions(), false);
86
   }
87

  
88
   /**
89
    * An expression ending with a substitution ends with its placeholder.
90
    */
91
   @Test
92
   public void finalExpressionEndingWithSubstitution()
93
   {
94
      assertText("x = ?0", new FQLExpression("x = ", true), true);
95
   }
96

  
97
   /**
98
    * Text appended to the buffered last part comes out in order.
99
    */
100
   @Test
101
   public void finalExpressionOfBufferedParts()
102
   {
103
      assertText("from t as t", new FQLExpression("from ").append("t").append(" as t"), true);
104
   }
105

  
106
   /**
107
    * A nested expression keeps its placeholders and the trailing space.
108
    */
109
   @Test
110
   public void finalExpressionOfNestedExpression()
111
   {
112
      assertText("from t where t.k = ?0 and t.n = ?1 ", nested(), true);
113
   }
114

  
115
   /**
116
    * An empty expression gives empty text and appends nothing.
117
    */
118
   @Test
119
   public void emptyExpressionAppendsNothing()
120
   {
121
      assertText("", new FQLExpression(), true);
122
      
123
      StringBuilder sb = new StringBuilder("x");
124
      new FQLExpression().appendFinalExpression(sb, true);
125
      assertEquals("x", sb.toString());
126
   }
127

  
128
   /**
129
    * Appending keeps what the builder already holds.
130
    */
131
   @Test
132
   public void appendKeepsExistingContent()
133
   {
134
      StringBuilder sb = new StringBuilder("select t.id ");
135
      nested().appendFinalExpression(sb, true);
136
      assertEquals("select t.id from t where t.k = ?0 and t.n = ?1 ", sb.toString());
137
   }
138

  
139
   /**
140
    * Appending changes no state: two appends and a final call give the same text.
141
    */
142
   @Test
143
   public void appendThenToFinalAgree()
144
   {
145
      FQLExpression e = nested();
146
      StringBuilder a = new StringBuilder();
147
      StringBuilder b = new StringBuilder();
148
      e.appendFinalExpression(a, true);
149
      e.appendFinalExpression(b, true);
150
      
151
      assertEquals(a.toString(), b.toString());
152
      assertEquals(a.toString(), e.toFinalExpression());
153
   }
154

  
155
   /**
156
    * The final length is the length of the final text, also with two-digit placeholder indexes.
157
    */
158
   @Test
159
   public void finalLengthMatchesText()
160
   {
161
      FQLExpression twelve = new FQLExpression("p0 = ", true);
162
      for (int i = 1; i < 12; i++)
163
      {
164
         twelve.append(" and p" + i + " = ", true);
165
      }
166
      assertTrue(twelve.toFinalExpression().contains("?11"));
167
      
168
      FQLExpression[] all =
169
      {
170
         twoSubstitutions(),
171
         new FQLExpression("x = ", true),
172
         new FQLExpression("from ").append("t").append(" as t"),
173
         nested(),
174
         new FQLExpression(),
175
         twelve
176
      };
177
      for (FQLExpression e : all)
178
      {
179
         for (boolean jpa : new boolean[] { true, false })
180
         {
181
            assertEquals(e.toFinalExpression(jpa).length(), e.finalLength(jpa), e.toFinalExpression(jpa));
182
         }
183
      }
184
   }
185

  
186
   /**
187
    * Check an expression's text through {@code toFinalExpression} and {@code appendFinalExpression}.
188
    *
189
    * @param    expected
190
    *           The expected text.
191
    * @param    e
192
    *           The expression.
193
    * @param    jpaStyle
194
    *           {@code true} for numbered placeholders.
195
    */
196
   private static void assertText(String expected, FQLExpression e, boolean jpaStyle)
197
   {
198
      assertEquals(expected, e.toFinalExpression(jpaStyle));
199
      
200
      StringBuilder sb = new StringBuilder();
201
      e.appendFinalExpression(sb, jpaStyle);
202
      assertEquals(expected, sb.toString());
203
   }
204

  
205
   /**
206
    * Build an expression with two substitutions followed by plain text.
207
    *
208
    * @return   {@code a = ? and b = ? order} with two placeholders.
209
    */
210
   private static FQLExpression twoSubstitutions()
211
   {
212
      return new FQLExpression("a = ", true).append(" and b = ", true).append(" order");
213
   }
214

  
215
   /**
216
    * Build an expression holding a nested expression with two substitutions.
217
    *
218
    * @return   {@code from t where t.k = ? and t.n = ? } with two placeholders.
219
    */
220
   private static FQLExpression nested()
221
   {
222
      return new FQLExpression("from t where ").append(new FQLExpression("t.k = ", true)
223
                                                          .append(" and t.n = ", true))
224
                                               .append(" ");
225
   }
226
}
new/test/com/goldencode/p2j/persist/SortCriterionTest.java
1
/*
2
** Module   : SortCriterionTest.java
3
** Abstract : Tests for the ORDER BY text of a sort criterion.
4
**
5
** Copyright (c) 2026, Golden Code Development Corporation.
6
**
7
** -#- -I- --Date-- ---------------------------------Description---------------------------------
8
** 001 SP  20261110 Created initial version.
9
*/
10

  
11
/*
12
** This program is free software: you can redistribute it and/or modify
13
** it under the terms of the GNU Affero General Public License as
14
** published by the Free Software Foundation, either version 3 of the
15
** License, or (at your option) any later version.
16
**
17
** This program is distributed in the hope that it will be useful,
18
** but WITHOUT ANY WARRANTY; without even the implied warranty of
19
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
** GNU Affero General Public License for more details.
21
**
22
** You may find a copy of the GNU Affero GPL version 3 at the following
23
** location: https://www.gnu.org/licenses/agpl-3.0.en.html
24
**
25
** Additional terms under GNU Affero GPL version 3 section 7:
26
**
27
**   Under Section 7 of the GNU Affero GPL version 3, the following additional
28
**   terms apply to the works covered under the License.  These additional terms
29
**   are non-permissive additional terms allowed under Section 7 of the GNU
30
**   Affero GPL version 3 and may not be removed by you.
31
**
32
**   0. Attribution Requirement.
33
**
34
**     You must preserve all legal notices or author attributions in the covered
35
**     work or Appropriate Legal Notices displayed by works containing the covered
36
**     work.  You may not remove from the covered work any author or developer
37
**     credit already included within the covered work.
38
**
39
**   1. No License To Use Trademarks.
40
**
41
**     This license does not grant any license or rights to use the trademarks
42
**     Golden Code, FWD, any Golden Code or FWD logo, or any other trademarks
43
**     of Golden Code Development Corporation. You are not authorized to use the
44
**     name Golden Code, FWD, or the names of any author or contributor, for
45
**     publicity purposes without written authorization.
46
**
47
**   2. No Misrepresentation of Affiliation.
48
**
49
**     You may not represent yourself as Golden Code Development Corporation or FWD.
50
**
51
**     You may not represent yourself for publicity purposes as associated with
52
**     Golden Code Development Corporation, FWD, or any author or contributor to
53
**     the covered work, without written authorization.
54
**
55
**   3. No Misrepresentation of Source or Origin.
56
**
57
**     You may not represent the covered work as solely your work.  All modified
58
**     versions of the covered work must be marked in a reasonable way to make it
59
**     clear that the modified work is not originating from Golden Code Development
60
**     Corporation or FWD.  All modified versions must contain the notices of
61
**     attribution required in this license.
62
*/
63

  
64
package com.goldencode.p2j.persist;
65

  
66
import static org.junit.jupiter.api.Assertions.*;
67

  
68
import java.util.*;
69
import java.util.concurrent.*;
70

  
71
import org.junit.jupiter.api.*;
72

  
73
import com.goldencode.asm.*;
74
import com.goldencode.p2j.persist.dialect.*;
75
import com.goldencode.p2j.persist.orm.*;
76

  
77
/**
78
 * Tests for {@link SortCriterion#toSortExpression(boolean)}: the ORDER BY text for every dialect branch
79
 * (upper and rtrim, rtrim only, plain names, computed-column prefixes, a copy with another alias), and
80
 * that a criterion builds that text once.
81
 * <p>
82
 * Registering the test DMO needs FWD's {@code AsmClassLoader} as the system class loader
83
 * ({@code -Djava.system.class.loader=com.goldencode.asm.AsmClassLoader}).
84
 */
85
public class SortCriterionTest
86
{
87
   /** Metadata of {@link SortCriterionTestDmo}. */
88
   private static DmoMeta meta;
89

  
90
   /**
91
    * Register the test DMO, or skip the tests when the JVM was not started with FWD's
92
    * {@code AsmClassLoader} as the system class loader, which DMO registration needs.
93
    */
94
   @BeforeAll
95
   public static void registerDmo()
96
   {
97
      Assumptions.assumeTrue(AsmClassLoader.getInstance() != null,
98
                             "needs -Djava.system.class.loader=com.goldencode.asm.AsmClassLoader");
99
      meta = DmoMetadataManager.registerDmo(SortCriterionTestDmo.class);
100
   }
101

  
102
   /**
103
    * Each dialect gives the expected text in both directions for a case-insensitive and a case-sensitive
104
    * character field, an integer field, the primary key and a copy with another alias.
105
    *
106
    * @throws   Exception
107
    *           If a criterion cannot be built.
108
    */
109
   @Test
110
   public void sortTextMatchesEachDialect()
111
   throws Exception
112
   {
113
      String[] plain = { "spike.nm desc", "spike.code desc", "other.nm asc" };
114
      
115
      assertDialect(new P2JPostgreSQLDialect(),
116
                    "upper(rtrim(spike.nm)) desc", "rtrim(spike.code) desc", "upper(rtrim(other.nm)) asc");
117
      assertDialect(new P2JH2Dialect(), plain[0], plain[1], plain[2]);
118
      assertDialect(new MariaDbLenientDialect(), plain[0], plain[1], plain[2]);
119
      assertDialect(new MariaDbDialect(), plain[0], plain[1], plain[2]);
120
      assertDialect(new P2JSQLServer2012Dialect(),
121
                    "spike.__inm desc", "spike.__scode desc", "other.__inm asc");
122
   }
123

  
124
   /**
125
    * A criterion returns the same text instance on every call, for each direction and through
126
    * {@code toString()}.
127
    *
128
    * @throws   Exception
129
    *           If the criterion cannot be built.
130
    */
131
   @Test
132
   public void sortTextIsBuiltOnce()
133
   throws Exception
134
   {
135
      SortCriterion c = new SortCriterion(new P2JPostgreSQLDialect(), "spike.nm desc", meta, false);
136
      
137
      assertSame(c.toSortExpression(false), c.toSortExpression(false));
138
      assertSame(c.toSortExpression(true), c.toSortExpression(true));
139
      assertSame(c.toString(), c.toSortExpression(false));
140
   }
141

  
142
   /**
143
    * Threads sharing one fresh criterion all get the complete text.
144
    *
145
    * @throws   Exception
146
    *           If the criterion cannot be built or a thread fails.
147
    */
148
   @Test
149
   public void sortTextIsCorrectFromManyThreads()
150
   throws Exception
151
   {
152
      SortCriterion c = new SortCriterion(new P2JPostgreSQLDialect(), "spike.nm desc", meta, false);
153
      ExecutorService pool = Executors.newFixedThreadPool(8);
154
      try
155
      {
156
         List<Future<Boolean>> results = new ArrayList<>();
157
         for (int t = 0; t < 8; t++)
158
         {
159
            results.add(pool.submit(() ->
160
            {
161
               boolean ok = true;
162
               for (int i = 0; i < 10_000; i++)
163
               {
164
                  ok &= "upper(rtrim(spike.nm)) desc".equals(c.toSortExpression(false));
165
                  ok &= "upper(rtrim(spike.nm)) asc".equals(c.toSortExpression(true));
166
               }
167
               return ok;
168
            }));
169
         }
170
         
171
         for (Future<Boolean> f : results)
172
         {
173
            assertTrue(f.get());
174
         }
175
      }
176
      finally
177
      {
178
         pool.shutdownNow();
179
      }
180
   }
181

  
182
   /**
183
    * Check the text of one dialect in both directions.
184
    *
185
    * @param    dialect
186
    *           The dialect.
187
    * @param    nm
188
    *           Expected text of {@code spike.nm desc}.
189
    * @param    code
190
    *           Expected text of {@code spike.code desc}.
191
    * @param    copy
192
    *           Expected text of the copy of {@code spike.nm} with alias {@code other}.
193
    *
194
    * @throws   Exception
195
    *           If a criterion cannot be built.
196
    */
197
   private static void assertDialect(Dialect dialect, String nm, String code, String copy)
198
   throws Exception
199
   {
200
      assertBoth(nm, new SortCriterion(dialect, "spike.nm desc", meta, false));
201
      assertBoth(code, new SortCriterion(dialect, "spike.code desc", meta, false));
202
      assertBoth("spike.k asc", new SortCriterion(dialect, "spike.k", meta, false));
203
      assertBoth("spike.recid asc", new SortCriterion(dialect, "spike.recid asc", meta, false));
204
      assertBoth(copy, new SortCriterion(new SortCriterion(dialect, "spike.nm", meta, false), "other"));
205
   }
206

  
207
   /**
208
    * Check a criterion's text, and that the inverted text swaps only the trailing direction.
209
    *
210
    * @param    expected
211
    *           Expected text in the original direction.
212
    * @param    c
213
    *           The criterion.
214
    */
215
   private static void assertBoth(String expected, SortCriterion c)
216
   {
217
      String inverted = expected.endsWith(" asc")
218
                        ? expected.substring(0, expected.length() - 4) + " desc"
219
                        : expected.substring(0, expected.length() - 5) + " asc";
220
      
221
      assertEquals(expected, c.toSortExpression(false));
222
      assertEquals(inverted, c.toSortExpression(true));
223
      assertEquals(expected, c.toString());
224
   }
225
}
new/test/com/goldencode/p2j/persist/SortCriterionTestDmo.java
1
/*
2
** Module   : SortCriterionTestDmo.java
3
** Abstract : Data model object for the SortCriterion tests.
4
**
5
** Copyright (c) 2026, Golden Code Development Corporation.
6
**
7
** -#- -I- --Date-- ---------------------------------Description---------------------------------
8
** 001 SP  20261110 Created initial version.
9
*/
10

  
11
/*
12
** This program is free software: you can redistribute it and/or modify
13
** it under the terms of the GNU Affero General Public License as
14
** published by the Free Software Foundation, either version 3 of the
15
** License, or (at your option) any later version.
16
**
17
** This program is distributed in the hope that it will be useful,
18
** but WITHOUT ANY WARRANTY; without even the implied warranty of
19
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
** GNU Affero General Public License for more details.
21
**
22
** You may find a copy of the GNU Affero GPL version 3 at the following
23
** location: https://www.gnu.org/licenses/agpl-3.0.en.html
24
**
25
** Additional terms under GNU Affero GPL version 3 section 7:
26
**
27
**   Under Section 7 of the GNU Affero GPL version 3, the following additional
28
**   terms apply to the works covered under the License.  These additional terms
29
**   are non-permissive additional terms allowed under Section 7 of the GNU
30
**   Affero GPL version 3 and may not be removed by you.
31
**
32
**   0. Attribution Requirement.
33
**
34
**     You must preserve all legal notices or author attributions in the covered
35
**     work or Appropriate Legal Notices displayed by works containing the covered
36
**     work.  You may not remove from the covered work any author or developer
37
**     credit already included within the covered work.
38
**
39
**   1. No License To Use Trademarks.
40
**
41
**     This license does not grant any license or rights to use the trademarks
42
**     Golden Code, FWD, any Golden Code or FWD logo, or any other trademarks
43
**     of Golden Code Development Corporation. You are not authorized to use the
44
**     name Golden Code, FWD, or the names of any author or contributor, for
45
**     publicity purposes without written authorization.
46
**
47
**   2. No Misrepresentation of Affiliation.
48
**
49
**     You may not represent yourself as Golden Code Development Corporation or FWD.
50
**
51
**     You may not represent yourself for publicity purposes as associated with
52
**     Golden Code Development Corporation, FWD, or any author or contributor to
53
**     the covered work, without written authorization.
54
**
55
**   3. No Misrepresentation of Source or Origin.
56
**
57
**     You may not represent the covered work as solely your work.  All modified
58
**     versions of the covered work must be marked in a reasonable way to make it
59
**     clear that the modified work is not originating from Golden Code Development
60
**     Corporation or FWD.  All modified versions must contain the notices of
61
**     attribution required in this license.
62
*/
63

  
64
package com.goldencode.p2j.persist;
65

  
66
import com.goldencode.p2j.persist.annotation.*;
67
import com.goldencode.p2j.util.*;
68

  
69
/**
70
 * Data model object for {@link SortCriterionTest}: an integer key, a case-insensitive character field
71
 * and a case-sensitive character field.
72
 */
73
@Table(name = "spike", legacy = "spike")
74
@Indices(
75
{
76
   @Index(name = "k", legacy = "k", primary = true, unique = true, components = 
77
   {
78
      @IndexComponent(name = "k", legacy = "k")
79
   }),
80
   @Index(name = "nm", legacy = "nm", components = 
81
   {
82
      @IndexComponent(name = "nm", legacy = "nm")
83
   }),
84
   @Index(name = "code", legacy = "code", components = 
85
   {
86
      @IndexComponent(name = "code", legacy = "code")
87
   })
88
})
89
public interface SortCriterionTestDmo
90
extends DataModelObject
91
{
92
   /**
93
    * Getter: k
94
    *
95
    * @return   The integer key.
96
    */
97
   @Property(id = 1, name = "k", column = "k", legacy = "k", format = ">>>>9", initial = "0", order = 10)
98
   public integer getK();
99

  
100
   /**
101
    * Setter: k
102
    *
103
    * @param    k
104
    *           The integer key.
105
    */
106
   public void setK(NumberType k);
107

  
108
   /**
109
    * Getter: nm
110
    *
111
    * @return   The case-insensitive character field.
112
    */
113
   @Property(id = 2, name = "nm", column = "nm", legacy = "nm", format = "x(30)", order = 20)
114
   public character getNm();
115

  
116
   /**
117
    * Setter: nm
118
    *
119
    * @param    nm
120
    *           The case-insensitive character field.
121
    */
122
   public void setNm(Text nm);
123

  
124
   /**
125
    * Getter: code
126
    *
127
    * @return   The case-sensitive character field.
128
    */
129
   @Property(id = 3, name = "code", column = "code", legacy = "code", format = "x(8)", caseSensitive = true,
130
             order = 30)
131
   public character getCode();
132

  
133
   /**
134
    * Setter: code
135
    *
136
    * @param    code
137
    *           The case-sensitive character field.
138
    */
139
   public void setCode(Text code);
140
}