├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── default-detekt-config.yml ├── gradle.properties ├── gradle ├── config │ ├── dependencies.gradle │ ├── quality.gradle │ └── tests.gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src ├── main └── kotlin │ └── com │ └── checkinx │ └── utils │ ├── asserts │ ├── CheckInxAssertService.kt │ ├── CoverageLevel.kt │ ├── CoverageLevelException.kt │ ├── IndexNotFoundException.kt │ ├── PlanException.kt │ └── impl │ │ └── CheckInxAssertServiceImpl.kt │ ├── configs │ ├── DataSourceWrapper.kt │ └── PostgresConfig.kt │ └── sql │ ├── interceptors │ ├── SqlInterceptor.kt │ └── postgres │ │ ├── IllegalDataSourceException.kt │ │ ├── PostgresInterceptor.kt │ │ └── SqlStatementQueryExecutionListener.kt │ └── plan │ ├── parse │ ├── ExecutionPlanParser.kt │ ├── impl │ │ └── PostgresExecutionPlanParser.kt │ └── models │ │ ├── ExecutionPlan.kt │ │ └── PlanNode.kt │ └── query │ ├── ExecutionPlanException.kt │ ├── ExecutionPlanQuery.kt │ └── impl │ └── PostgresExecutionPlanQuery.kt └── test └── kotlin └── com └── checkinx └── utils ├── asserts └── impl │ └── CheckInxAssertServiceImplTest.kt └── sql └── plan └── parse ├── impl └── PostgresExecutionPlanParserTest.kt └── models └── ExecutionPlanTest.kt /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | /.gradle/ 3 | /.idea/ 4 | /build/ 5 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | jdk: 3 | - openjdk8 4 | - openjdk11 5 | - openjdk12 6 | 7 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [2019] [Tinkoff Bank] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Build Status](https://travis-ci.com/TinkoffCreditSystems/checkinx-utils.svg?branch=master)](https://travis-ci.com/TinkoffCreditSystems/checkinx-utils) 2 | 3 | # CheckInx Utils 4 | 5 | You can check your query execution plan really simple by using this utils. Your tests could be look like: 6 | 7 | ```kotlin 8 | class DbIntensiveIntegrationTests : AbstractIntegrationTest() { 9 | @Autowired 10 | private lateinit var executionPlanQuery: ExecutionPlanQuery 11 | @Autowired 12 | private lateinit var executionPlanParser: ExecutionPlanParser 13 | @Autowired 14 | private lateinit var checkInxAssertService: CheckInxAssertService 15 | @Autowired 16 | private lateinit var sqlInterceptor: SqlInterceptor 17 | 18 | // If you want to get truthful execution plan, generate enough test data 19 | @Sql("pets.sql") // do it by db dump ... 20 | @Test 21 | fun testFindByLocation() { 22 | // ARRANGE 23 | val location = "Moscow" 24 | 25 | // ... or generate test data by code 26 | IntRange(1, 10000).forEach { 27 | val pet = Pet() 28 | pet.id = UUID.randomUUID() 29 | pet.age = it 30 | pet.location = "Saint Petersburg" 31 | pet.name = "Jack-$it" 32 | 33 | repository.save(pet) 34 | } 35 | 36 | // ACT 37 | 38 | // After all arrangements start interception of sql statements 39 | sqlInterceptor.startInterception() 40 | 41 | // Your investigation might be here 42 | val pets = repository.findByLocation(location) 43 | 44 | // After all investigating queries finished stop interception 45 | sqlInterceptor.stopInterception() 46 | 47 | // ASSERT 48 | 49 | // Here you can check how many queries were executed 50 | assertEquals(1, sqlInterceptor.statements.size.toLong()) 51 | 52 | // If you want something spicy, you can parse raw plan on your own ... 53 | val executionPlan = executionPlanQuery.execute(sqlInterceptor.statements[0]) 54 | assertTrue(executionPlan.isNotEmpty()) 55 | 56 | // ... or travers plan tree ... 57 | val plan = executionPlanParser.parse(executionPlan) 58 | assertNotNull(plan) 59 | 60 | val rootNode = plan.rootPlanNode 61 | assertEquals("Index Scan", rootNode.coverage) 62 | assertEquals("ix_pets_location", rootNode.target) 63 | assertEquals("pets pet0_", rootNode.table) 64 | 65 | // Now assert coverage is simple like never before ... 66 | checkInxAssertService.assertCoverage(CoverageLevel.HALF, "ix_pets_location", plan) 67 | 68 | // One more thing, it even could be more simple ... 69 | checkInxAssertService.assertCoverage(CoverageLevel.HALF, "ix_pets_location", sqlInterceptor.statements[0]) 70 | 71 | // ... or if you just want to prevent "seq scan" for example, without searching concrete index 72 | checkInxAssertService.assertCoverage(CoverageLevel.HALF, sqlInterceptor.statements[0]) 73 | } 74 | } 75 | ``` 76 | 77 | Look at the [demo repository](https://github.com/dsemyriazhko/checkinx-demo) to find more examples. 78 | 79 | ## Starting guide 80 | 81 | I’m going to publish checkinx in maven repository. Until I’ve done it use jitpack to get artifacts from github. 82 | 83 | Firstly, modify your build.gradle and add new repository 84 | ```groovy 85 | repositories { 86 | // ... 87 | maven { url 'https://jitpack.io' } 88 | } 89 | ``` 90 | 91 | Secondly, add new dependency (please checkout for latest release 92 | [here](https://github.com/TinkoffCreditSystems/checkinx-utils/releases/latest)) 93 | ```groovy 94 | dependencies { 95 | // ... 96 | implementation 'com.github.tinkoffcreditsystems:checkinx-utils:0.2.0' 97 | } 98 | ``` 99 | 100 | Finally, add beans & BeanPostProcessor to your configuration 101 | ```kotlin 102 | @Profile("test") 103 | @ImportAutoConfiguration(classes = [PostgresConfig::class]) 104 | @Configuration 105 | open class CheckInxConfig 106 | ``` 107 | _For now, only Postgres is supported, but you can easily change it. Just make pull request ;-)._ 108 | 109 | Be sure that you are using org.testcontainers. Its DB version and configuration equal your real DB. 110 | 111 | Now you are ready to create your first “intensive” integration test. 112 | 113 | ## Known issues 114 | 115 | Sometimes DataSourceWrapper could fail to replace dataSource because of Spring CGLIB proxy. The easiest workaround is to create HikariDataSource bean manually: 116 | ```kotlin 117 | @Profile("test") 118 | @ImportAutoConfiguration(classes = [PostgresConfig::class]) 119 | @Configuration 120 | open class CheckInxConfig { 121 | @Primary 122 | @Bean 123 | @ConfigurationProperties("spring.datasource") 124 | open fun dataSource(): DataSource { 125 | return DataSourceBuilder.create() 126 | .type(HikariDataSource::class.java) 127 | .build() 128 | } 129 | 130 | @Bean 131 | @ConfigurationProperties("spring.datasource.configuration") 132 | open fun dataSource(properties: DataSourceProperties): HikariDataSource { 133 | return properties.initializeDataSourceBuilder() 134 | .type(HikariDataSource::class.java) 135 | .build() 136 | } 137 | } 138 | ``` 139 | 140 | ## Contribution 141 | 142 | If you have time and ideas how to improve checkinx, welcome! I’ll be really happy if you decide to join and contribute. 143 | 144 | Hope you'll like it. 145 | -------------------------------------------------------------------------------- /default-detekt-config.yml: -------------------------------------------------------------------------------- 1 | autoCorrect: true 2 | 3 | test-pattern: # Configure exclusions for test sources 4 | active: true 5 | patterns: # Test file regexes 6 | - '.*/test/.*' 7 | - '.*Test.kt' 8 | exclude-rule-sets: 9 | - 'comments' 10 | exclude-rules: 11 | - 'NamingRules' 12 | - 'WildcardImport' 13 | - 'MagicNumber' 14 | - 'MaxLineLength' 15 | - 'LateinitUsage' 16 | - 'StringLiteralDuplication' 17 | - 'SpreadOperator' 18 | - 'TooManyFunctions' 19 | - 'ForEachOnRange' 20 | - 'FunctionMaxLength' 21 | - 'TooGenericExceptionCaught' 22 | - 'InstanceOfCheckForException' 23 | 24 | build: 25 | maxIssues: 0 26 | weights: 27 | # complexity: 2 28 | # LongParameterList: 1 29 | # style: 1 30 | # comments: 1 31 | 32 | processors: 33 | active: true 34 | exclude: 35 | # - 'FunctionCountProcessor' 36 | # - 'PropertyCountProcessor' 37 | # - 'ClassCountProcessor' 38 | # - 'PackageCountProcessor' 39 | # - 'KtFileCountProcessor' 40 | 41 | console-reports: 42 | active: true 43 | exclude: 44 | # - 'ProjectStatisticsReport' 45 | # - 'ComplexityReport' 46 | # - 'NotificationReport' 47 | # - 'FindingsReport' 48 | # - 'BuildFailureReport' 49 | 50 | comments: 51 | active: true 52 | CommentOverPrivateFunction: 53 | active: false 54 | CommentOverPrivateProperty: 55 | active: false 56 | EndOfSentenceFormat: 57 | active: false 58 | endOfSentenceFormat: ([.?!][ \t\n\r\f<])|([.?!]$) 59 | UndocumentedPublicClass: 60 | active: false 61 | searchInNestedClass: true 62 | searchInInnerClass: true 63 | searchInInnerObject: true 64 | searchInInnerInterface: true 65 | UndocumentedPublicFunction: 66 | active: false 67 | 68 | complexity: 69 | active: true 70 | ComplexCondition: 71 | active: true 72 | threshold: 4 73 | ComplexInterface: 74 | active: false 75 | threshold: 10 76 | includeStaticDeclarations: false 77 | ComplexMethod: 78 | active: true 79 | threshold: 10 80 | ignoreSingleWhenExpression: false 81 | ignoreSimpleWhenEntries: false 82 | LabeledExpression: 83 | active: false 84 | ignoredLabels: "" 85 | LargeClass: 86 | active: true 87 | threshold: 600 88 | LongMethod: 89 | active: true 90 | threshold: 60 91 | LongParameterList: 92 | active: true 93 | threshold: 6 94 | ignoreDefaultParameters: false 95 | MethodOverloading: 96 | active: false 97 | threshold: 6 98 | NestedBlockDepth: 99 | active: true 100 | threshold: 4 101 | StringLiteralDuplication: 102 | active: false 103 | threshold: 3 104 | ignoreAnnotation: true 105 | excludeStringsWithLessThan5Characters: true 106 | ignoreStringsRegex: '$^' 107 | TooManyFunctions: 108 | active: true 109 | thresholdInFiles: 11 110 | thresholdInClasses: 11 111 | thresholdInInterfaces: 11 112 | thresholdInObjects: 11 113 | thresholdInEnums: 11 114 | ignoreDeprecated: false 115 | ignorePrivate: false 116 | ignoreOverridden: false 117 | 118 | empty-blocks: 119 | active: true 120 | EmptyCatchBlock: 121 | active: true 122 | allowedExceptionNameRegex: "^(_|(ignore|expected).*)" 123 | EmptyClassBlock: 124 | active: true 125 | EmptyDefaultConstructor: 126 | active: true 127 | EmptyDoWhileBlock: 128 | active: true 129 | EmptyElseBlock: 130 | active: true 131 | EmptyFinallyBlock: 132 | active: true 133 | EmptyForBlock: 134 | active: true 135 | EmptyFunctionBlock: 136 | active: true 137 | ignoreOverriddenFunctions: false 138 | EmptyIfBlock: 139 | active: true 140 | EmptyInitBlock: 141 | active: true 142 | EmptyKtFile: 143 | active: true 144 | EmptySecondaryConstructor: 145 | active: true 146 | EmptyWhenBlock: 147 | active: true 148 | EmptyWhileBlock: 149 | active: true 150 | 151 | exceptions: 152 | active: true 153 | ExceptionRaisedInUnexpectedLocation: 154 | active: false 155 | methodNames: 'toString,hashCode,equals,finalize' 156 | InstanceOfCheckForException: 157 | active: false 158 | NotImplementedDeclaration: 159 | active: false 160 | PrintStackTrace: 161 | active: false 162 | RethrowCaughtException: 163 | active: false 164 | ReturnFromFinally: 165 | active: false 166 | SwallowedException: 167 | active: false 168 | ignoredExceptionTypes: 'InterruptedException,NumberFormatException,ParseException,MalformedURLException' 169 | ThrowingExceptionFromFinally: 170 | active: false 171 | ThrowingExceptionInMain: 172 | active: false 173 | ThrowingExceptionsWithoutMessageOrCause: 174 | active: false 175 | exceptions: 'IllegalArgumentException,IllegalStateException,IOException' 176 | ThrowingNewInstanceOfSameException: 177 | active: false 178 | TooGenericExceptionCaught: 179 | active: true 180 | exceptionNames: 181 | - ArrayIndexOutOfBoundsException 182 | - Error 183 | - Exception 184 | - IllegalMonitorStateException 185 | - NullPointerException 186 | - IndexOutOfBoundsException 187 | - RuntimeException 188 | - Throwable 189 | allowedExceptionNameRegex: "^(_|(ignore|expected).*)" 190 | TooGenericExceptionThrown: 191 | active: true 192 | exceptionNames: 193 | - Error 194 | - Exception 195 | - Throwable 196 | - RuntimeException 197 | 198 | formatting: 199 | active: true 200 | android: false 201 | autoCorrect: true 202 | ChainWrapping: 203 | active: true 204 | autoCorrect: true 205 | CommentSpacing: 206 | active: true 207 | autoCorrect: true 208 | Filename: 209 | active: true 210 | FinalNewline: 211 | active: true 212 | autoCorrect: true 213 | ImportOrdering: 214 | active: false 215 | Indentation: 216 | active: true 217 | autoCorrect: true 218 | indentSize: 4 219 | continuationIndentSize: 4 220 | MaximumLineLength: 221 | active: true 222 | maxLineLength: 120 223 | ModifierOrdering: 224 | active: true 225 | autoCorrect: true 226 | NoBlankLineBeforeRbrace: 227 | active: true 228 | autoCorrect: true 229 | NoConsecutiveBlankLines: 230 | active: true 231 | autoCorrect: true 232 | NoEmptyClassBody: 233 | active: true 234 | autoCorrect: true 235 | NoItParamInMultilineLambda: 236 | active: false 237 | NoLineBreakAfterElse: 238 | active: true 239 | autoCorrect: true 240 | NoLineBreakBeforeAssignment: 241 | active: true 242 | autoCorrect: true 243 | NoMultipleSpaces: 244 | active: true 245 | autoCorrect: true 246 | NoSemicolons: 247 | active: true 248 | autoCorrect: true 249 | NoTrailingSpaces: 250 | active: true 251 | autoCorrect: true 252 | NoUnitReturn: 253 | active: true 254 | autoCorrect: true 255 | NoUnusedImports: 256 | active: true 257 | autoCorrect: true 258 | NoWildcardImports: 259 | active: true 260 | autoCorrect: true 261 | PackageName: 262 | active: true 263 | autoCorrect: true 264 | ParameterListWrapping: 265 | active: true 266 | autoCorrect: true 267 | indentSize: 4 268 | SpacingAroundColon: 269 | active: true 270 | autoCorrect: true 271 | SpacingAroundComma: 272 | active: true 273 | autoCorrect: true 274 | SpacingAroundCurly: 275 | active: true 276 | autoCorrect: true 277 | SpacingAroundKeyword: 278 | active: true 279 | autoCorrect: true 280 | SpacingAroundOperators: 281 | active: true 282 | autoCorrect: true 283 | SpacingAroundParens: 284 | active: true 285 | autoCorrect: true 286 | SpacingAroundRangeOperator: 287 | active: true 288 | autoCorrect: true 289 | StringTemplate: 290 | active: true 291 | autoCorrect: true 292 | 293 | naming: 294 | active: true 295 | ClassNaming: 296 | active: true 297 | classPattern: '[A-Z$][a-zA-Z0-9$]*' 298 | ConstructorParameterNaming: 299 | active: true 300 | parameterPattern: '[a-z][A-Za-z0-9]*' 301 | privateParameterPattern: '[a-z][A-Za-z0-9]*' 302 | excludeClassPattern: '$^' 303 | EnumNaming: 304 | active: true 305 | enumEntryPattern: '^[A-Z][_a-zA-Z0-9]*' 306 | ForbiddenClassName: 307 | active: false 308 | forbiddenName: '' 309 | FunctionMaxLength: 310 | active: false 311 | maximumFunctionNameLength: 30 312 | FunctionMinLength: 313 | active: false 314 | minimumFunctionNameLength: 3 315 | FunctionNaming: 316 | active: true 317 | functionPattern: '^([a-z$][a-zA-Z$0-9]*)|(`.*`)$' 318 | excludeClassPattern: '$^' 319 | ignoreOverridden: true 320 | FunctionParameterNaming: 321 | active: true 322 | parameterPattern: '[a-z][A-Za-z0-9]*' 323 | excludeClassPattern: '$^' 324 | ignoreOverriddenFunctions: true 325 | MatchingDeclarationName: 326 | active: true 327 | MemberNameEqualsClassName: 328 | active: false 329 | ignoreOverriddenFunction: true 330 | ObjectPropertyNaming: 331 | active: true 332 | constantPattern: '[A-Za-z][_A-Za-z0-9]*' 333 | propertyPattern: '[A-Za-z][_A-Za-z0-9]*' 334 | privatePropertyPattern: '(_)?[A-Za-z][_A-Za-z0-9]*' 335 | PackageNaming: 336 | active: true 337 | packagePattern: '^[a-z]+(\.[a-z][A-Za-z0-9]*)*$' 338 | TopLevelPropertyNaming: 339 | active: true 340 | constantPattern: '[A-Z][_A-Z0-9]*' 341 | propertyPattern: '[A-Za-z][_A-Za-z0-9]*' 342 | privatePropertyPattern: '(_)?[A-Za-z][A-Za-z0-9]*' 343 | VariableMaxLength: 344 | active: false 345 | maximumVariableNameLength: 64 346 | VariableMinLength: 347 | active: false 348 | minimumVariableNameLength: 1 349 | VariableNaming: 350 | active: true 351 | variablePattern: '[a-z][A-Za-z0-9]*' 352 | privateVariablePattern: '(_)?[a-z][A-Za-z0-9]*' 353 | excludeClassPattern: '$^' 354 | ignoreOverridden: true 355 | 356 | performance: 357 | active: true 358 | ArrayPrimitive: 359 | active: false 360 | ForEachOnRange: 361 | active: true 362 | SpreadOperator: 363 | active: true 364 | UnnecessaryTemporaryInstantiation: 365 | active: true 366 | 367 | potential-bugs: 368 | active: true 369 | DuplicateCaseInWhenExpression: 370 | active: true 371 | EqualsAlwaysReturnsTrueOrFalse: 372 | active: false 373 | EqualsWithHashCodeExist: 374 | active: true 375 | ExplicitGarbageCollectionCall: 376 | active: true 377 | InvalidRange: 378 | active: false 379 | IteratorHasNextCallsNextMethod: 380 | active: false 381 | IteratorNotThrowingNoSuchElementException: 382 | active: false 383 | LateinitUsage: 384 | active: false 385 | excludeAnnotatedProperties: "" 386 | ignoreOnClassesPattern: "" 387 | UnconditionalJumpStatementInLoop: 388 | active: false 389 | UnreachableCode: 390 | active: true 391 | UnsafeCallOnNullableType: 392 | active: false 393 | UnsafeCast: 394 | active: false 395 | UselessPostfixExpression: 396 | active: false 397 | WrongEqualsTypeParameter: 398 | active: false 399 | 400 | style: 401 | active: true 402 | CollapsibleIfStatements: 403 | active: false 404 | DataClassContainsFunctions: 405 | active: false 406 | conversionFunctionPrefix: 'to' 407 | EqualsNullCall: 408 | active: false 409 | EqualsOnSignatureLine: 410 | active: false 411 | ExplicitItLambdaParameter: 412 | active: false 413 | ExpressionBodySyntax: 414 | active: false 415 | includeLineWrapping: false 416 | ForbiddenComment: 417 | active: true 418 | values: 'TODO:,FIXME:,STOPSHIP:' 419 | ForbiddenImport: 420 | active: true 421 | imports: 'org.junit.experimental' 422 | ForbiddenVoid: 423 | active: false 424 | FunctionOnlyReturningConstant: 425 | active: false 426 | ignoreOverridableFunction: true 427 | excludedFunctions: 'describeContents' 428 | LoopWithTooManyJumpStatements: 429 | active: false 430 | maxJumpCount: 1 431 | MagicNumber: 432 | active: true 433 | ignoreNumbers: '-1,0,1,2' 434 | ignoreHashCodeFunction: true 435 | ignorePropertyDeclaration: false 436 | ignoreConstantDeclaration: true 437 | ignoreCompanionObjectPropertyDeclaration: true 438 | ignoreAnnotation: false 439 | ignoreNamedArgument: true 440 | ignoreEnums: false 441 | MandatoryBracesIfStatements: 442 | active: false 443 | MaxLineLength: 444 | active: true 445 | maxLineLength: 120 446 | excludePackageStatements: true 447 | excludeImportStatements: true 448 | excludeCommentStatements: false 449 | MayBeConst: 450 | active: false 451 | ModifierOrder: 452 | active: true 453 | NestedClassesVisibility: 454 | active: false 455 | NewLineAtEndOfFile: 456 | active: true 457 | NoTabs: 458 | active: false 459 | OptionalAbstractKeyword: 460 | active: true 461 | OptionalUnit: 462 | active: false 463 | OptionalWhenBraces: 464 | active: false 465 | PreferToOverPairSyntax: 466 | active: false 467 | ProtectedMemberInFinalClass: 468 | active: false 469 | RedundantVisibilityModifierRule: 470 | active: false 471 | ReturnCount: 472 | active: true 473 | max: 4 474 | excludedFunctions: "equals" 475 | excludeLabeled: false 476 | excludeReturnFromLambda: true 477 | SafeCast: 478 | active: true 479 | SerialVersionUIDInSerializableClass: 480 | active: false 481 | SpacingBetweenPackageAndImports: 482 | active: false 483 | ThrowsCount: 484 | active: true 485 | max: 2 486 | TrailingWhitespace: 487 | active: false 488 | UnderscoresInNumericLiterals: 489 | active: false 490 | acceptableDecimalLength: 5 491 | UnnecessaryAbstractClass: 492 | active: false 493 | excludeAnnotatedClasses: "dagger.Module" 494 | UnnecessaryApply: 495 | active: false 496 | UnnecessaryInheritance: 497 | active: false 498 | UnnecessaryLet: 499 | active: false 500 | UnnecessaryParentheses: 501 | active: false 502 | UntilInsteadOfRangeTo: 503 | active: false 504 | UnusedImports: 505 | active: false 506 | UnusedPrivateClass: 507 | active: false 508 | UnusedPrivateMember: 509 | active: false 510 | allowedNames: "(_|ignored|expected|serialVersionUID)" 511 | UseDataClass: 512 | active: false 513 | excludeAnnotatedClasses: "" 514 | UtilityClassWithPublicConstructor: 515 | active: false 516 | VarCouldBeVal: 517 | active: false 518 | WildcardImport: 519 | active: true 520 | excludeImports: 'java.util.*,kotlinx.android.synthetic.*' 521 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | kotlin.code.style=official -------------------------------------------------------------------------------- /gradle/config/dependencies.gradle: -------------------------------------------------------------------------------- 1 | dependencies { 2 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" 3 | implementation group: 'org.jetbrains.kotlin', name: 'kotlin-reflect' 4 | 5 | implementation 'org.springframework.boot:spring-boot-starter-data-jpa:2.1.4.RELEASE' 6 | implementation 'org.postgresql:postgresql:42.2.5' 7 | 8 | compile group: 'net.ttddyy', name: 'datasource-proxy', version: '1.5.1' 9 | compile group: 'net.ttddyy', name: 'datasource-assert', version: '1.0' 10 | compile group: 'org.codehaus.mojo', name: 'animal-sniffer-annotations', version: '1.17' 11 | 12 | testImplementation 'org.springframework.boot:spring-boot-starter-test:2.1.4.RELEASE' 13 | testImplementation "io.mockk:mockk:1.9.3.kotlin12" 14 | } 15 | -------------------------------------------------------------------------------- /gradle/config/quality.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: "io.gitlab.arturbosch.detekt" 2 | 3 | detekt { 4 | toolVersion = "${getProperty('detektPluginVersion')}" 5 | input = files("src/main/kotlin", "src/test/kotlin") 6 | filters = ".*/resources/.*,.*/build/.*" 7 | config = files("default-detekt-config.yml") 8 | } 9 | 10 | check.dependsOn( 11 | 'detekt' 12 | ) 13 | check.mustRunAfter clean 14 | -------------------------------------------------------------------------------- /gradle/config/tests.gradle: -------------------------------------------------------------------------------- 1 | test { 2 | group 'verification' 3 | useJUnit { 4 | include '**/*Test.class' 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Tinkoff/checkinx-utils/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Sun May 12 11:37:52 MSK 2019 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.3-all.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'utils' 2 | 3 | -------------------------------------------------------------------------------- /src/main/kotlin/com/checkinx/utils/asserts/CheckInxAssertService.kt: -------------------------------------------------------------------------------- 1 | package com.checkinx.utils.asserts 2 | 3 | import com.checkinx.utils.sql.plan.parse.models.ExecutionPlan 4 | import com.checkinx.utils.sql.plan.parse.models.PlanNode 5 | 6 | interface CheckInxAssertService { 7 | 8 | fun assertCoverage(requiredLevel: CoverageLevel, target: String, sqlStatement: String) 9 | 10 | fun assertCoverage(requiredLevel: CoverageLevel, target: String, plan: ExecutionPlan) 11 | fun assertCoverage(requiredLevel: CoverageLevel, sqlStatement: String) 12 | fun assertCoverage(requiredLevel: CoverageLevel, plan: ExecutionPlan) 13 | fun assertPlan( 14 | sqlStatement: String, 15 | predicate: (PlanNode) -> Boolean 16 | ) 17 | fun assertPlan( 18 | plan: ExecutionPlan, 19 | predicate: (PlanNode) -> Boolean 20 | ) 21 | } 22 | -------------------------------------------------------------------------------- /src/main/kotlin/com/checkinx/utils/asserts/CoverageLevel.kt: -------------------------------------------------------------------------------- 1 | package com.checkinx.utils.asserts 2 | 3 | enum class CoverageLevel(val level: Int) { 4 | /* Index isn't using at all. */ 5 | NOT_USING(Int.MIN_VALUE), 6 | 7 | /* Seq Scan */ 8 | ZERO(0), 9 | 10 | /* Index Scan */ 11 | HALF(1), 12 | 13 | /* Index Only Scan */ 14 | FULL(2), 15 | 16 | UNKNOWN(Int.MAX_VALUE) 17 | } 18 | -------------------------------------------------------------------------------- /src/main/kotlin/com/checkinx/utils/asserts/CoverageLevelException.kt: -------------------------------------------------------------------------------- 1 | package com.checkinx.utils.asserts 2 | 3 | import com.checkinx.utils.sql.plan.parse.models.PlanNode 4 | 5 | class CoverageLevelException(requiredLevel: String, violator: PlanNode, executionPlan: String) 6 | : Throwable("""Required level: $requiredLevel, violator: $violator, executionPlan: $executionPlan""") 7 | -------------------------------------------------------------------------------- /src/main/kotlin/com/checkinx/utils/asserts/IndexNotFoundException.kt: -------------------------------------------------------------------------------- 1 | package com.checkinx.utils.asserts 2 | 3 | class IndexNotFoundException(indexName: String, executionPlan: String) 4 | : Throwable("""Index name: $indexName, executionPlan: $executionPlan""") 5 | -------------------------------------------------------------------------------- /src/main/kotlin/com/checkinx/utils/asserts/PlanException.kt: -------------------------------------------------------------------------------- 1 | package com.checkinx.utils.asserts 2 | 3 | import com.checkinx.utils.sql.plan.parse.models.PlanNode 4 | 5 | class PlanException(violator: PlanNode, executionPlan: String) 6 | : Throwable("""Violator: $violator, executionPlan: $executionPlan""") 7 | -------------------------------------------------------------------------------- /src/main/kotlin/com/checkinx/utils/asserts/impl/CheckInxAssertServiceImpl.kt: -------------------------------------------------------------------------------- 1 | package com.checkinx.utils.asserts.impl 2 | 3 | import com.checkinx.utils.asserts.CheckInxAssertService 4 | import com.checkinx.utils.asserts.CoverageLevel 5 | import com.checkinx.utils.asserts.CoverageLevelException 6 | import com.checkinx.utils.asserts.IndexNotFoundException 7 | import com.checkinx.utils.asserts.PlanException 8 | import com.checkinx.utils.sql.plan.parse.ExecutionPlanParser 9 | import com.checkinx.utils.sql.plan.parse.models.ExecutionPlan 10 | import com.checkinx.utils.sql.plan.parse.models.PlanNode 11 | import com.checkinx.utils.sql.plan.query.ExecutionPlanQuery 12 | import org.springframework.stereotype.Service 13 | 14 | @Service 15 | open class CheckInxAssertServiceImpl( 16 | private val executionPlanQuery: ExecutionPlanQuery, 17 | private val executionPlanParser: ExecutionPlanParser 18 | ) : CheckInxAssertService { 19 | 20 | override fun assertCoverage(requiredLevel: CoverageLevel, sqlStatement: String) { 21 | val executionPlan = executionPlanQuery.execute(sqlStatement) 22 | val plan = executionPlanParser.parse(executionPlan) 23 | 24 | assertCoverage(requiredLevel, plan) 25 | } 26 | 27 | override fun assertCoverage(requiredLevel: CoverageLevel, plan: ExecutionPlan) { 28 | assertPlan( 29 | plan 30 | ) { node: PlanNode -> 31 | node.coverageLevel.level < requiredLevel.level 32 | } 33 | } 34 | 35 | override fun assertPlan( 36 | sqlStatement: String, 37 | predicate: (PlanNode) -> Boolean 38 | ) { 39 | val executionPlan = executionPlanQuery.execute(sqlStatement) 40 | val plan = executionPlanParser.parse(executionPlan) 41 | 42 | assertPlan(plan, predicate) 43 | } 44 | 45 | override fun assertPlan( 46 | plan: ExecutionPlan, 47 | predicate: (PlanNode) -> Boolean 48 | ) { 49 | val violator = plan.findInPlanTree(predicate) 50 | 51 | if (violator != null) { 52 | throw PlanException( 53 | violator, 54 | plan.executionPlan.joinToString(separator = "\n") 55 | ) 56 | } 57 | } 58 | 59 | override fun assertCoverage(requiredLevel: CoverageLevel, target: String, sqlStatement: String) { 60 | val executionPlan = executionPlanQuery.execute(sqlStatement) 61 | val plan = executionPlanParser.parse(executionPlan) 62 | 63 | assertCoverage(requiredLevel, target, plan) 64 | } 65 | 66 | override fun assertCoverage(requiredLevel: CoverageLevel, target: String, plan: ExecutionPlan) { 67 | val node = plan.findInPlanTree { planNode -> planNode.target == target } 68 | 69 | if (requiredLevel == CoverageLevel.NOT_USING && node == null) { 70 | return 71 | } 72 | 73 | if (node == null) { 74 | throw IndexNotFoundException( 75 | target, 76 | plan.executionPlan.joinToString(separator = "\n") 77 | ) 78 | } 79 | 80 | if (requiredLevel.level > node.coverageLevel.level) { 81 | throw CoverageLevelException( 82 | requiredLevel.toString(), 83 | node, 84 | plan.executionPlan.joinToString(separator = "\n") 85 | ) 86 | } 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /src/main/kotlin/com/checkinx/utils/configs/DataSourceWrapper.kt: -------------------------------------------------------------------------------- 1 | package com.checkinx.utils.configs 2 | 3 | import javax.sql.DataSource 4 | 5 | import org.springframework.beans.BeansException 6 | import org.springframework.beans.factory.config.BeanPostProcessor 7 | import org.springframework.context.annotation.Configuration 8 | import org.springframework.context.annotation.Profile 9 | 10 | import net.ttddyy.dsproxy.support.ProxyDataSourceBuilder 11 | 12 | open class DataSourceWrapper : BeanPostProcessor { 13 | override fun postProcessBeforeInitialization(bean: Any, beanName: String?): Any? { 14 | return if (bean is DataSource) { 15 | ProxyDataSourceBuilder 16 | .create(bean) 17 | .build() 18 | } else bean 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/kotlin/com/checkinx/utils/configs/PostgresConfig.kt: -------------------------------------------------------------------------------- 1 | package com.checkinx.utils.configs 2 | 3 | import com.checkinx.utils.asserts.CheckInxAssertService 4 | import com.checkinx.utils.asserts.impl.CheckInxAssertServiceImpl 5 | import com.checkinx.utils.sql.interceptors.SqlInterceptor 6 | import com.checkinx.utils.sql.interceptors.postgres.PostgresInterceptor 7 | import com.checkinx.utils.sql.plan.parse.ExecutionPlanParser 8 | import com.checkinx.utils.sql.plan.parse.impl.PostgresExecutionPlanParser 9 | import com.checkinx.utils.sql.plan.query.ExecutionPlanQuery 10 | import com.checkinx.utils.sql.plan.query.impl.PostgresExecutionPlanQuery 11 | import net.ttddyy.dsproxy.support.ProxyDataSource 12 | import org.springframework.context.annotation.Bean 13 | import org.springframework.context.annotation.Configuration 14 | import org.springframework.jdbc.core.JdbcTemplate 15 | import javax.sql.DataSource 16 | 17 | @Configuration 18 | open class PostgresConfig { 19 | @Bean 20 | open fun dataSourceWrapperBeanPostProcessor(): DataSourceWrapper { 21 | return DataSourceWrapper() 22 | } 23 | 24 | @Bean 25 | open fun sqlInterceptor(dataSource: DataSource): SqlInterceptor { 26 | return PostgresInterceptor(dataSource as ProxyDataSource) 27 | } 28 | 29 | @Bean 30 | open fun executionPlanParser(): ExecutionPlanParser { 31 | return PostgresExecutionPlanParser() 32 | } 33 | 34 | @Bean 35 | open fun executionPlanQuery(jdbcTemplate: JdbcTemplate): ExecutionPlanQuery { 36 | return PostgresExecutionPlanQuery(jdbcTemplate) 37 | } 38 | 39 | @Bean 40 | open fun checkInxAssertService(query: ExecutionPlanQuery, parser: ExecutionPlanParser): CheckInxAssertService { 41 | return CheckInxAssertServiceImpl(query, parser) 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/kotlin/com/checkinx/utils/sql/interceptors/SqlInterceptor.kt: -------------------------------------------------------------------------------- 1 | package com.checkinx.utils.sql.interceptors 2 | 3 | interface SqlInterceptor { 4 | 5 | val statements: List 6 | 7 | fun startInterception() 8 | fun stopInterception() 9 | 10 | } 11 | -------------------------------------------------------------------------------- /src/main/kotlin/com/checkinx/utils/sql/interceptors/postgres/IllegalDataSourceException.kt: -------------------------------------------------------------------------------- 1 | package com.checkinx.utils.sql.interceptors.postgres 2 | 3 | class IllegalDataSourceException(typeName: String) : Throwable(typeName) 4 | -------------------------------------------------------------------------------- /src/main/kotlin/com/checkinx/utils/sql/interceptors/postgres/PostgresInterceptor.kt: -------------------------------------------------------------------------------- 1 | package com.checkinx.utils.sql.interceptors.postgres 2 | 3 | import com.checkinx.utils.sql.interceptors.SqlInterceptor 4 | import net.ttddyy.dsproxy.support.ProxyDataSource 5 | 6 | open class PostgresInterceptor(private val dataSource: ProxyDataSource) : SqlInterceptor { 7 | private var statementsList: MutableList = mutableListOf() 8 | 9 | private val sqlListener = SqlStatementQueryExecutionListener(statementsList) 10 | 11 | override val statements: List 12 | get() = statementsList.toList() 13 | 14 | override fun startInterception() { 15 | statementsList.clear() 16 | dataSource.addListener(sqlListener) 17 | } 18 | 19 | override fun stopInterception() { 20 | dataSource.proxyConfig.queryListener.listeners.removeIf { listener -> 21 | listener is SqlStatementQueryExecutionListener && listener.identifier == sqlListener.identifier} 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/kotlin/com/checkinx/utils/sql/interceptors/postgres/SqlStatementQueryExecutionListener.kt: -------------------------------------------------------------------------------- 1 | package com.checkinx.utils.sql.interceptors.postgres 2 | 3 | import com.zaxxer.hikari.pool.HikariProxyResultSet 4 | import net.ttddyy.dsproxy.ExecutionInfo 5 | import net.ttddyy.dsproxy.QueryInfo 6 | import net.ttddyy.dsproxy.listener.QueryExecutionListener 7 | import org.postgresql.jdbc.PgResultSet 8 | import java.util.* 9 | 10 | class SqlStatementQueryExecutionListener(private val statementsList: MutableList) : QueryExecutionListener { 11 | val identifier: UUID = UUID.randomUUID() 12 | 13 | override fun beforeQuery(execInfo: ExecutionInfo, queryInfoList: List) = Unit 14 | 15 | override fun afterQuery(execInfo: ExecutionInfo, queryInfoList: List) { 16 | if (execInfo.result !is HikariProxyResultSet) { 17 | return 18 | } 19 | 20 | val sql = (execInfo.result as HikariProxyResultSet).unwrap(PgResultSet::class.java) 21 | .statement.toString() 22 | 23 | statementsList.add(sql) 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/kotlin/com/checkinx/utils/sql/plan/parse/ExecutionPlanParser.kt: -------------------------------------------------------------------------------- 1 | package com.checkinx.utils.sql.plan.parse 2 | 3 | import com.checkinx.utils.sql.plan.parse.models.ExecutionPlan 4 | 5 | interface ExecutionPlanParser { 6 | fun parse(executionPlan: List): ExecutionPlan 7 | } 8 | -------------------------------------------------------------------------------- /src/main/kotlin/com/checkinx/utils/sql/plan/parse/impl/PostgresExecutionPlanParser.kt: -------------------------------------------------------------------------------- 1 | package com.checkinx.utils.sql.plan.parse.impl 2 | 3 | import com.checkinx.utils.sql.plan.parse.ExecutionPlanParser 4 | import com.checkinx.utils.sql.plan.parse.models.ExecutionPlan 5 | import com.checkinx.utils.sql.plan.parse.models.PlanNode 6 | 7 | open class PostgresExecutionPlanParser : ExecutionPlanParser { 8 | override fun parse(executionPlan: List): ExecutionPlan { 9 | val root = getTargetFromUsingOrOn(executionPlan.first()) 10 | 11 | createChildNodes(executionPlan, 0, root, 2) 12 | 13 | return ExecutionPlan(executionPlan, root) 14 | } 15 | 16 | private fun createChildNodes(executionPlan: List, planIndex: Int, parent: PlanNode, childMargin: Int): Int { 17 | var i = planIndex + 1 18 | while (i < executionPlan.size) { 19 | val item = executionPlan.get(i) 20 | 21 | val propertyRegex = """^\s*(?.+):\s+(?.+)${'$'}""".toRegex() 22 | when { 23 | """^\s{$childMargin}->\s+.*${'$'}""".toRegex().matches(item) -> { 24 | val node = getTargetFromUsingOrOn(item) 25 | 26 | parent.children.add(node) 27 | i = createChildNodes(executionPlan, i, node, childMargin + MARGIN_STEP) - 1 28 | } 29 | propertyRegex.matches(item) -> { 30 | val matchProperty = propertyRegex.find(item) 31 | 32 | parent.properties.add(Pair( 33 | matchProperty?.groups?.get("key")?.value!!, 34 | matchProperty.groups.get("value")?.value!!)) 35 | } 36 | !item.contains("->") -> { 37 | parent.others.add(item) 38 | } 39 | else -> return i 40 | } 41 | 42 | i++ 43 | } 44 | 45 | return i 46 | } 47 | 48 | private fun getTargetFromUsingOrOn(planLine: String): PlanNode { 49 | return getTargetFromUsing(planLine).let { 50 | when (it.target) { 51 | null -> return@let getTargetFromOn(it.raw) 52 | else -> return@let it 53 | } 54 | } 55 | } 56 | 57 | private fun getTargetFromOn( 58 | planLine: String 59 | ): PlanNode { 60 | val match = """^(\s+->\s+|)(?.+) on (?.*)\s{2,}\(.*${'$'}""".toRegex().find(planLine) 61 | 62 | return PlanNode( 63 | planLine, 64 | null, 65 | match?.groups?.get("target")?.value, 66 | match?.groups?.get("coverage")?.value 67 | ) 68 | } 69 | 70 | private fun getTargetFromUsing(planLine: String): PlanNode { 71 | val match = """^(\s+->\s+|)(?.+) using (?.+) on (?.*)\s{2,}\(.*${'$'}""" 72 | .toRegex() 73 | .find(planLine) 74 | 75 | return PlanNode( 76 | planLine, 77 | match?.groups?.get("table")?.value, 78 | match?.groups?.get("target")?.value, 79 | match?.groups?.get("coverage")?.value) 80 | } 81 | 82 | companion object { 83 | const val MARGIN_STEP = 6 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /src/main/kotlin/com/checkinx/utils/sql/plan/parse/models/ExecutionPlan.kt: -------------------------------------------------------------------------------- 1 | package com.checkinx.utils.sql.plan.parse.models 2 | 3 | data class ExecutionPlan( 4 | val executionPlan: List, 5 | val rootPlanNode: PlanNode 6 | ) { 7 | fun findInPlanTree(predicate: (PlanNode) -> Boolean): PlanNode? { 8 | return findInPlanTree(predicate, rootPlanNode) 9 | } 10 | 11 | private fun findInPlanTree(predicate: (PlanNode) -> Boolean, rootNode: PlanNode): PlanNode? { 12 | if (predicate(rootNode)) { 13 | return rootNode 14 | } 15 | 16 | rootNode.children.forEach { 17 | val result = findInPlanTree(predicate, it) 18 | if (result != null) { 19 | return result 20 | } 21 | } 22 | 23 | return null 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/kotlin/com/checkinx/utils/sql/plan/parse/models/PlanNode.kt: -------------------------------------------------------------------------------- 1 | package com.checkinx.utils.sql.plan.parse.models 2 | 3 | import com.checkinx.utils.asserts.CoverageLevel 4 | 5 | data class PlanNode( 6 | val raw: String, 7 | val table: String?, 8 | var target: String?, 9 | var coverage: String?, 10 | val children: MutableList = mutableListOf(), 11 | val properties: MutableList> = mutableListOf(), 12 | val others: MutableList = mutableListOf() 13 | ) { 14 | val coverageLevel: CoverageLevel 15 | get() { 16 | return when { 17 | coverage?.contains("Index Only Scan") ?: false -> CoverageLevel.FULL 18 | coverage?.contains("Index Scan") ?: false -> CoverageLevel.HALF 19 | coverage?.contains("Seq Scan") ?: false -> CoverageLevel.ZERO 20 | else -> CoverageLevel.UNKNOWN 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/kotlin/com/checkinx/utils/sql/plan/query/ExecutionPlanException.kt: -------------------------------------------------------------------------------- 1 | package com.checkinx.utils.sql.plan.query 2 | 3 | data class ExecutionPlanException(val description: String) : Throwable() 4 | -------------------------------------------------------------------------------- /src/main/kotlin/com/checkinx/utils/sql/plan/query/ExecutionPlanQuery.kt: -------------------------------------------------------------------------------- 1 | package com.checkinx.utils.sql.plan.query 2 | 3 | interface ExecutionPlanQuery { 4 | fun execute(sqlStatement: String): List 5 | } 6 | -------------------------------------------------------------------------------- /src/main/kotlin/com/checkinx/utils/sql/plan/query/impl/PostgresExecutionPlanQuery.kt: -------------------------------------------------------------------------------- 1 | package com.checkinx.utils.sql.plan.query.impl 2 | 3 | import com.checkinx.utils.sql.plan.query.ExecutionPlanException 4 | import com.checkinx.utils.sql.plan.query.ExecutionPlanQuery 5 | import org.springframework.jdbc.core.JdbcTemplate 6 | 7 | open class PostgresExecutionPlanQuery(private val jdbcTemplate: JdbcTemplate) : ExecutionPlanQuery { 8 | override fun execute(sqlStatement: String): List { 9 | val executionPlanSqlQuery = "explain $sqlStatement" 10 | val result = jdbcTemplate.queryForList(executionPlanSqlQuery) 11 | 12 | if (result.isEmpty() || result[0].isEmpty()) { 13 | throw ExecutionPlanException( 14 | "Couldn't get execution plan by sql query $executionPlanSqlQuery") 15 | } 16 | 17 | return result 18 | .map { it.values.elementAt(0).toString() } 19 | .toList() 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/test/kotlin/com/checkinx/utils/asserts/impl/CheckInxAssertServiceImplTest.kt: -------------------------------------------------------------------------------- 1 | package com.checkinx.utils.asserts.impl 2 | 3 | import com.checkinx.utils.asserts.CoverageLevel 4 | import com.checkinx.utils.asserts.CoverageLevelException 5 | import com.checkinx.utils.asserts.IndexNotFoundException 6 | import com.checkinx.utils.asserts.PlanException 7 | import com.checkinx.utils.sql.plan.parse.impl.PostgresExecutionPlanParser 8 | import io.mockk.mockk 9 | import org.junit.Before 10 | import org.junit.Test 11 | 12 | class CheckInxAssertServiceImplTest { 13 | 14 | private lateinit var checkInxAssertService: CheckInxAssertServiceImpl 15 | 16 | @Before 17 | fun setUp() { 18 | checkInxAssertService = CheckInxAssertServiceImpl( 19 | mockk(), mockk() 20 | ) 21 | } 22 | 23 | @Test 24 | fun testAssertIndexGivenIndexOnlyScanWhenRequireFullThenSuccess() { 25 | // ARRANGE 26 | val plan = PostgresExecutionPlanParser().parse(listOf( 27 | "Index Only Scan using ix_pets_age on pets (cost=0.29..8.36 rows=4 width=4)", 28 | " Index Cond: (age = 1)" 29 | )) 30 | 31 | // ACT & ASSERT 32 | checkInxAssertService.assertCoverage(CoverageLevel.FULL, "ix_pets_age", plan) 33 | } 34 | 35 | @Test(expected = CoverageLevelException::class) 36 | fun testAssertIndexGivenIndexScanWhenRequireFullThenLevelException() { 37 | // ARRANGE 38 | val plan = PostgresExecutionPlanParser().parse(listOf( 39 | "Index Scan using ix_pets_age on pets (cost=0.29..8.72 rows=25 width=36)", 40 | " Index Cond: (age < 10)" 41 | )) 42 | 43 | // ACT 44 | checkInxAssertService.assertCoverage(CoverageLevel.FULL, "ix_pets_age", plan) 45 | } 46 | 47 | @Test 48 | fun testAssertIndexGivenIndexScanWhenRequireHalfThenSuccess() { 49 | // ARRANGE 50 | val plan = PostgresExecutionPlanParser().parse(listOf( 51 | "Index Scan using ix_pets_age on pets (cost=0.29..8.72 rows=25 width=36)", 52 | " Index Cond: (age < 10)" 53 | )) 54 | 55 | // ACT & ASSERT 56 | checkInxAssertService.assertCoverage(CoverageLevel.HALF, "ix_pets_age", plan) 57 | } 58 | 59 | @Test(expected = IndexNotFoundException::class) 60 | fun testAssertIndexGivenIndexScanWhenNotExistingIndexThenNotFoundException() { 61 | // ARRANGE 62 | val plan = PostgresExecutionPlanParser().parse(listOf( 63 | "Index Scan using ix_pets_age on pets (cost=0.29..8.72 rows=25 width=36)", 64 | " Index Cond: (age < 10)" 65 | )) 66 | 67 | // ACT 68 | checkInxAssertService.assertCoverage(CoverageLevel.HALF, "ix_not_existing", plan) 69 | } 70 | 71 | @Test 72 | fun testAssertIndexGivenIndexScanWhenUsingIndexNotRootThenTargetAndTableFound() { 73 | val plan = PostgresExecutionPlanParser().parse(listOf( 74 | "Limit (cost=0.29..8.30 rows=1 width=36)", 75 | " -> Index Scan using ix_pets_age on pets (cost=0.29..8.30 rows=1 width=36)", 76 | " Index Cond: (age = 5000)" 77 | )) 78 | 79 | checkInxAssertService.assertCoverage(CoverageLevel.HALF, "ix_pets_age", plan) 80 | } 81 | 82 | @Test 83 | fun testAssertIndexGivenTableWhenUsingNotRootThenTargetFound() { 84 | val plan = PostgresExecutionPlanParser().parse(listOf( 85 | "Limit (cost=0.29..8.30 rows=1 width=36)", 86 | " -> Index Scan on some_table tbl (cost=0.14..8.17 rows=1 width=562)", 87 | " Index Cond: (age = 5000)" 88 | )) 89 | 90 | checkInxAssertService.assertCoverage(CoverageLevel.HALF, "some_table tbl", plan) 91 | } 92 | 93 | @Test(expected = PlanException::class) 94 | fun testAssertCoverageGivenSeqScanWhenLevelHalfThenCoverageLevelException() { 95 | // ARRANGE 96 | val plan = PostgresExecutionPlanParser().parse(listOf( 97 | "Limit (cost=11.64..11.65 rows=1 width=40)", 98 | " -> Sort (cost=11.63..11.64 rows=1 width=40)", 99 | " Sort Key: some_date", 100 | " -> Seq Scan on some_table (cost=0.00..11.62 rows=1 width=40)", 101 | " Filter: ((some_id IS NULL) AND ('2019-05-21 15:01:11.301'::timestamp without time zone <= some_date))" 102 | )) 103 | 104 | // ACT 105 | checkInxAssertService.assertCoverage(CoverageLevel.HALF, plan) 106 | } 107 | 108 | @Test 109 | fun testAssertCoverageGivenUsingIndexScanWhenLevelHalfThenSuccess() { 110 | // ARRANGE 111 | val plan = PostgresExecutionPlanParser().parse(listOf( 112 | "Limit (cost=11.64..11.65 rows=1 width=40)", 113 | " -> Sort (cost=11.63..11.64 rows=1 width=40)", 114 | " Sort Key: some_date", 115 | " -> Index Scan using ix_some_index on some_table (cost=0.00..11.62 rows=1 width=40)", 116 | " Filter: ((some_id IS NULL) AND ('2019-05-21 15:01:11.301'::timestamp without time zone <= some_date))" 117 | )) 118 | 119 | // ACT 120 | checkInxAssertService.assertCoverage(CoverageLevel.HALF, plan) 121 | } 122 | 123 | @Test 124 | fun testAssertCoverageGivenOnIndexScanWhenLevelHalfThenSuccess() { 125 | // ARRANGE 126 | val plan = PostgresExecutionPlanParser().parse(listOf( 127 | "Limit (cost=11.64..11.65 rows=1 width=40)", 128 | " -> Sort (cost=11.63..11.64 rows=1 width=40)", 129 | " Sort Key: some_date", 130 | " -> Index Scan on ix_some_index (cost=0.00..11.62 rows=1 width=40)", 131 | " Filter: ((some_id IS NULL) AND ('2019-05-21 15:01:11.301'::timestamp without time zone <= some_date))" 132 | )) 133 | 134 | // ACT 135 | checkInxAssertService.assertCoverage(CoverageLevel.HALF, plan) 136 | } 137 | 138 | @Test 139 | fun testAssertPredicateGivenOnIndexScanWhenLevelHalfThenSuccess() { 140 | // ARRANGE 141 | val plan = PostgresExecutionPlanParser().parse(listOf( 142 | "Limit (cost=11.64..11.65 rows=1 width=40)", 143 | " -> Sort (cost=11.63..11.64 rows=1 width=40)", 144 | " Sort Key: some_date", 145 | " -> Index Scan on ix_some_index (cost=0.00..11.62 rows=1 width=40)", 146 | " Filter: ((some_id IS NULL) AND ('2019-05-21 15:01:11.301'::timestamp without time zone <= some_date))" 147 | )) 148 | 149 | // ACT 150 | checkInxAssertService.assertPlan(plan) { 151 | it.coverageLevel.level < CoverageLevel.HALF.level 152 | } 153 | } 154 | 155 | @Test(expected = PlanException::class) 156 | fun testAssertPlanWhenIndexScanWhenLevelFullThenPlanException() { 157 | // ARRANGE 158 | val plan = PostgresExecutionPlanParser().parse(listOf( 159 | "Limit (cost=11.64..11.65 rows=1 width=40)", 160 | " -> Sort (cost=11.63..11.64 rows=1 width=40)", 161 | " Sort Key: some_date", 162 | " -> Index Scan on ix_some_index (cost=0.00..11.62 rows=1 width=40)", 163 | " Filter: ((some_id IS NULL) AND ('2019-05-21 15:01:11.301'::timestamp without time zone <= some_date))" 164 | )) 165 | 166 | // ACT 167 | checkInxAssertService.assertPlan(plan) { 168 | it.coverageLevel.level < CoverageLevel.FULL.level 169 | } 170 | } 171 | } 172 | -------------------------------------------------------------------------------- /src/test/kotlin/com/checkinx/utils/sql/plan/parse/impl/PostgresExecutionPlanParserTest.kt: -------------------------------------------------------------------------------- 1 | package com.checkinx.utils.sql.plan.parse.impl 2 | 3 | import org.junit.Assert.* 4 | import org.junit.Before 5 | 6 | import org.junit.Test 7 | 8 | class PostgresExecutionPlanParserTest { 9 | 10 | private lateinit var parserPostgres: PostgresExecutionPlanParser 11 | 12 | @Before 13 | fun setUp() { 14 | parserPostgres = PostgresExecutionPlanParser() 15 | } 16 | 17 | @Test 18 | fun testParseWhenUsingInFirstLineThenTableAndIndexNotSame() { 19 | // ARRANGE 20 | val plan = listOf( 21 | "Index Scan using ix_pets_age on pets (cost=0.29..8.77 rows=1 width=36)", 22 | " Index Cond: (age < 10)", 23 | " Filter: ((name)::text = 'Jack'::text)" 24 | ) 25 | 26 | // ACT 27 | val model = parserPostgres.parse(plan) 28 | 29 | // ASSERT 30 | assertNotNull(model) 31 | } 32 | 33 | @Test 34 | fun testParseWhenDeepTree() { 35 | // ARRANGE 36 | val plan = listOf( 37 | "Nested Loop Semi Join (cost=0.00..3.11 rows=1 width=50)", 38 | " Join Filter: ((pets.name)::text = (pets_1.name)::text)", 39 | " -> Seq Scan on pets (cost=0.00..1.02 rows=2 width=50)", 40 | " -> Materialize (cost=0.00..2.06 rows=1 width=32)", 41 | " -> Nested Loop Semi Join (cost=0.00..2.06 rows=1 width=32)", 42 | " -> Seq Scan on pets pets_1 (cost=0.00..1.02 rows=1 width=34)", 43 | " Filter: (age = 2)", 44 | " -> Seq Scan on pets pets_2 (cost=0.00..1.02 rows=1 width=2)", 45 | " Filter: (age = 2)" 46 | ) 47 | 48 | // ACT 49 | val model = parserPostgres.parse(plan) 50 | 51 | // ASSERT 52 | assertNotNull(model) 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/test/kotlin/com/checkinx/utils/sql/plan/parse/models/ExecutionPlanTest.kt: -------------------------------------------------------------------------------- 1 | package com.checkinx.utils.sql.plan.parse.models 2 | 3 | import com.checkinx.utils.asserts.CoverageLevel 4 | import com.checkinx.utils.sql.plan.parse.impl.PostgresExecutionPlanParser 5 | import org.junit.Assert.assertEquals 6 | import org.junit.Before 7 | import org.junit.Test 8 | 9 | class ExecutionPlanTest { 10 | 11 | private lateinit var parser: PostgresExecutionPlanParser 12 | 13 | @Before 14 | fun setUp() { 15 | parser = PostgresExecutionPlanParser() 16 | } 17 | 18 | @Test 19 | fun testFindTargetInPlanTreeGivenTargetIsExistingIndexWhenCoverageFullThenCheckEqLevel() { 20 | // ARRANGE 21 | val plan = parser.parse(listOf( 22 | "Index Only Scan using ix_pets_age on pets (cost=0.29..8.36 rows=4 width=4)", 23 | " Index Cond: (age = 1)" 24 | )) 25 | 26 | // ACT 27 | val result = plan.findInPlanTree { node -> node.target == "ix_pets_age" } 28 | 29 | // ASSERT 30 | assertEquals(CoverageLevel.FULL, result?.coverageLevel) 31 | } 32 | 33 | @Test 34 | fun testFindTargetInPlanTreeGivenTargetIsExistingIndexWhenCoverageHalfThenCheckEqLevel() { 35 | // ARRANGE 36 | val plan = parser.parse(listOf( 37 | "Bitmap Heap Scan on pets (cost=4.18..12.65 rows=1 width=80)", 38 | " Recheck Cond: ((location)::text = 'Moscow'::text)", 39 | " Filter: ((name)::text = 'Nick'::text)", 40 | " -> Bitmap Index Scan on ix_location (cost=0.00..4.18 rows=4 width=0)", 41 | " Index Cond: ((location)::text = 'Moscow'::text)" 42 | )) 43 | 44 | // ACT 45 | val result = plan.findInPlanTree { node -> node.target == "ix_location" } 46 | 47 | // ASSERT 48 | assertEquals(CoverageLevel.HALF, result?.coverageLevel) 49 | } 50 | 51 | @Test 52 | fun testFindTargetInPlanTreeGivenTargetIsTableWhenCoverageZeroThenCheckEqLevel() { 53 | // ARRANGE 54 | val plan = parser.parse(listOf( 55 | "Seq Scan on pets (cost=0.00..19.38 rows=4 width=80)", 56 | " Filter: ((name)::text = 'Nick'::text)" 57 | )) 58 | 59 | // ACT 60 | val result = plan.findInPlanTree { node -> node.target == "pets" } 61 | 62 | // ASSERT 63 | assertEquals(CoverageLevel.ZERO, result?.coverageLevel) 64 | } 65 | } 66 | --------------------------------------------------------------------------------