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 20KB

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