You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

BuiltinOperators.java 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670
  1. /*
  2. Copyright (c) 2016 James Ahlborn
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package com.healthmarketscience.jackcess.impl.expr;
  14. import java.math.BigDecimal;
  15. import java.util.regex.Pattern;
  16. import com.healthmarketscience.jackcess.expr.EvalContext;
  17. import com.healthmarketscience.jackcess.expr.EvalException;
  18. import com.healthmarketscience.jackcess.expr.Value;
  19. import com.healthmarketscience.jackcess.impl.NumberFormatter;
  20. import static com.healthmarketscience.jackcess.impl.expr.ValueSupport.*;
  21. /**
  22. *
  23. * @author James Ahlborn
  24. */
  25. public class BuiltinOperators
  26. {
  27. private static final String DIV_BY_ZERO = "/ by zero";
  28. private static final double MIN_INT = Integer.MIN_VALUE;
  29. private static final double MAX_INT = Integer.MAX_VALUE;
  30. private enum CoercionType {
  31. SIMPLE(true, true), GENERAL(false, true), COMPARE(false, false);
  32. final boolean _preferTemporal;
  33. final boolean _allowCoerceStringToNum;
  34. private CoercionType(boolean preferTemporal,
  35. boolean allowCoerceStringToNum) {
  36. _preferTemporal = preferTemporal;
  37. _allowCoerceStringToNum = allowCoerceStringToNum;
  38. }
  39. }
  40. private BuiltinOperators() {}
  41. // null propagation rules:
  42. // http://www.utteraccess.com/wiki/index.php/Nulls_And_Their_Behavior
  43. // https://theaccessbuddy.wordpress.com/2012/10/24/6-logical-operators-in-ms-access-that-you-must-know-operator-types-3-of-5/
  44. // - number ops
  45. // - comparison ops
  46. // - logical ops (some "special")
  47. // - And - can be false if one arg is false
  48. // - Or - can be true if one arg is true
  49. // - between, not, like, in
  50. // - *NOT* concal op '&'
  51. public static Value negate(EvalContext ctx, Value param1) {
  52. if(param1.isNull()) {
  53. // null propagation
  54. return NULL_VAL;
  55. }
  56. Value.Type mathType = param1.getType();
  57. switch(mathType) {
  58. case DATE:
  59. case TIME:
  60. case DATE_TIME:
  61. // dates/times get converted to date doubles for arithmetic
  62. double result = -param1.getAsDouble();
  63. return toDateValue(ctx, mathType, result, param1, null);
  64. case LONG:
  65. return toValue(-param1.getAsLongInt());
  66. case DOUBLE:
  67. return toValue(-param1.getAsDouble());
  68. case STRING:
  69. case BIG_DEC:
  70. return toValue(param1.getAsBigDecimal().negate(
  71. NumberFormatter.DEC_MATH_CONTEXT));
  72. default:
  73. throw new EvalException("Unexpected type " + mathType);
  74. }
  75. }
  76. public static Value add(EvalContext ctx, Value param1, Value param2) {
  77. if(anyParamIsNull(param1, param2)) {
  78. // null propagation
  79. return NULL_VAL;
  80. }
  81. Value.Type mathType = getMathTypePrecedence(param1, param2,
  82. CoercionType.SIMPLE);
  83. switch(mathType) {
  84. case STRING:
  85. // string '+' is a null-propagation (handled above) concat
  86. return nonNullConcat(param1, param2);
  87. case DATE:
  88. case TIME:
  89. case DATE_TIME:
  90. // dates/times get converted to date doubles for arithmetic
  91. double result = param1.getAsDouble() + param2.getAsDouble();
  92. return toDateValue(ctx, mathType, result, param1, param2);
  93. case LONG:
  94. return toValue(param1.getAsLongInt() + param2.getAsLongInt());
  95. case DOUBLE:
  96. return toValue(param1.getAsDouble() + param2.getAsDouble());
  97. case BIG_DEC:
  98. return toValue(param1.getAsBigDecimal().add(
  99. param2.getAsBigDecimal(),
  100. NumberFormatter.DEC_MATH_CONTEXT));
  101. default:
  102. throw new EvalException("Unexpected type " + mathType);
  103. }
  104. }
  105. public static Value subtract(EvalContext ctx, Value param1, Value param2) {
  106. if(anyParamIsNull(param1, param2)) {
  107. // null propagation
  108. return NULL_VAL;
  109. }
  110. Value.Type mathType = getMathTypePrecedence(param1, param2,
  111. CoercionType.SIMPLE);
  112. switch(mathType) {
  113. // case STRING: break; unsupported
  114. case DATE:
  115. case TIME:
  116. case DATE_TIME:
  117. // dates/times get converted to date doubles for arithmetic
  118. double result = param1.getAsDouble() - param2.getAsDouble();
  119. return toDateValue(ctx, mathType, result, param1, param2);
  120. case LONG:
  121. return toValue(param1.getAsLongInt() - param2.getAsLongInt());
  122. case DOUBLE:
  123. return toValue(param1.getAsDouble() - param2.getAsDouble());
  124. case BIG_DEC:
  125. return toValue(param1.getAsBigDecimal().subtract(
  126. param2.getAsBigDecimal(),
  127. NumberFormatter.DEC_MATH_CONTEXT));
  128. default:
  129. throw new EvalException("Unexpected type " + mathType);
  130. }
  131. }
  132. public static Value multiply(Value param1, Value param2) {
  133. if(anyParamIsNull(param1, param2)) {
  134. // null propagation
  135. return NULL_VAL;
  136. }
  137. Value.Type mathType = getMathTypePrecedence(param1, param2,
  138. CoercionType.GENERAL);
  139. switch(mathType) {
  140. // case STRING: break; unsupported
  141. // case DATE: break; promoted to double
  142. // case TIME: break; promoted to double
  143. // case DATE_TIME: break; promoted to double
  144. case LONG:
  145. return toValue(param1.getAsLongInt() * param2.getAsLongInt());
  146. case DOUBLE:
  147. return toValue(param1.getAsDouble() * param2.getAsDouble());
  148. case BIG_DEC:
  149. return toValue(param1.getAsBigDecimal().multiply(
  150. param2.getAsBigDecimal(),
  151. NumberFormatter.DEC_MATH_CONTEXT));
  152. default:
  153. throw new EvalException("Unexpected type " + mathType);
  154. }
  155. }
  156. public static Value divide(Value param1, Value param2) {
  157. if(anyParamIsNull(param1, param2)) {
  158. // null propagation
  159. return NULL_VAL;
  160. }
  161. Value.Type mathType = getMathTypePrecedence(param1, param2,
  162. CoercionType.GENERAL);
  163. switch(mathType) {
  164. // case STRING: break; unsupported
  165. // case DATE: break; promoted to double
  166. // case TIME: break; promoted to double
  167. // case DATE_TIME: break; promoted to double
  168. case LONG:
  169. int lp1 = param1.getAsLongInt();
  170. int lp2 = param2.getAsLongInt();
  171. if((lp1 % lp2) == 0) {
  172. return toValue(lp1 / lp2);
  173. }
  174. return toValue((double)lp1 / (double)lp2);
  175. case DOUBLE:
  176. double d2 = param2.getAsDouble();
  177. if(d2 == 0.0d) {
  178. throw new ArithmeticException(DIV_BY_ZERO);
  179. }
  180. return toValue(param1.getAsDouble() / d2);
  181. case BIG_DEC:
  182. return toValue(divide(param1.getAsBigDecimal(), param2.getAsBigDecimal()));
  183. default:
  184. throw new EvalException("Unexpected type " + mathType);
  185. }
  186. }
  187. public static Value intDivide(Value param1, Value param2) {
  188. if(anyParamIsNull(param1, param2)) {
  189. // null propagation
  190. return NULL_VAL;
  191. }
  192. Value.Type mathType = getMathTypePrecedence(param1, param2,
  193. CoercionType.GENERAL);
  194. if(mathType == Value.Type.STRING) {
  195. throw new EvalException("Unexpected type " + mathType);
  196. }
  197. return toValue(param1.getAsLongInt() / param2.getAsLongInt());
  198. }
  199. public static Value exp(Value param1, Value param2) {
  200. if(anyParamIsNull(param1, param2)) {
  201. // null propagation
  202. return NULL_VAL;
  203. }
  204. Value.Type mathType = getMathTypePrecedence(param1, param2,
  205. CoercionType.GENERAL);
  206. if(mathType == Value.Type.BIG_DEC) {
  207. // see if we can handle the limited options supported for BigDecimal
  208. // (must be a positive int exponent)
  209. try {
  210. BigDecimal result = param1.getAsBigDecimal().pow(
  211. param2.getAsBigDecimal().intValueExact(),
  212. NumberFormatter.DEC_MATH_CONTEXT);
  213. return toValue(result);
  214. } catch(ArithmeticException ae) {
  215. // fall back to general handling via doubles...
  216. }
  217. }
  218. // jdk only supports general pow() as doubles, let's go with that
  219. double result = Math.pow(param1.getAsDouble(), param2.getAsDouble());
  220. // attempt to convert integral types back to integrals if possible
  221. if((mathType == Value.Type.LONG) && isIntegral(result)) {
  222. return toValue((int)result);
  223. }
  224. return toValue(result);
  225. }
  226. public static Value mod(Value param1, Value param2) {
  227. if(anyParamIsNull(param1, param2)) {
  228. // null propagation
  229. return NULL_VAL;
  230. }
  231. Value.Type mathType = getMathTypePrecedence(param1, param2,
  232. CoercionType.GENERAL);
  233. if(mathType == Value.Type.STRING) {
  234. throw new EvalException("Unexpected type " + mathType);
  235. }
  236. return toValue(param1.getAsLongInt() % param2.getAsLongInt());
  237. }
  238. public static Value concat(Value param1, Value param2) {
  239. // note, this op converts null to empty string
  240. if(param1.isNull()) {
  241. param1 = EMPTY_STR_VAL;
  242. }
  243. if(param2.isNull()) {
  244. param2 = EMPTY_STR_VAL;
  245. }
  246. return nonNullConcat(param1, param2);
  247. }
  248. private static Value nonNullConcat(Value param1, Value param2) {
  249. return toValue(param1.getAsString().concat(param2.getAsString()));
  250. }
  251. public static Value not(Value param1) {
  252. if(param1.isNull()) {
  253. // null propagation
  254. return NULL_VAL;
  255. }
  256. return toValue(!param1.getAsBoolean());
  257. }
  258. public static Value lessThan(Value param1, Value param2) {
  259. if(anyParamIsNull(param1, param2)) {
  260. // null propagation
  261. return NULL_VAL;
  262. }
  263. return toValue(nonNullCompareTo(param1, param2) < 0);
  264. }
  265. public static Value greaterThan(Value param1, Value param2) {
  266. if(anyParamIsNull(param1, param2)) {
  267. // null propagation
  268. return NULL_VAL;
  269. }
  270. return toValue(nonNullCompareTo(param1, param2) > 0);
  271. }
  272. public static Value lessThanEq(Value param1, Value param2) {
  273. if(anyParamIsNull(param1, param2)) {
  274. // null propagation
  275. return NULL_VAL;
  276. }
  277. return toValue(nonNullCompareTo(param1, param2) <= 0);
  278. }
  279. public static Value greaterThanEq(Value param1, Value param2) {
  280. if(anyParamIsNull(param1, param2)) {
  281. // null propagation
  282. return NULL_VAL;
  283. }
  284. return toValue(nonNullCompareTo(param1, param2) >= 0);
  285. }
  286. public static Value equals(Value param1, Value param2) {
  287. if(anyParamIsNull(param1, param2)) {
  288. // null propagation
  289. return NULL_VAL;
  290. }
  291. return toValue(nonNullCompareTo(param1, param2) == 0);
  292. }
  293. public static Value notEquals(Value param1, Value param2) {
  294. if(anyParamIsNull(param1, param2)) {
  295. // null propagation
  296. return NULL_VAL;
  297. }
  298. return toValue(nonNullCompareTo(param1, param2) != 0);
  299. }
  300. public static Value and(Value param1, Value param2) {
  301. // "and" uses short-circuit logic
  302. if(param1.isNull()) {
  303. return NULL_VAL;
  304. }
  305. boolean b1 = param1.getAsBoolean();
  306. if(!b1) {
  307. return FALSE_VAL;
  308. }
  309. if(param2.isNull()) {
  310. return NULL_VAL;
  311. }
  312. return toValue(param2.getAsBoolean());
  313. }
  314. public static Value or(Value param1, Value param2) {
  315. // "or" uses short-circuit logic
  316. if(param1.isNull()) {
  317. return NULL_VAL;
  318. }
  319. boolean b1 = param1.getAsBoolean();
  320. if(b1) {
  321. return TRUE_VAL;
  322. }
  323. if(param2.isNull()) {
  324. return NULL_VAL;
  325. }
  326. return toValue(param2.getAsBoolean());
  327. }
  328. public static Value eqv(Value param1, Value param2) {
  329. if(anyParamIsNull(param1, param2)) {
  330. // null propagation
  331. return NULL_VAL;
  332. }
  333. boolean b1 = param1.getAsBoolean();
  334. boolean b2 = param2.getAsBoolean();
  335. return toValue(b1 == b2);
  336. }
  337. public static Value xor(Value param1, Value param2) {
  338. if(anyParamIsNull(param1, param2)) {
  339. // null propagation
  340. return NULL_VAL;
  341. }
  342. boolean b1 = param1.getAsBoolean();
  343. boolean b2 = param2.getAsBoolean();
  344. return toValue(b1 ^ b2);
  345. }
  346. public static Value imp(Value param1, Value param2) {
  347. // "imp" uses short-circuit logic
  348. if(param1.isNull()) {
  349. if(param2.isNull() || !param2.getAsBoolean()) {
  350. // null propagation
  351. return NULL_VAL;
  352. }
  353. return TRUE_VAL;
  354. }
  355. boolean b1 = param1.getAsBoolean();
  356. if(!b1) {
  357. return TRUE_VAL;
  358. }
  359. if(param2.isNull()) {
  360. // null propagation
  361. return NULL_VAL;
  362. }
  363. return toValue(param2.getAsBoolean());
  364. }
  365. public static Value isNull(Value param1) {
  366. return toValue(param1.isNull());
  367. }
  368. public static Value isNotNull(Value param1) {
  369. return toValue(!param1.isNull());
  370. }
  371. public static Value like(Value param1, Pattern pattern) {
  372. if(param1.isNull()) {
  373. // null propagation
  374. return NULL_VAL;
  375. }
  376. return toValue(pattern.matcher(param1.getAsString()).matches());
  377. }
  378. public static Value notLike(Value param1, Pattern pattern) {
  379. return not(like(param1, pattern));
  380. }
  381. public static Value between(Value param1, Value param2, Value param3) {
  382. // null propagate any param. uses short circuit eval of params
  383. if(anyParamIsNull(param1, param2, param3)) {
  384. // null propagation
  385. return NULL_VAL;
  386. }
  387. // the between values can be in either order!?!
  388. Value min = param2;
  389. Value max = param3;
  390. Value gt = greaterThan(min, max);
  391. if(gt.getAsBoolean()) {
  392. min = param3;
  393. max = param2;
  394. }
  395. return and(greaterThanEq(param1, min), lessThanEq(param1, max));
  396. }
  397. public static Value notBetween(Value param1, Value param2, Value param3) {
  398. return not(between(param1, param2, param3));
  399. }
  400. public static Value in(Value param1, Value[] params) {
  401. // null propagate any param. uses short circuit eval of params
  402. if(param1.isNull()) {
  403. // null propagation
  404. return NULL_VAL;
  405. }
  406. for(Value val : params) {
  407. if(val.isNull()) {
  408. continue;
  409. }
  410. Value eq = equals(param1, val);
  411. if(eq.getAsBoolean()) {
  412. return TRUE_VAL;
  413. }
  414. }
  415. return FALSE_VAL;
  416. }
  417. public static Value notIn(Value param1, Value[] params) {
  418. return not(in(param1, params));
  419. }
  420. private static boolean anyParamIsNull(Value param1, Value param2) {
  421. return (param1.isNull() || param2.isNull());
  422. }
  423. private static boolean anyParamIsNull(Value param1, Value param2,
  424. Value param3) {
  425. return (param1.isNull() || param2.isNull() || param3.isNull());
  426. }
  427. protected static int nonNullCompareTo(
  428. Value param1, Value param2)
  429. {
  430. // note that comparison does not do string to num coercion
  431. Value.Type compareType = getMathTypePrecedence(param1, param2,
  432. CoercionType.COMPARE);
  433. switch(compareType) {
  434. case STRING:
  435. // string comparison is only valid if _both_ params are strings
  436. if(param1.getType() != param2.getType()) {
  437. throw new EvalException("Unexpected type " + compareType);
  438. }
  439. return param1.getAsString().compareToIgnoreCase(param2.getAsString());
  440. // case DATE: break; promoted to double
  441. // case TIME: break; promoted to double
  442. // case DATE_TIME: break; promoted to double
  443. case LONG:
  444. return param1.getAsLongInt().compareTo(param2.getAsLongInt());
  445. case DOUBLE:
  446. return param1.getAsDouble().compareTo(param2.getAsDouble());
  447. case BIG_DEC:
  448. return param1.getAsBigDecimal().compareTo(param2.getAsBigDecimal());
  449. default:
  450. throw new EvalException("Unexpected type " + compareType);
  451. }
  452. }
  453. private static Value.Type getMathTypePrecedence(
  454. Value param1, Value param2, CoercionType cType)
  455. {
  456. Value.Type t1 = param1.getType();
  457. Value.Type t2 = param2.getType();
  458. // note: for general math, date/time become double
  459. if(t1 == t2) {
  460. if(!cType._preferTemporal && t1.isTemporal()) {
  461. return t1.getPreferredNumericType();
  462. }
  463. return t1;
  464. }
  465. if((t1 == Value.Type.STRING) || (t2 == Value.Type.STRING)) {
  466. if(cType._allowCoerceStringToNum) {
  467. // see if this is mixed string/numeric and the string can be coerced
  468. // to a number
  469. Value.Type numericType = coerceStringToNumeric(param1, param2, cType);
  470. if(numericType != null) {
  471. // string can be coerced to number
  472. return numericType;
  473. }
  474. }
  475. // string always wins
  476. return Value.Type.STRING;
  477. }
  478. // for "simple" math, keep as date/times
  479. if(cType._preferTemporal &&
  480. (t1.isTemporal() || t2.isTemporal())) {
  481. return (t1.isTemporal() ?
  482. (t2.isTemporal() ?
  483. // for mixed temporal types, always go to date/time
  484. Value.Type.DATE_TIME : t1) :
  485. t2);
  486. }
  487. return getPreferredNumericType(t1.getPreferredNumericType(),
  488. t2.getPreferredNumericType());
  489. }
  490. private static Value.Type getPreferredNumericType(Value.Type t1, Value.Type t2)
  491. {
  492. // if both types are integral, choose "largest"
  493. if(t1.isIntegral() && t2.isIntegral()) {
  494. return max(t1, t2);
  495. }
  496. // choose largest relevant floating-point type
  497. return max(t1.getPreferredFPType(), t2.getPreferredFPType());
  498. }
  499. private static Value.Type coerceStringToNumeric(
  500. Value param1, Value param2, CoercionType cType) {
  501. Value.Type t1 = param1.getType();
  502. Value.Type t2 = param2.getType();
  503. Value.Type prefType = null;
  504. Value strParam = null;
  505. if(t1.isNumeric()) {
  506. prefType = t1;
  507. strParam = param2;
  508. } else if(t2.isNumeric()) {
  509. prefType = t2;
  510. strParam = param1;
  511. } else if(t1.isTemporal()) {
  512. prefType = (cType._preferTemporal ? t1 : t1.getPreferredNumericType());
  513. strParam = param2;
  514. } else if(t2.isTemporal()) {
  515. prefType = (cType._preferTemporal ? t2 : t2.getPreferredNumericType());
  516. strParam = param1;
  517. } else {
  518. // no numeric type involved
  519. return null;
  520. }
  521. try {
  522. // see if string can be coerced to a number
  523. strParam.getAsBigDecimal();
  524. if(prefType.isNumeric()) {
  525. // seems like when strings are coerced to numbers, they are usually
  526. // doubles, unless the current context is decimal
  527. prefType = ((prefType == Value.Type.BIG_DEC) ?
  528. Value.Type.BIG_DEC : Value.Type.DOUBLE);
  529. }
  530. return prefType;
  531. } catch(NumberFormatException ignored) {
  532. // not a number
  533. }
  534. return null;
  535. }
  536. private static Value.Type max(Value.Type t1, Value.Type t2) {
  537. return ((t1.compareTo(t2) > 0) ? t1 : t2);
  538. }
  539. static BigDecimal divide(BigDecimal num, BigDecimal denom) {
  540. return num.divide(denom, NumberFormatter.DEC_MATH_CONTEXT);
  541. }
  542. static boolean isIntegral(double d) {
  543. double id = Math.rint(d);
  544. return ((d == id) && (d >= MIN_INT) && (d <= MAX_INT) &&
  545. !Double.isInfinite(d) && !Double.isNaN(d));
  546. }
  547. }