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 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717
| package com.ruben.simpleboot.interceptor
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper import com.baomidou.mybatisplus.core.plugins.InterceptorIgnoreHelper import com.baomidou.mybatisplus.core.toolkit.* import com.baomidou.mybatisplus.extension.parser.JsqlParserSupport import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor import com.baomidou.mybatisplus.extension.toolkit.PropertyMapper import net.sf.jsqlparser.expression.* import net.sf.jsqlparser.expression.Function import net.sf.jsqlparser.expression.operators.conditional.AndExpression import net.sf.jsqlparser.expression.operators.conditional.OrExpression import net.sf.jsqlparser.expression.operators.relational.* import net.sf.jsqlparser.schema.Column import net.sf.jsqlparser.schema.Table import net.sf.jsqlparser.statement.Statement import net.sf.jsqlparser.statement.delete.Delete import net.sf.jsqlparser.statement.insert.Insert import net.sf.jsqlparser.statement.select.* import net.sf.jsqlparser.statement.update.Update import org.apache.ibatis.executor.Executor import org.apache.ibatis.executor.statement.StatementHandler import org.apache.ibatis.mapping.BoundSql import org.apache.ibatis.mapping.MappedStatement import org.apache.ibatis.mapping.SqlCommandType import org.apache.ibatis.session.ResultHandler import org.apache.ibatis.session.RowBounds import java.sql.Connection import java.sql.SQLException import java.util.* import java.util.function.Consumer import java.util.stream.Collectors
class RecycleBinInterceptor(private var recycleBinLineHandler: RecycleBinLineHandler? = null) : JsqlParserSupport(), InnerInterceptor {
@Throws(SQLException::class) override fun beforeQuery( executor: Executor?, ms: MappedStatement, parameter: Any?, rowBounds: RowBounds?, resultHandler: ResultHandler<*>?, boundSql: BoundSql? ) { if (InterceptorIgnoreHelper.willIgnoreOthersByKey(ms.id, "recycleBin")) return val mpBs = PluginUtils.mpBoundSql(boundSql) mpBs.sql(parserSingle(mpBs.sql(), null)) }
override fun processParser(statement: Statement?, index: Int, sql: String?, obj: Any?): String { if (logger.isDebugEnabled) { logger.debug("SQL to parse, SQL: $sql") } var sql: String? = null if (statement is Insert) { processInsert((statement as Insert?)!!, index, sql, obj) } else if (statement is Select) { processSelect((statement as Select?)!!, index, sql, obj) } else if (statement is Update) { processUpdate((statement as Update?)!!, index, sql, obj) } else if (statement is Delete) { if (!RecycleThreadLocal.REAL_DELETE.get() && !recycleBinLineHandler!!.ignoreTable(statement.table.name)) { sql = Update().apply { table = statement.table where = statement.where addUpdateSet( Column(recycleBinLineHandler!!.getRecycleBinColumn()), Column("NOW()") ) }.toString() } else { processDelete((statement as Delete?)!!, index, sql, obj) } } sql = sql ?: statement.toString() if (logger.isDebugEnabled) { logger.debug("parse the finished SQL: $sql") } return sql }
override fun beforePrepare(sh: StatementHandler?, connection: Connection?, transactionTimeout: Int?) { val mpSh = PluginUtils.mpStatementHandler(sh) val ms = mpSh.mappedStatement() val sct = ms.sqlCommandType if (sct == SqlCommandType.INSERT || sct == SqlCommandType.DELETE || sct == SqlCommandType.UPDATE || sct == SqlCommandType.SELECT ) { if (InterceptorIgnoreHelper.willIgnoreOthersByKey(ms.id, "recycleBin")) { return } val mpBs = mpSh.mPBoundSql() mpBs.sql(parserMulti(mpBs.sql(), null)) } }
override fun processSelect(select: Select, index: Int, sql: String?, obj: Any?) { processSelectBody(select.selectBody) val withItemsList = select.withItemsList if (!CollectionUtils.isEmpty(withItemsList)) { withItemsList.forEach(Consumer { selectBody: WithItem? -> processSelectBody( selectBody ) }) } }
protected fun processSelectBody(selectBody: SelectBody?) { if (selectBody == null) { return } if (selectBody is PlainSelect) { processPlainSelect(selectBody) } else if (selectBody is WithItem) { processSelectBody(selectBody.subSelect.selectBody) } else { val operationList = selectBody as SetOperationList val selectBodyList = operationList.selects if (CollectionUtils.isNotEmpty(selectBodyList)) { selectBodyList.forEach(Consumer { body: SelectBody? -> processSelectBody(body) }) } } }
override fun processInsert(insert: Insert, index: Int, sql: String?, obj: Any?) { if (recycleBinLineHandler!!.ignoreTable(insert.table.name)) { return } val columns = insert.columns if (CollectionUtils.isEmpty(columns)) { return } val recycleBinColumn = recycleBinLineHandler!!.getRecycleBinColumn() if (recycleBinLineHandler!!.ignoreInsert(columns, recycleBinColumn)) { return } columns.add(Column(recycleBinColumn))
val duplicateUpdateColumns = insert.duplicateUpdateExpressionList if (CollectionUtils.isNotEmpty(duplicateUpdateColumns)) { val equalsTo = if (RecycleThreadLocal.ONLY_SHOW_RECYCLE.get()) NotEqualsTo() else EqualsTo() equalsTo.leftExpression = StringValue(recycleBinColumn) equalsTo.rightExpression = recycleBinLineHandler!!.getRecycleBin() duplicateUpdateColumns.add(equalsTo) } val select = insert.select if (select != null) { processInsertSelect(select.selectBody) } else if (insert.itemsList != null) { val itemsList = insert.itemsList if (itemsList is MultiExpressionList) { itemsList.expressionLists.forEach(Consumer { el: ExpressionList -> el.expressions.add( recycleBinLineHandler!!.getRecycleBin() ) }) } else { (itemsList as ExpressionList).expressions.add( recycleBinLineHandler!!.getRecycleBin() ) } } else { throw ExceptionUtils.mpe("Failed to process multiple-table update, please exclude the tableName or statementId") } }
override fun processUpdate(update: Update, index: Int, sql: String?, obj: Any?) { val table = update.table if (recycleBinLineHandler!!.ignoreTable(table.name)) { return } update.where = andExpression(table, update.where) val tableInfo = TableInfoHelper.getTableInfo(update.table.name) if (update.updateSets.any { it.columns.any { it.columnName == tableInfo.logicDeleteFieldInfo.column } } && !RecycleThreadLocal.REAL_DELETE.get() ) { update.updateSets.clear() update.addUpdateSet( Column(recycleBinLineHandler!!.getRecycleBinColumn()), Column("NOW()") ) } }
override fun processDelete(delete: Delete, index: Int, sql: String?, obj: Any?) { if (recycleBinLineHandler!!.ignoreTable(delete.table.name)) { return } delete.where = andExpression(delete.table, delete.where) }
protected fun andExpression(table: Table?, where: Expression?): BinaryExpression { val equalsTo = if (RecycleThreadLocal.ONLY_SHOW_RECYCLE.get()) NotEqualsTo() else EqualsTo() equalsTo.leftExpression = getAliasColumn(table) equalsTo.rightExpression = recycleBinLineHandler!!.getRecycleBin() return if (null != where) { if (where is OrExpression) { AndExpression(equalsTo, Parenthesis(where)) } else { AndExpression(equalsTo, where) } } else equalsTo }
protected fun processInsertSelect(selectBody: SelectBody) { val plainSelect = selectBody as PlainSelect val fromItem = plainSelect.fromItem if (fromItem is Table) { processPlainSelect(plainSelect) appendSelectItem(plainSelect.selectItems) } else if (fromItem is SubSelect) { appendSelectItem(plainSelect.selectItems) processInsertSelect(fromItem.selectBody) } }
protected fun appendSelectItem(selectItems: MutableList<SelectItem?>) { if (CollectionUtils.isEmpty(selectItems)) { return } if (selectItems.size == 1) { val item = selectItems[0] if (item is AllColumns || item is AllTableColumns) { return } } selectItems.add(SelectExpressionItem(Column(recycleBinLineHandler!!.getRecycleBinColumn()))) }
protected fun processPlainSelect(plainSelect: PlainSelect) { val selectItems = plainSelect.selectItems if (CollectionUtils.isNotEmpty(selectItems)) { selectItems.forEach(Consumer { selectItem: SelectItem? -> processSelectItem( selectItem ) }) }
val where = plainSelect.where processWhereSubSelect(where)
val fromItem = plainSelect.fromItem val list = processFromItem(fromItem) var mainTables: MutableList<Table?>? = ArrayList(list)
val joins = plainSelect.joins if (CollectionUtils.isNotEmpty(joins)) { mainTables = processJoins(mainTables, joins) }
if (CollectionUtils.isNotEmpty(mainTables)) { plainSelect.where = builderExpression(where, mainTables) } }
private fun processFromItem(fromItem: FromItem): List<Table?> { var fromItem: FromItem? = fromItem while (fromItem is ParenthesisFromItem) { fromItem = fromItem.fromItem } val mainTables: MutableList<Table?> = ArrayList() if (fromItem is Table) { mainTables.add(fromItem) } else if (fromItem is SubJoin) { val tables: List<Table?>? = processSubJoin(fromItem) mainTables.addAll(tables!!) } else { processOtherFromItem(fromItem) } return mainTables }
protected fun processWhereSubSelect(where: Expression?) { if (where == null) { return } if (where is FromItem) { processOtherFromItem(where as FromItem?) return } if (where.toString().indexOf("SELECT") > 0) { if (where is BinaryExpression) { val expression = where processWhereSubSelect(expression.leftExpression) processWhereSubSelect(expression.rightExpression) } else if (where is InExpression) { val inExpression = where.rightExpression if (inExpression is SubSelect) { processSelectBody(inExpression.selectBody) } } else if (where is ExistsExpression) { processWhereSubSelect(where.rightExpression) } else if (where is NotExpression) { processWhereSubSelect(where.expression) } else if (where is Parenthesis) { processWhereSubSelect(where.expression) } } }
protected fun processSelectItem(selectItem: SelectItem?) { if (selectItem is SelectExpressionItem) { val selectExpressionItem = selectItem if (selectExpressionItem.expression is SubSelect) { processSelectBody((selectExpressionItem.expression as SubSelect).selectBody) } else if (selectExpressionItem.expression is Function) { processFunction(selectExpressionItem.expression as Function) } } }
protected fun processFunction(function: Function) { val parameters = function.parameters parameters?.expressions?.forEach(Consumer { expression: Expression? -> if (expression is SubSelect) { processSelectBody(expression.selectBody) } else if (expression is Function) { processFunction(expression) } }) }
protected fun processOtherFromItem(fromItem: FromItem?) { var fromItem = fromItem while (fromItem is ParenthesisFromItem) { fromItem = fromItem.fromItem } if (fromItem is SubSelect) { val subSelect = fromItem if (subSelect.selectBody != null) { processSelectBody(subSelect.selectBody) } } else if (fromItem is ValuesList) { logger.debug("Perform a subQuery, if you do not give us feedback") } else if (fromItem is LateralSubSelect) { val lateralSubSelect = fromItem if (lateralSubSelect.subSelect != null) { val subSelect = lateralSubSelect.subSelect if (subSelect.selectBody != null) { processSelectBody(subSelect.selectBody) } } } }
private fun processSubJoin(subJoin: SubJoin): MutableList<Table?>? { var mainTables: MutableList<Table?>? = ArrayList() if (subJoin.joinList != null) { val list = processFromItem(subJoin.left) mainTables!!.addAll(list) mainTables = processJoins(mainTables, subJoin.joinList) } return mainTables }
private fun processJoins(mainTables: MutableList<Table?>?, joins: List<Join?>): MutableList<Table?>? { var mainTables = mainTables var mainTable: Table? = null var leftTable: Table? = null if (mainTables == null) { mainTables = ArrayList() } else if (mainTables.size == 1) { mainTable = mainTables[0] leftTable = mainTable }
val onTableDeque: Deque<List<Table?>?> = LinkedList() for (join in joins) { val joinItem = join!!.rightItem
var joinTables: MutableList<Table?>? = null if (joinItem is Table) { joinTables = ArrayList() joinTables.add(joinItem) } else if (joinItem is SubJoin) { joinTables = processSubJoin(joinItem) } if (joinTables != null) {
if (join.isSimple) { mainTables!!.addAll(joinTables) continue }
val joinTable = joinTables[0] var onTables: List<Table?>? = null if (join.isRight) { mainTable = joinTable if (leftTable != null) { onTables = listOf(leftTable) } } else if (join.isLeft) { onTables = listOf(joinTable) } else if (join.isInner) { onTables = if (mainTable == null) { listOf(joinTable) } else { Arrays.asList(mainTable, joinTable) } mainTable = null } mainTables = ArrayList() if (mainTable != null) { mainTables.add(mainTable) }
val originOnExpressions = join.onExpressions if (originOnExpressions.size == 1 && onTables != null) { val onExpressions: MutableList<Expression?> = LinkedList() onExpressions.add(builderExpression(originOnExpressions.iterator().next(), onTables)) join.onExpressions = onExpressions leftTable = joinTable continue } onTableDeque.push(onTables) if (originOnExpressions.size > 1) { val onExpressions: MutableCollection<Expression?> = LinkedList() for (originOnExpression in originOnExpressions) { val currentTableList = onTableDeque.poll() if (CollectionUtils.isEmpty(currentTableList)) { onExpressions.add(originOnExpression) } else { onExpressions.add(builderExpression(originOnExpression, currentTableList)) } } join.onExpressions = onExpressions } leftTable = joinTable } else { processOtherFromItem(joinItem) leftTable = null } } return mainTables }
protected fun builderExpression(currentExpression: Expression?, tables: List<Table?>?): Expression? { if (CollectionUtils.isEmpty(tables)) { return currentExpression } val tempTables = tables!!.stream() .filter { x: Table? -> !recycleBinLineHandler!!.ignoreTable( x!!.name ) } .collect(Collectors.toList())
if (CollectionUtils.isEmpty(tempTables)) { return currentExpression } val recycleBin = recycleBinLineHandler!!.getRecycleBin() val equalsTos = tempTables.stream() .map { item: Table? -> if (RecycleThreadLocal.ONLY_SHOW_RECYCLE.get()) NotEqualsTo( getAliasColumn(item), recycleBin ) else EqualsTo( getAliasColumn(item), recycleBin ) } .collect(Collectors.toList())
var injectExpression: Expression = equalsTos[0] if (equalsTos.size > 1) { for (i in 1 until equalsTos.size) { injectExpression = AndExpression(injectExpression, equalsTos[i]) } } if (currentExpression == null) { return injectExpression } return if (currentExpression is OrExpression) { AndExpression(Parenthesis(currentExpression), injectExpression) } else { AndExpression(currentExpression, injectExpression) } }
protected fun getAliasColumn(table: Table?): Column { val column = StringBuilder() if (table!!.alias != null) { column.append(table.alias.name) } else { column.append(table.name) } column.append(StringPool.DOT).append(recycleBinLineHandler!!.getRecycleBinColumn()) return Column(column.toString()) }
override fun setProperties(properties: Properties?) { PropertyMapper.newInstance(properties).whenNotBlank("recycleBinLineHandler", { clazzName: String? -> ClassUtils.newInstance( clazzName ) } ) { recycleBinLineHandler: RecycleBinLineHandler? -> this.recycleBinLineHandler = recycleBinLineHandler } }
}
interface RecycleBinLineHandler {
companion object { const val NOT_RECYCLE_VALUE = "2001-01-01 00:00:00" }
fun getRecycleBin(): Expression? { return StringValue(NOT_RECYCLE_VALUE) }
fun getRecycleBinColumn(): String? { return "gmt_recycled" }
fun ignoreTable(tableName: String?): Boolean { return TableInfoHelper.getTableInfo(tableName).fieldList.none { f -> f.column == getRecycleBinColumn() } }
fun ignoreInsert(columns: List<Column>, recycleBinColumn: String?): Boolean { return columns.stream().map { obj: Column -> obj.columnName }.anyMatch { i: String -> i.equals(recycleBinColumn, ignoreCase = true) } } }
class RecycleThreadLocal {
companion object { val ONLY_SHOW_RECYCLE: ThreadLocal<Boolean> = InheritableThreadLocal.withInitial { false } val REAL_DELETE: ThreadLocal<Boolean> = InheritableThreadLocal.withInitial { false } } }
|