├── .gitattributes ├── .gitignore ├── Dockerfile ├── LICENSE ├── README.en.md ├── README.md ├── config └── config.json ├── create_insert_data.sql ├── docker-compose.yml ├── images ├── 1.jpg ├── 2.jpg ├── 3.jpg ├── 4.jpg └── 5.jpg ├── pom.xml ├── release ├── config │ └── config.json ├── database-sync-1.3.jar └── lib │ ├── activation-1.1.jar │ ├── adal4j-1.0.0.jar │ ├── azure-core-0.9.3.jar │ ├── azure-keyvault-0.9.3.jar │ ├── bcprov-jdk15on-1.51.jar │ ├── checker-qual-3.8.0.jar │ ├── commons-codec-1.10.jar │ ├── commons-lang-2.6.jar │ ├── commons-lang3-3.3.1.jar │ ├── commons-logging-1.1.3.jar │ ├── db2jcc4-10.1.jar │ ├── error_prone_annotations-2.5.1.jar │ ├── failureaccess-1.0.1.jar │ ├── fastjson-1.2.47.jar │ ├── gson-2.2.4.jar │ ├── guava-30.1.1-jre.jar │ ├── hamcrest-core-1.3.jar │ ├── httpclient-4.3.6.jar │ ├── httpcore-4.3.3.jar │ ├── j2objc-annotations-1.3.jar │ ├── jackson-core-asl-1.9.2.jar │ ├── jackson-jaxrs-1.9.2.jar │ ├── jackson-mapper-asl-1.9.2.jar │ ├── jackson-xc-1.9.2.jar │ ├── javax.inject-1.jar │ ├── jaxb-api-2.2.2.jar │ ├── jaxb-impl-2.2.3-1.jar │ ├── jcip-annotations-1.0.jar │ ├── jersey-client-1.13.jar │ ├── jersey-core-1.13.jar │ ├── jersey-json-1.13.jar │ ├── jettison-1.1.jar │ ├── json-smart-1.1.1.jar │ ├── jsr305-3.0.2.jar │ ├── junit-4.13.1.jar │ ├── lang-tag-1.4.jar │ ├── listenablefuture-9999.0-empty-to-avoid-conflict-with-guava.jar │ ├── log4j-api-2.14.1.jar │ ├── log4j-core-2.14.1.jar │ ├── mail-1.4.5.jar │ ├── mssql-jdbc-6.1.0.jre8.jar │ ├── mysql-connector-java-8.0.16.jar │ ├── nimbus-jose-jwt-3.1.2.jar │ ├── oauth2-oidc-sdk-4.5.jar │ ├── ojdbc10-19.3.0.0.jar │ ├── ojdbc8-19.3.0.0.jar │ ├── postgresql-42.2.5.jar │ ├── protobuf-java-3.6.1.jar │ ├── slf4j-api-1.7.5.jar │ ├── stax-api-1.0-2.jar │ ├── stax-api-1.0.1.jar │ └── ucp-19.3.0.0.jar ├── run.sh ├── src ├── main │ ├── java │ │ └── com │ │ │ └── data │ │ │ └── database │ │ │ ├── App.java │ │ │ ├── Config.java │ │ │ ├── api │ │ │ ├── DataSync.java │ │ │ ├── MyEnum.java │ │ │ └── impl │ │ │ │ ├── DataBaseSync.java │ │ │ │ ├── DataBaseSyncFactory.java │ │ │ │ ├── Db2DataBaseSync.java │ │ │ │ ├── OracleDataBaseSync.java │ │ │ │ └── PostgresDataBaseSync.java │ │ │ └── utils │ │ │ └── Tools.java │ └── resources │ │ └── log4j2.xml └── test │ └── java │ └── com │ └── data │ └── database │ ├── AppTest.java │ ├── ConfigTest.java │ └── DataBaseSyncTest.java └── start_docker.md /.gitattributes: -------------------------------------------------------------------------------- 1 | # When shell scripts end in CRLF, bash gives a cryptic error message 2 | *.sh text eol=lf 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # 2 | # Standard Maven .gitignore 3 | # 4 | target/ 5 | pom.xml.tag 6 | pom.xml.releaseBackup 7 | pom.xml.versionsBackup 8 | pom.xml.next 9 | release.properties 10 | dependency-reduced-pom.xml 11 | buildNumber.properties 12 | .mvn/timing.properties 13 | *.DS_Store 14 | # 15 | # IntelliJ 16 | # 17 | *.iml 18 | .idea/* 19 | !.idea/runConfigurations/ 20 | 21 | # 22 | # Visual Studio Code 23 | # 24 | .settings/ 25 | .classpath 26 | .project 27 | .vscode/ 28 | config/ 29 | logs/ 30 | src/note.md 31 | *.xlsx 32 | *.swp 33 | .editorconfig 34 | .travis.yml -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM mysql:latest 2 | 3 | # 数据库名 4 | ENV MYSQL_DATABASE testdb 5 | 6 | # 默认根用户密码 7 | ENV MYSQL_ROOT_PASSWORD root 8 | 9 | # 拷贝初始化sql脚本 10 | COPY ./create_insert_data.sql /docker-entrypoint-initdb.d/ -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /README.en.md: -------------------------------------------------------------------------------- 1 | # table-sync 2 | 3 | #### Description 4 | 传入一定的参数,即可在相同或不同的数据库间进行表的同步,包括表结构的同步及数据的同步。作业的调试工具进行调度,本项目旨在提供一种数据库间表同步的通用工具 5 | 6 | #### Software Architecture 7 | Software architecture description 8 | 9 | #### Installation 10 | 11 | 1. xxxx 12 | 2. xxxx 13 | 3. xxxx 14 | 15 | #### Instructions 16 | 17 | 1. xxxx 18 | 2. xxxx 19 | 3. xxxx 20 | 21 | #### Contribution 22 | 23 | 1. Fork the repository 24 | 2. Create Feat_xxx branch 25 | 3. Commit your code 26 | 4. Create Pull Request 27 | 28 | 29 | #### Gitee Feature 30 | 31 | 1. You can use Readme\_XXX.md to support different languages, such as Readme\_en.md, Readme\_zh.md 32 | 2. Gitee blog [blog.gitee.com](https://blog.gitee.com) 33 | 3. Explore open source project [https://gitee.com/explore](https://gitee.com/explore) 34 | 4. The most valuable open source project [GVP](https://gitee.com/gvp) 35 | 5. The manual of Gitee [https://gitee.com/help](https://gitee.com/help) 36 | 6. The most popular members [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/) 37 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # [database-sync](https://gitee.com/somenzz/database-sync) 2 | 3 | 这是为数据开发人员使用的辅助工具,用于数据库之间的表同步,说同步并不严谨,因为不是实时更新的,更确切的说法是复制,可以方便的从一个数据库复制表到另一个数据库,以下遇到同步的词请理解为复制。 4 | 5 | ## 介绍 6 | 7 | 需求背景: 8 | 9 | 有很多业务系统,他们的数据库是相互独立的,需要把这些数据归集在一个数据库中(数据仓库),以便做数据统计和分析。希望能有这样的工具,输入数据库名,表名就可以将数据从源数据库拷贝到目标数据库中。具体需求如下: 10 |  11 | - 能自动同步表结构,如:源表扩字段,目标表自动扩字段。 12 | - 支持增量或全量同步数据,可以仅同步某个日期之后的数据。 13 | - 支持指定字段同步,只同步关心的那些字段。 14 | - 支持主流的关系型数据库: mysql、db2、postgresql、oracle、sqlserver 15 | - 源表和目标表表名可以不同,字段名也可以不同(已存在目标表的情况下) 16 | 17 | 因为自己要用,我就自己写了一个,顺便熟悉下 java 开发(之前一直用 Python),本程序的最大用处就是构建集市或数仓所需要的基础层数据源,欢迎感兴趣的朋友一起加入。 18 | 19 | ## 程序的使用方法 20 | 21 | ### Docker 方式: 22 | 23 | 这里用到三个容器: 24 | - app 也就是主程序本身,app 容器使用的程序文件就是 release 目录下的文件,已经做了绑定。 25 | - mysql 测试用的数据库,已提前放好了 7000 条测试数据。 26 | - postgres 测试用的数据库,没有数据。 27 | 28 | 先部署,执行 `docker-compose up -d` 就自动完成了部署: 29 | 30 | ```sh 31 | $ git clone https://github.com/somenzz/database-sync.git 32 | $ cd database-sync 33 | $ docker-compose up -d 34 | Creating database-sync_postgres_1 ... done 35 | Creating database-sync_app_1 ... done 36 | Creating database-sync_mysql_1 ... done 37 | ``` 38 | 这样三个容器就启动了,使用 `docker ps -a |grep database-sync` 可以查看到三个正在运行的容器: 39 | 40 | ![](images/1.jpg) 41 | 42 | 现在直接使用 `docker exec -i database-sync_app_1 java -jar database-sync-1.3.jar` 来执行程序: 43 | 44 | ![](images/2.jpg) 45 | 46 | mysql 容器已有测试数据,`release/config/config.json` 已经配置好了数据库的连接,因此可以直接试用,以下演示的是从 mysql 复制表和数据到 postgres: 47 | 48 | #### 1. 全量复制,自动建表: 49 | 50 | ```sh 51 | docker exec -i database-sync_app_1 java -jar database-sync-1.3.jar mysql_test testdb somenzz_users postgres_test public users --sync-ddl 52 | ``` 53 | ![](images/3.jpg) 54 | 55 | 56 | 如果你不想每次都敲 `docker exec -i database-sync_app_1` ,可以进入容器内部执行: 57 | 58 | ```sh 59 | (py38env) ➜ database-sync git:(master) ✗ docker exec -it database-sync_app_1 /bin/bash 60 | root@063b1dc76fe1:/app# ls 61 | config database-sync-1.3.jar lib logs 62 | root@063b1dc76fe1:/app# java -jar database-sync-1.3.jar mysql_test testdb somenzz_users postgres_test public users -sd 63 | ``` 64 | 65 | #### 2. 增量复制: 66 | 67 | ```sh 68 | root@063b1dc76fe1:/app# java -jar database-sync-1.3.jar mysql_test testdb somenzz_users postgres_test public zz_users "create_at >= '2018-01-09'" 69 | ``` 70 | ![](images/4.jpg) 71 | 72 | #### 3. 指定字段: 73 | 74 | ```sh 75 | root@063b1dc76fe1:/app# java -jar database-sync-1.3.jar mysql_test testdb somenzz_users postgres_test public zz_users -ff="user_id,name,age" -tf="user_id,name,age" "create_at >= '2018-01-09'" 76 | ``` 77 | ![](images/5.jpg) 78 | 79 | 80 | 81 | ### 普通方式 82 | 83 | 程序运行前确保已安装 java 1.8 或后续版本,已经安装 maven,然后 clone 源码,打包: 84 | 85 | ```sh 86 | git clone https://gitee.com/somenzz/database-sync.git 87 | cd database-sync 88 | mvn package 89 | ``` 90 | 此时你会看到 target 目录,将 target 下的 lib 目录 和 database-sync-1.3.jar 复制出来,放在同一目录下,然后再创建一个 config 目录,在 config 下新建一个 config.json 文件写入配置信息,然后将这个目录压缩,就可以传到服务器运行了,请注意先充分测试,jdk 要求 1.8+ 91 | 92 | ```sh 93 | [aaron@hdp002 /home/aaron/App/Java/database-sync]$ ls -ltr 94 | total 48 95 | drwxr-xr-x 2 aaron aaron 4096 Apr 23 2020 lib 96 | -rwxrw-r-- 1 aaron aaron 157 Jun 23 2020 run.sh 97 | drwxrwxr-x 2 aaron aaron 4096 Jul 3 2020 logs 98 | -rw-rw-r-- 1 aaron aaron 24773 Mar 16 2021 database-sync-1.3.jar 99 | drwxr-xr-x 7 aaron aaron 4096 Aug 3 2020 jdk1.8.0_231 100 | drwxrwxr-x 2 aaron aaron 4096 Feb 19 17:07 config 101 | ``` 102 | 103 | 你也可以直接下载我打包好的使用。 104 | 105 | 程序名称叫 database-sync,运行方式是这样的: 106 | 107 | ```sh 108 | (py38env) ➜ target git:(master) ✗ java -jar database-sync-1.3.jar -h 109 | Usage: 110 | java -jar database-sync-1.0.jar [options] {fromDB} {fromSchema} {fromTable} {toDB} {toSchema} {toTable} [whereClause] 111 | options: 112 | -v or --version :print version then exit 113 | -h or --help :print help info then exit 114 | -sd or --sync-ddl :auto synchronize table structure 115 | -ff=col1,col2 or --from-fields=col1,col2 :specify from fields 116 | -tf=col3,col4 or --to-fields=col3,col4 :specify to fields 117 | --no-feature or -nf :will not use database's feature 118 | ``` 119 | 120 | 121 | 帮助说明: 122 | 123 | [] 中括号里的内容表示选填,例如 [options] 表示 options 下的参数不是必须的。 124 | 125 | 1、其中 options 参数解释如下: 126 | 127 | - `--sync-ddl` 或者 `-sd` : 加入该参数会自动同步表结构。 128 | - `--from_fields=col1,col2` 或者 `-ff=col1,col2` : 指定原表的字段序列,注意 = 前后不能有空格。 129 | - `--to_fields=col3,col4` 或者 `-tf=col3,col4` : 指定目标表的字段序列,注意 = 前后不能有空格。 130 | 131 | 2、whereClause 表示 where 条件,用于增量更新,程序再插入数据前先按照 where 条件进行清理数据,然后按照 where 条件从原表进行读取数据。 whereClause 最好使用双引号包起来,表示一个完整的参数。如:"jyrq='2020-12-31'" 132 | 133 | 134 | {} 大括号里的内容表示必填。 135 | 136 | `fromDb` 是指配置在 config.json 的数据库信息的键,假如有以下配置文件: 137 | 138 | ```json 139 | { 140 | "postgres":{ 141 | "type":"postgres", 142 | "driver":"org.postgresql.Driver", 143 | "url":"jdbc:postgresql://localhost:5432/apidb", 144 | "user": "postgres", 145 | "password":"aaron", 146 | "encoding": "utf-8" 147 | }, 148 | 149 | 150 | "aarondb":{ 151 | "type":"mysql", 152 | "driver":"com.mysql.cj.jdbc.Driver", 153 | "url":"jdbc:mysql://localhost:3306/aarondb?useSSL=false&characterEncoding=utf8&serverTimezone=UTC", 154 | "user": "aaron", 155 | "password":"aaron" 156 | } 157 | } 158 | ``` 159 | 160 | fromDb、toDb 可以是 aarondb 或者 postgres。 161 | 162 | - `fromSchema` 读取数据的表的模式名,可以填写 "". 163 | - `fromTable` 读取数据的表明,必须提供。 164 | - `toSchema` 写入数据表的模式名,可以填写 "",可以和 fromSchema 不同. 165 | - `toTable` 写入数据表的表名,必须提供,当写入表不存在时,自动按读取表的表结构创建,可以和 fromTable 不同。 166 | 167 | 168 | **全量、增量、指定字段的使用样例请参考 Docker 方式。** 169 | 170 | ## 配置文件说明 171 | 172 | 配置文件位于 config/config.json,如下所示: 173 | 174 | ```json 175 | 176 | { 177 | "sjwb":{ 178 | "type":"db2", 179 | "driver":"com.ibm.db2.jcc.DB2Driver", 180 | "url":"jdbc:db2://192.168.1.*:50000/wbsj", 181 | "user": "****", 182 | "password":"****", 183 | "tbspace_ddl": "/*这里可以放置指定表空间的语句*/", 184 | "encoding":"utf-8" 185 | }, 186 | 187 | "dw_test":{ 188 | "type":"db2", 189 | "driver":"com.ibm.db2.jcc.DB2Driver", 190 | "url":"jdbc:db2://192.168.169.*:60990/dwdb", 191 | "user": "****", 192 | "password":"****", 193 | "encoding":"gbk" 194 | }, 195 | 196 | "postgres":{ 197 | "type":"postgres", 198 | "driver":"org.postgresql.Driver", 199 | "url":"jdbc:postgresql://10.99.**.**:5432/apidb", 200 | "user": "****", 201 | "password":"****", 202 | "tbspace_ddl": "WITH (compression=no, orientation=orc, version=0.12)\ntablespace hdfs\n", 203 | "encoding":"utf-8" 204 | }, 205 | 206 | 207 | "aarondb":{ 208 | "type":"mysql", 209 | "driver":"com.mysql.cj.jdbc.Driver", 210 | "url":"jdbc:mysql://localhost:3306/aarondb?useSSL=false&characterEncoding=utf8&serverTimezone=UTC", 211 | "user": "****", 212 | "password":"****", 213 | "encoding":"utf-8" 214 | }, 215 | 216 | "buffer-rows": 100000 217 | } 218 | 219 | ``` 220 | 221 | 配置文件说明: 222 | 223 | `type` 表示数据库类型,均为小写: 224 | 225 | - mysql 226 | - postgres 227 | - db2 228 | - oracle 229 | - sqlserver 230 | 231 | `tbspace_ddl` 表示自动建表时指定的表空间,该选项不是必需的,可以删除。 232 | 233 | `buffer-rows` 表示读取多少行时一块写入目标数据库,根据服务器内存大小自己做调整,100000 行提交一次满足大多数情况了。 234 | 235 | `encoding` 用于表结构同步时确定字段长度,比如说源库的字段是 gbk varchar(10),目标库是 utf-8,那么就应该为 varchar(15),这样字段有中文就不会出现截断或插入失败问题,程序这里 2 倍,也就是 varchar(20) ,这样字段长度不会出现小数位。 236 | 237 | 238 | ## 编写目的 239 | 240 | 提高数据库间表的复制效率,如果不需要对源表字段进行转换,就丢掉低效的 datastage 和 kettle 吧。 -------------------------------------------------------------------------------- /config/config.json: -------------------------------------------------------------------------------- 1 | { 2 | "mysql_test": { 3 | "type": "mysql", 4 | "driver": "com.mysql.cj.jdbc.Driver", 5 | "url": "jdbc:mysql://mysql:3306/testdb", 6 | "user": "root", 7 | "password": "root", 8 | "encoding": "utf-8" 9 | }, 10 | 11 | "postgres_test": { 12 | "type": "postgres", 13 | "driver": "org.postgresql.Driver", 14 | "url": "jdbc:postgresql://postgres:5432/postgres", 15 | "user": "postgres", 16 | "password": "root", 17 | "tbspace_ddl": "/*WITH (compression=no, orientation=orc, version=0.12)\ntablespace hdfs\n*/", 18 | "encoding": "utf-8" 19 | }, 20 | 21 | "dw_test": { 22 | "type": "dw", 23 | "driver": "com.ibm.db2.jcc.DB2Driver", 24 | "url": "jdbc:db2://192.168.168.169:60000/dwdb", 25 | "user": "dw", 26 | "password": "dw", 27 | "tbspace_ddl": "IN TBS_DATA\nINDEX IN TBS_INDEX\n", 28 | "encoding": "gbk" 29 | }, 30 | 31 | "oracle_test":{ 32 | "type":"oracle", 33 | "driver":"oracle.jdbc.driver.OracleDriver", 34 | "url":"jdbc:oracle:thin:@192.168.168.196:1521:orcl", 35 | "user": "ocrm", 36 | "password":"ocrm", 37 | "encoding": "utf-8" 38 | }, 39 | 40 | 41 | "buffer-rows": 1000 42 | } 43 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: "3.7" 2 | services: 3 | app: 4 | image: java:latest 5 | working_dir: /app 6 | volumes: 7 | - ./release:/app 8 | command: /bin/bash -c "while true;do sleep 1;done" #为了让容器不退出,写个循环 sleep 9 | mysql: 10 | image: somenzz/mysql:8.0 #含有测试数据 11 | environment: 12 | MYSQL_ROOT_PASSWORD: root 13 | MYSQL_DATABASE: testdb 14 | postgres: 15 | image: postgres:latest 16 | environment: 17 | POSTGRES_PASSWORD: root -------------------------------------------------------------------------------- /images/1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/somenzz/database-sync/586fab23bfa26c24ea0c40385ddb15c898c20da3/images/1.jpg -------------------------------------------------------------------------------- /images/2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/somenzz/database-sync/586fab23bfa26c24ea0c40385ddb15c898c20da3/images/2.jpg -------------------------------------------------------------------------------- /images/3.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/somenzz/database-sync/586fab23bfa26c24ea0c40385ddb15c898c20da3/images/3.jpg -------------------------------------------------------------------------------- /images/4.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/somenzz/database-sync/586fab23bfa26c24ea0c40385ddb15c898c20da3/images/4.jpg -------------------------------------------------------------------------------- /images/5.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/somenzz/database-sync/586fab23bfa26c24ea0c40385ddb15c898c20da3/images/5.jpg -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4.0.0 3 | com.data.database 4 | database-sync 5 | 1.3 6 | 7 | 1.8 8 | 1.8 9 | UTF-8 10 | 11 | 12 | 13 | 25 | 26 | maven_nexus 27 | maven_nexus 28 | default 29 | https://artifacts.alfresco.com/nexus/content/repositories/public/ 30 | 31 | true 32 | 33 | 34 | 35 | maven.oracle.com 36 | oracle-maven-repo 37 | https://maven.oracle.com 38 | 39 | true 40 | never 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | maven.oracle.com 49 | oracle-maven-repo 50 | https://maven.oracle.com 51 | default 52 | 53 | true 54 | never 55 | 56 | 57 | 58 | 59 | 60 | 61 | junit 62 | junit 63 | 4.13.1 64 | test 65 | 66 | 67 | mysql 68 | mysql-connector-java 69 | 8.0.16 70 | runtime 71 | 72 | 73 | 74 | org.postgresql 75 | postgresql 76 | 42.2.5 77 | 78 | 79 | 80 | 81 | com.google.guava 82 | guava 83 | [30.0-jre,) 84 | 85 | 86 | 87 | com.alibaba 88 | fastjson 89 | 1.2.47 90 | 91 | 92 | 93 | 94 | com.microsoft.sqlserver 95 | mssql-jdbc 96 | 6.1.0.jre8 97 | 98 | 99 | 100 | org.apache.logging.log4j 101 | log4j-api 102 | 2.14.1 103 | 104 | 105 | org.apache.logging.log4j 106 | log4j-core 107 | 2.14.1 108 | 109 | 110 | 111 | 116 | 117 | 118 | 119 | com.oracle.jdbc 120 | ojdbc8 121 | 19.3.0.0 122 | 123 | 124 | 125 | 126 | com.ibm.db2.jcc 127 | db2jcc4 128 | 10.1 129 | runtime 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | org.apache.maven.plugins 139 | maven-checkstyle-plugin 140 | 3.0.0 141 | 142 | 143 | com.puppycrawl.tools 144 | checkstyle 145 | 8.29 146 | 147 | 148 | com.github.ngeor 149 | checkstyle-rules 150 | 1.1.0 151 | 152 | 153 | 154 | com/github/ngeor/checkstyle.xml 155 | true 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | org.apache.maven.plugins 165 | maven-checkstyle-plugin 166 | 167 | 168 | 172 | 173 | org.jacoco 174 | jacoco-maven-plugin 175 | 0.8.1 176 | 177 | 178 | 179 | 180 | 181 | 182 | org.apache.maven.plugins 183 | maven-jar-plugin 184 | 3.0.2 185 | 186 | 187 | 188 | true 189 | lib/ 190 | com.data.database.App 191 | 192 | 193 | 194 | 195 | 196 | 197 | 198 | org.apache.maven.plugins 199 | maven-dependency-plugin 200 | 3.0.1 201 | 202 | 203 | copy-dependencies 204 | package 205 | 206 | copy-dependencies 207 | 208 | 209 | ${project.build.directory}/lib 210 | 211 | 212 | 213 | 214 | 215 | 216 | 217 | 218 | 219 | org.apache.maven.plugins 220 | maven-javadoc-plugin 221 | 3.0.0 222 | 223 | 224 | org.apache.maven.plugins 225 | maven-checkstyle-plugin 226 | 227 | com/github/ngeor/checkstyle.xml 228 | true 229 | 230 | 231 | 232 | 233 | 234 | 235 | 240 | 241 | jacoco 242 | 243 | 244 | env.TRAVIS 245 | 246 | 247 | 248 | 249 | 250 | org.jacoco 251 | jacoco-maven-plugin 252 | 253 | 254 | prepare-agent 255 | validate 256 | 257 | prepare-agent 258 | 259 | 260 | 261 | report 262 | test 263 | 264 | report 265 | 266 | 267 | 268 | 269 | 270 | 271 | 272 | 273 | 278 | 279 | travis 280 | 281 | 282 | env.TRAVIS 283 | 284 | 285 | 286 | 287 | 288 | org.apache.maven.plugins 289 | maven-checkstyle-plugin 290 | 291 | 292 | checkstyle 293 | test 294 | 295 | check 296 | 297 | 298 | 299 | 300 | 301 | org.eluder.coveralls 302 | coveralls-maven-plugin 303 | 4.3.0 304 | 305 | 306 | 307 | 308 | 309 | -------------------------------------------------------------------------------- /release/config/config.json: -------------------------------------------------------------------------------- 1 | { 2 | "mysql_test": { 3 | "type": "mysql", 4 | "driver": "com.mysql.cj.jdbc.Driver", 5 | "url": "jdbc:mysql://mysql:3306/testdb", 6 | "user": "root", 7 | "password": "root", 8 | "encoding": "utf-8" 9 | }, 10 | 11 | "postgres_test": { 12 | "type": "postgres", 13 | "driver": "org.postgresql.Driver", 14 | "url": "jdbc:postgresql://postgres:5432/postgres", 15 | "user": "postgres", 16 | "password": "root", 17 | "tbspace_ddl": "/*WITH (compression=no, orientation=orc, version=0.12)\ntablespace hdfs\n*/", 18 | "encoding": "utf-8" 19 | }, 20 | 21 | "dw_test": { 22 | "type": "dw", 23 | "driver": "com.ibm.db2.jcc.DB2Driver", 24 | "url": "jdbc:db2://192.168.168.169:60000/dwdb", 25 | "user": "dw", 26 | "password": "dw", 27 | "tbspace_ddl": "IN TBS_DATA\nINDEX IN TBS_INDEX\n", 28 | "encoding": "gbk" 29 | }, 30 | 31 | "oracle_test":{ 32 | "type":"oracle", 33 | "driver":"oracle.jdbc.driver.OracleDriver", 34 | "url":"jdbc:oracle:thin:@192.168.168.196:1521:orcl", 35 | "user": "ocrm", 36 | "password":"ocrm", 37 | "encoding": "utf-8" 38 | }, 39 | 40 | 41 | "buffer-rows": 1000 42 | } 43 | -------------------------------------------------------------------------------- /release/database-sync-1.3.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/somenzz/database-sync/586fab23bfa26c24ea0c40385ddb15c898c20da3/release/database-sync-1.3.jar -------------------------------------------------------------------------------- /release/lib/activation-1.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/somenzz/database-sync/586fab23bfa26c24ea0c40385ddb15c898c20da3/release/lib/activation-1.1.jar -------------------------------------------------------------------------------- /release/lib/adal4j-1.0.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/somenzz/database-sync/586fab23bfa26c24ea0c40385ddb15c898c20da3/release/lib/adal4j-1.0.0.jar -------------------------------------------------------------------------------- /release/lib/azure-core-0.9.3.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/somenzz/database-sync/586fab23bfa26c24ea0c40385ddb15c898c20da3/release/lib/azure-core-0.9.3.jar -------------------------------------------------------------------------------- /release/lib/azure-keyvault-0.9.3.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/somenzz/database-sync/586fab23bfa26c24ea0c40385ddb15c898c20da3/release/lib/azure-keyvault-0.9.3.jar -------------------------------------------------------------------------------- /release/lib/bcprov-jdk15on-1.51.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/somenzz/database-sync/586fab23bfa26c24ea0c40385ddb15c898c20da3/release/lib/bcprov-jdk15on-1.51.jar -------------------------------------------------------------------------------- /release/lib/checker-qual-3.8.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/somenzz/database-sync/586fab23bfa26c24ea0c40385ddb15c898c20da3/release/lib/checker-qual-3.8.0.jar -------------------------------------------------------------------------------- /release/lib/commons-codec-1.10.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/somenzz/database-sync/586fab23bfa26c24ea0c40385ddb15c898c20da3/release/lib/commons-codec-1.10.jar -------------------------------------------------------------------------------- /release/lib/commons-lang-2.6.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/somenzz/database-sync/586fab23bfa26c24ea0c40385ddb15c898c20da3/release/lib/commons-lang-2.6.jar -------------------------------------------------------------------------------- /release/lib/commons-lang3-3.3.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/somenzz/database-sync/586fab23bfa26c24ea0c40385ddb15c898c20da3/release/lib/commons-lang3-3.3.1.jar -------------------------------------------------------------------------------- /release/lib/commons-logging-1.1.3.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/somenzz/database-sync/586fab23bfa26c24ea0c40385ddb15c898c20da3/release/lib/commons-logging-1.1.3.jar -------------------------------------------------------------------------------- /release/lib/db2jcc4-10.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/somenzz/database-sync/586fab23bfa26c24ea0c40385ddb15c898c20da3/release/lib/db2jcc4-10.1.jar -------------------------------------------------------------------------------- /release/lib/error_prone_annotations-2.5.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/somenzz/database-sync/586fab23bfa26c24ea0c40385ddb15c898c20da3/release/lib/error_prone_annotations-2.5.1.jar -------------------------------------------------------------------------------- /release/lib/failureaccess-1.0.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/somenzz/database-sync/586fab23bfa26c24ea0c40385ddb15c898c20da3/release/lib/failureaccess-1.0.1.jar -------------------------------------------------------------------------------- /release/lib/fastjson-1.2.47.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/somenzz/database-sync/586fab23bfa26c24ea0c40385ddb15c898c20da3/release/lib/fastjson-1.2.47.jar -------------------------------------------------------------------------------- /release/lib/gson-2.2.4.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/somenzz/database-sync/586fab23bfa26c24ea0c40385ddb15c898c20da3/release/lib/gson-2.2.4.jar -------------------------------------------------------------------------------- /release/lib/guava-30.1.1-jre.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/somenzz/database-sync/586fab23bfa26c24ea0c40385ddb15c898c20da3/release/lib/guava-30.1.1-jre.jar -------------------------------------------------------------------------------- /release/lib/hamcrest-core-1.3.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/somenzz/database-sync/586fab23bfa26c24ea0c40385ddb15c898c20da3/release/lib/hamcrest-core-1.3.jar -------------------------------------------------------------------------------- /release/lib/httpclient-4.3.6.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/somenzz/database-sync/586fab23bfa26c24ea0c40385ddb15c898c20da3/release/lib/httpclient-4.3.6.jar -------------------------------------------------------------------------------- /release/lib/httpcore-4.3.3.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/somenzz/database-sync/586fab23bfa26c24ea0c40385ddb15c898c20da3/release/lib/httpcore-4.3.3.jar -------------------------------------------------------------------------------- /release/lib/j2objc-annotations-1.3.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/somenzz/database-sync/586fab23bfa26c24ea0c40385ddb15c898c20da3/release/lib/j2objc-annotations-1.3.jar -------------------------------------------------------------------------------- /release/lib/jackson-core-asl-1.9.2.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/somenzz/database-sync/586fab23bfa26c24ea0c40385ddb15c898c20da3/release/lib/jackson-core-asl-1.9.2.jar -------------------------------------------------------------------------------- /release/lib/jackson-jaxrs-1.9.2.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/somenzz/database-sync/586fab23bfa26c24ea0c40385ddb15c898c20da3/release/lib/jackson-jaxrs-1.9.2.jar -------------------------------------------------------------------------------- /release/lib/jackson-mapper-asl-1.9.2.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/somenzz/database-sync/586fab23bfa26c24ea0c40385ddb15c898c20da3/release/lib/jackson-mapper-asl-1.9.2.jar -------------------------------------------------------------------------------- /release/lib/jackson-xc-1.9.2.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/somenzz/database-sync/586fab23bfa26c24ea0c40385ddb15c898c20da3/release/lib/jackson-xc-1.9.2.jar -------------------------------------------------------------------------------- /release/lib/javax.inject-1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/somenzz/database-sync/586fab23bfa26c24ea0c40385ddb15c898c20da3/release/lib/javax.inject-1.jar -------------------------------------------------------------------------------- /release/lib/jaxb-api-2.2.2.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/somenzz/database-sync/586fab23bfa26c24ea0c40385ddb15c898c20da3/release/lib/jaxb-api-2.2.2.jar -------------------------------------------------------------------------------- /release/lib/jaxb-impl-2.2.3-1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/somenzz/database-sync/586fab23bfa26c24ea0c40385ddb15c898c20da3/release/lib/jaxb-impl-2.2.3-1.jar -------------------------------------------------------------------------------- /release/lib/jcip-annotations-1.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/somenzz/database-sync/586fab23bfa26c24ea0c40385ddb15c898c20da3/release/lib/jcip-annotations-1.0.jar -------------------------------------------------------------------------------- /release/lib/jersey-client-1.13.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/somenzz/database-sync/586fab23bfa26c24ea0c40385ddb15c898c20da3/release/lib/jersey-client-1.13.jar -------------------------------------------------------------------------------- /release/lib/jersey-core-1.13.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/somenzz/database-sync/586fab23bfa26c24ea0c40385ddb15c898c20da3/release/lib/jersey-core-1.13.jar -------------------------------------------------------------------------------- /release/lib/jersey-json-1.13.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/somenzz/database-sync/586fab23bfa26c24ea0c40385ddb15c898c20da3/release/lib/jersey-json-1.13.jar -------------------------------------------------------------------------------- /release/lib/jettison-1.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/somenzz/database-sync/586fab23bfa26c24ea0c40385ddb15c898c20da3/release/lib/jettison-1.1.jar -------------------------------------------------------------------------------- /release/lib/json-smart-1.1.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/somenzz/database-sync/586fab23bfa26c24ea0c40385ddb15c898c20da3/release/lib/json-smart-1.1.1.jar -------------------------------------------------------------------------------- /release/lib/jsr305-3.0.2.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/somenzz/database-sync/586fab23bfa26c24ea0c40385ddb15c898c20da3/release/lib/jsr305-3.0.2.jar -------------------------------------------------------------------------------- /release/lib/junit-4.13.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/somenzz/database-sync/586fab23bfa26c24ea0c40385ddb15c898c20da3/release/lib/junit-4.13.1.jar -------------------------------------------------------------------------------- /release/lib/lang-tag-1.4.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/somenzz/database-sync/586fab23bfa26c24ea0c40385ddb15c898c20da3/release/lib/lang-tag-1.4.jar -------------------------------------------------------------------------------- /release/lib/listenablefuture-9999.0-empty-to-avoid-conflict-with-guava.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/somenzz/database-sync/586fab23bfa26c24ea0c40385ddb15c898c20da3/release/lib/listenablefuture-9999.0-empty-to-avoid-conflict-with-guava.jar -------------------------------------------------------------------------------- /release/lib/log4j-api-2.14.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/somenzz/database-sync/586fab23bfa26c24ea0c40385ddb15c898c20da3/release/lib/log4j-api-2.14.1.jar -------------------------------------------------------------------------------- /release/lib/log4j-core-2.14.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/somenzz/database-sync/586fab23bfa26c24ea0c40385ddb15c898c20da3/release/lib/log4j-core-2.14.1.jar -------------------------------------------------------------------------------- /release/lib/mail-1.4.5.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/somenzz/database-sync/586fab23bfa26c24ea0c40385ddb15c898c20da3/release/lib/mail-1.4.5.jar -------------------------------------------------------------------------------- /release/lib/mssql-jdbc-6.1.0.jre8.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/somenzz/database-sync/586fab23bfa26c24ea0c40385ddb15c898c20da3/release/lib/mssql-jdbc-6.1.0.jre8.jar -------------------------------------------------------------------------------- /release/lib/mysql-connector-java-8.0.16.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/somenzz/database-sync/586fab23bfa26c24ea0c40385ddb15c898c20da3/release/lib/mysql-connector-java-8.0.16.jar -------------------------------------------------------------------------------- /release/lib/nimbus-jose-jwt-3.1.2.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/somenzz/database-sync/586fab23bfa26c24ea0c40385ddb15c898c20da3/release/lib/nimbus-jose-jwt-3.1.2.jar -------------------------------------------------------------------------------- /release/lib/oauth2-oidc-sdk-4.5.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/somenzz/database-sync/586fab23bfa26c24ea0c40385ddb15c898c20da3/release/lib/oauth2-oidc-sdk-4.5.jar -------------------------------------------------------------------------------- /release/lib/ojdbc10-19.3.0.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/somenzz/database-sync/586fab23bfa26c24ea0c40385ddb15c898c20da3/release/lib/ojdbc10-19.3.0.0.jar -------------------------------------------------------------------------------- /release/lib/ojdbc8-19.3.0.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/somenzz/database-sync/586fab23bfa26c24ea0c40385ddb15c898c20da3/release/lib/ojdbc8-19.3.0.0.jar -------------------------------------------------------------------------------- /release/lib/postgresql-42.2.5.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/somenzz/database-sync/586fab23bfa26c24ea0c40385ddb15c898c20da3/release/lib/postgresql-42.2.5.jar -------------------------------------------------------------------------------- /release/lib/protobuf-java-3.6.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/somenzz/database-sync/586fab23bfa26c24ea0c40385ddb15c898c20da3/release/lib/protobuf-java-3.6.1.jar -------------------------------------------------------------------------------- /release/lib/slf4j-api-1.7.5.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/somenzz/database-sync/586fab23bfa26c24ea0c40385ddb15c898c20da3/release/lib/slf4j-api-1.7.5.jar -------------------------------------------------------------------------------- /release/lib/stax-api-1.0-2.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/somenzz/database-sync/586fab23bfa26c24ea0c40385ddb15c898c20da3/release/lib/stax-api-1.0-2.jar -------------------------------------------------------------------------------- /release/lib/stax-api-1.0.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/somenzz/database-sync/586fab23bfa26c24ea0c40385ddb15c898c20da3/release/lib/stax-api-1.0.1.jar -------------------------------------------------------------------------------- /release/lib/ucp-19.3.0.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/somenzz/database-sync/586fab23bfa26c24ea0c40385ddb15c898c20da3/release/lib/ucp-19.3.0.0.jar -------------------------------------------------------------------------------- /run.sh: -------------------------------------------------------------------------------- 1 | /path/jdk1.8.0_231/bin/java -jar database-sync-1.2.jar "$@" -------------------------------------------------------------------------------- /src/main/java/com/data/database/App.java: -------------------------------------------------------------------------------- 1 | package com.data.database; 2 | 3 | import java.sql.*; 4 | 5 | import com.data.database.utils.Tools; 6 | import java.io.IOException; 7 | 8 | import com.data.database.api.impl.DataBaseSyncFactory; 9 | import com.data.database.api.impl.DataBaseSync; 10 | import java.util.ArrayList; 11 | import java.util.HashMap; 12 | import java.util.Map.Entry; 13 | import java.util.Iterator; 14 | import java.util.List; 15 | import com.data.database.api.MyEnum.ColSizeTimes; 16 | 17 | import org.apache.logging.log4j.Logger; 18 | import org.apache.logging.log4j.LogManager; 19 | 20 | /** 21 | * 数据库表同步主程序 22 | */ 23 | public final class App { 24 | 25 | private static final Logger logger = LogManager.getLogger(App.class); 26 | 27 | private String fromDBId; //源数据库标识符 28 | private String fromSchema; //源数据库中的模式名 29 | private String fromTable; //源数据库表名 30 | private String toDBId; //目标数据库标识符 31 | private String toSchema; //目标数据库的模式名 32 | private String toTable; //目标数据库的表名 33 | 34 | //可选参数 35 | private boolean isSyncTableDDL = false;// 默认不同步表结构 36 | private boolean isSpecificFeture = true; //某些具体数据库会有自己特定的支持,比如 PostGressSql 中的 copy 模式会比 jdbc 一行一行插入要快的多。为 true 表示优先使用具体特性,否则仅使用 jdbc 同步。 37 | private String whereClause; //where 子句的条件,适用于增量同步,应当检查安全性,防止sql注入 38 | private List toTableFields; /* 指定插入目标表哪些字段 */ 39 | private List fromTableFields; /* 指定插入目标表哪些字段 */ 40 | 41 | public String getFromDBId(){ 42 | return this.fromDBId; 43 | } 44 | public String getFromSchema(){ 45 | return this.fromSchema; 46 | } 47 | public String getFromTable(){ 48 | return this.fromTable; 49 | } 50 | public String getToDbId(){ 51 | return this.toDBId; 52 | } 53 | public String getToSchema(){ 54 | return this.toSchema; 55 | } 56 | public String getToTable(){ 57 | return this.toTable; 58 | } 59 | 60 | 61 | public boolean getIsSyncTableDDL(){ 62 | return this.isSyncTableDDL; 63 | } 64 | 65 | public boolean getIsSpecificFeture(){ 66 | return this.isSpecificFeture; 67 | } 68 | 69 | public List getFromTableFields(){ 70 | return this.fromTableFields; 71 | } 72 | public List getToTableFields(){ 73 | return this.toTableFields; 74 | } 75 | 76 | public String getWhereClause(){ 77 | return this.whereClause; 78 | } 79 | 80 | /*处理并检查输入的参数,如果返回 false,则在主函数中退出程序*/ 81 | public boolean handleCommandLineArgs(String[] args){ 82 | List argList = new ArrayList<>(); 83 | for (String arg : args) { 84 | if ("--version".equals(arg) || "-v".equals(arg)) { 85 | System.out.println("database-sync v1.3"); 86 | return false; 87 | } else if ("--help".equals(arg) || "-h".equals(arg)) { 88 | printHelp(); 89 | return false; 90 | } else if ("--sync-ddl".equals(arg) || "-sd".equals(arg)) { 91 | //同步表结构一般情况下比较危险,默认不同步表结构 92 | this.isSyncTableDDL = true; 93 | } else if ("--no-feature".equals(arg) || "-nf".equals(arg)) { 94 | this.isSpecificFeture = false; 95 | 96 | } else if (arg.startsWith("--to-fields=") || arg.startsWith("-tf=")) { 97 | String fields = arg.replace("--to-fields=", "").replace("-tf=", ""); 98 | for (String s : fields.split(",")) { 99 | this.toTableFields.add(s); 100 | } 101 | } else if (arg.startsWith("--from-fields=") || arg.startsWith("-ff=")) { 102 | String fields = arg.replace("--from-fields=", "").replace("-ff=", ""); 103 | for (String s : fields.split(",")) { 104 | this.fromTableFields.add(s); 105 | } 106 | } else { 107 | argList.add(arg); 108 | } 109 | } 110 | if (argList.size() < 6) { 111 | printHelp(); 112 | return false; 113 | } 114 | 115 | 116 | this.fromDBId = argList.get(0); 117 | this.fromSchema = argList.get(1); 118 | this.fromTable = argList.get(2); 119 | this.toDBId = argList.get(3); 120 | this.toSchema = argList.get(4); 121 | this.toTable = argList.get(5); 122 | this.whereClause = argList.size() >= 7 ? argList.get(6) : ""; 123 | 124 | if (this.fromDBId.equalsIgnoreCase(this.toDBId) && this.fromSchema.equalsIgnoreCase(this.toSchema) 125 | && this.fromTable.equalsIgnoreCase(this.toTable)) { 126 | System.out.println("You don't need to do that."); 127 | return false; 128 | } 129 | 130 | this.whereClause = this.whereClause.replaceAll("(?i)where", ""); 131 | 132 | String paramsPrint = String.format( 133 | "Your input params are:\n" 134 | + "<=== fromDb=%s, fromSchema=%s, fromTable=%s, fromTableFields=%s, whereClause=%s\n" 135 | + "===> toDb=%s, toSchema=%s, toTable=%s, toTableFields=%s", 136 | this.fromDBId, this.fromSchema, this.fromTable, 137 | this.fromTableFields.size() > 0 ? String.join(",", this.fromTableFields) : "[toTableFields]", this.whereClause, this.toDBId, 138 | this.toSchema, this.toTable, this.toTableFields.size() > 0 ? String.join(",", this.toTableFields) : "*"); 139 | 140 | logger.info(paramsPrint); 141 | logger.info("argList=" + String.join(",", argList)); 142 | 143 | return true; 144 | } 145 | 146 | 147 | private App() { 148 | //构造函数,初始化使用 149 | this.toTableFields = new ArrayList<>(); 150 | this.fromTableFields = new ArrayList<>(); 151 | } 152 | 153 | public static App getInstance(){ 154 | //for test 155 | return new App(); 156 | } 157 | 158 | /** 159 | * 比较原表与目标表的表结构,获取表结构同步语句:添加、删除字段,扩长度等等。 160 | * 161 | * @param args The arguments of the program. 162 | * @throws ClassNotFoundException 163 | * @throws SQLException 164 | */ 165 | 166 | public static String getAlterSqlFromMetaData(String toType, String toSchema, String toTable, ResultSet fromColumnMeta, 167 | ResultSet toColumnMeta, ColSizeTimes colSizeTimes) throws SQLException { 168 | StringBuilder sb = new StringBuilder(); 169 | 170 | HashMap> fromColMap = new HashMap>(); 171 | HashMap> toColMap = new HashMap>(); 172 | 173 | while (fromColumnMeta.next()) { 174 | HashMap fromMap = new HashMap(); 175 | fromMap.put("DATA_TYPE", fromColumnMeta.getInt("DATA_TYPE")); 176 | fromMap.put("TYPE_NAME", fromColumnMeta.getString("TYPE_NAME")); 177 | fromMap.put("COLUMN_SIZE", fromColumnMeta.getInt("COLUMN_SIZE")); 178 | fromMap.put("DECIMAL_DIGITS", fromColumnMeta.getInt("DECIMAL_DIGITS")); 179 | String colName = fromColumnMeta.getString("COLUMN_NAME"); 180 | fromColMap.put(colName.toUpperCase(), fromMap); 181 | } 182 | 183 | while (toColumnMeta.next()) { 184 | HashMap toMap = new HashMap(); 185 | toMap.put("DATA_TYPE", toColumnMeta.getInt("DATA_TYPE")); 186 | toMap.put("TYPE_NAME", toColumnMeta.getString("TYPE_NAME")); 187 | toMap.put("COLUMN_SIZE", toColumnMeta.getInt("COLUMN_SIZE")); 188 | toMap.put("DECIMAL_DIGITS", toColumnMeta.getInt("DECIMAL_DIGITS")); 189 | String colName = toColumnMeta.getString("COLUMN_NAME"); 190 | toColMap.put(colName.toUpperCase(), toMap); 191 | } 192 | 193 | Iterator>> toIterator = toColMap.entrySet().iterator(); 194 | Iterator>> fromIterator = fromColMap.entrySet().iterator(); 195 | 196 | while (toIterator.hasNext()) { 197 | // 以目标字段为基准进行检查 198 | Entry> toEntry = toIterator.next(); 199 | String toColName = toEntry.getKey(); 200 | HashMap toMap = toEntry.getValue(); 201 | HashMap fromMap = fromColMap.get(toColName); 202 | 203 | if (fromMap == null) { 204 | // 原表找不到字段,说明该字段被删除,删除的sql语句是通用的,执行完直接比较下一个 205 | sb.append(String.format("alter table %s.%s drop column %s ;", toSchema, toTable, toColName)); 206 | continue; 207 | } 208 | // 当两者不一致时以原表为准。 209 | Integer colType = (Integer) fromMap.get("DATA_TYPE"); 210 | if (colType == Types.CHAR || colType == Types.VARCHAR) {// 处理字符串类型 211 | Integer fromColLength = (Integer) fromMap.get("COLUMN_SIZE") * colSizeTimes.getTimes(); 212 | Integer toColLength = (Integer) toMap.get("COLUMN_SIZE"); 213 | if (fromColLength > toColLength) { 214 | //针对不同数据库使用与之匹配的 sql 语句 215 | if ("db2".equals(toType)) { 216 | sb.append(String.format("alter table %s.%s alter column %s set data type varchar(%d);", 217 | toSchema, toTable, toColName, fromColLength)); 218 | } else if ("mysql".equals(toType) || "oracle".equals(toType)) { 219 | sb.append(String.format("alter table %s.%s modify column %s varchar(%d);", toSchema, toTable, 220 | toColName, fromColLength)); 221 | } else if ("postgres".equals(toType)) { 222 | sb.append(String.format("alter table %s.%s alter column %s type character varying(%d);", 223 | toSchema, toTable, toColName, fromColLength)); 224 | } else{ 225 | sb.append(String.format("alter table %s.%s alter column %s type character varying(%d);", 226 | toSchema, toTable, toColName, fromColLength)); 227 | } 228 | 229 | } 230 | } else if (colType == Types.DECIMAL) {// 处理小数字段类型 231 | Integer fromColLength = (Integer) fromMap.get("COLUMN_SIZE"); 232 | Integer fromColDigitLength = (Integer) fromMap.get("DECIMAL_DIGITS"); 233 | Integer toColLength = (Integer) toMap.get("COLUMN_SIZE"); 234 | Integer toColDigitLength = (Integer) toMap.get("DECIMAL_DIGITS"); 235 | 236 | if (fromColLength > toColLength || fromColDigitLength > toColDigitLength) { 237 | if ("db2".equals(toType)) { 238 | sb.append(String.format("alter table %s.%s alter column %s set data type decimal(%d,%d);", 239 | toSchema, toTable, toColName, fromColLength, fromColDigitLength)); 240 | } else if ("mysql".equals(toType) || "oracle".equals(toType)) { 241 | sb.append(String.format("alter table %s.%s modify column %s decimal(%d,%d);", toSchema, toTable, 242 | toColName, fromColLength, fromColDigitLength)); 243 | } else if ("postgres".equals(toType)) { 244 | sb.append(String.format("alter table %s.%s alter column %s type decimal(%d,%d);", toSchema, 245 | toTable, toColName, fromColLength, fromColDigitLength)); 246 | } else{ 247 | sb.append(String.format("alter table %s.%s alter column %s type decimal(%d,%d);", toSchema, 248 | toTable, toColName, fromColLength, fromColDigitLength)); 249 | } 250 | 251 | } 252 | } 253 | } 254 | 255 | // 自动增加字段,以原表为主 256 | while (fromIterator.hasNext()) { 257 | Entry> fromEntry = fromIterator.next(); 258 | String fromColName = fromEntry.getKey(); 259 | HashMap fromMap = fromEntry.getValue(); 260 | HashMap toMap = toColMap.get(fromColName); 261 | 262 | if (toMap == null) { 263 | String typeName = (String) fromMap.get("TYPE_NAME"); 264 | Integer colType = (Integer) fromMap.get("DATA_TYPE"); 265 | Integer fromColLength = (Integer) fromMap.get("COLUMN_SIZE"); 266 | Integer fromColDigitLength = (Integer) fromMap.get("DECIMAL_DIGITS"); 267 | switch (colType) { 268 | case Types.CHAR: 269 | case Types.VARCHAR: 270 | sb.append(String.format("alter table %s.%s add column %s varchar(%d);", toSchema, toTable, 271 | fromColName, fromColLength * colSizeTimes.getTimes())); 272 | break; 273 | case Types.DECIMAL: 274 | sb.append(String.format("alter table %s.%s add column %s decimal(%d,%d);", toSchema, toTable, 275 | fromColName, fromColLength, fromColDigitLength)); 276 | break; 277 | default: 278 | sb.append(String.format("alter table %s.%s add column %s %s;", toSchema, toTable, fromColName, 279 | typeName)); 280 | } 281 | } 282 | 283 | } 284 | return sb.toString(); 285 | 286 | } 287 | 288 | public static void printHelp() { 289 | System.out.println( 290 | "Usage: \njava -jar database-sync-1.0.jar [options] {fromDB} {fromSchema} {fromTable} {toDB} {toSchema} {toTable} [whereClause]"); 291 | System.out.println("options:"); 292 | System.out.println(" -v or --version :print version then exit"); 293 | System.out.println(" -h or --help :print help info then exit"); 294 | System.out.println(" -sd or --sync-ddl :auto synchronize table structure"); 295 | System.out.println(" -ff=col1,col2 or --from-fields=col1,col2 :specify from fields"); 296 | System.out.println(" -tf=col3,col4 or --to-fields=col3,col4 :specify to fields"); 297 | System.out.println(" --no-feature or -nf :will not use database's feature"); 298 | 299 | } 300 | 301 | public static void main(String[] args) throws ClassNotFoundException, IOException, SQLException { 302 | App app = new App(); 303 | if(!app.handleCommandLineArgs(args)){ 304 | return; 305 | } 306 | 307 | String currentPath = System.getProperty("user.dir"); 308 | logger.info("current path: " + currentPath); 309 | logger.info( 310 | String.format("begin (%s)%s.%s -> (%s)%s.%s", app.getFromDBId(), app.getFromSchema(), app.getFromTable(), app.getToDbId(), app.getToSchema(), app.getToTable())); 311 | 312 | Config configFrom = Config.getInstance(app.getFromDBId()); 313 | Config configTo = Config.getInstance(app.getToDbId()); 314 | 315 | try { 316 | 317 | //读取都采用默认的 jdbc 318 | DataBaseSync fromDataBase = DataBaseSyncFactory.getInstance(configFrom, false); 319 | 320 | //写入的话,可以根据传入参数,决定是否优先使用数据库具体特性 321 | DataBaseSync toDataBase = DataBaseSyncFactory.getInstance(configTo,app.getIsSpecificFeture()); 322 | 323 | List fromColumnNames = new ArrayList<>(); 324 | List toColumnNames = new ArrayList<>(); 325 | 326 | // 原表必须存在 327 | if (!fromDataBase.existsTable(app.getFromSchema(), app.getFromTable())) { 328 | logger.info(String.format("fromTable -> (%s) %s.%s not exists! Program exit.", app.getFromDBId(), app.getFromSchema(), 329 | app.getFromTable())); 330 | return; 331 | } 332 | 333 | if (!app.getIsSyncTableDDL()) { 334 | // 如果不同步表结构,那么目标表必须存在 335 | if (!toDataBase.existsTable(app.getToSchema(), app.getToTable())) { 336 | logger.info( 337 | String.format("toTable -> (%s) %s.%s not exists! Program exit.", app.getToDbId(), app.getToSchema(), app.getToTable())); 338 | return; 339 | } 340 | 341 | if(app.getToTableFields().size() > 0) { 342 | // 如果指定目标列,则使用目标列,不指定则自动获取 343 | toColumnNames = app.getToTableFields(); 344 | } else { 345 | toColumnNames = toDataBase.getTableColumns(app.getToSchema(), app.getToTable()); 346 | } 347 | 348 | if (app.getFromTableFields().size() > 0) { 349 | // 如果指定源列,则使用源列,不指定则使用目标列 350 | fromColumnNames = app.getFromTableFields(); 351 | } else { 352 | fromColumnNames = toColumnNames; 353 | } 354 | 355 | ResultSet rs = fromDataBase.readData(app.getFromSchema(), app.getFromTable(), fromColumnNames, app.getWhereClause()); 356 | toDataBase.writeData(app.getToSchema(), app.getToTable(), toColumnNames, rs, app.getWhereClause()); 357 | logger.info(String.format("finished (%s)%s.%s -> (%s)%s.%s", app.getFromDBId(), app.getFromSchema(), app.getFromTable(), app.getToDbId(), 358 | app.getToSchema(), app.getToTable())); 359 | return; 360 | } 361 | 362 | ColSizeTimes colTimes = "gbk".equals(configFrom.getEncoding()) && "utf-8".equals(configTo.getEncoding()) ? ColSizeTimes.DOUBLE : ColSizeTimes.EQUAL; 363 | 364 | if (colTimes != ColSizeTimes.EQUAL) { 365 | //提示字段长度扩大了 366 | logger.info( 367 | String.format("The varchar column length of target table is %d times that of the source table", 368 | colTimes.getTimes())); 369 | } 370 | 371 | if (!toDataBase.existsTable(app.getToSchema(), app.getToTable())) { 372 | // 目标表不存在,先创建 373 | logger.info(String.format("toTable -> (%s) %s.%s not exists, create it.", app.getToDbId(), app.getToSchema(), app.getToTable())); 374 | String ddl = fromDataBase.getDDL(app.getToDbId(), app.getFromSchema(), app.getFromTable(), colTimes); 375 | try { 376 | toDataBase.createTable(app.getToSchema(), app.getToTable(), ddl); 377 | } catch (SQLException e) { 378 | e.printStackTrace(); 379 | } 380 | 381 | } else { 382 | 383 | // 目标表存在,判断同名字段长度是否一致 384 | ResultSet fromColMeta = fromDataBase.getColMetaData(app.getFromSchema(),app.getFromTable()); 385 | ResultSet toColMeta = toDataBase.getColMetaData(app.toSchema, app.toTable); 386 | /* 同步扩充字段长度 */ 387 | String alterSql = getAlterSqlFromMetaData(configTo.getDbType(),app.toSchema, app.toTable, fromColMeta, toColMeta, colTimes); 388 | String[] alterSqlArray = alterSql.split(";"); 389 | for (int i = alterSqlArray.length - 1; i >= 0; i--) { 390 | String sql = alterSqlArray[i]; 391 | if (!sql.isEmpty()) { 392 | logger.info(sql); 393 | try { 394 | toDataBase.executeUpdateSQL(sql); 395 | } catch (Exception e) { 396 | e.printStackTrace(); 397 | } 398 | } 399 | } 400 | } 401 | 402 | if (app.getToTableFields().size() > 0) { 403 | // 如果指定目标列,则使用目标列,不指定则自动获取 404 | toColumnNames = app.getToTableFields(); 405 | } else { 406 | toColumnNames = toDataBase.getTableColumns(app.getToSchema(),app.getToTable()); 407 | } 408 | 409 | if (app.getFromTableFields().size() > 0) { 410 | // 如果指定源列,则使用源列,不指定则 使用目标列 411 | fromColumnNames = app.getFromTableFields(); 412 | } else { 413 | fromColumnNames = toColumnNames; 414 | } 415 | 416 | ResultSet rs = fromDataBase.readData(app.getFromSchema(), app.getFromTable(), fromColumnNames, app.getWhereClause()); 417 | toDataBase.writeData(app.getToSchema(), app.getToTable(), toColumnNames, rs, app.getWhereClause()); 418 | logger.info(String.format("finished (%s)%s.%s -> (%s)%s.%s", app.getFromDBId(), app.getFromSchema(), app.getFromTable(), app.getToDbId(), app.getToSchema(), 419 | app.getToTable())); 420 | } finally { 421 | 422 | 423 | } 424 | } 425 | } 426 | -------------------------------------------------------------------------------- /src/main/java/com/data/database/Config.java: -------------------------------------------------------------------------------- 1 | package com.data.database; 2 | import com.alibaba.fastjson.JSON; 3 | import com.alibaba.fastjson.JSONObject; 4 | import java.util.HashMap; 5 | import com.data.database.utils.Tools; 6 | 7 | public class Config{ 8 | 9 | private String jdbcDriver; 10 | private String dbUrl; 11 | private String userName; 12 | private String password; 13 | private String dbType; 14 | private String encoding; 15 | private Integer bufferRows; 16 | private String tbspaceDDL; 17 | 18 | private static HashMap instanceMap = new HashMap<>(); 19 | 20 | /* 21 | db_identifier 是 config.json 中的数据库的标识符,如样例配置文件中的 "mysql_test" 22 | */ 23 | private Config(String db_identifier){ 24 | 25 | JSONObject jobj = JSON.parseObject(Tools.readJsonFile("./config/config.json")); 26 | this.jdbcDriver = jobj.getJSONObject(db_identifier).getString("driver"); 27 | this.dbUrl = jobj.getJSONObject(db_identifier).getString("url"); 28 | this.userName = jobj.getJSONObject(db_identifier).getString("user"); 29 | this.password = jobj.getJSONObject(db_identifier).getString("password"); 30 | this.dbType = jobj.getJSONObject(db_identifier).getString("type"); 31 | this.encoding = jobj.getJSONObject(db_identifier).getString("encoding"); 32 | this.tbspaceDDL = jobj.getJSONObject(db_identifier).getString("tbspace_ddl"); 33 | this.bufferRows = (Integer) jobj.getOrDefault("buffer-rows", 100000); 34 | 35 | } 36 | 37 | 38 | //让配置类成为例类,每个数据库的配置信息在内存只保留一份 39 | 40 | public static synchronized Config getInstance(String db_identifier){ 41 | Config instance; 42 | if(instanceMap.containsKey(db_identifier)){ 43 | instance = instanceMap.get(db_identifier); 44 | }else{ 45 | instance = new Config(db_identifier); 46 | instanceMap.put(db_identifier,instance); 47 | } 48 | return instance; 49 | } 50 | 51 | public String getJdbcDriver(){ 52 | return this.jdbcDriver; 53 | } 54 | public String getDbUrl(){ 55 | return this.dbUrl; 56 | } 57 | public String getUserName(){ 58 | return this.userName; 59 | } 60 | 61 | public String getPassword(){ 62 | return this.password; 63 | } 64 | 65 | public String getDbType(){ 66 | return this.dbType; 67 | } 68 | 69 | public String getEncoding(){ 70 | return this.encoding == null ? "utf-8":this.encoding; 71 | } 72 | 73 | public Integer getBufferRows(){ 74 | return this.bufferRows; 75 | } 76 | 77 | public String getTbspaceDDL(){ 78 | return this.tbspaceDDL == null? "": this.tbspaceDDL; 79 | } 80 | 81 | } -------------------------------------------------------------------------------- /src/main/java/com/data/database/api/DataSync.java: -------------------------------------------------------------------------------- 1 | package com.data.database.api; 2 | 3 | import java.sql.SQLException; 4 | import java.io.IOException; 5 | import java.sql.ResultSet; 6 | 7 | import com.data.database.api.MyEnum.ColSizeTimes; 8 | import java.util.List; 9 | 10 | 11 | /* 12 | 数据库表同步接口 13 | 只要实现了下述方法就可以实现同步 14 | */ 15 | public interface DataSync { 16 | 17 | /* 18 | 获取一个表的列名,用于 readData 时指定一个表的字段,之所以不使用 * 是因为源数据库表的字段有可能新增, 19 | 也可以用于表结构的自动同步:当目标表的字段数少于源表时,对目标表自动执行 alter table add columns xxx 20 | */ 21 | public List getTableColumns(String schemaName,String tableName) throws SQLException ; 22 | 23 | /*判断一个表是否存在*/ 24 | public boolean existsTable(String schemaName,String tableName) throws SQLException; 25 | 26 | 27 | /** 28 | * 获取一个表的 DDL 语句,用于在目标数据库创建表, 29 | * 这个类演示了文档注释 30 | * @param lenSize 用于将char 类型的字段长度扩大 lenSize 倍,如 gbk-》utf8 需要扩 1.5 倍 31 | * @param targetDBIdentifier : 配置文件中目标数据库的标识符 32 | * @version 1.2 33 | */ 34 | public String getDDL(String targetDBIdentifier ,String schemaName,String tableName,ColSizeTimes lenSize) throws SQLException; 35 | 36 | /*获取一个表的数据,采用流式读,可以提供 whereClause 表示增量读取 ,如果 whereClause 为空,表示全量读取*/ 37 | public ResultSet readData(String schemaName, String tableName,List columnNames,String whereClause) throws SQLException ; 38 | 39 | /* 将 ResultSet 类型的数据定入一张表,写入成功返回 true,否则返回 false*/ 40 | 41 | public boolean writeData(String schemaName, String tableName,List columnNames, ResultSet rs, String whereClause) throws IOException, SQLException ; 42 | 43 | /* 执行提供的 ddl 建表*/ 44 | public boolean createTable(String schemaName, String tableName,String ddl) throws SQLException; 45 | 46 | } -------------------------------------------------------------------------------- /src/main/java/com/data/database/api/MyEnum.java: -------------------------------------------------------------------------------- 1 | package com.data.database.api; 2 | 3 | public class MyEnum { 4 | public enum ColSizeTimes{ 5 | 6 | EQUAL(1),DOUBLE(2); 7 | private int times = 0; 8 | // 定义一个带参数的构造器,枚举类的构造器只能使用 private 修饰 9 | private ColSizeTimes(int times) { 10 | this.times = times; 11 | } 12 | public int getTimes(){ 13 | return times; 14 | } 15 | }; 16 | 17 | } -------------------------------------------------------------------------------- /src/main/java/com/data/database/api/impl/DataBaseSync.java: -------------------------------------------------------------------------------- 1 | package com.data.database.api.impl; 2 | 3 | import com.data.database.Config; 4 | import com.data.database.api.DataSync; 5 | 6 | import java.io.IOException; 7 | import java.net.SecureCacheResponse; 8 | import java.sql.Connection; 9 | import java.sql.SQLException; 10 | import java.sql.ResultSet; 11 | import java.sql.Types; 12 | import java.sql.DriverManager; 13 | import java.sql.PreparedStatement; 14 | import java.sql.DatabaseMetaData; 15 | 16 | import java.util.List; 17 | import java.util.Objects; 18 | import java.util.ArrayList; 19 | import java.util.HashMap; 20 | 21 | import com.google.common.base.Joiner; 22 | import com.data.database.utils.Tools; 23 | import com.data.database.api.MyEnum.ColSizeTimes; 24 | 25 | import org.apache.logging.log4j.Logger; 26 | import org.apache.logging.log4j.LogManager; 27 | 28 | public class DataBaseSync implements DataSync { 29 | 30 | /* 31 | * 获取一个表的列名,用于 readData 时指定一个表的字段,之所以不使用 * 是因为源数据库表的字段有可能新增, 32 | * 也可以用于表结构的自动同步:当目标表的字段数少于源表时,对目标表自动执行 alter table add columns xxx 33 | */ 34 | protected final String jdbcDriver; 35 | protected final String dbUrl; 36 | // 数据库的用户名与密码,需要根据自己的设置 37 | protected final String dbUser; 38 | protected final String dbPass; 39 | protected Connection dbConn; 40 | protected final String dbType; 41 | protected final Logger logger = LogManager.getLogger(DataBaseSync.class); 42 | protected final Integer bufferRows; 43 | 44 | protected HashMap mysqlMap = new HashMap<>(); 45 | 46 | protected final HashMap db2Map = new HashMap<>(); 47 | 48 | protected final HashMap oracleMap = new HashMap<>(); 49 | 50 | protected final HashMap postgresqlMap = new HashMap<>(); 51 | 52 | protected final HashMap sqlserverMap = new HashMap<>(); 53 | 54 | 55 | public DataBaseSync(final String dbType, final String jdbcDriver, final String dbUrl, final String dbUser, 56 | final String dbPass, final Integer bufferRows) throws SQLException, ClassNotFoundException { 57 | this.dbType = dbType; 58 | this.jdbcDriver = jdbcDriver; 59 | this.dbUrl = dbUrl; 60 | this.dbUser = dbUser; 61 | this.dbPass = dbPass; 62 | Class.forName(this.jdbcDriver); 63 | if (this.jdbcDriver.equals("com.ibm.db2.jcc.DB2Driver")) { 64 | //ERROR Code=-4220 and SQLSTATE= null 65 | //https://stackoverflow.com/questions/42623220/error-code-4220-and-sqlstate-null 66 | System.setProperty("db2.jcc.charsetDecoderEncoder", "3"); 67 | } 68 | this.dbConn = DriverManager.getConnection(this.dbUrl, this.dbUser, this.dbPass); 69 | if ("oracle.jdbc.driver.OracleDriver".equals(this.jdbcDriver)) { 70 | // 设置oracle的事务级别 71 | } else { 72 | // oracle 不支持脏读 73 | this.dbConn.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);// 读未提交 74 | } 75 | this.bufferRows = bufferRows; 76 | logger.info(this.dbUrl + " connection establied."); 77 | 78 | //以下为 java.sql.types 到各数据库类型的映射关系,可以添加其他类型。 79 | 80 | mysqlMap.put("BINARY","TINYBLOB"); 81 | mysqlMap.put("BIT",""); 82 | mysqlMap.put("LONGVARBINARY","MEDIUMBLOB"); 83 | mysqlMap.put("LONGVARCHAR","TEXT"); 84 | mysqlMap.put("REAL","FLOAT"); 85 | mysqlMap.put("VARBINARY",""); 86 | mysqlMap.put("INT","INTEGER"); 87 | 88 | db2Map.put("BIT",""); 89 | db2Map.put("LONGVARBINARY","BLOB"); 90 | db2Map.put("LONGVARCHAR","CLOB"); 91 | db2Map.put("REAL","REAL"); 92 | db2Map.put("TINYINT","SMALLINT"); 93 | db2Map.put("TEXT","CLOB"); 94 | db2Map.put("INT","INTEGER"); 95 | 96 | 97 | oracleMap.put("BIGINT","NUMBER"); 98 | oracleMap.put("BINARY","RAW"); 99 | oracleMap.put("DECIMAL","NUMBER"); 100 | oracleMap.put("FLOAT","FLOAT"); 101 | oracleMap.put("LONGVARBINARY","LONG RAW "); 102 | oracleMap.put("LONGVARCHAR","TEXT"); 103 | oracleMap.put("TIME","DATE"); 104 | oracleMap.put("TIMESTAMP","DATE"); 105 | oracleMap.put("TINYINT","TINYINT"); 106 | oracleMap.put("VARBINARY","RAW"); 107 | 108 | 109 | postgresqlMap.put("BINARY",""); 110 | postgresqlMap.put("BIT",""); 111 | postgresqlMap.put("LONGVARBINARY",""); 112 | postgresqlMap.put("LONGVARCHAR","TEXT"); 113 | postgresqlMap.put("VARBINARY",""); 114 | postgresqlMap.put("INT UNSIGNED","INT"); 115 | 116 | sqlserverMap.put("BINARY",""); 117 | sqlserverMap.put("BIT",""); 118 | sqlserverMap.put("LONGVARBINARY",""); 119 | sqlserverMap.put("LONGVARCHAR","TEXT"); 120 | sqlserverMap.put("VARBINARY",""); 121 | 122 | } 123 | 124 | public String convertColumnType(String dbType, String colType) { 125 | if (dbType.equals("postgres")) { 126 | return postgresqlMap.getOrDefault(colType,colType); 127 | } else if (dbType.equals("db2")) { 128 | return db2Map.getOrDefault(colType,colType); 129 | } else if (dbType.equals("oracle")) { 130 | return oracleMap.getOrDefault(colType,colType); 131 | } else if(dbType.equals("mysql")){ 132 | return mysqlMap.getOrDefault(colType,colType); 133 | }else{ 134 | return colType; 135 | } 136 | 137 | } 138 | 139 | public ResultSet getColMetaData(String schemaName, String tableName) throws SQLException { 140 | // to do 如果源表与目标表不一致,则以愿表为准,修改目标表: 141 | // 用于 扩字段长度,增加字段,删除字段,修改字段类型。 142 | /* 由于 mysql postgres 数据库大小写是区分的,因此这里不做任何统一转换,自行控制输入参数大小写*/ 143 | 144 | String tableCatalog = null; 145 | if (this.dbType.equals("mysql")) { 146 | tableCatalog = schemaName; 147 | } 148 | DatabaseMetaData metaData = this.dbConn.getMetaData(); 149 | ResultSet resultSet = metaData.getColumns(tableCatalog, schemaName, tableName, null); 150 | return resultSet; 151 | 152 | } 153 | 154 | public List getColumnTypes(String schemaName, String tableName) throws SQLException { 155 | List colTypes = new ArrayList<>(); 156 | String tableCatalog = null; 157 | if(schemaName.equals("null")){ 158 | schemaName = null; 159 | } 160 | if (this.dbType.equals("mysql")) { 161 | tableCatalog = schemaName; 162 | } 163 | DatabaseMetaData metaData = this.dbConn.getMetaData(); 164 | ResultSet resultSet = metaData.getColumns(tableCatalog, schemaName, tableName, null); 165 | while (resultSet.next()) { 166 | colTypes.add(resultSet.getInt(5)); 167 | } 168 | return colTypes; 169 | 170 | } 171 | 172 | public List getTableColumns(String schemaName, String tableName) throws SQLException { 173 | logger.info(String.format("get table columns from %s.%s ", schemaName, tableName)); 174 | List columnNames = new ArrayList<>(); 175 | DatabaseMetaData metaData = this.dbConn.getMetaData(); 176 | 177 | if(schemaName.equals("null")){ 178 | schemaName = null; 179 | } 180 | 181 | String tableCatalog = null; 182 | if (this.dbType.equals("mysql")) { 183 | tableCatalog = schemaName; 184 | } 185 | ResultSet resultSet = metaData.getColumns(tableCatalog, schemaName, tableName, null); 186 | while (resultSet.next()) { 187 | // for(int i =0 ;i < 24; i++){ 188 | // System.out.print(resultSet.getObject(i+1)+"\t"); 189 | // } 190 | // System.out.println(""); 191 | columnNames.add(resultSet.getString(4)); 192 | } 193 | return columnNames; 194 | 195 | }; 196 | 197 | /* 判断一个表是否存在 */ 198 | public boolean existsTable(String schemaName, String tableName) throws SQLException { 199 | DatabaseMetaData metaData = this.dbConn.getMetaData(); 200 | /* 由于 mysql postgres 数据库大小写是区分的,因此这里不做任何统一转换,自行控制输入参数大小写*/ 201 | // if (this.dbType.equals("postgres") || this.dbType.equals("elk")) { 202 | // if (schemaName != null) { 203 | // schemaName = schemaName.toLowerCase(); 204 | // } 205 | // if (tableName != null) { 206 | // tableName = tableName.toLowerCase(); 207 | // } 208 | // } else { 209 | // schemaName = schemaName == null ? null : schemaName.toUpperCase(); 210 | // tableName = tableName == null ? null : tableName.toUpperCase(); 211 | // } 212 | 213 | schemaName = schemaName.equals("null") ? null : schemaName; 214 | tableName = tableName.equals("null") ? null : tableName; 215 | ResultSet resultSet = metaData.getTables(null, schemaName, tableName, null); 216 | if (resultSet.next()) { 217 | return true; 218 | } 219 | return false; 220 | 221 | }; 222 | 223 | /* 获取一个表的 DDL 语句,用于在目标数据库创建表 lenSize 默认值 1 224 | 这里传入的 db_identifier 传入的是目标数据库的配置信息,为了获取配置信息中表空间部分的 ddl 225 | */ 226 | public String getDDL(String db_identifier, String schemaName, String tableName, ColSizeTimes lenSize) throws SQLException { 227 | Config config = Config.getInstance(db_identifier); 228 | DatabaseMetaData metaData = this.dbConn.getMetaData(); 229 | // ResultSet tables = metaData.getTables(null, schemaName, null, null); 230 | // while (tables.next()) { 231 | // System.out.println(String.format("%s.%s", tables.getString(2), 232 | // tables.getString(3))); 233 | // } 234 | 235 | StringBuilder sb = new StringBuilder(1024); 236 | StringBuilder sb_remark = new StringBuilder(1024); 237 | String table_remark = ""; 238 | 239 | String tableCatalog = null; 240 | 241 | if(schemaName.equals("null")){ 242 | schemaName = null; 243 | } 244 | ResultSet tbResultset = metaData.getTables(tableCatalog, schemaName, tableName, null); 245 | if (tbResultset.next()) { 246 | table_remark = tbResultset.getString(5); 247 | } 248 | 249 | ResultSet resultSet = metaData.getColumns(tableCatalog, schemaName, tableName, null); 250 | 251 | int i = 0; 252 | ArrayList pks = new ArrayList(); 253 | ResultSet resultSetPKS = metaData.getPrimaryKeys(null, schemaName, tableName); 254 | while (resultSetPKS.next()) { 255 | pks.add(resultSetPKS.getString(4)); 256 | } 257 | 258 | sb.append("create table #tabname#"); 259 | while (resultSet.next()) { 260 | i++; 261 | String colunmName = resultSet.getString(4); 262 | Integer dataType = resultSet.getInt(5); 263 | String columnType = ""; 264 | if(this.dbType.equals(config.getDbType())){ 265 | //说明原数据库与目标数据库一致,不需要任何字段类型转换 266 | columnType = resultSet.getString(6); 267 | } else{ 268 | columnType = convertColumnType(config.getDbType(), resultSet.getString(6)); 269 | 270 | } 271 | Integer columnSize = resultSet.getInt(7); 272 | Integer digitSize = resultSet.getInt(9); 273 | String remark = resultSet.getString(12); 274 | String columnTypeText = ""; 275 | if (columnType.equals("TEXT") || columnType.equals("CLOB") || columnType.equals("BLOB")) { 276 | columnTypeText = columnType; 277 | } else if (dataType == Types.VARCHAR || dataType == Types.CHAR) { 278 | // varchar || char 279 | columnSize = columnSize * lenSize.getTimes(); 280 | columnTypeText = columnType + "(" + columnSize + ")"; 281 | } else if (dataType == Types.DECIMAL || dataType == Types.NUMERIC) { 282 | columnTypeText = columnType + "(" + columnSize + "," + digitSize + ")"; 283 | } else { 284 | columnTypeText = columnType; 285 | } 286 | 287 | if (i == 1) { 288 | sb.append("(\n"); 289 | sb.append(colunmName); 290 | sb.append(" "); 291 | sb.append(columnTypeText); 292 | } else { 293 | sb.append(","); 294 | sb.append(colunmName); 295 | sb.append(" "); 296 | sb.append(columnTypeText); 297 | } 298 | // 如果是主键,则不能为空 299 | if (pks.contains(colunmName)) { 300 | sb.append(" not null"); 301 | } 302 | 303 | if (remark != null) { 304 | remark = remark.replace(";", "|").replace("'", ""); 305 | if (config.getDbType().equals("mysql")) { 306 | // mysql的注释比较特别 307 | sb.append(" comment '" + remark + "'"); 308 | } else { 309 | sb_remark.append("comment on column #tabname#."); 310 | sb_remark.append(colunmName); 311 | sb_remark.append(" is '" + remark + "';\n"); 312 | } 313 | } 314 | 315 | sb.append(" \n"); 316 | } 317 | 318 | sb.append(")"); 319 | 320 | // 添加表空间信息 321 | sb.append(config.getTbspaceDDL()); 322 | 323 | // 添加主键或分区键信息,之所以放在这里是因为某些数据库不支持主键,这里报错不影响建表成功 324 | if (pks.size() > 0) { 325 | sb.append(";\n"); 326 | sb.append("alter table #tabname# add constraint pk_#pk_name# primary key (" + Joiner.on(",").join(pks) 327 | + ")"); 328 | } 329 | 330 | // 统一添加分号结尾 331 | sb.append(";\n"); 332 | // 添加表注释信息 333 | if (table_remark != null && !table_remark.isEmpty()) { 334 | table_remark = table_remark.replace(";", "").replace("'", ""); 335 | if (config.getDbType().equals("mysql")) { 336 | //如果目标数据库是mysql,则如下构造sql 337 | sb.append("alter table #tabname# comment '" + table_remark + "';\n"); 338 | } else { 339 | sb.append("comment on table #tabname# is '" + table_remark + "';\n"); 340 | } 341 | 342 | } 343 | // 添加字段注释信息 344 | sb.append(sb_remark.toString()); 345 | String ddl = sb.toString(); 346 | logger.info(String.format("get ddl from %s.%s ", schemaName, tableName)); 347 | return ddl; 348 | 349 | }; 350 | 351 | /* 获取一个表的数据,采用流式读取,可以提供 whereClause 表示增量读取 ,如果 whereClause 为空,表示全量读取 */ 352 | public ResultSet readData(String schemaName, final String tableName, final List columnNames, 353 | String whereClause) throws SQLException { 354 | this.dbConn.setAutoCommit(false); 355 | logger.info(String.format("read data from %s.%s ", schemaName, tableName)); 356 | final String columns = Joiner.on(", ").join(columnNames); 357 | String selectSql = ""; 358 | if (whereClause == null || whereClause.isEmpty()) { 359 | selectSql = "select " + columns + " from " + schemaName + "." + tableName; 360 | } else { 361 | selectSql = "select " + columns + " from " + schemaName + "." + tableName + " where " + whereClause; 362 | } 363 | logger.info(selectSql); 364 | PreparedStatement pStemt = null; 365 | pStemt = this.dbConn.prepareStatement(selectSql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); 366 | pStemt.setFetchSize(bufferRows + 10000); 367 | final ResultSet rs = pStemt.executeQuery(); 368 | return rs; 369 | 370 | }; 371 | 372 | /* 将 ResultSet 类型的数据定入一张表,写入成功返回 true,否则返回 false */ 373 | public boolean writeData(String schemaName, final String tableName, final List columnNames, ResultSet rs, 374 | final String whereClause) throws IOException, SQLException { 375 | this.dbConn.setAutoCommit(false); 376 | logger.info(String.format("begin insert into %s.%s...", schemaName, tableName)); 377 | String tbName = ""; 378 | String clearSql = ""; 379 | if (schemaName != null && schemaName.length() != 0) { 380 | tbName = schemaName + "." + tableName; 381 | } else { 382 | tbName = tableName; 383 | } 384 | if (whereClause != null && !whereClause.isEmpty()) { 385 | // 如果 whereClause 不为空 386 | clearSql = "delete from " + tbName + " where " + whereClause; 387 | } else { 388 | // 如果 whereClause 为空 389 | clearSql = "truncate table " + tbName; 390 | if (dbType.equals("db2") || dbType.equals("edw")) { 391 | clearSql = clearSql + " immediate"; 392 | } else if (dbType.equals("elk")) { 393 | clearSql = "delete from " + tbName; 394 | } 395 | // 如果是 elk 请修改为 delete from 396 | } 397 | 398 | logger.info(String.format("clear data for %s is begin...", tbName)); 399 | logger.info("clearSql : " + clearSql); 400 | this.dbConn.commit(); 401 | PreparedStatement pStemt = this.dbConn.prepareStatement(clearSql); 402 | pStemt.executeUpdate(); 403 | this.dbConn.commit(); 404 | logger.info(String.format("clear data for %s is done", tbName)); 405 | 406 | List colTypes = this.getColumnTypes(schemaName, tableName); 407 | 408 | final String insertSql = Tools.buildInsertSql(tbName, columnNames.stream().toArray(String[]::new)); 409 | // System.out.println(insertSql); 410 | pStemt = this.dbConn.prepareStatement(insertSql); 411 | // final int numberOfCols = rs.getMetaData().getColumnCount(); 412 | final int numberOfCols = columnNames.size(); 413 | int rowCount = 0; 414 | long totalAffectRows = 0; 415 | long starttime = System.currentTimeMillis(); 416 | while (rs.next()) { 417 | for (int i = 0; i < numberOfCols; i++) { 418 | if (colTypes.get(i) == Types.VARCHAR || colTypes.get(i) == Types.CHAR 419 | || colTypes.get(i) == Types.CLOB) { 420 | pStemt.setString(i + 1, Objects.toString(rs.getString(i + 1), "")); // 将 null 转化为空 421 | } else { 422 | pStemt.setObject(i + 1, rs.getObject(i + 1)); 423 | } 424 | } 425 | pStemt.addBatch(); 426 | rowCount++; 427 | if (rowCount >= bufferRows) { 428 | // 每10万行提交一次记录 429 | int affectRows = 0; 430 | for (int i : pStemt.executeBatch()) { 431 | affectRows += i; 432 | } 433 | this.dbConn.commit(); 434 | logger.info(String.format("rows insert into %s is %d", tbName, affectRows)); 435 | totalAffectRows += affectRows; 436 | rowCount = 0; 437 | } 438 | } 439 | // 处理剩余的记录 440 | int affectRows = 0; 441 | for (int i : pStemt.executeBatch()) { 442 | affectRows += i; 443 | } 444 | this.dbConn.commit(); 445 | logger.info(String.format("rows insert into %s is %d", tbName, affectRows)); 446 | totalAffectRows += affectRows; 447 | rowCount = 0; 448 | long endtime = System.currentTimeMillis(); 449 | logger.info( 450 | String.format("insert into %s %d rows has been completed, cost %.3f seconds", tbName,totalAffectRows,(endtime - starttime) * 1.0 / 1000)); 451 | return true; 452 | }; 453 | 454 | /* 执行提供的 ddl 建表 */ 455 | public boolean createTable(String schemaName, String tableName, String ddl) throws SQLException { 456 | 457 | this.dbConn.setAutoCommit(true); 458 | String newDDL = ""; 459 | if (schemaName == null || schemaName.length() == 0) { 460 | newDDL = ddl.replace("#tabname#", tableName); 461 | } else { 462 | // 针对 postgres 如果模式名不存在,先创建模式名,否则创建表失败。 463 | newDDL = ddl.replace("#tabname#", schemaName + "." + tableName); 464 | } 465 | newDDL = newDDL.replace("#pk_name#", tableName); 466 | logger.info(newDDL); 467 | String[] sqls = newDDL.split(";"); 468 | for (String sql : sqls) { 469 | if (sql.replaceAll("\r|\n|\\s", "").length() > 1) { 470 | //如果是非空的sql语句,那么执行它 471 | PreparedStatement pStemt = this.dbConn.prepareStatement(sql); 472 | pStemt.executeUpdate(); 473 | } 474 | } 475 | return true; 476 | 477 | }; 478 | 479 | public boolean executeUpdateSQL(String sql) throws SQLException { 480 | PreparedStatement pStemt = this.dbConn.prepareStatement(sql); 481 | pStemt.executeUpdate(); 482 | return true; 483 | } 484 | 485 | } -------------------------------------------------------------------------------- /src/main/java/com/data/database/api/impl/DataBaseSyncFactory.java: -------------------------------------------------------------------------------- 1 | package com.data.database.api.impl; 2 | import com.data.database.Config; 3 | import java.util.Map; 4 | import java.sql.SQLException; 5 | 6 | public class DataBaseSyncFactory { 7 | 8 | public static DataBaseSync getInstance(Config config, boolean IsSpecificFeture) throws SQLException,ClassNotFoundException { 9 | DataBaseSync dataBaseSync = null; 10 | if(!IsSpecificFeture){ 11 | return new DataBaseSync(config.getDbType(), config.getJdbcDriver(),config.getDbUrl(),config.getUserName(),config.getPassword(),config.getBufferRows()); 12 | } 13 | else if("postgres".equals(config.getDbType()) ){ 14 | dataBaseSync = new PostgresDataBaseSync(config.getDbType(), config.getJdbcDriver(),config.getDbUrl(),config.getUserName(),config.getPassword(),config.getBufferRows()) ; 15 | }else{ 16 | dataBaseSync = new DataBaseSync(config.getDbType(), config.getJdbcDriver(),config.getDbUrl(),config.getUserName(),config.getPassword(),config.getBufferRows()); 17 | } 18 | return dataBaseSync; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/data/database/api/impl/Db2DataBaseSync.java: -------------------------------------------------------------------------------- 1 | package com.data.database.api.impl; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.IOException; 5 | import java.io.StringReader; 6 | import java.sql.PreparedStatement; 7 | import java.sql.ResultSet; 8 | import java.sql.SQLException; 9 | import java.util.List; 10 | 11 | 12 | public class Db2DataBaseSync extends DataBaseSync { 13 | //在此编写db2特性的代码逻辑 14 | 15 | 16 | public Db2DataBaseSync(String dbType, String jdbcDriver, String dbUrl, String dbUser, String dbPass, 17 | Integer bufferRows) throws SQLException, ClassNotFoundException { 18 | super(dbType, jdbcDriver, dbUrl, dbUser, dbPass, bufferRows); 19 | } 20 | 21 | // @Override 22 | // public boolean writeData(String schemaName, final String tableName, List columnNames, ResultSet rs, 23 | // final String whereClause) { 24 | // //如果 db2 有更好的写入方法,在此实现 25 | 26 | // return true; 27 | 28 | // } 29 | 30 | }; -------------------------------------------------------------------------------- /src/main/java/com/data/database/api/impl/OracleDataBaseSync.java: -------------------------------------------------------------------------------- 1 | package com.data.database.api.impl; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.IOException; 5 | import java.io.StringReader; 6 | import java.sql.PreparedStatement; 7 | import java.sql.ResultSet; 8 | import java.sql.SQLException; 9 | import java.util.List; 10 | 11 | 12 | public class OracleDataBaseSync extends DataBaseSync { 13 | //在此编写db2特性的代码逻辑 14 | 15 | 16 | public OracleDataBaseSync(String dbType, String jdbcDriver, String dbUrl, String dbUser, String dbPass, 17 | Integer bufferRows) throws SQLException, ClassNotFoundException { 18 | super(dbType, jdbcDriver, dbUrl, dbUser, dbPass, bufferRows); 19 | } 20 | 21 | 22 | // @Override 23 | // public boolean writeData(String schemaName, final String tableName, List columnNames, ResultSet rs, 24 | // final String whereClause) { 25 | // //如果 oracle 有更好的写入方法,在此实现 26 | 27 | // return true; 28 | 29 | // } 30 | }; -------------------------------------------------------------------------------- /src/main/java/com/data/database/api/impl/PostgresDataBaseSync.java: -------------------------------------------------------------------------------- 1 | package com.data.database.api.impl; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.IOException; 5 | import java.io.StringReader; 6 | import java.sql.PreparedStatement; 7 | import java.sql.ResultSet; 8 | import java.sql.SQLException; 9 | import java.util.List; 10 | 11 | import org.postgresql.copy.CopyManager; 12 | import org.postgresql.core.BaseConnection; 13 | 14 | public class PostgresDataBaseSync extends DataBaseSync { 15 | 16 | public PostgresDataBaseSync(String dbType, String jdbcDriver, String dbUrl, String dbUser, String dbPass, 17 | Integer bufferRows) throws SQLException, ClassNotFoundException { 18 | super(dbType, jdbcDriver, dbUrl, dbUser, dbPass, bufferRows); 19 | } 20 | 21 | @Override 22 | public boolean writeData(String schemaName, final String tableName, List columnNames, ResultSet rs, 23 | final String whereClause) throws IOException, SQLException { 24 | this.dbConn.setAutoCommit(false); 25 | logger.info(String.format("begin insert into %s.%s...", schemaName, tableName)); 26 | String tbName = ""; 27 | String clearSql = ""; 28 | 29 | if (schemaName != null && schemaName.length() != 0) { 30 | tbName = schemaName + "." + tableName; 31 | } else { 32 | tbName = tableName; 33 | } 34 | 35 | if (whereClause != null && whereClause.length() != 0) { 36 | clearSql = "delete from " + tbName + " where " + whereClause; 37 | } else { 38 | clearSql = "truncate table " + tbName; 39 | if (dbType.equals("db2") || dbType.equals("edw")) { 40 | clearSql = clearSql + " immediate"; 41 | } else if (dbType.equals("elk")) { 42 | clearSql = "delete from " + tbName; 43 | } 44 | // 如果是 elk 请修改为 delete from 45 | } 46 | 47 | logger.info(String.format("clear data for %s is begin...", tbName)); 48 | logger.info("clearSql : " + clearSql); 49 | this.dbConn.commit(); 50 | PreparedStatement pStemt = this.dbConn.prepareStatement(clearSql); 51 | pStemt.executeUpdate(); 52 | this.dbConn.commit(); 53 | logger.info(String.format("clear data for %s is done", tbName)); 54 | 55 | // List colTypes = this.getColumnTypes(schemaName, tableName); 56 | // final int numberOfcols = rs.getMetaData().getColumnCount(); 57 | final int numberOfCols = columnNames.size(); 58 | logger.info("numberOfcols = "+numberOfCols); 59 | // String[] rowArray = new String[numberOfcols]; 60 | int rowCount = 0; 61 | long totalAffectRows = 0; 62 | StringBuilder sBuilder = new StringBuilder(bufferRows); 63 | String copyFromSql = String.format("copy %s (%s) from stdin csv delimiter e'\\x02' quote e'\\x03' escape e'\\x03' ", 64 | tbName,String.join(",",columnNames)); 65 | logger.info("copyFromSql = "+copyFromSql); 66 | long starttime = System.currentTimeMillis(); 67 | while (rs.next()) { 68 | for (int i = 0; i < numberOfCols - 1; i++) { 69 | String col = rs.getString(i+1); 70 | if (col != null) { 71 | //去除字符串中最后的\\ 72 | int col_len = col.length(); 73 | while (col_len > 0 && col.charAt(col_len - 1) == '\\') { 74 | col_len-- ; 75 | } 76 | sBuilder.append((char) 3).append(col.substring(0, col_len)).append((char) 3); 77 | } else { 78 | sBuilder.append(""); 79 | } 80 | sBuilder.append((char) 2); 81 | } 82 | String col = rs.getString(numberOfCols); 83 | if (col != null) { 84 | int col_len = col.length(); 85 | while (col_len > 0 && col.charAt(col_len - 1) == '\\') { 86 | col_len-- ; 87 | } 88 | sBuilder.append((char) 3).append(col.substring(0, col_len)).append((char) 3); 89 | } else { 90 | sBuilder.append(""); 91 | } 92 | sBuilder.append('\n'); 93 | rowCount++; 94 | if (rowCount >= bufferRows) { 95 | // 每10万行提交一次记录 96 | CopyManager copyManager = new CopyManager((BaseConnection) this.dbConn); 97 | // long rowsInserted = copyManager.copyIn("copy " + tbName + " from stdin 98 | // delimiter e'\\x02' NULL as ''", 99 | long rowsInserted = copyManager.copyIn(copyFromSql, 100 | new BufferedReader(new StringReader(sBuilder.toString()))); 101 | this.dbConn.commit(); 102 | // sBuilder.delete(0, sBuilder.length());//清空缓冲区 103 | sBuilder.setLength(0);// 清空缓冲区 104 | logger.info(String.format("rows insert into %s is %d", tbName, rowsInserted)); 105 | totalAffectRows += rowsInserted; 106 | rowCount = 0; 107 | } 108 | } 109 | // 处理剩余的记录 110 | 111 | CopyManager copyManager = new CopyManager((BaseConnection) this.dbConn); 112 | long rowsInserted = copyManager.copyIn(copyFromSql, new BufferedReader(new StringReader(sBuilder.toString()))); 113 | this.dbConn.commit(); 114 | sBuilder.setLength(0);// 清空缓冲区 115 | logger.info(String.format("rows insert into %s is %d", tbName, rowsInserted)); 116 | totalAffectRows += rowsInserted; 117 | this.dbConn.setAutoCommit(true); 118 | long endtime = System.currentTimeMillis(); 119 | logger.info( 120 | String.format("insert into %s %d rows has been completed, cost %.3f seconds", tbName, totalAffectRows,(endtime - starttime) * 1.0 / 1000)); 121 | return true; 122 | }; 123 | 124 | } -------------------------------------------------------------------------------- /src/main/java/com/data/database/utils/Tools.java: -------------------------------------------------------------------------------- 1 | package com.data.database.utils; 2 | import java.io.File; 3 | import java.io.Reader; 4 | import java.io.FileInputStream; 5 | import java.io.IOException; 6 | import java.io.InputStreamReader; 7 | 8 | public class Tools { 9 | public static String buildInsertSql(String table, String[] fields) { 10 | StringBuilder sb = new StringBuilder(); 11 | sb.append("INSERT INTO ").append(table).append(" ("); 12 | sb.append(String.join(", ", fields)); 13 | sb.append(") "); 14 | sb.append("VALUES ("); 15 | for (int i = 0; i < fields.length; i++) { 16 | if (i == fields.length - 1) { 17 | sb.append("?").append(")"); 18 | break; 19 | } 20 | sb.append("?").append(", "); 21 | } 22 | return sb.toString(); 23 | } 24 | 25 | /** 26 | * * 读取json文件,返回json串 27 | * 28 | * @param fileName 29 | * @return 30 | */ 31 | public static String readJsonFile(String fileName) { 32 | String jsonStr = ""; 33 | try { 34 | File jsonFile = new File(fileName); 35 | Reader reader = new InputStreamReader(new FileInputStream(jsonFile), "utf-8"); 36 | int ch = 0; 37 | StringBuffer sb = new StringBuffer(); 38 | while ((ch = reader.read()) != -1) { 39 | sb.append((char) ch); 40 | } 41 | reader.close(); 42 | jsonStr = sb.toString(); 43 | return jsonStr; 44 | } catch (IOException e) { 45 | e.printStackTrace(); 46 | return null; 47 | } 48 | } 49 | 50 | 51 | } -------------------------------------------------------------------------------- /src/main/resources/log4j2.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 17 | 18 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | -------------------------------------------------------------------------------- /src/test/java/com/data/database/AppTest.java: -------------------------------------------------------------------------------- 1 | package com.data.database; 2 | 3 | import org.junit.Test; 4 | import com.data.database.api.DataSync; 5 | import com.data.database.api.impl.DataBaseSync; 6 | import com.data.database.api.MyEnum; 7 | import org.junit.BeforeClass; 8 | import org.junit.AfterClass; 9 | 10 | import static org.junit.Assert.*; 11 | 12 | import java.io.StringWriter; 13 | import java.sql.SQLException; 14 | import java.util.List; 15 | import java.sql.ResultSet; 16 | 17 | /** 18 | * Unit test for simple App. 19 | */ 20 | public class AppTest { 21 | /** 22 | * Rigorous Test. 23 | */ 24 | 25 | @Test 26 | public void testApp(){ 27 | App app = App.getInstance(); 28 | assertTrue(true); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/test/java/com/data/database/ConfigTest.java: -------------------------------------------------------------------------------- 1 | package com.data.database; 2 | 3 | import org.junit.Test; 4 | import static org.junit.Assert.*; 5 | 6 | public class ConfigTest{ 7 | 8 | @Test 9 | public void testSingle(){ 10 | Config config1 = Config.getInstance("mysql_test"); 11 | Config config2 = Config.getInstance("mysql_test"); 12 | assertTrue(config1 == config2); 13 | } 14 | 15 | @Test 16 | public void testOutput(){ 17 | Config config1 = Config.getInstance("mysql_test"); 18 | assertTrue(config1.getBufferRows() >= 1000); 19 | } 20 | 21 | 22 | } -------------------------------------------------------------------------------- /src/test/java/com/data/database/DataBaseSyncTest.java: -------------------------------------------------------------------------------- 1 | package com.data.database; 2 | 3 | import org.junit.Test; 4 | import static org.junit.Assert.*; 5 | 6 | import java.sql.SQLException; 7 | 8 | import com.data.database.api.MyEnum.ColSizeTimes; 9 | import com.data.database.api.impl.DataBaseSync; 10 | 11 | public class DataBaseSyncTest { 12 | 13 | @Test 14 | public void testGetDDL() throws SQLException, ClassNotFoundException{ 15 | Config config = Config.getInstance("mysql_test"); 16 | // DataBaseSync dbs = new DataBaseSync(config.getDbType(),config.getJdbcDriver(), config.getDbUrl(), config.getUserName(),config.getPassword(),config.getBufferRows()); 17 | // String ddl = dbs.getDDL("mysql_test", "mysql", "users", ColSizeTimes.EQUAL); 18 | // System.out.print(ddl); 19 | assertTrue(true); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /start_docker.md: -------------------------------------------------------------------------------- 1 | # docker 容器操作 2 | 3 | 4 | ## mysql 容器 5 | 6 | 启动 mysql 服务,数据保存在本地卷 database-sync,连接网络 database-sync,先创建网络 database-sync 7 | 8 | ```sh 9 | docker run -d --name mysql \ 10 | --network database-sync \ 11 | --network-alias mysql \ 12 | -v database-sync:/var/lib/mysql \ 13 | -e MYSQL_ROOT_PASSWORD=root \ 14 | -e MYSQL_DATABASE=testdb \ 15 | mysql:latest 16 | ``` 17 | 18 | 进入 mysql 容器内部环境,可查询数据 19 | 20 | ```sh 21 | docker exec -it mysql env LANG=C.UTF-8 /bin/bash 22 | ``` 23 | 24 | 25 | ## postgres 容器 26 | 27 | 启动 postgres 服务 28 | 29 | ```sh 30 | docker run -d --name postgres \ 31 | --network database-sync \ 32 | --network-alias postgres \ 33 | -e POSTGRES_PASSWORD=root \ 34 | postgres:latest 35 | ``` 36 | 37 | 进入 posgres 容器内部: 38 | 39 | ```sh 40 | docker exec -it postgres /bin/bash 41 | ``` 42 | 43 | 44 | 45 | ## 启动 database-sync app 容器,连接到 database-sync 网络上 46 | 47 | ```sh 48 | docker run -it --name app \ 49 | --network database-sync \ 50 | -v "$(pwd)/target:/app/release" \ 51 | java:latest \ 52 | /bin/bash 53 | ``` 54 | 55 | 挂载 target 目录到 java 容器,jar 文件更新后,直接生效,方便 debug。 56 | 57 | 58 | eg: mysql 向 postgre 同步表结构及数据: 59 | 60 | ```sh 61 | java -jar database-sync-1.3.jar mysql_test testdb somenzz_users postgres_test public users -sd -nf 62 | ``` 63 | 64 | 65 | --------------------------------------------------------------------------------