diff --git a/.gitignore b/.gitignore index 0e4701a8c..de7837a7b 100644 --- a/.gitignore +++ b/.gitignore @@ -21,6 +21,8 @@ java_pid* # InteliJ IDEA *.iml +.idea_modules/ +.idea/ # sbt specific dist/* @@ -35,7 +37,3 @@ project/plugins/project/ # MacOS X specific .DS_Store - -#InteliJ -.idea_modules/ -.idea/ diff --git a/.travis.yml b/.travis.yml index 36934f745..0f2f9649a 100644 --- a/.travis.yml +++ b/.travis.yml @@ -32,6 +32,11 @@ jdk: - oraclejdk7 - oraclejdk8 +matrix: + include: + - scala: 2.12.0 + jdk: oraclejdk8 + addons: apt: packages: @@ -39,7 +44,7 @@ addons: before_install: unset SBT_OPTS JVM_OPTS -before_script: travis_retry sbt ++$TRAVIS_SCALA_VERSION update +before_script: travis_retry sbt "plz $TRAVIS_SCALA_VERSION update" install: - pip install 'requests[security]' diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2e99564ac..b2f953811 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,6 +1,6 @@ -phantom [![Build Status](https://travis-ci.org/websudos/phantom.svg?branch=develop)](https://travis-ci.org/websudos/phantom) - -============== +phantom +[![Build Status](https://travis-ci.org/outworkers/phantom.svg?branch=develop)](https://travis-ci.org/outworkers/phantom) [![Coverage Status](https://coveralls.io/repos/outworkers/phantom/badge.svg)](https://coveralls.io/r/outworkers/phantom) [![Codacy Rating](https://api.codacy.com/project/badge/grade/25bee222a7d142ff8151e6ceb39151b4)](https://www.codacy.com/app/flavian/phantom_2) [![Maven Central](https://maven-badges.herokuapp.com/maven-central/com.outworkers/phantom-dsl_2.11/badge.svg)](https://maven-badges.herokuapp.com/maven-central/com.outworkers/phantom-dsl_2.11) [![Bintray](https://api.bintray.com/packages/websudos/oss-releases/phantom-dsl/images/download.svg) ](https://bintray.com/websudos/oss-releases/phantom-dsl/_latestVersion) [![ScalaDoc](http://javadoc-badge.appspot.com/com.outworkers/phantom-dsl_2.11.svg?label=scaladoc)](http://javadoc-badge.appspot.com/com.outworkers/phantom-dsl_2.11) [![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/outworkers/phantom?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) +=============================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================== Reactive type-safe Scala DSL for Cassandra - Contributing to phantom diff --git a/LICENSE.txt b/LICENSE.txt index df8abc4cd..e68e6104d 100644 --- a/LICENSE.txt +++ b/LICENSE.txt @@ -1,33 +1,201 @@ -/* - * Copyright 2013-2016 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Redistributions of source code for the purpose of contribution to the source - * are wholly permitted via all available channels. - * - * - Redistributions in binary form to sources other than the official ones - * are only permitted with our explicit written consent. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {2013 - 2017} {outworkers ltd. "outworkers" is a registered trademark of outworkers ltd, Park Mansions Knightsbridge, London SW1X 7QT, United Kingdom} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md index faf4c38c5..5b5dc9f2a 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ phantom -[![Build Status](https://travis-ci.org/outworkers/phantom.svg?branch=develop)](https://travis-ci.org/outworkers/phantom) [![Coverage Status](https://coveralls.io/repos/outworkers/phantom/badge.svg)](https://coveralls.io/r/outworkers/phantom) [![Codacy Rating](https://api.codacy.com/project/badge/grade/25bee222a7d142ff8151e6ceb39151b4)](https://www.codacy.com/app/flavian/phantom_2) [![Maven Central](https://maven-badges.herokuapp.com/maven-central/com.websudos/phantom-dsl_2.11/badge.svg)](https://maven-badges.herokuapp.com/maven-central/com.websudos/phantom-dsl_2.11) [![Bintray](https://api.bintray.com/packages/websudos/oss-releases/phantom-dsl/images/download.svg) ](https://bintray.com/websudos/oss-releases/phantom-dsl/_latestVersion) [![ScalaDoc](http://javadoc-badge.appspot.com/com.websudos/phantom-dsl_2.11.svg?label=scaladoc)](http://javadoc-badge.appspot.com/com.websudos/phantom-dsl_2.11) [![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/outworkers/phantom?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) +[![Build Status](https://travis-ci.org/outworkers/phantom.svg?branch=develop)](https://travis-ci.org/outworkers/phantom) [![Coverage Status](https://coveralls.io/repos/outworkers/phantom/badge.svg)](https://coveralls.io/r/outworkers/phantom) [![Codacy Rating](https://api.codacy.com/project/badge/grade/25bee222a7d142ff8151e6ceb39151b4)](https://www.codacy.com/app/flavian/phantom_2) [![Maven Central](https://maven-badges.herokuapp.com/maven-central/com.outworkers/phantom-dsl_2.11/badge.svg)](https://maven-badges.herokuapp.com/maven-central/com.outworkers/phantom-dsl_2.11) [![Bintray](https://api.bintray.com/packages/outworkers/oss-releases/phantom-dsl/images/download.svg) ](https://bintray.com/outworkers/oss-releases/phantom-dsl/_latestVersion) [![ScalaDoc](http://javadoc-badge.appspot.com/com.outworkers/phantom-dsl_2.11.svg?label=scaladoc)](http://javadoc-badge.appspot.com/com.outworkers/phantom-dsl_2.11) [![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/outworkers/phantom?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) =============================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================== Reactive type-safe Scala driver for Apache Cassandra/Datastax Enterprise @@ -11,17 +11,64 @@ phantom is and will always be [freeware](https://en.wikipedia.org/wiki/Freeware) ![phantom](https://s3-eu-west-1.amazonaws.com/websudos/oss/logos/phantom.png "Outworkers Phantom") +2.0.0 Migration guide +===================== + +- The OSS version of phantom has as of 2.0.0 returned to the Apache V2 license and the license is here to stay. +- All packages and dependencies are now available under the `com.outworkers` organisation instead of `com.websudos`. As +part of long term re-branding efforts, we have finally felt it's time to make sure the change is consistent throughout. +- There is a new and now completely optional Bintray resolver, `Resolver.bintrayRepo("outworkers", "oss-releases")`, + that gives you free access to the latest cuts of our open source releases before they hit Maven Central. We assume + no liability for your usage of latest cuts, but we welcome feedback and we do our best to have elaborate CI processes in place. +- Manually defining a `fromRow` inside a `CassandraTable` is no longer required if your column types match your case class types. +- `EnumColumn` is now relying entirely on `Primitive.macroImpl`, which means you will not need to pass in the enumeration +as an argument to `EnumColumn` anymore. This means `object enum extends EnumColumn(this, enum: MyEnum)` is now simply +`object enum extends EnumColumn[MyEnum#Value](this)` +- All dependencies are now being published to Maven Central. This includes outworkers util and outworkers diesel, +projects which have in their own right been completely open sourced under Apache V2 and made public on GitHub. +- All dependencies on `scala-reflect` have been completely removed. +- A new, macro based mechanism now performs the same auto-discovery task that reflection used to, thanks to `macro-compat`. +- Index modifiers no longer require a type parameter, `PartitionKey`, `PrimaryKey`, `ClusteringOrder` and `Index` don't require +the column type passed anymore. +- `KeySpaceDef` has been renamed to the more appropiate ` +CassandraConnector`. +- `CassandraConnector` now natively supports specifying a keyspace creation query. +- `TimeWindowCompactionStrategy` is now natively supported in the CREATE/ALTER dsl. +- Collections can now be used as part of a primary or partition key. +- Tuples are now natively supported as valid types via `TupleColumn`. +- `phantom-reactivestreams` is now simply called `phantom-streams`. +- `Database.autocreate` and `Database.autotruncate` are now no longer accessible. Use `create`, `createAsync`, `truncate` and `truncateAsync` instead. +- `Database` now requires an f-bounded type argument: `class MyDb(override val connector: CassandraConnection) extends Database[MyDb](connector)`. +- Automated Cassandra pagination via paging states has been moved to a new method called `paginateRecord`. Using `fetchRecord` with a `PagingState` is no longer possible. +This is done to distinguish the underlying consumer mechanism of parsing and fetching records from Cassandra. + + +Available modules +================= + +This is a table of the available modules for the various Scala versions. Not all modules are available for all versions just yet, and this is because certain dependencies have yet to be published for Scala 2.12. + +| Module name | Scala 2.10.x | Scala 2.11.x | Scala 2.12.0 | +| ------------ | ------------------- | ------------------| ----------------- | +| phantom-connectors | yes | yes | yes | +| phantom-dsl | yes | yes | yes | +| phantom-jdk8 | yes | yes | yes | +| phantom-sbt | yes | no | no | +| phantom-example | yes | yes | no | +| phantom-thrift | yes | yes | no | +| phantom-finagle | yes | yes | no | +| phantom-streams | yes | yes | no | Using phantom ============= -### Scala 2.10 and 2.11 releases ### +### Scala 2.10, 2.11 and 2.12 releases ### We publish phantom in 2 formats, stable releases and bleeding edge. - The stable release is always available on Maven Central and will be indicated by the badge at the top of this readme. The Maven Central badge is pointing at the latest version -- Intermediary releases are available through our managed Bintray repository available at `https://dl.bintray.com/websudos/oss-releases/`. The latest version available on our Bintray repository is indicated by the Bintray badge at the top of this readme. +- Intermediary releases are available through our managed Bintray repository available at `https://dl.bintray.com/outworkers/oss-releases/`. The latest version available on our Bintray repository is indicated by the Bintray badge at the top of this readme. ### How phantom compares @@ -32,8 +79,8 @@ To compare phantom to similar tools in the Scala/Cassandra category, you can rea The latest versions are available here. The badges automatically update when a new version is released. -- Latest stable version: [![Maven Central](https://maven-badges.herokuapp.com/maven-central/com.websudos/phantom-dsl_2.11/badge.svg)](https://maven-badges.herokuapp.com/maven-central/com.websudos/phantom-dsl_2.11) (Maven Central) -- Bleeding edge: [![Bintray](https://api.bintray.com/packages/websudos/oss-releases/phantom-dsl/images/download.svg)](https://bintray.com/websudos/oss-releases/phantom-dsl/_latestVersion) (OSS releases on Bintray) +- Latest stable version: [![Maven Central](https://maven-badges.herokuapp.com/maven-central/com.outworkers/phantom-dsl_2.11/badge.svg)](https://maven-badges.herokuapp.com/maven-central/com.outworkers/phantom-dsl_2.11) (Maven Central) +- Bleeding edge: [![Bintray](https://api.bintray.com/packages/outworkers/oss-releases/phantom-dsl/images/download.svg)](https://bintray.com/outworkers/oss-releases/phantom-dsl/_latestVersion) (OSS releases on Bintray) ### Roadmap to Phantom 2.0.0 @@ -69,7 +116,7 @@ Intermediary releases of phantom 2.0.x are already available via `Resolver.bintr - [x] Generate the `fromRow` method of `CassandraTable` using a macro if the `case class` fields and `table` columns are matched. - [ ] Enforce a same ordering restriction for case class fields and table columns to avoid generating invalid methods with the macro. - [ ] Generate the `fromRow` if the fields match, they are in abitrary order, but there are no duplicate types. -- [ ] Allow arbitrary inheritance and usage patterns for Cassandra tables, and resolve inheritance resolutions with macros to correctly identify desired table structures. +- [x] Allow arbitrary inheritance and usage patterns for Cassandra tables, and resolve inheritance resolutions with macros to correctly identify desired table structures. #### Tech debt @@ -88,14 +135,16 @@ Intermediary releases of phantom 2.0.x are already available via `Resolver.bintr #### Scala 2.12 support -- [ ] Add support for Scala 2.12 in the `util` library, remove all dependencies that don't comply. +- [x] Add support for Scala 2.12 in the `util` library, remove all dependencies that don't comply. - [x] Add support for Scala 2.12 in the `diesel-engine`. -- [ ] Add support for Scala 2.12 in `phantom-dsl` -- [ ] Add support for Scala 2.12 in `phantom-connectors` -- [ ] Add support for Scala 2.12 in `phantom-reactivestreams` +- [x] Add support for Scala 2.12 in `phantom-dsl` +- [x] Add support for Scala 2.12 in `phantom-connectors` +- [ ] Add support for Scala 2.12 in `phantom-example` +- [ ] Add support for Scala 2.12 in `phantom-streams` +- [ ] Add support for Scala 2.12 in `phantom-thrift` - [ ] Add support for Scala 2.12 in `phantom-finagle` -#### Documentatiom +#### Documentation - [ ] Offer a complete migration guide for transitioning to Phantom 2.0.0. [Guide here](https://github.com/outworkers/phantom/tree/feature/2.0.0#200-migration-guide). - [ ] Move documentation back to the docs folder. @@ -141,13 +190,17 @@ We are very happy to help implement missing features in phantom, answer question Adopters ======== -Some of the companies using phantom: +The following are just some of the biggest phantom adopters, though the full list +is far more comprehensive. +- [Starbucks Corporation](https://www.starbucks.com/) +- [Microsoft](https://www.microsoft.com/en-gb/) - [CreditSuisse](https://www.credit-suisse.com/global/en/) - [ING](http://www.ing.com/en.htm) - [UBS](https://www.ubs.com/global/en.html) - [Wincor Nixdorf](http://www.wincor-nixdorf.com/internet/site_EN/EN/Home/homepage_node.html) - [Paddy Power](http://www.paddypower.com/) +- [Strava](https://www.strava.com/) - [Mobli](https://www.mobli.com/) - [Pellucid Analytics](http://www.pellucid.com/) - [Equens](http://www.equens.com/) @@ -165,17 +218,13 @@ Some of the companies using phantom: License and copyright ====================== -Phantom is [freeware software](https://en.wikipedia.org/wiki/Freeware) and uses a proprietary license that in plain English says the following: +Phantom is distributed under the Apache V2 License. -- Phantom is the intellectual property of `Outworkers`, it is not provided under an OSS license. +- `Outworkers, Limited` is the copyright holder. -- You can use phantom in commercial products or otherwise, so long as you use one of the official versions available on Bintray or Maven Central. +- You can use phantom in commercial products or otherwise. -- You are not allowed to distribute altered copies of phantom in binary form. - -- You cannot offer paid for training on phantom unless you are a direct partner to `Outworkers` and you have a written intellectual property agreement in place with us. - -- If you simply have a `Build.scala` or `build.sbt` dependency on phantom, you have nothing to worry about. +- We strongly appreciate and encourage contributions. - All paid for features are published and sold separately as `phantom-pro`, everything that is currently available for free will remain so forever. @@ -208,7 +257,7 @@ Scala/Cassandra users in the world rely on phantom. Special thanks to Viktor Taranenko from WhiskLabs, who gave us the original idea. -Copyright © 2013 - 2016 outworkers. +Copyright © 2013 - 2017 outworkers. Contributing to phantom ======================= diff --git a/build.sbt b/build.sbt index ac22deda2..fd32e1710 100644 --- a/build.sbt +++ b/build.sbt @@ -1,32 +1,17 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit written consent must be obtained from the copyright owner, - * Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ import sbt.Keys._ import sbt._ @@ -34,27 +19,35 @@ import com.twitter.sbt._ lazy val Versions = new { val logback = "1.1.7" - val util = "0.25.0" - val json4s = "3.3.0" + val util = "0.26.4" + val json4s = "3.5.0" val datastax = "3.1.0" - val scalatest = "2.2.4" + val scalatest = "3.0.0" val shapeless = "2.3.2" val thrift = "0.8.0" val finagle = "6.37.0" val twitterUtil = "6.34.0" - val scalameter = "0.6" + val scalameter = "0.8+" val diesel = "0.5.0" - val scalacheck = "1.13.0" + val scalacheck = "1.13.4" val slf4j = "1.7.21" val reactivestreams = "1.0.0" - val jetty = "9.1.2.v20140210" val cassandraUnit = "3.0.0.1" val javaxServlet = "3.0.1" - val typesafeConfig = "1.2.1" + val typesafeConfig = "1.3.1" + val joda = "2.9.4" + val jodaConvert = "1.8.1" + + val twitterUtilVersion: String => String = { + s => CrossVersion.partialVersion(s) match { + case Some((major, minor)) if minor >= 12 => "6.39.0" + case _ => "6.34.0" + } + } val akka: String => String = { s => CrossVersion.partialVersion(s) match { - case Some((major, minor)) if minor >= 11 && Publishing.isJdk8 => "2.4.10" + case Some((major, minor)) if minor >= 11 && Publishing.isJdk8 => "2.4.14" case _ => "2.3.15" } } @@ -98,28 +91,27 @@ lazy val Versions = new { val defaultConcurrency = 4 val PerformanceTest = config("perf").extend(Test) -lazy val performanceFilter: String => Boolean = _.endsWith("PerformanceTest") +lazy val performanceFilter: String => Boolean = _.endsWith("PerformanceTest") val sharedSettings: Seq[Def.Setting[_]] = Defaults.coreDefaultSettings ++ Seq( - organization := "com.websudos", + organization := "com.outworkers", scalaVersion := "2.11.8", credentials ++= Publishing.defaultCredentials, - crossScalaVersions := Seq("2.10.6", "2.11.8"), resolvers ++= Seq( "Twitter Repository" at "http://maven.twttr.com", Resolver.typesafeRepo("releases"), Resolver.sonatypeRepo("releases"), + Resolver.bintrayRepo("outworkers", "oss-releases"), Resolver.jcenterRepo ), - scalacOptions ++= Seq( + scalacOptions in ThisBuild ++= Seq( "-language:experimental.macros", "-language:postfixOps", "-language:implicitConversions", "-language:reflectiveCalls", "-language:higherKinds", "-language:existentials", - "-Yinline-warnings", "-Xlint", "-deprecation", "-feature", @@ -127,7 +119,7 @@ val sharedSettings: Seq[Def.Setting[_]] = Defaults.coreDefaultSettings ++ Seq( ), logLevel in ThisBuild := Level.Info, libraryDependencies ++= Seq( - "ch.qos.logback" % "logback-classic" % Versions.logback, + "ch.qos.logback" % "logback-classic" % Versions.logback % Test, "org.slf4j" % "log4j-over-slf4j" % Versions.slf4j ), fork in Test := true, @@ -141,7 +133,7 @@ val sharedSettings: Seq[Def.Setting[_]] = Defaults.coreDefaultSettings ++ Seq( }, testFrameworks in PerformanceTest := Seq(new TestFramework("org.scalameter.ScalaMeterFramework")), testOptions in Test := Seq(Tests.Filter(x => !performanceFilter(x))), - testOptions in PerformanceTest := Seq(Tests.Filter(x => performanceFilter(x))), + testOptions in PerformanceTest := Seq(Tests.Filter(performanceFilter)), fork in PerformanceTest := false, parallelExecution in ThisBuild := false ) ++ VersionManagement.newSettings ++ @@ -153,13 +145,11 @@ lazy val baseProjectList: Seq[ProjectReference] = Seq( phantomExample, phantomConnectors, phantomFinagle, - phantomReactiveStreams, + phantomStreams, phantomThrift ) -lazy val fullProjectList = baseProjectList ++ - Publishing.addOnCondition(Publishing.isJdk8, phantomJdk8) ++ - Publishing.addOnCondition(Publishing.isTravisScala210, phantomSbtPlugin) +lazy val fullProjectList = baseProjectList ++ Publishing.addOnCondition(Publishing.isJdk8, phantomJdk8) lazy val phantom = (project in file(".")) .configs( @@ -174,7 +164,7 @@ lazy val phantom = (project in file(".")) pgpPassphrase := Publishing.pgpPass ).aggregate( fullProjectList: _* - ) + ).enablePlugins(CrossPerProjectPlugin) lazy val phantomDsl = (project in file("phantom-dsl")).configs( PerformanceTest @@ -185,36 +175,37 @@ lazy val phantomDsl = (project in file("phantom-dsl")).configs( ).settings( name := "phantom-dsl", moduleName := "phantom-dsl", - testOptions in Test += Tests.Argument("-oF"), concurrentRestrictions in Test := Seq( Tags.limit(Tags.ForkedTestGroup, defaultConcurrency) ), + crossScalaVersions := Seq("2.10.6", "2.11.8", "2.12.0"), libraryDependencies ++= Seq( "org.typelevel" %% "macro-compat" % "1.1.1", "org.scala-lang" % "scala-compiler" % scalaVersion.value % "provided", compilerPlugin("org.scalamacros" % "paradise" % "2.1.0" cross CrossVersion.full), - "org.scala-lang" % "scala-reflect" % scalaVersion.value, - "com.outworkers" %% "diesel-reflection" % Versions.diesel, + "com.outworkers" %% "diesel-engine" % Versions.diesel, "com.chuusai" %% "shapeless" % Versions.shapeless, - "joda-time" % "joda-time" % "2.9.4", - "org.joda" % "joda-convert" % "1.8.1", + "joda-time" % "joda-time" % Versions.joda, + "org.joda" % "joda-convert" % Versions.jodaConvert, "com.datastax.cassandra" % "cassandra-driver-core" % Versions.datastax, "com.datastax.cassandra" % "cassandra-driver-extras" % Versions.datastax, + "org.json4s" %% "json4s-native" % Versions.json4s, + "org.scalamock" %% "scalamock-scalatest-support" % "3.4.2" % Test, "org.scalacheck" %% "scalacheck" % Versions.scalacheck % Test, - "com.outworkers" %% "util-lift" % Versions.util % Test, "com.outworkers" %% "util-testing" % Versions.util % Test, "com.storm-enroute" %% "scalameter" % Versions.scalameter % Test, "ch.qos.logback" % "logback-classic" % Versions.logback % Test ) ).dependsOn( phantomConnectors -) +).enablePlugins(CrossPerProjectPlugin) lazy val phantomJdk8 = (project in file("phantom-jdk8")) .settings( name := "phantom-jdk8", moduleName := "phantom-jdk8", testOptions in Test += Tests.Argument("-oF"), + crossScalaVersions := Seq("2.10.6", "2.11.8", "2.12.0"), concurrentRestrictions in Test := Seq( Tags.limit(Tags.ForkedTestGroup, defaultConcurrency) ) @@ -222,7 +213,7 @@ lazy val phantomJdk8 = (project in file("phantom-jdk8")) sharedSettings: _* ).dependsOn( phantomDsl % "compile->compile;test->test" - ) + ).enablePlugins(CrossPerProjectPlugin) lazy val phantomConnectors = (project in file("phantom-connectors")) .configs(PerformanceTest) @@ -230,18 +221,20 @@ lazy val phantomConnectors = (project in file("phantom-connectors")) sharedSettings: _* ).settings( name := "phantom-connectors", + crossScalaVersions := Seq("2.10.6", "2.11.8", "2.12.0"), libraryDependencies ++= Seq( "com.datastax.cassandra" % "cassandra-driver-core" % Versions.datastax, "com.outworkers" %% "util-testing" % Versions.util % Test ) - ) + ).enablePlugins(CrossPerProjectPlugin) lazy val phantomFinagle = (project in file("phantom-finagle")) .configs(PerformanceTest).settings( name := "phantom-finagle", moduleName := "phantom-finagle", + crossScalaVersions := Seq("2.10.6", "2.11.8"), libraryDependencies ++= Seq( - "com.twitter" %% "util-core" % Versions.twitterUtil, + "com.twitter" %% "util-core" % Versions.twitterUtilVersion(scalaVersion.value), "com.outworkers" %% "util-testing" % Versions.util % Test, "com.storm-enroute" %% "scalameter" % Versions.scalameter % Test ) @@ -249,12 +242,13 @@ lazy val phantomFinagle = (project in file("phantom-finagle")) inConfig(PerformanceTest)(Defaults.testTasks) ++ sharedSettings: _* ).dependsOn( phantomDsl % "compile->compile;test->test" - ) + ).enablePlugins(CrossPerProjectPlugin) lazy val phantomThrift = (project in file("phantom-thrift")) .settings( name := "phantom-thrift", moduleName := "phantom-thrift", + crossScalaVersions := Seq("2.10.6", "2.11.8"), libraryDependencies ++= Seq( "org.apache.thrift" % "libthrift" % Versions.thrift, "com.twitter" %% "scrooge-core" % Versions.scrooge(scalaVersion.value), @@ -266,43 +260,30 @@ lazy val phantomThrift = (project in file("phantom-thrift")) ).dependsOn( phantomDsl, phantomFinagle - ) + ).enablePlugins(CrossPerProjectPlugin) lazy val phantomSbtPlugin = (project in file("phantom-sbt")) .settings( sharedSettings: _* ).settings( - name := "phantom-sbt", - moduleName := "phantom-sbt", - scalaVersion := "2.10.6", - unmanagedSourceDirectories in Compile ++= Seq( - (sourceDirectory in Compile).value / ("scala-2." + { - CrossVersion.partialVersion(scalaBinaryVersion.value) match { - case Some((major, minor)) => minor - case None => "10" - - } - })), - publish := { - CrossVersion.partialVersion(scalaVersion.value).map { - case (2, scalaMajor) if scalaMajor >= 11 => false - case _ => true - } - }, - publishMavenStyle := false, - sbtPlugin := true, - libraryDependencies ++= Seq( - "org.cassandraunit" % "cassandra-unit" % Versions.cassandraUnit excludeAll ( - ExclusionRule("org.slf4j", "slf4j-log4j12"), - ExclusionRule("org.slf4j", "slf4j-jdk14") + name := "phantom-sbt", + moduleName := "phantom-sbt", + crossScalaVersions := Seq("2.10.6"), + publishMavenStyle := false, + sbtPlugin := true, + libraryDependencies ++= Seq( + "org.cassandraunit" % "cassandra-unit" % Versions.cassandraUnit excludeAll ( + ExclusionRule("org.slf4j", "slf4j-log4j12"), + ExclusionRule("org.slf4j", "slf4j-jdk14") + ) ) - ) -) + ).enablePlugins(CrossPerProjectPlugin) -lazy val phantomReactiveStreams = (project in file("phantom-reactivestreams")) +lazy val phantomStreams = (project in file("phantom-streams")) .settings( - name := "phantom-reactivestreams", - moduleName := "phantom-reactivestreams", + name := "phantom-streams", + moduleName := "phantom-streams", + crossScalaVersions := Seq("2.10.6", "2.11.8"), libraryDependencies ++= Seq( "com.typesafe.play" %% "play-iteratees" % Versions.play(scalaVersion.value) exclude ("com.typesafe", "config"), Versions.playStreams(scalaVersion.value) exclude ("com.typesafe", "config"), @@ -322,11 +303,12 @@ lazy val phantomReactiveStreams = (project in file("phantom-reactivestreams")) sharedSettings: _* ).dependsOn( phantomDsl % "compile->compile;test->test" - ) + ).enablePlugins(CrossPerProjectPlugin) lazy val phantomExample = (project in file("phantom-example")) .settings( name := "phantom-example", + crossScalaVersions := Seq("2.10.6", "2.11.8"), moduleName := "phantom-example", libraryDependencies ++= Seq( "com.outworkers" %% "util-lift" % Versions.util % Test, @@ -335,7 +317,7 @@ lazy val phantomExample = (project in file("phantom-example")) ).settings( sharedSettings: _* ).dependsOn( - phantomDsl, - phantomReactiveStreams, + phantomDsl % "test->test;compile->compile;", + phantomStreams, phantomThrift - ) + ).enablePlugins(CrossPerProjectPlugin) diff --git a/build/publish_develop.sh b/build/publish_develop.sh index 3a4744737..e610a78c9 100755 --- a/build/publish_develop.sh +++ b/build/publish_develop.sh @@ -1,5 +1,5 @@ #!/usr/bin/env bash -if [ "$TRAVIS_PULL_REQUEST" == "false" ] && [ "$TRAVIS_BRANCH" == "develop" ]; +if [ "$TRAVIS_PULL_REQUEST" == "false" ] && ([ "$TRAVIS_BRANCH" == "develop" ] || [ "$TRAVIS_BRANCH" == "feature/2.0.0" ]); then if [ "${TRAVIS_SCALA_VERSION}" == "2.11.8" ] && [ "${TRAVIS_JDK_VERSION}" == "oraclejdk8" ]; @@ -55,7 +55,18 @@ then echo "Bintray credentials still not found" fi - sbt version-bump-patch git-tag + COMMIT_MSG=$(git log -1 --pretty=%B 2>&1) + COMMIT_SKIP_MESSAGE = "[version skip]" + + echo "Last commit message $COMMIT_MSG" + + if [[ $COMMIT_MSG == *"${COMMIT_SKIP_MESSAGE}"* ]] + then + echo "Skipping version bump and simply tagging" + sbt git-tag + else + sbt version-bump-patch git-tag + fi echo "Pushing tag to GitHub." git push --tags "https://${github_token}@${GH_REF}" @@ -64,23 +75,30 @@ then git add . git commit -m "TravisCI: Bumping version to match CI definition [ci skip]" git checkout -b version_branch - git checkout -B develop version_branch + git checkout -B $TRAVIS_BRANCH version_branch - git push "https://${github_token}@${GH_REF}" develop + git push "https://${github_token}@${GH_REF}" $TRAVIS_BRANCH echo "Publishing new version to bintray" - sbt +bintray:publish - - echo "Creating GPG deploy key" - openssl aes-256-cbc -K $encrypted_759d2b7e5bb0_key -iv $encrypted_759d2b7e5bb0_iv -in build/deploy.asc.enc -out build/deploy.asc -d - - echo "importing GPG key to local GBP repo" - gpg --fast-import build/deploy.asc - - echo "Setting MAVEN_PUBLISH mode to true" - export MAVEN_PUBLISH="true" - export pgp_passphrase=${maven_password} - sbt +publishSigned sonatypeReleaseAll + sbt "such publish" + + if [ "$TRAVIS_BRANCH" == "develop" ]; + then + echo "Creating GPG deploy key" + openssl aes-256-cbc -K $encrypted_759d2b7e5bb0_key -iv $encrypted_759d2b7e5bb0_iv -in build/deploy.asc.enc -out build/deploy.asc -d + + echo "importing GPG key to local GBP repo" + gpg --fast-import build/deploy.asc + + echo "Setting MAVEN_PUBLISH mode to true" + export MAVEN_PUBLISH="true" + export pgp_passphrase=${maven_password} + sbt "such publishSigned" + sbt sonatypeReleaseAll + exit $? + else + echo "Not deploying to Maven Central, branch is not develop, current branch is ${TRAVIS_BRANCH}" + fi else echo "Only publishing version for Scala 2.11.8 and Oracle JDK 8 to prevent multiple artifacts" diff --git a/build/run_tests.sh b/build/run_tests.sh index 057328f1e..24fca4e6b 100755 --- a/build/run_tests.sh +++ b/build/run_tests.sh @@ -6,6 +6,7 @@ then exit $? else echo "Running tests without attempting to submit coverage reports" - sbt ++$TRAVIS_SCALA_VERSION test + sbt "plz $TRAVIS_SCALA_VERSION test" exit $? fi +q diff --git a/comparison.md b/comparison.md index c9ed7b3ab..ef30347b4 100644 --- a/comparison.md +++ b/comparison.md @@ -105,7 +105,7 @@ Let's have a look at a basic example, for the basic `Recipe` case class, in this ```scala -import com.websudos.phantom.dsl._ +import com.outworkers.phantom.dsl._ case class Recipe( url: String, @@ -256,13 +256,14 @@ play-streams somewhere else in you app, otherwise it makes little sense to not s much impossible to build Thrift services without a dependency on Thrift itself, so in that respect it is highly unlikely that using those extra modules will end up bringing in more dependencies than you already have. -- The one place where phantom sucks is the dependency on `scala-reflect`, which is causing some ugly things inside the +- The one place where phantom used to suck is the dependency on `scala-reflect`, which is causing some ugly things inside the framework, namely the need for global locks to make reflection thread safe in the presence of multiple class loaders. This -is however going away in 2.0.0, and we are replacing `scala-reflect` with a macro based approach. +is however going away in 2.0.0, already available on `feature/2.0.0`, and we are replacing `scala-reflect` with a macro based approach. - The only notable dependencies of phantom are `shapeless` and `cassandra-driver-core`, the latter of which you will have inevitably. Shapeless is also quite light and compile time, it depends only on macro libraries such as `macro-compat`. You -can have a look yourself [here](https://github.com/milessabin/shapeless). +can have a look yourself [here](https://github.com/milessabin/shapeless). We also depend on an internal engine called the +diesel engine, which itself only depends on `macro-compat`, since it's nothing more than a customised macro toolchain. #### Documentation and commercial support diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 000000000..60296ea97 --- /dev/null +++ b/docs/README.md @@ -0,0 +1,113 @@ +phantom + +[![Build Status](https://travis-ci.org/outworkers/phantom.svg?branch=develop)](https://travis-ci.org/outworkers/phantom) [![Coverage Status](https://coveralls.io/repos/outworkers/phantom/badge.svg)](https://coveralls.io/r/outworkers/phantom) [![Codacy Rating](https://api.codacy.com/project/badge/grade/25bee222a7d142ff8151e6ceb39151b4)](https://www.codacy.com/app/flavian/phantom_2) [![Maven Central](https://maven-badges.herokuapp.com/maven-central/com.outworkers/phantom-dsl_2.11/badge.svg)](https://maven-badges.herokuapp.com/maven-central/com.outworkers/phantom-dsl_2.11) [![Bintray](https://api.bintray.com/packages/outworkers/oss-releases/phantom-dsl/images/download.svg) ](https://bintray.com/outworkers/oss-releases/phantom-dsl/_latestVersion) [![ScalaDoc](http://javadoc-badge.appspot.com/com.outworkers/phantom-dsl_2.11.svg?label=scaladoc)](http://javadoc-badge.appspot.com/com.outworkers/phantom-dsl_2.11) [![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/outworkers/phantom?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) +============================================================================================================= +Reactive type-safe Scala driver for Apache Cassandra/Datastax Enterprise + +![phantom](https://s3-eu-west-1.amazonaws.com/websudos/oss/logos/phantom.png "Outworkers Phantom") + +To stay up-to-date with our latest releases and news, follow us on Twitter: [@outworkers](https://twitter.com/outworkers_uk). + +If you use phantom, please consider adding your company to our list of adopters. Phantom is and will always be completely free and open source, under the Apache V2 license. Adopters encourage further adoption and a wider community around the project, which is quid pro quo for everyone involved. + +Roadmap +======== + +### Phantom OSS + +While dates are not fixed, we will use this list to tell you about our plans for the future. If you have great ideas about what could benefit all phantom +adopters, please get in touch. We are very happy and eager to listen. + +- [x] Prepared statements(available as of 1.15.0) + +- [x] A new QueryBuilder(available as of 1.6.0) + +- [x] Zookeeper support(available as of 1.1.0). + +- [x] Reactive streams support(available as of 1.15.0) + +- [x] Improved DSL, complete separation of reactive streams into separate module(available as of 1.26.0) + +- [x] Further cleanup of build, making project more lightweight, separating Twitter primitives support into `phantom-finagle`. (1.26.0) + + +#### Phantom 1.30.x + +- [x] Comparison of Phantom versus other established tools. + +- [ ] Support for case sensitive Cassandra tables and keyspace names. + +- [ ] Support for tuple columns and collection columns + +- [x] Support for frozen collection columns as primary columns. + +- [ ] SASI Index support. + +- [x] A `KeySpaceBuilder` that allows type safe specification of keyspace creation properties.(available as of 1.29.4) + + +#### Phantom 2.0.0 + +- [x] Remove `scala-reflect.jar` from `build.sbt`, replacing the DSL mechanism with a macro based one. + +- [ ] Allow using collection columns as primary keys. + +- [ ] Use `QueryPart` as a building block for schema inference during table auto-generation. + +- [ ] Stabilise tracing and discovery of inheritance patterns via macros. + +- [ ] Add Scala 2.12 support. + +- [x] Add native support for `TupleColumn`, with implicit macro generation. + +- [x] Add support for `TimeWindowCompactionStrategy`. + +- [ ] Deeper integration of CQL features, such as advanced `USING` clauses, `GROUP BY` and `PER PARTITION LIMIT`.(2.0.0) + +- [ ] Move documentation back to a branch and to a dedicated versioned website based on Git tags. + +- [ ] Added implicit.ly integration to notify our audience of new releases. + +- [ ] Bring test coverage to 100%(2.0.0) + +- [ ] Add ability to specify application wide configuration, such as case sensitive column names. + +- [ ] A new website with highly improved documentation, as well as a per version docs browser. + +- [x] Replacing Travis Cassandra service with CCM to natively include multi-version testing in our setup. + +- [x] Add support for macro derived primitives for complex types. + +### Phantom Pro + +#### v.1.0 + +- [x] Full support for UDTs. +- [x] Support for UDT collection types. +- [ ] Scala language based User defined functions. +- [ ] Scala language based User defined aggregates. +- [ ] Cassandra 3.8+ support. +- [ ] Materialised views. +- [ ] Development automated schema migrations. + +#### 1.1.0 +- [ ] Auto-tables, ability to generate queries entirely of out `case class` definitions. +- [ ] Advanced table migrations. + +Commercial support +=================== +back to top + +We, the people behind phantom, run a software development house specialising in Scala and NoSQL. If you are after enterprise grade +training or support for using phantom, [Outworkers](http://outworkers.com) is here to help! + +We offer a comprehensive range of elite Scala development services, including but not limited to: + +- Software development +- Remote contractors for hire +- Advanced Scala and Cassandra training + +We are huge advocates of open source and we will open source every project we can! To read more about our open source efforts, click [here](http://www.outworkers.com/work). + + + diff --git a/phantom-connectors/src/main/scala/com/outworkers/phantom/connectors/CassandraConnection.scala b/phantom-connectors/src/main/scala/com/outworkers/phantom/connectors/CassandraConnection.scala new file mode 100644 index 000000000..da8855556 --- /dev/null +++ b/phantom-connectors/src/main/scala/com/outworkers/phantom/connectors/CassandraConnection.scala @@ -0,0 +1,102 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.connectors + +import com.datastax.driver.core.Session + +import scala.collection.JavaConverters._ +import scala.util.control.NoStackTrace + +/** + * Represents a single Cassandra keySpace. + * + * Provides access to the associated `Session` as well as to a + * `Connector` trait that can be mixed into `CassandraTable` + * instances. + * + * @param name the name of the keySpace + * @param clusterBuilder the provider for this keySpace + */ +class CassandraConnection( + val name: String, + clusterBuilder: ClusterBuilder, + autoinit: Boolean, + keyspaceFn: Option[(Session, KeySpace) => String] = None, + errorHander: Throwable => Throwable = identity +) { outer => + + lazy val provider = new DefaultSessionProvider( + KeySpace(name), + clusterBuilder, + autoinit, + keyspaceFn, + errorHander + ) + + /** + * The Session associated with this keySpace. + */ + lazy val session: Session = provider.session + + def cassandraVersions: Set[VersionNumber] = { + session.getCluster.getMetadata.getAllHosts + .asScala.map(_.getCassandraVersion) + .toSet[VersionNumber] + } + + def cassandraVersion: Option[VersionNumber] = { + val versions = cassandraVersions + + if (versions.nonEmpty) { + + val single = versions.headOption + + if (cassandraVersions.size == 1) { + single + } else { + + if (single.forall(item => versions.forall(item ==))) { + single + } else { + throw new RuntimeException( + s"Illegal single version comparison. You are connected to clusters of different versions." + + s"Available versions are: ${versions.mkString(", ")}" + ) with NoStackTrace + } + } + } else { + throw new RuntimeException("Could not extract any versions from the cluster, versions were empty") + } + } + + /** + * Trait that can be mixed into `CassandraTable` + * instances. + */ + trait Connector extends com.outworkers.phantom.connectors.Connector with SessionAugmenterImplicits { + + lazy val provider = outer.provider + + lazy val keySpace = outer.name + + implicit val space: KeySpace = KeySpace(outer.name) + + def cassandraVersion: Option[VersionNumber] = outer.cassandraVersion + + def cassandraVersions: Set[VersionNumber] = outer.cassandraVersions + } + +} diff --git a/phantom-connectors/src/main/scala/com/outworkers/phantom/connectors/Connector.scala b/phantom-connectors/src/main/scala/com/outworkers/phantom/connectors/Connector.scala new file mode 100644 index 000000000..db21db28d --- /dev/null +++ b/phantom-connectors/src/main/scala/com/outworkers/phantom/connectors/Connector.scala @@ -0,0 +1,66 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.connectors + +import com.datastax.driver.core.Session + +/* Trait to be mixed into the table classes that extend + * phantom's CassandraTable. + * + * The main purpose of this trait is to provide an implicit + * `Session` to the query and update logic in your table + * class. + * + * The most convenient approach is to mix in this abstract + * base trait into your abstract table classes, so that + * the implicit `Session` is available in your table + * implementation and then instantiate a sub-class + * that mixes in the concrete trait from a `KeySpace` + * instance. + * + * {{{ + * // table class: + * abstract class Foos extends CassandraTable[Foos, Foo] with Connector { + * [...] + * } + * + * // concrete instance: + * val hosts = Seq("35.0.0.1", "35.0.0.2") + * val keySpace = ContactPoints(hosts).keySpace("myApp") + * + * object foos extends Foos with keySpace.Connector + * }}} + */ +trait Connector { + + /** + * The name of the keyspace this Connector should use. + */ + def keySpace: String + + /** + * The provider for the session instance. + */ + def provider: SessionProvider + + /** + * The implicit Session instance for the + * query and update operations in phantom + * table implementations. + */ + implicit lazy val session: Session = provider.session + +} diff --git a/phantom-connectors/src/main/scala/com/websudos/phantom/connectors/ContactPoint.scala b/phantom-connectors/src/main/scala/com/outworkers/phantom/connectors/ContactPoint.scala similarity index 96% rename from phantom-connectors/src/main/scala/com/websudos/phantom/connectors/ContactPoint.scala rename to phantom-connectors/src/main/scala/com/outworkers/phantom/connectors/ContactPoint.scala index 2232fe8ea..f7e949638 100644 --- a/phantom-connectors/src/main/scala/com/websudos/phantom/connectors/ContactPoint.scala +++ b/phantom-connectors/src/main/scala/com/outworkers/phantom/connectors/ContactPoint.scala @@ -1,5 +1,5 @@ /* - * Copyright 2014-2015 Websudos Ltd, Sphonic Ltd. All Rights Reserved. + * Copyright 2013 - 2017 Outworkers Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.websudos.phantom.connectors +package com.outworkers.phantom.connectors /** * Entry point for defining a keySpace based diff --git a/phantom-connectors/src/main/scala/com/websudos/phantom/connectors/DefaultSessionProvider.scala b/phantom-connectors/src/main/scala/com/outworkers/phantom/connectors/DefaultSessionProvider.scala similarity index 98% rename from phantom-connectors/src/main/scala/com/websudos/phantom/connectors/DefaultSessionProvider.scala rename to phantom-connectors/src/main/scala/com/outworkers/phantom/connectors/DefaultSessionProvider.scala index 62e147d84..362ad1935 100644 --- a/phantom-connectors/src/main/scala/com/websudos/phantom/connectors/DefaultSessionProvider.scala +++ b/phantom-connectors/src/main/scala/com/outworkers/phantom/connectors/DefaultSessionProvider.scala @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.websudos.phantom.connectors +package com.outworkers.phantom.connectors import com.datastax.driver.core.{Cluster, Session} import org.slf4j.LoggerFactory diff --git a/phantom-connectors/src/main/scala/com/websudos/phantom/connectors/KeySpaceBuilder.scala b/phantom-connectors/src/main/scala/com/outworkers/phantom/connectors/KeySpaceBuilder.scala similarity index 83% rename from phantom-connectors/src/main/scala/com/websudos/phantom/connectors/KeySpaceBuilder.scala rename to phantom-connectors/src/main/scala/com/outworkers/phantom/connectors/KeySpaceBuilder.scala index 71e3edca5..fd62a1a9a 100644 --- a/phantom-connectors/src/main/scala/com/websudos/phantom/connectors/KeySpaceBuilder.scala +++ b/phantom-connectors/src/main/scala/com/outworkers/phantom/connectors/KeySpaceBuilder.scala @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.websudos.phantom.connectors +package com.outworkers.phantom.connectors import com.datastax.driver.core.{PoolingOptions, Session} @@ -40,9 +40,8 @@ class KeySpaceBuilder(clusterBuilder: ClusterBuilder) { * @return A new cluster builder, with the heartbeat interval set to 0(disabled). */ def noHeartbeat(): KeySpaceBuilder = { - new KeySpaceBuilder(clusterBuilder andThen(_.withPoolingOptions( - new PoolingOptions().setHeartbeatIntervalSeconds(0)) - ) + new KeySpaceBuilder(clusterBuilder andThen ( + _.withPoolingOptions(new PoolingOptions().setHeartbeatIntervalSeconds(0))) ) } @@ -56,9 +55,10 @@ class KeySpaceBuilder(clusterBuilder: ClusterBuilder) { def keySpace( name: String, autoinit: Boolean = true, - query: Option[(Session, KeySpace) => String] = None - ): KeySpaceDef = { - new KeySpaceDef(name, clusterBuilder, autoinit, query) + query: Option[(Session, KeySpace) => String] = None, + errorHandler: Throwable => Throwable = identity + ): CassandraConnection = { + new CassandraConnection(name, clusterBuilder, autoinit, query) } /** @@ -72,8 +72,6 @@ class KeySpaceBuilder(clusterBuilder: ClusterBuilder) { def keySpace( name: String, query: (Session, KeySpace) => String - ): KeySpaceDef = { - new KeySpaceDef(name, clusterBuilder, true, Some(query)) - } - -} + ): CassandraConnection = { + new CassandraConnection(name, clusterBuilder, true, Some(query)) + }} diff --git a/phantom-connectors/src/main/scala/com/outworkers/phantom/connectors/Keyspace.scala b/phantom-connectors/src/main/scala/com/outworkers/phantom/connectors/Keyspace.scala new file mode 100644 index 000000000..fc9f4866a --- /dev/null +++ b/phantom-connectors/src/main/scala/com/outworkers/phantom/connectors/Keyspace.scala @@ -0,0 +1,48 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.connectors + +import scala.collection.JavaConverters._ +import com.datastax.driver.core.{ProtocolVersion, Session} + +import scala.util.control.NoStackTrace + +trait SessionAugmenter { + + def session: Session + + def protocolVersion: ProtocolVersion = { + session.getCluster.getConfiguration.getProtocolOptions.getProtocolVersion + } + + def isNewerThan(pv: ProtocolVersion): Boolean = { + protocolVersion.compareTo(pv) > 0 + } + + def v3orNewer: Boolean = isNewerThan(ProtocolVersion.V2) + + def protocolConsistency: Boolean = isNewerThan(ProtocolVersion.V1) + + def v4orNewer: Boolean = isNewerThan(ProtocolVersion.V3) +} + +trait SessionAugmenterImplicits { + implicit class RichSession(val session: Session) extends SessionAugmenter +} + + + +case class KeySpace(name: String) diff --git a/phantom-connectors/src/main/scala/com/outworkers/phantom/connectors/RootConnector.scala b/phantom-connectors/src/main/scala/com/outworkers/phantom/connectors/RootConnector.scala new file mode 100644 index 000000000..fe75cc964 --- /dev/null +++ b/phantom-connectors/src/main/scala/com/outworkers/phantom/connectors/RootConnector.scala @@ -0,0 +1,25 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.connectors + +import com.datastax.driver.core.Session + +trait RootConnector { + + implicit def space: KeySpace + + implicit def session: Session +} diff --git a/phantom-connectors/src/main/scala/com/websudos/phantom/connectors/SessionProvider.scala b/phantom-connectors/src/main/scala/com/outworkers/phantom/connectors/SessionProvider.scala similarity index 92% rename from phantom-connectors/src/main/scala/com/websudos/phantom/connectors/SessionProvider.scala rename to phantom-connectors/src/main/scala/com/outworkers/phantom/connectors/SessionProvider.scala index c798bcdef..8a125b480 100644 --- a/phantom-connectors/src/main/scala/com/websudos/phantom/connectors/SessionProvider.scala +++ b/phantom-connectors/src/main/scala/com/outworkers/phantom/connectors/SessionProvider.scala @@ -1,5 +1,5 @@ /* - * Copyright 2014-2015 Sphonic Ltd. All Rights Reserved. + * Copyright 2013 - 2017 Outworkers Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.websudos.phantom.connectors +package com.outworkers.phantom.connectors import com.datastax.driver.core.{ Cluster, Session } diff --git a/phantom-connectors/src/main/scala/com/outworkers/phantom/connectors/Versions.scala b/phantom-connectors/src/main/scala/com/outworkers/phantom/connectors/Versions.scala new file mode 100644 index 000000000..fdcdf6363 --- /dev/null +++ b/phantom-connectors/src/main/scala/com/outworkers/phantom/connectors/Versions.scala @@ -0,0 +1,59 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.connectors + +import com.datastax.driver.core.{VersionNumber => DatastaxVersionNumber} + +sealed trait VersionBuilder { + def apply(major: Int, minor: Int, patch: Int): DatastaxVersionNumber = { + DatastaxVersionNumber.parse(s"$major.$minor.$patch") + } +} + +private object Version extends VersionBuilder + +object DefaultVersions { + val `2.0.8` = Version(2, 0, 8) + val `2.0.9` = Version(2, 0, 9) + val `2.0.10` = Version(2, 0, 10) + val `2.0.11` = Version(2, 0, 11) + val `2.0.12` = Version(2, 0, 12) + val `2.0.13` = Version(2, 0, 13) + val `2.1.0` = Version(2, 1, 0) + val `2.1.1` = Version(2, 1, 1) + val `2.1.2` = Version(2, 1, 2) + val `2.1.3` = Version(2, 1, 3) + val `2.1.4` = Version(2, 1, 4) + val `2.1.5` = Version(2, 1, 5) + val `2.1.6` = Version(2, 1, 6) + val `2.1.7` = Version(2, 1, 7) + val `2.1.8` = Version(2, 1, 8) + val `2.1.9` = Version(2, 1, 9) + val `2.2.0` = Version(2, 2, 0) + val `2.2.1` = Version(2, 2, 1) + val `2.2.2` = Version(2, 2, 2) + val `2.2.8` = Version(2, 2, 8) + val `2.3.0` = Version(2, 3, 0) + val `3.0.0` = Version(3, 0, 0) + val `3.1.0` = Version(3, 1, 0) + val `3.2.0` = Version(3, 2, 0) + val `3.3.0` = Version(3, 3, 0) + val `3.4.0` = Version(3, 4, 0) + val `3.5.0` = Version(3, 5, 0) + val `3.6.0` = Version(3, 6, 0) + val `3.7.0` = Version(3, 7, 0) + val `3.8.0` = Version(3, 8, 0) +} \ No newline at end of file diff --git a/phantom-connectors/src/main/scala/com/websudos/phantom/connectors/package.scala b/phantom-connectors/src/main/scala/com/outworkers/phantom/connectors/package.scala similarity index 77% rename from phantom-connectors/src/main/scala/com/websudos/phantom/connectors/package.scala rename to phantom-connectors/src/main/scala/com/outworkers/phantom/connectors/package.scala index 2896278e5..b4d292f67 100644 --- a/phantom-connectors/src/main/scala/com/websudos/phantom/connectors/package.scala +++ b/phantom-connectors/src/main/scala/com/outworkers/phantom/connectors/package.scala @@ -1,5 +1,5 @@ /* - * Copyright 2014-2015 Sphonic Ltd. All Rights Reserved. + * Copyright 2013 - 2017 Outworkers Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.websudos.phantom +package com.outworkers.phantom import com.datastax.driver.core.Cluster @@ -22,4 +22,7 @@ package object connectors { type ClusterBuilder = (Cluster.Builder => Cluster.Builder) type VersionNumber = com.datastax.driver.core.VersionNumber + + @deprecated("Renamed to the more descriptive CassandraConnection", "2.0.0") + type KeySpaceDef = com.outworkers.phantom.connectors.CassandraConnection } \ No newline at end of file diff --git a/phantom-connectors/src/main/scala/com/websudos/phantom/connectors/Connector.scala b/phantom-connectors/src/main/scala/com/websudos/phantom/connectors/Connector.scala deleted file mode 100644 index 6bb8f4793..000000000 --- a/phantom-connectors/src/main/scala/com/websudos/phantom/connectors/Connector.scala +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.connectors - -import com.datastax.driver.core.Session - -/* Trait to be mixed into the table classes that extend - * phantom's CassandraTable. - * - * The main purpose of this trait is to provide an implicit - * `Session` to the query and update logic in your table - * class. - * - * The most convenient approach is to mix in this abstract - * base trait into your abstract table classes, so that - * the implicit `Session` is available in your table - * implementation and then instantiate a sub-class - * that mixes in the concrete trait from a `KeySpace` - * instance. - * - * {{{ - * // table class: - * abstract class Foos extends CassandraTable[Foos, Foo] with Connector { - * [...] - * } - * - * // concrete instance: - * val hosts = Seq("35.0.0.1", "35.0.0.2") - * val keySpace = ContactPoints(hosts).keySpace("myApp") - * - * object foos extends Foos with keySpace.Connector - * }}} - */ -trait Connector { - - /** - * The name of the keyspace this Connector should use. - */ - def keySpace: String - - /** - * The provider for the session instance. - */ - def provider: SessionProvider - - /** - * The implicit Session instance for the - * query and update operations in phantom - * table implementations. - */ - implicit lazy val session: Session = provider.session - -} diff --git a/phantom-connectors/src/main/scala/com/websudos/phantom/connectors/Keyspace.scala b/phantom-connectors/src/main/scala/com/websudos/phantom/connectors/Keyspace.scala deleted file mode 100644 index 12d637bf8..000000000 --- a/phantom-connectors/src/main/scala/com/websudos/phantom/connectors/Keyspace.scala +++ /dev/null @@ -1,149 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -/* - * Copyright 2014-2015 Sphonic Ltd. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.websudos.phantom.connectors - -import scala.collection.JavaConverters._ -import com.datastax.driver.core.{ProtocolVersion, Session} - -import scala.util.control.NoStackTrace - -trait SessionAugmenter { - - def session: Session - - def protocolVersion: ProtocolVersion = { - session.getCluster.getConfiguration.getProtocolOptions.getProtocolVersion - } - - def isNewerThan(pv: ProtocolVersion): Boolean = { - protocolVersion.compareTo(pv) > 0 - } - - def v3orNewer : Boolean = isNewerThan(ProtocolVersion.V2) - - def protocolConsistency: Boolean = isNewerThan(ProtocolVersion.V1) - - def v4orNewer : Boolean = isNewerThan(ProtocolVersion.V3) -} - -trait SessionAugmenterImplicits { - implicit class RichSession(val session: Session) extends SessionAugmenter -} - -/** - * Represents a single Cassandra keySpace. - * - * Provides access to the associated `Session` as well as to a - * `Connector` trait that can be mixed into `CassandraTable` - * instances. - * - * @param name the name of the keySpace - * @param clusterBuilder the provider for this keySpace - */ -class KeySpaceDef( - val name: String, - clusterBuilder: ClusterBuilder, - autoinit: Boolean, - keyspaceFn: Option[(Session, KeySpace) => String] = None -) { outer ⇒ - - lazy val provider: SessionProvider = new DefaultSessionProvider(KeySpace(name), clusterBuilder, autoinit, keyspaceFn) - - /** - * The Session associated with this keySpace. - */ - lazy val session: Session = provider.session - - def cassandraVersions: Set[VersionNumber] = { - session.getCluster.getMetadata.getAllHosts - .asScala.map(_.getCassandraVersion) - .toSet[VersionNumber] - } - - def cassandraVersion: Option[VersionNumber] = { - val versions = cassandraVersions - - if (versions.nonEmpty) { - - val single = versions.headOption - - if (cassandraVersions.size == 1) { - single - } else { - - if (single.forall(item => versions.forall(item ==))) { - single - } else { - throw new RuntimeException( - s"Illegal single version comparison. You are connected to clusters of different versions." + - s"Available versions are: ${versions.mkString(", ")}" - ) with NoStackTrace - } - } - } else { - throw new RuntimeException("Could not extract any versions from the cluster, versions were empty") - } - } - - /** - * Trait that can be mixed into `CassandraTable` - * instances. - */ - trait Connector extends com.websudos.phantom.connectors.Connector with SessionAugmenterImplicits { - - lazy val provider = outer.provider - - lazy val keySpace = outer.name - - implicit val space: KeySpace = KeySpace(outer.name) - - def cassandraVersion: Option[VersionNumber] = outer.cassandraVersion - - def cassandraVersions: Set[VersionNumber] = outer.cassandraVersions - } - -} - -case class KeySpace(name: String) diff --git a/phantom-connectors/src/main/scala/com/websudos/phantom/connectors/RootConnector.scala b/phantom-connectors/src/main/scala/com/websudos/phantom/connectors/RootConnector.scala deleted file mode 100644 index 2bd59b0e1..000000000 --- a/phantom-connectors/src/main/scala/com/websudos/phantom/connectors/RootConnector.scala +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.connectors - -import com.datastax.driver.core.Session - -trait RootConnector { - - implicit def space: KeySpace - - implicit def session: Session -} diff --git a/phantom-connectors/src/main/scala/com/websudos/phantom/connectors/Versions.scala b/phantom-connectors/src/main/scala/com/websudos/phantom/connectors/Versions.scala deleted file mode 100644 index 0deb1e282..000000000 --- a/phantom-connectors/src/main/scala/com/websudos/phantom/connectors/Versions.scala +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.connectors - -import com.datastax.driver.core.{ VersionNumber => DatastaxVersionNumber } - -sealed trait VersionBuilder { - def apply(major: Int, minor: Int, patch: Int): DatastaxVersionNumber = { - DatastaxVersionNumber.parse(s"$major.$minor.$patch") - } -} - -object DefaultVersions extends VersionBuilder { - val `2.0.8` = apply(2, 0, 8) - val `2.0.9` = apply(2, 0, 9) - val `2.0.10` = apply(2, 0, 10) - val `2.0.11` = apply(2, 0, 11) - val `2.0.12` = apply(2, 0, 12) - val `2.0.13` = apply(2, 0, 13) - val `2.1.0` = apply(2, 1, 0) - val `2.1.1` = apply(2, 1, 1) - val `2.1.2` = apply(2, 1, 2) - val `2.1.3` = apply(2, 1, 3) - val `2.1.4` = apply(2, 1, 4) - val `2.1.5` = apply(2, 1, 5) - val `2.1.6` = apply(2, 1, 6) - val `2.1.7` = apply(2, 1, 7) - val `2.1.8` = apply(2, 1, 8) - val `2.1.9` = apply(2, 1, 9) - val `2.2.0` = apply(2, 2, 0) - val `2.2.1` = apply(2, 2, 1) - val `2.2.2` = apply(2, 2, 2) - val `2.2.8` = apply(2, 2, 8) - val `2.3.0` = apply(2, 3, 0) - val `3.0.0` = apply(2, 2, 2) -} \ No newline at end of file diff --git a/phantom-dsl/src/main/scala/com/outworkers/phantom/CassandraTable.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/CassandraTable.scala new file mode 100644 index 000000000..df0c34ec4 --- /dev/null +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/CassandraTable.scala @@ -0,0 +1,109 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom + +import com.datastax.driver.core.{Row, Session} +import com.outworkers.phantom.builder.clauses.DeleteClause +import com.outworkers.phantom.builder.query.{RootCreateQuery, _} +import com.outworkers.phantom.column.AbstractColumn +import com.outworkers.phantom.connectors.KeySpace +import com.outworkers.phantom.exceptions.{InvalidClusteringKeyException, InvalidPrimaryKeyException} +import com.outworkers.phantom.macros.TableHelper +import org.slf4j.LoggerFactory + +import scala.concurrent.duration._ +import scala.concurrent.{Await, ExecutionContextExecutor} + +/** + * Main representation of a Cassandra table. + * @tparam T Type of this table. + * @tparam R Type of record. + */ +abstract class CassandraTable[T <: CassandraTable[T, R], R]( + implicit helper: TableHelper[T, R] +) extends SelectTable[T, R] { self => + + def columns: Set[AbstractColumn[_]] = helper.fields(self) + + def secondaryKeys: Set[AbstractColumn[_]] = columns.filter(_.isSecondaryKey) + + def primaryKeys: Set[AbstractColumn[_]] = columns.filter(_.isPrimary).filterNot(_.isPartitionKey) + + def partitionKeys: Set[AbstractColumn[_]] = columns.filter(_.isPartitionKey) + + def clusteringColumns: Set[AbstractColumn[_]] = columns.filter(_.isClusteringKey) + + def tableKey: String = helper.tableKey(instance) + + @deprecated("Method replaced with macro implementation", "2.0.0") + def defineTableKey(): String = tableKey + + def instance: T = self.asInstanceOf[T] + + lazy val logger = LoggerFactory.getLogger(getClass.getName.stripSuffix("$")) + + type ListColumn[RR] = com.outworkers.phantom.column.ListColumn[T, R, RR] + type SetColumn[RR] = com.outworkers.phantom.column.SetColumn[T, R, RR] + type MapColumn[KK, VV] = com.outworkers.phantom.column.MapColumn[T, R, KK, VV] + type JsonColumn[RR] = com.outworkers.phantom.column.JsonColumn[T, R, RR] + type EnumColumn[RR <: Enumeration#Value] = com.outworkers.phantom.column.PrimitiveColumn[T, R, RR] + type OptionalEnumColumn[RR <: Enumeration#Value] = com.outworkers.phantom.column.OptionalPrimitiveColumn[T, R, RR] + type JsonSetColumn[RR] = com.outworkers.phantom.column.JsonSetColumn[T, R, RR] + type JsonListColumn[RR] = com.outworkers.phantom.column.JsonListColumn[T, R, RR] + type JsonMapColumn[KK,VV] = com.outworkers.phantom.column.JsonMapColumn[T, R, KK, VV] + type TupleColumn[RR] = com.outworkers.phantom.column.PrimitiveColumn[T, R, RR] + + def insertSchema()( + implicit session: Session, + keySpace: KeySpace, + ec: ExecutionContextExecutor + ): Unit = { + Await.result(autocreate(keySpace).future(), 10.seconds) + } + + def tableName: String = helper.tableName + + def fromRow(r: Row): R = helper.fromRow(instance, r) + + /** + * The new create mechanism introduced in Phantom 1.6.0. + * This uses the phantom proprietary QueryBuilder instead of the already available one in the underlying Java Driver. + * @return A root create block, with full support for all CQL Create query options. + */ + final def create: RootCreateQuery[T, R] = new RootCreateQuery(instance) + + def autocreate(keySpace: KeySpace): CreateQuery.Default[T, R] = create.ifNotExists()(keySpace) + + final def alter()(implicit keySpace: KeySpace): AlterQuery.Default[T, R] = AlterQuery(instance) + + final def update()(implicit keySpace: KeySpace): UpdateQuery.Default[T, R] = UpdateQuery(instance) + + final def insert()(implicit keySpace: KeySpace): InsertQuery.Default[T, R] = InsertQuery(instance) + + final def store()(implicit keySpace: KeySpace): InsertQuery.Default[T, R] = helper.store(instance) + + final def delete()(implicit keySpace: KeySpace): DeleteQuery.Default[T, R] = DeleteQuery[T, R](instance) + + final def delete( + conditions: (T => DeleteClause.Condition)* + )(implicit keySpace: KeySpace): DeleteQuery.Default[T, R] = { + DeleteQuery[T, R](instance, conditions.map(_(instance).qb): _*) + } + + final def truncate()( + implicit keySpace: KeySpace + ): TruncateQuery.Default[T, R] = TruncateQuery[T, R](instance) +} diff --git a/phantom-dsl/src/main/scala/com/outworkers/phantom/Manager.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/Manager.scala new file mode 100644 index 000000000..df4669ab5 --- /dev/null +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/Manager.scala @@ -0,0 +1,40 @@ +/* + * Copyright 2014-2015 Sphonic Ltd. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom + +import java.util.concurrent.Executors + +import org.slf4j.LoggerFactory + +import scala.concurrent.{ExecutionContext, ExecutionContextExecutor} + +object Manager { + + private[this] lazy val taskExecutor = Executors.newCachedThreadPool() + + implicit lazy val scalaExecutor: ExecutionContextExecutor = ExecutionContext.fromExecutor(taskExecutor) + + val logger = LoggerFactory.getLogger("com.outworkers.phantom") + + /** + * Shuts down the default task executors for Guava ListenableFutures and for Scala Futures. + * @deprecated ("Call shutdown on a [[com.outworkers.phantom.database.Database]] instead", "1.15.0") + */ + def shutdown(): Unit = { + logger.info("Shutting down executors") + taskExecutor.shutdown() + } +} diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/SelectTable.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/SelectTable.scala similarity index 92% rename from phantom-dsl/src/main/scala/com/websudos/phantom/SelectTable.scala rename to phantom-dsl/src/main/scala/com/outworkers/phantom/SelectTable.scala index 27d8c7b89..8fd3fe76b 100644 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/SelectTable.scala +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/SelectTable.scala @@ -1,44 +1,7 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom - -import com.datastax.driver.core.Row -import com.websudos.phantom.builder.clauses.OperatorClause -import com.websudos.phantom.builder.ops.SelectColumn -import com.websudos.phantom.builder.query.RootSelectBlock -import shapeless.ops.hlist.Mapper -import shapeless.ops.traversable.FromTraversable -import shapeless.ops.tuple.ToList -import shapeless.{Generic, HList, LUBConstraint, Poly1} +package com.outworkers.phantom -import scala.util.Try +import com.outworkers.phantom.builder.ops.SelectColumn +import com.outworkers.phantom.builder.query.RootSelectBlock trait SelectTable[T <: CassandraTable[T, R], R] { self: CassandraTable[T, R] => diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/batch/BatchQuery.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/batch/BatchQuery.scala similarity index 70% rename from phantom-dsl/src/main/scala/com/websudos/phantom/batch/BatchQuery.scala rename to phantom-dsl/src/main/scala/com/outworkers/phantom/batch/BatchQuery.scala index 5457815b3..47c03c597 100644 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/batch/BatchQuery.scala +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/batch/BatchQuery.scala @@ -1,39 +1,25 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.batch +package com.outworkers.phantom.batch import com.datastax.driver.core.{QueryOptions => _, _} -import com.websudos.phantom.builder.query._ -import com.websudos.phantom.builder.syntax.CQLSyntax -import com.websudos.phantom.builder.{ConsistencyBound, QueryBuilder, Specified, Unspecified} -import com.websudos.phantom.connectors.KeySpace +import com.outworkers.phantom.builder.query._ +import com.outworkers.phantom.builder.syntax.CQLSyntax +import com.outworkers.phantom.builder.{ConsistencyBound, QueryBuilder, Specified, Unspecified} +import com.outworkers.phantom.connectors.KeySpace import scala.annotation.implicitNotFound import scala.concurrent.{ExecutionContextExecutor, Future => ScalaFuture} diff --git a/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/Bounds.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/Bounds.scala new file mode 100644 index 000000000..711cf65b9 --- /dev/null +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/Bounds.scala @@ -0,0 +1,32 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.builder + +sealed trait LimitBound +trait Limited extends LimitBound +trait Unlimited extends LimitBound + +sealed trait OrderBound +trait Ordered extends OrderBound +trait Unordered extends OrderBound + +sealed trait ConsistencyBound +trait Specified extends ConsistencyBound +trait Unspecified extends ConsistencyBound + +sealed trait WhereBound +trait Chainned extends WhereBound +trait Unchainned extends WhereBound \ No newline at end of file diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/QueryBuilder.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/QueryBuilder.scala similarity index 60% rename from phantom-dsl/src/main/scala/com/websudos/phantom/builder/QueryBuilder.scala rename to phantom-dsl/src/main/scala/com/outworkers/phantom/builder/QueryBuilder.scala index 1e278f9dc..e3b67405d 100644 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/QueryBuilder.scala +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/QueryBuilder.scala @@ -1,38 +1,24 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder +package com.outworkers.phantom.builder -import com.websudos.phantom.builder.query.CQLQuery -import com.websudos.phantom.builder.serializers._ -import com.websudos.phantom.builder.syntax.CQLSyntax -import com.websudos.phantom.connectors.KeySpace +import com.outworkers.phantom.builder.query.CQLQuery +import com.outworkers.phantom.builder.serializers._ +import com.outworkers.phantom.builder.syntax.CQLSyntax +import com.outworkers.phantom.connectors.KeySpace case class QueryBuilderConfig(caseSensitiveTables: Boolean) @@ -135,4 +121,4 @@ abstract class QueryBuilder(val config: QueryBuilderConfig = QueryBuilderConfig. } -private[phantom] object QueryBuilder extends QueryBuilder(QueryBuilderConfig.Default) +object QueryBuilder extends QueryBuilder(QueryBuilderConfig.Default) diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/clauses/QueryCondition.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/clauses/QueryCondition.scala similarity index 68% rename from phantom-dsl/src/main/scala/com/websudos/phantom/builder/clauses/QueryCondition.scala rename to phantom-dsl/src/main/scala/com/outworkers/phantom/builder/clauses/QueryCondition.scala index 4590136ee..37666c0c5 100644 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/clauses/QueryCondition.scala +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/clauses/QueryCondition.scala @@ -1,40 +1,26 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.clauses +package com.outworkers.phantom.builder.clauses import com.datastax.driver.core.Row -import com.websudos.phantom.builder.QueryBuilder -import com.websudos.phantom.builder.query.CQLQuery -import com.websudos.phantom.builder.syntax.CQLSyntax -import com.websudos.phantom.column.AbstractColumn -import com.websudos.phantom.dsl.? +import com.outworkers.phantom.builder.QueryBuilder +import com.outworkers.phantom.builder.query.CQLQuery +import com.outworkers.phantom.builder.syntax.CQLSyntax +import com.outworkers.phantom.column.AbstractColumn +import com.outworkers.phantom.dsl.? import shapeless.{::, HList, HNil} abstract class QueryCondition[T <: HList](val qb: CQLQuery) diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/ops/ImplicitMechanism.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/ops/ImplicitMechanism.scala similarity index 77% rename from phantom-dsl/src/main/scala/com/websudos/phantom/builder/ops/ImplicitMechanism.scala rename to phantom-dsl/src/main/scala/com/outworkers/phantom/builder/ops/ImplicitMechanism.scala index c907eb4bb..bc29be2a1 100644 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/ops/ImplicitMechanism.scala +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/ops/ImplicitMechanism.scala @@ -1,40 +1,26 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.ops - -import com.websudos.phantom.builder.QueryBuilder -import com.websudos.phantom.builder.clauses.{WhereClause, OrderingColumn, CompareAndSetClause} -import com.websudos.phantom.builder.primitives.Primitive -import com.websudos.phantom.column._ -import com.websudos.phantom.dsl._ -import com.websudos.phantom.keys.{Undroppable, Indexed} +package com.outworkers.phantom.builder.ops + +import com.outworkers.phantom.builder.QueryBuilder +import com.outworkers.phantom.builder.clauses.{WhereClause, OrderingColumn, CompareAndSetClause} +import com.outworkers.phantom.builder.primitives.Primitive +import com.outworkers.phantom.column._ +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.keys.{Undroppable, Indexed} import shapeless.<:!< import scala.annotation.implicitNotFound @@ -169,9 +155,9 @@ private[phantom] trait ImplicitMechanism extends ModifyMechanism { implicit def optionalIndexToQueryColumn[T : Primitive](col: AbstractColumn[Option[T]] with Indexed): QueryColumn[T] = new QueryColumn(col.name) - implicit def orderingColumn[RR](col: AbstractColumn[RR] with PrimaryKey[RR]): OrderingColumn[RR] = new OrderingColumn[RR](col) + implicit def orderingColumn[RR](col: AbstractColumn[RR] with PrimaryKey): OrderingColumn[RR] = new OrderingColumn[RR](col) - implicit def setColumnToQueryColumn[T <: CassandraTable[T, R], R, RR](col: AbstractSetColumn[T, R, RR] with Index[Set[RR]]): SetConditionals[T, R, RR] = { + implicit def setColumnToQueryColumn[T <: CassandraTable[T, R], R, RR](col: AbstractSetColumn[T, R, RR] with Index): SetConditionals[T, R, RR] = { new SetConditionals(col) } @@ -201,7 +187,7 @@ private[phantom] trait ImplicitMechanism extends ModifyMechanism { * @return A MapConditionals class with CONTAINS support. */ implicit def mapColumnToQueryColumn[T <: CassandraTable[T, R], R, K, V]( - col: AbstractMapColumn[T, R, K, V] with Index[Map[K, V]] + col: AbstractMapColumn[T, R, K, V] with Index )(implicit ev: col.type <:!< Keys): MapConditionals[T, R, K, V] = { new MapConditionals(col) } @@ -218,7 +204,7 @@ private[phantom] trait ImplicitMechanism extends ModifyMechanism { * @return A MapConditionals class with CONTAINS KEY support. */ implicit def mapKeysColumnToQueryColumn[T <: CassandraTable[T, R], R, K, V]( - col: AbstractMapColumn[T, R, K, V] with Index[Map[K, V]] with Keys): MapKeyConditionals[T, R, K, V] = { + col: AbstractMapColumn[T, R, K, V] with Index with Keys): MapKeyConditionals[T, R, K, V] = { new MapKeyConditionals(col) } diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/ops/Modify.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/ops/Modify.scala similarity index 80% rename from phantom-dsl/src/main/scala/com/websudos/phantom/builder/ops/Modify.scala rename to phantom-dsl/src/main/scala/com/outworkers/phantom/builder/ops/Modify.scala index 2b59a0adf..555e6463e 100644 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/ops/Modify.scala +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/ops/Modify.scala @@ -1,42 +1,28 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.ops +package com.outworkers.phantom.builder.ops import com.datastax.driver.core.Row -import com.websudos.phantom.CassandraTable -import com.websudos.phantom.builder.QueryBuilder -import com.websudos.phantom.builder.clauses.{PreparedWhereClause, UpdateClause} -import com.websudos.phantom.builder.query.CQLQuery -import com.websudos.phantom.builder.query.prepared.PrepareMark -import com.websudos.phantom.column._ -import com.websudos.phantom.keys._ +import com.outworkers.phantom.CassandraTable +import com.outworkers.phantom.builder.QueryBuilder +import com.outworkers.phantom.builder.clauses.{PreparedWhereClause, UpdateClause} +import com.outworkers.phantom.builder.query.CQLQuery +import com.outworkers.phantom.builder.query.prepared.PrepareMark +import com.outworkers.phantom.column._ +import com.outworkers.phantom.keys._ import shapeless.<:!< import scala.annotation.implicitNotFound diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/ops/Operators.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/ops/Operators.scala similarity index 72% rename from phantom-dsl/src/main/scala/com/websudos/phantom/builder/ops/Operators.scala rename to phantom-dsl/src/main/scala/com/outworkers/phantom/builder/ops/Operators.scala index d84434715..086944694 100644 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/ops/Operators.scala +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/ops/Operators.scala @@ -1,45 +1,31 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.ops +package com.outworkers.phantom.builder.ops import java.util.Date import com.datastax.driver.core.Session -import com.websudos.phantom.builder.QueryBuilder -import com.websudos.phantom.builder.clauses.OperatorClause.Condition -import com.websudos.phantom.builder.clauses.{OperatorClause, TypedClause, WhereClause} -import com.websudos.phantom.builder.primitives.Primitive -import com.websudos.phantom.builder.query.CQLQuery -import com.websudos.phantom.builder.syntax.CQLSyntax -import com.websudos.phantom.column.{AbstractColumn, Column, TimeUUIDColumn} -import com.websudos.phantom.connectors.SessionAugmenterImplicits +import com.outworkers.phantom.builder.QueryBuilder +import com.outworkers.phantom.builder.clauses.OperatorClause.Condition +import com.outworkers.phantom.builder.clauses.{OperatorClause, TypedClause, WhereClause} +import com.outworkers.phantom.builder.primitives.Primitive +import com.outworkers.phantom.builder.query.CQLQuery +import com.outworkers.phantom.builder.syntax.CQLSyntax +import com.outworkers.phantom.column.{AbstractColumn, Column, TimeUUIDColumn} +import com.outworkers.phantom.connectors.SessionAugmenterImplicits import org.joda.time.DateTime import shapeless.{=:!=, HList} diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/ops/QueryColumn.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/ops/QueryColumn.scala similarity index 79% rename from phantom-dsl/src/main/scala/com/websudos/phantom/builder/ops/QueryColumn.scala rename to phantom-dsl/src/main/scala/com/outworkers/phantom/builder/ops/QueryColumn.scala index 4e2d02a7f..c090b3583 100644 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/ops/QueryColumn.scala +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/ops/QueryColumn.scala @@ -1,38 +1,24 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.ops +package com.outworkers.phantom.builder.ops -import com.websudos.phantom.builder.QueryBuilder -import com.websudos.phantom.builder.clauses._ -import com.websudos.phantom.builder.primitives.Primitive -import com.websudos.phantom.builder.query.prepared.{PrepareMark} +import com.outworkers.phantom.builder.QueryBuilder +import com.outworkers.phantom.builder.clauses._ +import com.outworkers.phantom.builder.primitives.Primitive +import com.outworkers.phantom.builder.query.prepared.{PrepareMark} /** * A class enforcing columns used in where clauses to be indexed. @@ -199,7 +185,7 @@ class MapKeyUpdateClause[K : Primitive, V : Primitive](val column: String, val k /** * Overloaded variants of setTo that allows using prepared statements for map key updates. - * This will only accept the ? global singleton found in [[com.websudos.phantom.dsl]]. + * This will only accept the ? global singleton found in [[com.outworkers.phantom.dsl]]. * When used, the final "bind" to the prepared clause will require an additional V type * in the provided tuple to match the type of the MapColumn being updated. * diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/ops/TokenOps.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/ops/TokenOps.scala similarity index 58% rename from phantom-dsl/src/main/scala/com/websudos/phantom/builder/ops/TokenOps.scala rename to phantom-dsl/src/main/scala/com/outworkers/phantom/builder/ops/TokenOps.scala index 36835e010..a904a52ae 100644 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/ops/TokenOps.scala +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/ops/TokenOps.scala @@ -1,36 +1,22 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.ops +package com.outworkers.phantom.builder.ops -import com.websudos.phantom.builder.primitives.Primitive -import com.websudos.phantom.column.AbstractColumn +import com.outworkers.phantom.builder.primitives.Primitive +import com.outworkers.phantom.column.AbstractColumn import shapeless._ object TokenTypes { diff --git a/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/primitives/Primitive.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/primitives/Primitive.scala new file mode 100644 index 000000000..7d7f8b978 --- /dev/null +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/primitives/Primitive.scala @@ -0,0 +1,161 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.builder.primitives + +import java.util.Date + +import com.datastax.driver.core.{GettableByIndexData, GettableByNameData, GettableData, LocalDate} +import org.joda.time.DateTime + +import scala.annotation.implicitNotFound +import scala.util.control.NoStackTrace +import scala.util.{Failure, Try} + +private[phantom] object DateSerializer { + + def asCql(date: Date): String = date.getTime.toString + + def asCql(date: LocalDate): String = date.getMillisSinceEpoch.toString + + def asCql(date: org.joda.time.LocalDate): String = date.toString + + def asCql(date: DateTime): String = date.getMillis.toString +} + +@implicitNotFound(msg = "Type ${RR} must be a pre-defined Cassandra primitive.") +abstract class Primitive[RR] { + + /** + * A way of maintaining compatibility with the underlying Java driver. + * The driver often type checks records before casting them and to do that + * it needs the correct Java Class obtained via classOf[] or .getClass in Java. + * + * We use this because the appropriate Scala type is often different than the + * Java equivalent. For instance, we don't want users to deal with [[java.util.List]], + * even if the Java Driver will attempt to look for one. + */ + type PrimitiveType + + protected[this] def nullCheck[T](column: String, row: GettableByNameData)(fn: GettableByNameData => T): Try[T] = { + if (Option(row).isEmpty || row.isNull(column)) { + Failure(new Exception(s"Column $column is null") with NoStackTrace) + } else { + Try(fn(row)) + } + } + + protected[this] def nullCheck[T](index: Int, row: GettableByIndexData)(fn: GettableByIndexData => T): Try[T] = { + if (Option(row).isEmpty || row.isNull(index)) { + Failure(new Exception(s"Column with index $index is null") with NoStackTrace) + } else { + Try(fn(row)) + } + } + + /** + * Converts the type to a CQL compatible string. + * The primitive is responsible for handling all aspects of adequate escaping as well. + * This is used to generate the final queries from domain objects. + * @param value The strongly typed value. + * @return The string representation of the value with respect to CQL standards. + */ + def asCql(value: RR): String + + def cassandraType: String + + def fromRow(column: String, row: GettableByNameData): Try[RR] + + def fromRow(index: Int, row: GettableByIndexData): Try[RR] + + def fromString(value: String): RR + + def clz: Class[PrimitiveType] + + def extract(obj: PrimitiveType): RR = identity(obj).asInstanceOf[RR] + + def frozen: Boolean = false +} + +object Primitive { + + /** + * A helper for implicit lookups that require the refined inner abstract type of a concrete + * primitive implementation produced by an implicit macro. + * This is useful to eliminate a compiler warning produced for map columns, where + * we need to manually cast values to their PrimitiveType after extraction + * just to please the compiler. + * @tparam Outer The outer, visible Scala type of a primitive. + * @tparam Inner The inner, primitive type, used to unwrap Java bindings. + */ + type Aux[Outer, Inner] = Primitive[Outer] { type PrimitiveType = Inner } + + /** + * !! Warning !! Black magic going on. This will use the excellent macro compat + * library to macro materialise an instance of the required primitive based on the type argument. + * If this does not highlight properly in your IDE, fear not, it works on my machine :) + * @tparam T The type parameter to materialise a primitive for. + * @return A concrete instance of a primitive, materialised via implicit blackbox macros. + */ + implicit def materializer[T]: Primitive[T] = macro PrimitiveMacro.materializer[T] + + /** + * Derives primitives and encodings for a non standard type. + * @param to The function that converts a [[Target]] instance to a [[Source]] instance. + * @param from The function that converts a [[Source]] instance to a [[Target]] instance. + * @tparam Target The type you want to derive a primitive for. + * @tparam Source The source type of the primitive, must already have a primitive defined for it. + * @return A new primitive that can interact with the target type. + */ + def derive[Target, Source : Primitive](to: Target => Source)(from: Source => Target): Primitive[Target] = { + + val source = implicitly[Primitive[Source]] + + new Primitive[Target] { + override type PrimitiveType = source.PrimitiveType + + /** + * Converts the type to a CQL compatible string. + * The primitive is responsible for handling all aspects of adequate escaping as well. + * This is used to generate the final queries from domain objects. + * + * @param value The strongly typed value. + * @return The string representation of the value with respect to CQL standards. + */ + override def asCql(value: Target): String = source.asCql(to(value)) + + override def cassandraType: String = source.cassandraType + + override def fromRow(column: String, row: GettableByNameData): Try[Target] = { + source.fromRow(column, row) map from + } + + override def fromRow(index: Int, row: GettableByIndexData): Try[Target] = { + source.fromRow(index, row) map from + } + override def fromString(value: String): Target = from(source.fromString(value)) + + override def clz: Class[source.PrimitiveType] = source.clz + } + } + + /** + * Convenience method to materialise the context bound and return a reference to it. + * This is somewhat shorter syntax than using implicitly. + * @tparam RR The type of the primitive to retrieve. + * @return A reference to a concrete materialised implementation of a primitive for the given type. + */ + def apply[RR : Primitive]: Primitive[RR] = implicitly[Primitive[RR]] +} diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/primitives/PrimitiveMacro.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/primitives/PrimitiveMacro.scala similarity index 52% rename from phantom-dsl/src/main/scala/com/websudos/phantom/builder/primitives/PrimitiveMacro.scala rename to phantom-dsl/src/main/scala/com/outworkers/phantom/builder/primitives/PrimitiveMacro.scala index c3470a502..181e0ccd3 100644 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/primitives/PrimitiveMacro.scala +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/primitives/PrimitiveMacro.scala @@ -1,33 +1,19 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.primitives +package com.outworkers.phantom.builder.primitives import java.net.InetAddress import java.nio.ByteBuffer @@ -36,13 +22,15 @@ import java.util.{Date, UUID} import macrocompat.bundle import org.joda.time.DateTime +import scala.collection.concurrent.TrieMap import scala.language.experimental.macros @bundle class PrimitiveMacro(val c: scala.reflect.macros.blackbox.Context) { import c.universe._ - val rowType = tq"com.datastax.driver.core.GettableData" + val rowByNameType = tq"com.datastax.driver.core.GettableByNameData" + val rowByIndexType = tq"com.datastax.driver.core.GettableByIndexData" val boolType = tq"scala.Boolean" val strType: Tree = tq"java.lang.String" val intType: Tree = tq"scala.Int" @@ -53,6 +41,7 @@ class PrimitiveMacro(val c: scala.reflect.macros.blackbox.Context) { val longType: Tree = tq"scala.Long" val floatType: Tree = tq"scala.Float" val dateType: Tree = tq"java.util.Date" + val tupleValue: Tree = tq"com.datastax.driver.core.TupleValue" val localDate: Tree = tq"com.datastax.driver.core.LocalDate" val dateTimeType: Tree = tq"org.joda.time.DateTime" val localJodaDate: Tree = tq"org.joda.time.LocalDate" @@ -61,13 +50,23 @@ class PrimitiveMacro(val c: scala.reflect.macros.blackbox.Context) { val bigIntType = tq"scala.math.BigInt" val bufferType = tq"java.nio.ByteBuffer" - val cql = q"com.websudos.phantom.builder.query.CQLQuery" - val syntax = q"com.websudos.phantom.builder.syntax.CQLSyntax" + val builder = q"com.outworkers.phantom.builder" + val cql = q"com.outworkers.phantom.builder.query.CQLQuery" + val syntax = q"com.outworkers.phantom.builder.syntax.CQLSyntax" + + val prefix = q"com.outworkers.phantom.builder.primitives" def tryT(x: Tree): Tree = tq"scala.util.Try[$x]" + def tryT(x: Type): Tree = tq"scala.util.Try[$x]" def typed[A : c.WeakTypeTag]: Symbol = weakTypeOf[A].typeSymbol + /** + * Adds a caching layer for subsequent requests to materialise the same primitive type. + * This adds a simplistic caching layer that computes primitives based on types. + */ + val treeCache = TrieMap.empty[Symbol, Tree] + object Symbols { val intSymbol = typed[Int] val byteSymbol = typed[Byte] @@ -96,6 +95,7 @@ class PrimitiveMacro(val c: scala.reflect.macros.blackbox.Context) { val tpe = weakTypeOf[T].typeSymbol val tree = tpe match { + case sym if sym.name.toTypeName.decodedName.toString.contains("Tuple") => tuplePrimitive[T]() case Symbols.boolSymbol => booleanPrimitive case Symbols.byteSymbol => bytePrimitive case Symbols.shortSymbol => shortPrimitive @@ -113,17 +113,17 @@ class PrimitiveMacro(val c: scala.reflect.macros.blackbox.Context) { case Symbols.bigInt => bigIntPrimitive case Symbols.bigDecimal => bigDecimalPrimitive case Symbols.buffer => bufferPrimitive - case Symbols.enum => enumPrimitive[T]() - case Symbols.listSymbol => listPrimitive[T]() - case Symbols.setSymbol => setPrimitive[T]() - case Symbols.mapSymbol => mapPrimitive[T]() - case _ => c.abort(c.enclosingPosition, s"Cannot find primitive implemention for $tpe") + case Symbols.enum => treeCache.getOrElseUpdate(typed[T], enumPrimitive[T]()) + case Symbols.listSymbol => treeCache.getOrElseUpdate(typed[T], listPrimitive[T]()) + case Symbols.setSymbol => treeCache.getOrElseUpdate(typed[T], setPrimitive[T]()) + case Symbols.mapSymbol => treeCache.getOrElseUpdate(typed[T], mapPrimitive[T]()) + case _ => c.abort(c.enclosingPosition, s"Cannot find primitive implementation for $tpe") } c.Expr[Primitive[T]](tree) } - def primitive(nm: String): Tree = q"new com.websudos.phantom.builder.primitives.Primitives.${TypeName(nm)}" + def primitive(nm: String): Tree = q"new $prefix.Primitives.${TypeName(nm)}" val booleanPrimitive: Tree = primitive("BooleanIsPrimitive") @@ -166,12 +166,91 @@ class PrimitiveMacro(val c: scala.reflect.macros.blackbox.Context) { innerTpe match { case Some(inner) => { - q"""com.websudos.phantom.builder.primitives.Primitives.list[$inner]""" + q"""$prefix.Primitives.list[$inner]""" } case None => c.abort(c.enclosingPosition, "Expected inner type to be defined") } } + case class TupleType( + term: TermName, + cassandraType: Tree, + extractor: Tree, + serializer: Tree + ) + + def tupleFields(tpe: Type): List[TupleType] = { + val sourceTerm = TermName("source") + + tpe.typeArgs.zipWithIndex.map { + case (argTpe, i) => { + val currentTerm = TermName(s"tp${i + 1}") + val tupleRef = TermName("_" + (i + 1).toString) + + val index = q"$i" + + TupleType( + currentTerm, + q"$prefix.Primitive[$argTpe].cassandraType", + fq"$currentTerm <- $prefix.Primitive[$argTpe].fromRow(index = $index, row = $sourceTerm)", + q"$prefix.Primitive[$argTpe].asCql(tp.$tupleRef)" + ) + } + } + } + + def tuplePrimitive[T : WeakTypeTag](): Tree = { + val tpe = weakTypeOf[T] + + val comp = tpe.typeSymbol.name.toTermName + val sourceTerm = TermName("source") + + val fields: List[TupleType] = tupleFields(tpe) + + q"""new $prefix.Primitive[$tpe] { + override type PrimitiveType = $tupleValue + + override def cassandraType: $strType = { + $builder.QueryBuilder.Collections + .tupleType(..${fields.map(_.cassandraType)}) + .queryString + } + + override def extract($sourceTerm: $tupleValue): $tpe = { + val tp = for (..${fields.map(_.extractor)}) yield $comp.apply(..${fields.map(_.term)}) + tp.get + } + + override def fromRow(name: $strType, row: $rowByNameType): ${tryT(tpe)} = { + if (scala.Option(row).isEmpty || row.isNull(name)) { + scala.util.Failure(new Exception("Column with name " + name + " is null") with scala.util.control.NoStackTrace) + } else { + val $sourceTerm = row.getTupleValue(name) + for (..${fields.map(_.extractor)}) yield $comp.apply(..${fields.map(_.term)}) + } + } + + override def fromRow(index: $intType, row: $rowByIndexType): ${tryT(tpe)} = { + if (scala.Option(row).isEmpty || row.isNull(index)) { + scala.util.Failure(new Exception("Column with index " + index + " is null") with scala.util.control.NoStackTrace) + } else { + val $sourceTerm = row.getTupleValue(index) + for (..${fields.map(_.extractor)}) yield $comp.apply(..${fields.map(_.term)}) + } + } + + override def asCql(tp: $tpe): $strType = { + $builder.QueryBuilder.Collections.tupled(..${fields.map(_.serializer)}).queryString + } + + override def fromString(value: $strType): $tpe = ??? + + override def clz: Class[$tupleValue] = classOf[$tupleValue] + + override def frozen: $boolType = true + }""" + } + def mapPrimitive[T : WeakTypeTag](): Tree = { val tpe = weakTypeOf[T] @@ -180,7 +259,7 @@ class PrimitiveMacro(val c: scala.reflect.macros.blackbox.Context) { (keyTpe, valueType) match { case (Some(key), Some(value)) => { - q"""com.websudos.phantom.builder.primitives.Primitives.map[$key, $value]""" + q"""$prefix.Primitives.map[$key, $value]""" } case _ => c.abort(c.enclosingPosition, "Expected inner type to be defined") } @@ -193,7 +272,7 @@ class PrimitiveMacro(val c: scala.reflect.macros.blackbox.Context) { innerTpe match { case Some(inner) => { - q"""com.websudos.phantom.builder.primitives.Primitives.set[$inner]""" + q"""$prefix.Primitives.set[$inner]""" } case None => c.abort(c.enclosingPosition, "Expected inner type to be defined") } @@ -203,14 +282,14 @@ class PrimitiveMacro(val c: scala.reflect.macros.blackbox.Context) { val tpe = tag.tpe val comp = c.parse(s"${tag.tpe.toString.replace("#Value", "")}") - q""" new com.websudos.phantom.builder.primitives.Primitive[$tpe] { - val strP = implicitly[com.websudos.phantom.builder.primitives.Primitive[String]] + q""" new $prefix.Primitive[$tpe] { + val strP = implicitly[$prefix.Primitive[$strType]] override type PrimitiveType = java.lang.String override def cassandraType: $strType = strP.cassandraType - override def fromRow(name: $strType, row: $rowType): scala.util.Try[$tpe] = { + override def fromRow(name: $strType, row: $rowByNameType): scala.util.Try[$tpe] = { nullCheck(name, row) { r => $comp.values.find(_.toString == r.getString(name)) match { case Some(value) => value @@ -219,12 +298,21 @@ class PrimitiveMacro(val c: scala.reflect.macros.blackbox.Context) { } } - override def asCql(value: $tpe): String = { + override def fromRow(index: $intType, row: $rowByIndexType): scala.util.Try[$tpe] = { + nullCheck(index, row) { + r => $comp.values.find(_.toString == r.getString(index)) match { + case Some(value) => value + case _ => throw new Exception("Value not found in enumeration") with scala.util.control.NoStackTrace + } + } + } + + override def asCql(value: $tpe): $strType = { strP.asCql(value.toString) } override def fromString(value: $strType): $tpe = { - $comp.values.find(value == _.toString).getOrElse(None.orNull) + $comp.values.find(value == _.toString).getOrElse(scala.None.orNull) } override def clz: Class[$strType] = classOf[$strType] diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/primitives/Primitives.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/primitives/Primitives.scala similarity index 60% rename from phantom-dsl/src/main/scala/com/websudos/phantom/builder/primitives/Primitives.scala rename to phantom-dsl/src/main/scala/com/outworkers/phantom/builder/primitives/Primitives.scala index 8135acb21..d67fccc1a 100644 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/primitives/Primitives.scala +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/primitives/Primitives.scala @@ -1,43 +1,29 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.primitives +package com.outworkers.phantom.builder.primitives import java.net.InetAddress import java.nio.ByteBuffer import java.util.{Date, UUID} -import com.datastax.driver.core.{GettableData, LocalDate} import com.datastax.driver.core.utils.Bytes -import com.websudos.phantom.builder.QueryBuilder -import com.websudos.phantom.builder.query.CQLQuery -import com.websudos.phantom.builder.syntax.CQLSyntax +import com.datastax.driver.core.{GettableByIndexData, GettableByNameData, GettableData, LocalDate} +import com.outworkers.phantom.builder.QueryBuilder +import com.outworkers.phantom.builder.query.CQLQuery +import com.outworkers.phantom.builder.syntax.CQLSyntax import org.joda.time.{DateTime, DateTimeZone} import scala.collection.JavaConverters._ @@ -55,10 +41,14 @@ object Primitives { override def fromString(value: String): String = value - override def fromRow(column: String, row: GettableData): Try[String] = { + override def fromRow(column: String, row: GettableByNameData): Try[String] = { nullCheck(column, row)(_.getString(column)) } + override def fromRow(index: Int, row: GettableByIndexData): Try[String] = { + nullCheck(index, row)(_.getString(index)) + } + override def clz: Class[String] = classOf[String] } @@ -72,8 +62,12 @@ object Primitives { override def fromString(value: String): Int = value.toInt - override def fromRow(column: String, row: GettableData): Try[Int] = nullCheck(column, row) { - r => r.getInt(column) + override def fromRow(column: String, row: GettableByNameData): Try[Int] = nullCheck(column, row) { + _.getInt(column) + } + + override def fromRow(index: Int, row: GettableByIndexData): Try[Int] = { + nullCheck(index, row)(_.getInt(index)) } override def clz: Class[java.lang.Integer] = classOf[java.lang.Integer] @@ -89,8 +83,12 @@ object Primitives { override def fromString(value: String): Short = value.toShort - override def fromRow(column: String, row: GettableData): Try[Short] = nullCheck(column, row) { - r => r.getShort(column) + override def fromRow(column: String, row: GettableByNameData): Try[Short] = { + nullCheck(column, row)(_.getShort(column)) + } + + override def fromRow(index: Int, row: GettableByIndexData): Try[Short] = { + nullCheck(index, row)(_.getShort(index)) } override def clz: Class[java.lang.Short] = classOf[java.lang.Short] @@ -106,11 +104,15 @@ object Primitives { override def fromString(value: String): Byte = value.toByte - override def fromRow(column: String, row: GettableData): Try[Byte] = nullCheck(column, row) { - r => r.getByte(column) + override def fromRow(column: String, row: GettableByNameData): Try[Byte] = { + nullCheck(column, row)(_.getByte(column)) } override def clz: Class[java.lang.Byte] = classOf[java.lang.Byte] + + override def fromRow(index: Int, row: GettableByIndexData): Try[Byte] = { + nullCheck(index, row)(_.getByte(index)) + } } class DoublePrimitive extends Primitive[Double] { @@ -123,11 +125,15 @@ object Primitives { override def fromString(value: String): Double = value.toDouble - override def fromRow(column: String, row: GettableData): Try[Double] = nullCheck(column, row) { - r => r.getDouble(column) + override def fromRow(column: String, row: GettableByNameData): Try[Double] = { + nullCheck(column, row)(_.getDouble(column)) } override def clz: Class[java.lang.Double] = classOf[java.lang.Double] + + override def fromRow(index: Int, row: GettableByIndexData): Try[Double] = { + nullCheck(index, row)(_.getDouble(index)) + } } class LongPrimitive extends Primitive[Long] { @@ -140,10 +146,14 @@ object Primitives { override def fromString(value: String): Long = value.toLong - override def fromRow(column: String, row: GettableData): Try[Long] = { + override def fromRow(column: String, row: GettableByNameData): Try[Long] = { nullCheck(column, row)(_.getLong(column)) } + override def fromRow(index: Int, row: GettableByIndexData): Try[Long] = { + nullCheck(index, row)(_.getLong(index)) + } + override def clz: Class[java.lang.Long] = classOf[java.lang.Long] } @@ -157,8 +167,12 @@ object Primitives { override def fromString(value: String): Float = value.toFloat - override def fromRow(column: String, row: GettableData): Try[Float] = nullCheck(column, row) { - r => r.getFloat(column) + override def fromRow(column: String, row: GettableByNameData): Try[Float] = { + nullCheck(column, row)(r => r.getFloat(column)) + } + + override def fromRow(index: Int, row: GettableByIndexData): Try[Float] = { + nullCheck(index, row)(_.getFloat(index)) } override def clz: Class[java.lang.Float] = classOf[java.lang.Float] @@ -174,8 +188,12 @@ object Primitives { override def fromString(value: String): UUID = UUID.fromString(value) - override def fromRow(column: String, row: GettableData): Try[UUID] = nullCheck(column, row) { - r => r.getUUID(column) + override def fromRow(column: String, row: GettableByNameData): Try[UUID] = { + nullCheck(column, row)(_.getUUID(column)) + } + + override def fromRow(index: Int, row: GettableByIndexData): Try[UUID] = { + nullCheck(index, row)(_.getUUID(index)) } override def clz: Class[UUID] = classOf[UUID] @@ -194,8 +212,12 @@ object Primitives { DateSerializer.asCql(value) } - override def fromRow(column: String, row: GettableData): Try[Date] = nullCheck(column, row) { - r => r.getTimestamp(column) + override def fromRow(column: String, row: GettableByNameData): Try[Date] = { + nullCheck(column, row)(_.getTimestamp(column)) + } + + override def fromRow(index: Int, row: GettableByIndexData): Try[Date] = { + nullCheck(index, row)(_.getTimestamp(index)) } override def fromString(value: String): Date = { @@ -218,14 +240,18 @@ object Primitives { DateSerializer.asCql(value) } - override def fromRow(column: String, row: GettableData): Try[LocalDate] = nullCheck(column, row) { - r => r.getDate(column) + override def fromRow(column: String, row: GettableByNameData): Try[LocalDate] = { + nullCheck(column, row)(_.getDate(column)) } override def fromString(value: String): LocalDate = { LocalDate.fromMillisSinceEpoch(new DateTime(value, DateTimeZone.UTC).getMillis) } + override def fromRow(index: Int, row: GettableByIndexData): Try[LocalDate] = { + nullCheck(index, row)(_.getDate(index)) + } + override def clz: Class[LocalDate] = classOf[LocalDate] } @@ -245,8 +271,10 @@ object Primitives { CQLQuery.empty.singleQuote(DateSerializer.asCql(value)) } - override def fromRow(column: String, row: GettableData): Try[org.joda.time.LocalDate] = nullCheck(column, row) { - r => new DateTime(r.getDate(column).getMillisSinceEpoch, DateTimeZone.UTC).toLocalDate + override def fromRow(column: String, row: GettableByNameData): Try[org.joda.time.LocalDate] = { + nullCheck(column, row) { + r => new DateTime(r.getDate(column).getMillisSinceEpoch, DateTimeZone.UTC).toLocalDate + } } override def fromString(value: String): org.joda.time.LocalDate = { @@ -254,6 +282,12 @@ object Primitives { } override def clz: Class[com.datastax.driver.core.LocalDate] = classOf[com.datastax.driver.core.LocalDate] + + override def fromRow(index: Int, row: GettableByIndexData): Try[org.joda.time.LocalDate] = { + nullCheck(index, row) { + r => new DateTime(r.getDate(index).getMillisSinceEpoch, DateTimeZone.UTC).toLocalDate + } + } } class DateTimeIsPrimitive extends Primitive[DateTime] { @@ -266,8 +300,10 @@ object Primitives { DateSerializer.asCql(value) } - override def fromRow(column: String, row: GettableData): Try[DateTime] = nullCheck(column, row) { - r => new DateTime(r.getTimestamp(column), DateTimeZone.UTC) + override def fromRow(column: String, row: GettableByNameData): Try[DateTime] = { + nullCheck(column, row) { + r => new DateTime(r.getTimestamp(column), DateTimeZone.UTC) + } } override def fromString(value: String): DateTime = new DateTime(value, DateTimeZone.UTC) @@ -275,6 +311,12 @@ object Primitives { override def clz: Class[Date] = classOf[Date] override def extract(obj: PrimitiveType): DateTime = new DateTime(obj, DateTimeZone.UTC) + + override def fromRow(index: Int, row: GettableByIndexData): Try[DateTime] = { + nullCheck(index, row) { + r => new DateTime(r.getTimestamp(index), DateTimeZone.UTC) + } + } } @@ -289,8 +331,12 @@ object Primitives { override def asCql(value: Boolean): String = value.toString - override def fromRow(column: String, row: GettableData): Try[Boolean] = nullCheck(column, row) { - r => r.getBool(column) + override def fromRow(column: String, row: GettableByNameData): Try[Boolean] = { + nullCheck(column, row)(_.getBool(column)) + } + + override def fromRow(index: Int, row: GettableByIndexData): Try[Boolean] = { + nullCheck(index, row)(_.getBool(index)) } override def fromString(value: String): Boolean = value match { @@ -308,8 +354,12 @@ object Primitives { val cassandraType = CQLSyntax.Types.Decimal - override def fromRow(column: String, row: GettableData): Try[BigDecimal] = nullCheck(column, row) { - r => BigDecimal(r.getDecimal(column)) + override def fromRow(column: String, row: GettableByNameData): Try[BigDecimal] = { + nullCheck(column, row)(r => BigDecimal(r.getDecimal(column))) + } + + override def fromRow(index: Int, row: GettableByIndexData): Try[BigDecimal] = { + nullCheck(index, row)(r => BigDecimal(r.getDecimal(index))) } override def asCql(value: BigDecimal): String = value.toString() @@ -327,8 +377,12 @@ object Primitives { val cassandraType = CQLSyntax.Types.Inet - override def fromRow(column: String, row: GettableData): Try[InetAddress] = nullCheck(column, row) { - r => r.getInet(column) + override def fromRow(column: String, row: GettableByNameData): Try[InetAddress] = { + nullCheck(column, row)(_.getInet(column)) + } + + override def fromRow(index: Int, row: GettableByIndexData): Try[InetAddress] = { + nullCheck(index, row)(_.getInet(index)) } override def asCql(value: InetAddress): String = CQLQuery.empty.singleQuote(value.getHostAddress) @@ -336,6 +390,7 @@ object Primitives { override def fromString(value: String): InetAddress = InetAddress.getByName(value) override def clz: Class[InetAddress] = classOf[InetAddress] + } class BigIntPrimitive extends Primitive[BigInt] { @@ -344,8 +399,12 @@ object Primitives { val cassandraType = CQLSyntax.Types.Varint - override def fromRow(column: String, row: GettableData): Try[BigInt] = nullCheck(column, row) { - r => r.getVarint(column) + override def fromRow(column: String, row: GettableByNameData): Try[BigInt] = { + nullCheck(column, row)(_.getVarint(column)) + } + + override def fromRow(index: Int, row: GettableByIndexData): Try[BigInt] = { + nullCheck(index, row)(_.getVarint(index)) } override def asCql(value: BigInt): String = value.toString() @@ -353,6 +412,7 @@ object Primitives { override def fromString(value: String): BigInt = BigInt(value) override def clz: Class[java.math.BigInteger] = classOf[java.math.BigInteger] + } class BlobIsPrimitive extends Primitive[ByteBuffer] { @@ -361,8 +421,12 @@ object Primitives { val cassandraType = CQLSyntax.Types.Blob - override def fromRow(column: String, row: GettableData): Try[ByteBuffer] = nullCheck(column, row) { - r => r.getBytes(column) + override def fromRow(column: String, row: GettableByNameData): Try[ByteBuffer] = { + nullCheck(column, row)(_.getBytes(column)) + } + + override def fromRow(index: Int, row: GettableByIndexData): Try[ByteBuffer] = { + nullCheck(index, row)(_.getBytes(index)) } override def asCql(value: ByteBuffer): String = Bytes.toHexString(value) @@ -370,6 +434,7 @@ object Primitives { override def fromString(value: String): ByteBuffer = Bytes.fromHexString(value) override def clz: Class[java.nio.ByteBuffer] = classOf[java.nio.ByteBuffer] + } def list[T : Primitive](): Primitive[List[T]] = { @@ -377,15 +442,23 @@ object Primitives { val ev = implicitly[Primitive[T]] - override def fromRow(column: String, row: GettableData): Try[List[T]] = { + override def fromRow(column: String, row: GettableByNameData): Try[List[T]] = { Try(row.getList(column, ev.clz).asScala.toList.map(ev.extract)) } + override def fromRow(index: Int, row: GettableByIndexData): Try[List[T]] = { + Try(row.getList(index, ev.clz).asScala.toList.map(ev.extract)) + } + override def cassandraType: String = QueryBuilder.Collections.listType(ev.cassandraType).queryString override def fromString(value: String): List[T] = value.split(",").map(Primitive[T].fromString).toList - override def asCql(value: List[T]): String = QueryBuilder.Utils.collection(value.map(Primitive[T].asCql)).queryString + override def asCql(value: List[T]): String = { + QueryBuilder.Collections + .serialize(value.map(Primitive[T].asCql)) + .queryString + } override def clz: Class[List[Primitive[T]#PrimitiveType]] = classOf[List[Primitive[T]#PrimitiveType]] @@ -398,15 +471,21 @@ object Primitives { val ev = implicitly[Primitive[T]] - override def fromRow(column: String, row: GettableData): Try[Set[T]] = { + override def fromRow(column: String, row: GettableByNameData): Try[Set[T]] = { Try(row.getSet(column, ev.clz).asScala.toSet.map(ev.extract)) } + override def fromRow(index: Int, row: GettableByIndexData): Try[Set[T]] = { + Try(row.getSet(index, ev.clz).asScala.toSet.map(ev.extract)) + } + override def cassandraType: String = QueryBuilder.Collections.setType(ev.cassandraType).queryString override def fromString(value: String): Set[T] = value.split(",").map(Primitive[T].fromString).toSet - override def asCql(value: Set[T]): String = QueryBuilder.Utils.collection(value.map(Primitive[T].asCql)).queryString + override def asCql(value: Set[T]): String = { + QueryBuilder.Collections.serialize(value.map(Primitive[T].asCql)).queryString + } override def clz: Class[Set[Primitive[T]#PrimitiveType]] = classOf[Set[Primitive[T]#PrimitiveType]] @@ -420,7 +499,7 @@ object Primitives { val keyPrimitive = implicitly[Primitive[K]] val valuePrimitive = implicitly[Primitive[V]] - override def fromRow(column: String, row: GettableData): Try[Map[K, V]] = { + override def fromRow(column: String, row: GettableByNameData): Try[Map[K, V]] = { Try { row.getMap(column, keyPrimitive.clz, valuePrimitive.clz).asScala.toMap.map { case (key, value) => keyPrimitive.extract(key) -> valuePrimitive.extract(value) @@ -428,6 +507,14 @@ object Primitives { } } + override def fromRow(index: Int, row: GettableByIndexData): Try[Map[K, V]] = { + Try { + row.getMap(index, keyPrimitive.clz, valuePrimitive.clz).asScala.toMap.map { + case (key, value) => keyPrimitive.extract(key) -> valuePrimitive.extract(value) + } + } + } + override def cassandraType: String = QueryBuilder.Collections.mapType( keyPrimitive.cassandraType, valuePrimitive.cassandraType diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/query/AlterQuery.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/query/AlterQuery.scala similarity index 65% rename from phantom-dsl/src/main/scala/com/websudos/phantom/builder/query/AlterQuery.scala rename to phantom-dsl/src/main/scala/com/outworkers/phantom/builder/query/AlterQuery.scala index 943304e6f..a880c41a2 100644 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/query/AlterQuery.scala +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/query/AlterQuery.scala @@ -1,44 +1,29 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.query +package com.outworkers.phantom.builder.query -import com.websudos.phantom.CassandraTable -import com.websudos.phantom.builder.ops.DropColumn -import com.websudos.phantom.builder.query.options.{TablePropertyClause, WithBound, WithChainned, WithUnchainned} -import com.websudos.phantom.builder.{ConsistencyBound, QueryBuilder, Unspecified} -import com.websudos.phantom.column.AbstractColumn -import com.websudos.phantom.connectors.KeySpace +import com.outworkers.phantom.CassandraTable +import com.outworkers.phantom.builder.ops.DropColumn +import com.outworkers.phantom.builder.query.options.{TablePropertyClause, WithBound, WithChainned, WithUnchainned} +import com.outworkers.phantom.builder.{ConsistencyBound, QueryBuilder, Unspecified} +import com.outworkers.phantom.column.AbstractColumn +import com.outworkers.phantom.connectors.KeySpace import scala.annotation.implicitNotFound - class AlterQuery[ Table <: CassandraTable[Table, _], Record, @@ -118,17 +103,19 @@ class AlterQuery[ new AlterQuery(table, QueryBuilder.Alter.drop(qb, column), options) } - @implicitNotFound("You cannot use 2 `with` clauses on the same create query. Use `and` instead.") - final def `with`(clause: TablePropertyClause)(implicit ev: Chain =:= WithUnchainned): AlterQuery[Table, Record, Status, WithChainned] = { - new AlterQuery(table, QueryBuilder.Alter.`with`(qb, clause.qb), options) + @deprecated("Use option instead", "2.0.0") + final def `with`(clause: TablePropertyClause)( + implicit ev: Chain =:= WithUnchainned + ): AlterQuery[Table, Record, Status, WithChainned] = { + new AlterQuery(table, QueryBuilder.Alter.option(qb, clause.qb), options) } - @implicitNotFound("You cannot use 2 `with` clauses on the same create query. Use `and` instead.") - final def option(clause: TablePropertyClause)(implicit ev: Chain =:= WithUnchainned): AlterQuery[Table, Record, Status, WithChainned] = { - new AlterQuery(table, QueryBuilder.Alter.`with`(qb, clause.qb), options) + final def option(clause: TablePropertyClause)( + implicit ev: Chain =:= WithUnchainned + ): AlterQuery[Table, Record, Status, WithChainned] = { + new AlterQuery(table, QueryBuilder.Alter.option(qb, clause.qb), options) } - @implicitNotFound("You have to use `with` before using `and` in a create query.") final def and(clause: TablePropertyClause)(implicit ev: Chain =:= WithChainned): AlterQuery[Table, Record, Status, WithChainned] = { new AlterQuery(table, QueryBuilder.Where.and(qb, clause.qb), options) } diff --git a/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/query/CQLQuery.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/query/CQLQuery.scala new file mode 100644 index 000000000..73810d441 --- /dev/null +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/query/CQLQuery.scala @@ -0,0 +1,34 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.builder.query + +import com.outworkers.diesel.engine.query.AbstractQuery + +case class CQLQuery(override val queryString: String) extends AbstractQuery[CQLQuery](queryString) { + def create(str: String): CQLQuery = CQLQuery(str) + + override def toString: String = queryString +} + +object CQLQuery { + def empty: CQLQuery = CQLQuery("") + + def escape(str: String): String = "'" + str.replaceAll("'", "''") + "'" + + def escaped(str: String): CQLQuery = CQLQuery("'" + str.replaceAll("'", "''") + "'") + + def apply(collection: TraversableOnce[String]): CQLQuery = CQLQuery(collection.mkString(", ")) +} diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/query/CassandraOperations.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/query/CassandraOperations.scala similarity index 50% rename from phantom-dsl/src/main/scala/com/websudos/phantom/builder/query/CassandraOperations.scala rename to phantom-dsl/src/main/scala/com/outworkers/phantom/builder/query/CassandraOperations.scala index dc9eca5de..90dd53d42 100644 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/query/CassandraOperations.scala +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/query/CassandraOperations.scala @@ -1,38 +1,24 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.query +package com.outworkers.phantom.builder.query import com.datastax.driver.core._ import com.google.common.util.concurrent.{FutureCallback, Futures} -import com.websudos.phantom.Manager -import com.websudos.phantom.connectors.{KeySpace, SessionAugmenterImplicits} +import com.outworkers.phantom.Manager +import com.outworkers.phantom.connectors.{KeySpace, SessionAugmenterImplicits} import scala.concurrent.{ExecutionContextExecutor, Future => ScalaFuture, Promise => ScalaPromise} @@ -51,7 +37,7 @@ private[phantom] trait CassandraOperations extends SessionAugmenterImplicits { keyspace: KeySpace, executor: ExecutionContextExecutor ): ScalaPromise[PreparedStatement] = { - Manager.logger.debug(s"Executing query: ${st.toString}") + Manager.logger.debug(s"Executing prepared statement: ${st.toString}") val promise = ScalaPromise[PreparedStatement]() @@ -77,7 +63,7 @@ private[phantom] trait CassandraOperations extends SessionAugmenterImplicits { keyspace: KeySpace, executor: ExecutionContextExecutor ): ScalaPromise[ResultSet] = { - Manager.logger.debug(s"Executing query: ${st.toString}") + Manager.logger.debug(s"Executing query: $st") val promise = ScalaPromise[ResultSet]() diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/query/CreateQuery.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/query/CreateQuery.scala similarity index 70% rename from phantom-dsl/src/main/scala/com/websudos/phantom/builder/query/CreateQuery.scala rename to phantom-dsl/src/main/scala/com/outworkers/phantom/builder/query/CreateQuery.scala index 4c214fb1c..e7fc29e5f 100644 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/query/CreateQuery.scala +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/query/CreateQuery.scala @@ -1,40 +1,27 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.query +package com.outworkers.phantom.builder.query import com.datastax.driver.core._ -import com.websudos.phantom.builder._ -import com.websudos.phantom.builder.query.options.TablePropertyClause -import com.websudos.phantom.builder.syntax.CQLSyntax -import com.websudos.phantom.connectors.KeySpace -import com.websudos.phantom.{CassandraTable, Manager} +import com.outworkers.phantom.builder._ +import com.outworkers.phantom.builder.query.options.TablePropertyClause +import com.outworkers.phantom.builder.syntax.CQLSyntax +import com.outworkers.phantom.column.AbstractColumn +import com.outworkers.phantom.connectors.KeySpace +import com.outworkers.phantom.{CassandraTable, Manager} import scala.annotation.implicitNotFound import scala.concurrent.{ExecutionContextExecutor, Future => ScalaFuture} @@ -48,20 +35,16 @@ class RootCreateQuery[ QueryBuilder.Create.defaultCreateQuery( keySpace.name, table.tableName, - table.defineTableKey(), + table.tableKey, table.columns.map(_.qb).toSeq ) } - private[phantom] def toQuery()(implicit keySpace: KeySpace): CreateQuery.Default[Table, Record] = { - new CreateQuery[Table, Record, Unspecified](table, default, WithPart.empty, UsingPart.empty) - } - private[this] def lightweight()(implicit keySpace: KeySpace): CQLQuery = { QueryBuilder.Create.createIfNotExists( keySpace.name, table.tableName, - table.defineTableKey(), + table.tableKey, table.columns.map(_.qb).toSeq ) } @@ -77,14 +60,21 @@ class RootCreateQuery[ */ def ifNotExists()(implicit keySpace: KeySpace): CreateQuery.Default[Table, Record] = { if (table.clusteringColumns.nonEmpty) { - new CreateQuery(table, lightweight(), WithPart.empty).withClustering() + new CreateQuery( + table, + lightweight(), + WithPart.empty + ).withClustering() } else { - new CreateQuery(table, lightweight(), WithPart.empty) + new CreateQuery( + table, + lightweight(), + WithPart.empty + ) } } } - class CreateQuery[ Table <: CassandraTable[Table, _], Record, @@ -214,15 +204,25 @@ private[phantom] trait CreateImplicits extends TablePropertyClauses { val Cache = Caching - implicit def rootCreateQueryToCreateQuery[ + def apply[ T <: CassandraTable[T, _], R ](root: RootCreateQuery[T, R])(implicit keySpace: KeySpace): CreateQuery.Default[T, R] = { - if (root.table.clusteringColumns.nonEmpty) { - new CreateQuery(root.table, root.default, WithPart.empty).withClustering() + new CreateQuery[T, R, Unspecified]( + root.table, + root.default() + ).withClustering() } else { - new CreateQuery(root.table, root.default, WithPart.empty) + new CreateQuery[T, R, Unspecified]( + root.table, + root.default() + ) } } + + implicit def rootCreateQueryToCreateQuery[ + T <: CassandraTable[T, _], + R + ](root: RootCreateQuery[T, R])(implicit keySpace: KeySpace): CreateQuery.Default[T, R] = apply(root) } diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/query/DeleteQuery.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/query/DeleteQuery.scala similarity index 78% rename from phantom-dsl/src/main/scala/com/websudos/phantom/builder/query/DeleteQuery.scala rename to phantom-dsl/src/main/scala/com/outworkers/phantom/builder/query/DeleteQuery.scala index 499a701cc..d4c8285b5 100644 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/query/DeleteQuery.scala +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/query/DeleteQuery.scala @@ -1,43 +1,29 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.query +package com.outworkers.phantom.builder.query import com.datastax.driver.core.{ConsistencyLevel, Row, Session} -import com.websudos.phantom.CassandraTable -import com.websudos.phantom.builder._ -import com.websudos.phantom.builder.clauses._ -import com.websudos.phantom.builder.ops.MapKeyUpdateClause -import com.websudos.phantom.builder.query.prepared.PreparedBlock -import com.websudos.phantom.column.AbstractColumn -import com.websudos.phantom.connectors.KeySpace -import com.websudos.phantom.dsl.DateTime +import com.outworkers.phantom.CassandraTable +import com.outworkers.phantom.builder._ +import com.outworkers.phantom.builder.clauses._ +import com.outworkers.phantom.builder.ops.MapKeyUpdateClause +import com.outworkers.phantom.builder.query.prepared.PreparedBlock +import com.outworkers.phantom.column.AbstractColumn +import com.outworkers.phantom.connectors.KeySpace +import com.outworkers.phantom.dsl.DateTime import shapeless.ops.hlist.{Prepend, Reverse} import shapeless.{=:!=, HList, HNil} diff --git a/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/query/ExecutableQuery.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/query/ExecutableQuery.scala new file mode 100644 index 000000000..ba30562ca --- /dev/null +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/query/ExecutableQuery.scala @@ -0,0 +1,438 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.builder.query + +import java.util.{List => JavaList, Iterator => JavaIterator} +import com.datastax.driver.core._ +import com.outworkers.phantom.CassandraTable +import com.outworkers.phantom.builder.{LimitBound, Unlimited} +import com.outworkers.phantom.connectors.KeySpace + +import scala.collection.JavaConverters._ +import scala.concurrent.{ExecutionContextExecutor, Future => ScalaFuture} + +trait RecordResult[R] { + + def result: ResultSet + + def pagingState: PagingState = result.getExecutionInfo.getPagingState +} + +case class ListResult[R](records: List[R], result: ResultSet) extends RecordResult[R] + +object ListResult { + def apply[R](res: ResultSet, records: List[R]): ListResult[R] = ListResult(records, res) + + def apply[R](rec: (ResultSet, List[R])): ListResult[R] = apply(rec._2, rec._1) +} + +case class IteratorResult[R](records: Iterator[R], result: ResultSet) extends RecordResult[R] + +trait ExecutableStatement extends CassandraOperations { + + type Modifier = Statement => Statement + + def options: QueryOptions + + def qb: CQLQuery + + def queryString: String = qb.terminate().queryString + + def statement()(implicit session: Session): Statement = { + new SimpleStatement(qb.terminate().queryString) + .setConsistencyLevel(options.consistencyLevel.orNull) + } + + /** + * Default asynchronous query execution method. This will convert the underlying + * call to Cassandra done with Google Guava ListenableFuture to a consumable + * Scala Future that will be completed once the operation is completed on the + * database end. + * + * The execution context of the transformation is provided by phantom via + * [[com.outworkers.phantom.Manager.scalaExecutor]] and it is recommended to + * use [[com.outworkers.phantom.dsl.context]] for operations that chain + * database calls. + * + * @param session The implicit session provided by a [[com.outworkers.phantom.connectors.Connector]]. + * @param keySpace The implicit keySpace definition provided by a [[com.outworkers.phantom.connectors.Connector]]. + * @param ec The implicit Scala execution context. + * @return An asynchronous Scala future wrapping the Datastax result set. + */ + def future()( + implicit session: Session, + keySpace: KeySpace, + ec: ExecutionContextExecutor + ): ScalaFuture[ResultSet] = { + scalaQueryStringExecuteToFuture(statement) + } + + /** + * This will convert the underlying call to Cassandra done with Google Guava ListenableFuture to a consumable + * Scala Future that will be completed once the operation is completed on the + * database end. + * + * The execution context of the transformation is provided by phantom via + * [[com.outworkers.phantom.Manager.scalaExecutor]] and it is recommended to + * use [[com.outworkers.phantom.dsl.context]] for operations that chain + * database calls. + * + * @param modifyStatement The function allowing to modify underlying [[Statement]] + * @param session The implicit session provided by a [[com.outworkers.phantom.connectors.Connector]]. + * @param keySpace The implicit keySpace definition provided by a [[com.outworkers.phantom.connectors.Connector]]. + * @param executor The implicit Scala executor. + * @return An asynchronous Scala future wrapping the Datastax result set. + */ + def future(modifyStatement: Modifier)( + implicit session: Session, + keySpace: KeySpace, + executor: ExecutionContextExecutor + ): ScalaFuture[ResultSet] = { + scalaQueryStringExecuteToFuture(modifyStatement(statement)) + } +} + +class ExecutableStatementList(val queries: Seq[CQLQuery]) extends CassandraOperations { + + /** + * Secondary constructor to allow passing in Sets instead of Sequences. + * Although this may appear to be fruitless and uninteresting it a necessary evil. + * + * The TwitterFuture.collect method does not support passing in arbitrary collections using the Scala API + * just as Scala.future does. Scala Futures can sequence over traversables and return a collection of the appropiate type. + * + * @param queries The list of CQL queries to execute. + * @return An instance of an ExecutableStatement with the matching sequence of CQL queries. + */ + def this(queries: Set[CQLQuery]) = this(queries.toSeq) + + def add(appendable: Seq[CQLQuery]): ExecutableStatementList = { + new ExecutableStatementList(queries ++ appendable) + } + + def ++(appendable: Seq[CQLQuery]): ExecutableStatementList = add(appendable) + + def ++(st: ExecutableStatementList): ExecutableStatementList = add(st.queries) + + def future()( + implicit session: Session, + keySpace: KeySpace, + ec: ExecutionContextExecutor + ): ScalaFuture[Seq[ResultSet]] = { + ScalaFuture.sequence(queries.map(item => { + scalaQueryStringExecuteToFuture(new SimpleStatement(item.terminate().queryString)) + })) + } +} + +private[phantom] trait RootExecutableQuery[R] { + + def fromRow(r: Row): R + + protected[this] def singleResult(row: Row): Option[R] = { + if (Option(row).isDefined) Some(fromRow(row)) else None + } + + protected[this] def directMapper(results: JavaList[Row]): List[R] = { + List.tabulate(results.size())(index => fromRow(results.get(index))) + } + + protected[this] def directMapper(results: JavaIterator[Row]): List[R] = { + results.asScala.map(fromRow).toList + } +} + +/** + * An ExecutableQuery implementation, meant to retrieve results from Cassandra. + * This provides the root implementation of a Select query. + * + * @tparam T The class owning the table. + * @tparam R The record type to store. + */ +trait ExecutableQuery[T <: CassandraTable[T, _], R, Limit <: LimitBound] + extends ExecutableStatement with RootExecutableQuery[R] { + + def fromRow(r: Row): R + + protected[this] def greedyEval( + f: ScalaFuture[ResultSet] + )(implicit ex: ExecutionContextExecutor): ScalaFuture[ListResult[R]] = { + f map { r => + val records = if (r.isFullyFetched) directMapper(r.all()) else directMapper(r.iterator()) + ListResult(records, r) + } + } + + protected[this] def lazyEval( + f: ScalaFuture[ResultSet] + )(implicit ex: ExecutionContextExecutor): ScalaFuture[IteratorResult[R]] = { + f map { r => IteratorResult(r.iterator().asScala.map(fromRow), r) } + } + + private[phantom] def singleFetch()( + implicit session: Session, + keySpace: KeySpace, + ec: ExecutionContextExecutor + ): ScalaFuture[Option[R]] = { + future() map { res => singleResult(res.one) } + } + + /** + * Returns the first row from the select ignoring everything else + * + * @param session The implicit session provided by a [[com.outworkers.phantom.connectors.Connector]]. + * @param keySpace The implicit keySpace definition provided by a [[com.outworkers.phantom.connectors.Connector]]. + * @param ev The implicit limit for the query. + * @param ec The implicit Scala execution context. + * @return A Scala future guaranteed to contain a single result wrapped as an Option. + */ + def one()( + implicit session: Session, + keySpace: KeySpace, + ev: Limit =:= Unlimited, + ec: ExecutionContextExecutor + ): ScalaFuture[Option[R]] + + /** + * Returns a parsed sequence of [R]ows + * This is not suitable for big results set + * + * @param session The implicit session provided by a [[com.outworkers.phantom.connectors.Connector]]. + * @param keySpace The implicit keySpace definition provided by a [[com.outworkers.phantom.connectors.Connector]]. + * @param ec The implicit Scala execution context. + * @return A Scala future wrapping a list of mapped results. + */ + def fetch()( + implicit session: Session, + keySpace: KeySpace, + ec: ExecutionContextExecutor + ): ScalaFuture[List[R]] = { + future() map { resultSet => directMapper(resultSet.all) } + } + + /** + * Returns a parsed sequence of [R]ows + * This is not suitable for big results set + * + * @param session The implicit session provided by a [[com.outworkers.phantom.connectors.Connector]]. + * @param keySpace The implicit keySpace definition provided by a [[com.outworkers.phantom.connectors.Connector]]. + * @param ec The implicit Scala execution context. + * @return A Scala future wrapping a list of mapped results. + */ + def fetch(modifyStatement : Modifier)( + implicit session: Session, + keySpace: KeySpace, + ec: ExecutionContextExecutor + ): ScalaFuture[List[R]] = { + future(modifyStatement) map { resultSet => directMapper(resultSet.all) } + } + + /** + * Returns a parsed sequence of [R]ows + * This is not suitable for big results set as it will attempt to fetch the entire result set + * as a List, circumventing pagination settings. + * + * Use [[paginateRecord()]] or other means if you like to deal with bigger result sets. + * + * @param session The implicit session provided by a [[com.outworkers.phantom.connectors.Connector]]. + * @param keySpace The implicit keySpace definition provided by a [[com.outworkers.phantom.connectors.Connector]]. + * @param ec The implicit Scala execution context. + * @return A Scala future wrapping a list of mapped results. + */ + def fetchRecord()( + implicit session: Session, + keySpace: KeySpace, + ec: ExecutionContextExecutor + ): ScalaFuture[ListResult[R]] = { + future() map (resultSet => ListResult(directMapper(resultSet.all), resultSet)) + } + + /** + * Returns a parsed sequence of [R]ows + * This is not suitable for big results set + * + * @param session The implicit session provided by a [[com.outworkers.phantom.connectors.Connector]]. + * @param keySpace The implicit keySpace definition provided by a [[com.outworkers.phantom.connectors.Connector]]. + * @param ec The implicit Scala execution context. + * @return A Scala future wrapping a list of mapped results. + */ + def fetchRecord(modifyStatement: Modifier)( + implicit session: Session, + keySpace: KeySpace, + ec: ExecutionContextExecutor + ): ScalaFuture[ListResult[R]] = { + future(modifyStatement) map { + set => ListResult(directMapper(set.all), set) + } + } + + /** + * Returns a parsed sequence of [R]ows but paginates the results using paging state. + * This will not consume or return the entire set of available results, it will + * instead return an amount of records equal to the fetch size setting. + * + * @param session The implicit session provided by a [[com.outworkers.phantom.connectors.Connector]]. + * @param keySpace The implicit keySpace definition provided by a [[com.outworkers.phantom.connectors.Connector]]. + * @param ec The implicit Scala execution context. + * @return A Scala future wrapping a list of mapped results. + */ + def paginateRecord()( + implicit session: Session, + keySpace: KeySpace, + ec: ExecutionContextExecutor + ): ScalaFuture[ListResult[R]] = { + greedyEval(future()) + } + + /** + * Returns a parsed sequence of [R]ows. + * This will only fetch the amount of records defined in the fetchSize setting. + * It will allow pagination of the inner result set as a [[scala.collection.immutable.List]]. + * + * It will greedy evaluate the records inside a single fetch size batch as it returns a list as opposed to + * an iterator. For a non greedy variant of the size method use [[iterator()]]. + * + * @param session The implicit session provided by a [[com.outworkers.phantom.connectors.Connector]]. + * @param keySpace The implicit keySpace definition provided by a [[com.outworkers.phantom.connectors.Connector]]. + * @param ec The implicit Scala execution context. + * @return A Scala future wrapping a list of mapped results. + */ + def paginateRecord(state: PagingState)( + implicit session: Session, + keySpace: KeySpace, + ec: ExecutionContextExecutor + ): ScalaFuture[ListResult[R]] = { + greedyEval(future(_.setPagingState(state))) + } + + /** + * Returns a parsed sequence of [R]ows + * This is not suitable for big results set + * + * @param session The implicit session provided by a [[com.outworkers.phantom.connectors.Connector]]. + * @param keySpace The implicit keySpace definition provided by a [[com.outworkers.phantom.connectors.Connector]]. + * @param ec The implicit Scala execution context. + * @return A Scala future wrapping a list of mapped results. + */ + def paginateRecord(state: Option[PagingState])( + implicit session: Session, + keySpace: KeySpace, + ec: ExecutionContextExecutor + ): ScalaFuture[ListResult[R]] = { + state match { + case None => greedyEval(future()) + case Some(defined) => greedyEval(future(_.setPagingState(defined))) + } + } + + /** + * Returns a parsed sequence of [R]ows. + * This will only fetch the amount of records defined in the fetchSize setting. + * It will allow pagination of the inner result set as a [[scala.collection.immutable.List]]. + * + * It will greedy evaluate the records inside a single fetch size batch as it returns a list as opposed to + * an iterator. For a non greedy variant of the size method use [[iterator()]]. + * + * @param session The implicit session provided by a [[com.outworkers.phantom.connectors.Connector]]. + * @param keySpace The implicit keySpace definition provided by a [[com.outworkers.phantom.connectors.Connector]]. + * @param ec The implicit Scala execution context. + * @return A Scala future wrapping a list of mapped results. + */ + def paginateRecord(modifier: Modifier)( + implicit session: Session, + keySpace: KeySpace, + ec: ExecutionContextExecutor + ): ScalaFuture[ListResult[R]] = { + greedyEval(future(modifier)) + } + + /** + * Returns a parsed iterator of [R]ows lazily evaluated. This will respect the fetch size setting + * of a query, meaning you will need to provide a paging state to fetch records beyond the regular fetch + * size. + * + * @param session The implicit session provided by a [[com.outworkers.phantom.connectors.Connector]]. + * @param keySpace The implicit keySpace definition provided by a [[com.outworkers.phantom.connectors.Connector]]. + * @param ec The implicit Scala execution context. + * @return A Scala future wrapping scala iterator of mapped results. + */ + def iterator()( + implicit session: Session, + keySpace: KeySpace, + ec: ExecutionContextExecutor + ): ScalaFuture[IteratorResult[R]] = { + future() map { res => IteratorResult(res.iterator().asScala.map(fromRow), res) } + } + + /** + * Returns a parsed iterator of [R]ows lazily evaluated. This will respect the fetch size setting + * of a query, meaning you will need to provide a paging state to fetch records beyond the regular fetch + * size. + * + * @param session The implicit session provided by a [[com.outworkers.phantom.connectors.Connector]]. + * @param keySpace The implicit keySpace definition provided by a [[com.outworkers.phantom.connectors.Connector]]. + * @param ec The implicit Scala execution context. + * @return A Scala future wrapping scala iterator of mapped results. + */ + def iterator(modifier: Modifier)( + implicit session: Session, + keySpace: KeySpace, + ec: ExecutionContextExecutor + ): ScalaFuture[IteratorResult[R]] = { + future(modifier) map { res => IteratorResult(res.iterator().asScala.map(fromRow), res) } + } + + /** + * Returns a parsed sequence of [R]ows. + * This will only fetch the amount of records defined in the fetchSize setting. + * It will allow pagination of the inner result set as a [[scala.collection.immutable.List]]. + * + * It will greedy evaluate the records inside a single fetch size batch as it returns a list as opposed to + * an iterator. For a non greedy variant of the size method use [[iterator()]]. + * + * @param session The implicit session provided by a [[com.outworkers.phantom.connectors.Connector]]. + * @param keySpace The implicit keySpace definition provided by a [[com.outworkers.phantom.connectors.Connector]]. + * @param ec The implicit Scala execution context. + * @return A Scala future wrapping a list of mapped results. + */ + def iterator(state: PagingState)( + implicit session: Session, + keySpace: KeySpace, + ec: ExecutionContextExecutor + ): ScalaFuture[IteratorResult[R]] = { + lazyEval(future(_.setPagingState(state))) + } + + /** + * Returns a parsed sequence of [R]ows + * This is not suitable for big results set + * + * @param session The implicit session provided by a [[com.outworkers.phantom.connectors.Connector]]. + * @param keySpace The implicit keySpace definition provided by a [[com.outworkers.phantom.connectors.Connector]]. + * @param ec The implicit Scala execution context. + * @return A Scala future wrapping a list of mapped results. + */ + def iterator(state: Option[PagingState])( + implicit session: Session, + keySpace: KeySpace, + ec: ExecutionContextExecutor + ): ScalaFuture[IteratorResult[R]] = { + state match { + case None => lazyEval(future()) + case Some(defined) => lazyEval(future(_.setPagingState(defined))) + } + } +} diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/query/InsertQuery.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/query/InsertQuery.scala similarity index 77% rename from phantom-dsl/src/main/scala/com/websudos/phantom/builder/query/InsertQuery.scala rename to phantom-dsl/src/main/scala/com/outworkers/phantom/builder/query/InsertQuery.scala index 69cf3c648..c91a48044 100644 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/query/InsertQuery.scala +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/query/InsertQuery.scala @@ -1,43 +1,29 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.query +package com.outworkers.phantom.builder.query import com.datastax.driver.core.{ConsistencyLevel, Session} -import com.websudos.phantom.CassandraTable -import com.websudos.phantom.builder._ -import com.websudos.phantom.builder.clauses._ -import com.websudos.phantom.builder.query.prepared.{PrepareMark, PreparedBlock} -import com.websudos.phantom.builder.syntax.CQLSyntax -import com.websudos.phantom.column.AbstractColumn -import com.websudos.phantom.connectors.KeySpace -import com.websudos.phantom.dsl.? +import com.outworkers.phantom.CassandraTable +import com.outworkers.phantom.builder._ +import com.outworkers.phantom.builder.clauses._ +import com.outworkers.phantom.builder.query.prepared.{PrepareMark, PreparedBlock} +import com.outworkers.phantom.builder.syntax.CQLSyntax +import com.outworkers.phantom.column.AbstractColumn +import com.outworkers.phantom.connectors.KeySpace +import com.outworkers.phantom.dsl.? import org.joda.time.DateTime import shapeless.ops.hlist.{Prepend, Reverse} import shapeless.{::, =:!=, HList, HNil} diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/query/Parts.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/query/Parts.scala similarity index 75% rename from phantom-dsl/src/main/scala/com/websudos/phantom/builder/query/Parts.scala rename to phantom-dsl/src/main/scala/com/outworkers/phantom/builder/query/Parts.scala index b16e3570d..843bf9dce 100644 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/query/Parts.scala +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/query/Parts.scala @@ -1,36 +1,22 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.query +package com.outworkers.phantom.builder.query import com.outworkers.diesel.engine.query.multiparts.{QueryPart, MergedQueryList} -import com.websudos.phantom.builder.QueryBuilder +import com.outworkers.phantom.builder.QueryBuilder sealed class CQLMergeList(override val list: List[CQLQuery]) extends MergedQueryList[CQLQuery](list) { diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/query/Query.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/query/Query.scala similarity index 73% rename from phantom-dsl/src/main/scala/com/websudos/phantom/builder/query/Query.scala rename to phantom-dsl/src/main/scala/com/outworkers/phantom/builder/query/Query.scala index 7e25f66c2..47d862300 100644 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/query/Query.scala +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/query/Query.scala @@ -1,38 +1,24 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.query +package com.outworkers.phantom.builder.query import com.datastax.driver.core.{ConsistencyLevel, Row, Session} -import com.websudos.phantom.CassandraTable -import com.websudos.phantom.builder._ -import com.websudos.phantom.builder.clauses.{QueryCondition, WhereClause} +import com.outworkers.phantom.CassandraTable +import com.outworkers.phantom.builder._ +import com.outworkers.phantom.builder.clauses.{QueryCondition, WhereClause} import shapeless.HList import shapeless.ops.hlist.Prepend diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/query/QueryOptions.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/query/QueryOptions.scala similarity index 51% rename from phantom-dsl/src/main/scala/com/websudos/phantom/builder/query/QueryOptions.scala rename to phantom-dsl/src/main/scala/com/outworkers/phantom/builder/query/QueryOptions.scala index 972f791aa..a91fc4e8b 100644 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/query/QueryOptions.scala +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/query/QueryOptions.scala @@ -1,33 +1,19 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.query +package com.outworkers.phantom.builder.query import com.datastax.driver.core.ConsistencyLevel diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/query/SelectQuery.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/query/SelectQuery.scala similarity index 85% rename from phantom-dsl/src/main/scala/com/websudos/phantom/builder/query/SelectQuery.scala rename to phantom-dsl/src/main/scala/com/outworkers/phantom/builder/query/SelectQuery.scala index a7b3fcbd1..0df295a5d 100644 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/query/SelectQuery.scala +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/query/SelectQuery.scala @@ -1,41 +1,27 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.query +package com.outworkers.phantom.builder.query import com.datastax.driver.core.{ConsistencyLevel, Row, Session} -import com.websudos.phantom.CassandraTable -import com.websudos.phantom.builder.{ConsistencyBound, LimitBound, OrderBound, WhereBound, _} -import com.websudos.phantom.builder.clauses._ -import com.websudos.phantom.builder.query.prepared.PreparedSelectBlock -import com.websudos.phantom.builder.syntax.CQLSyntax -import com.websudos.phantom.connectors.KeySpace +import com.outworkers.phantom.CassandraTable +import com.outworkers.phantom.builder.{ConsistencyBound, LimitBound, OrderBound, WhereBound, _} +import com.outworkers.phantom.builder.clauses._ +import com.outworkers.phantom.builder.query.prepared.PreparedSelectBlock +import com.outworkers.phantom.builder.syntax.CQLSyntax +import com.outworkers.phantom.connectors.KeySpace import shapeless.ops.hlist.{Prepend, Reverse} import shapeless.{::, =:!=, HList, HNil} @@ -280,8 +266,8 @@ class SelectQuery[ /** * Returns the first row from the select ignoring everything else - * @param session The implicit session provided by a [[com.websudos.phantom.connectors.Connector]]. - * @param keySpace The implicit keySpace definition provided by a [[com.websudos.phantom.connectors.Connector]]. + * @param session The implicit session provided by a [[com.outworkers.phantom.connectors.Connector]]. + * @param keySpace The implicit keySpace definition provided by a [[com.outworkers.phantom.connectors.Connector]]. * @param ev The implicit limit for the query. * @param ec The implicit Scala execution context. * @return A Scala future guaranteed to contain a single result wrapped as an Option. diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/query/TablePropertyClauses.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/query/TablePropertyClauses.scala similarity index 52% rename from phantom-dsl/src/main/scala/com/websudos/phantom/builder/query/TablePropertyClauses.scala rename to phantom-dsl/src/main/scala/com/outworkers/phantom/builder/query/TablePropertyClauses.scala index eae0aa21b..965946b80 100644 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/query/TablePropertyClauses.scala +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/query/TablePropertyClauses.scala @@ -1,41 +1,26 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.query - -import com.websudos.phantom.builder.query.options._ -import com.websudos.phantom.builder.syntax.CQLSyntax +package com.outworkers.phantom.builder.query +import com.outworkers.phantom.builder.query.options._ +import com.outworkers.phantom.builder.syntax.CQLSyntax /** * A collection of available table property clauses with all the default objects available. - * This serves as a helper trait for [[com.websudos.phantom.dsl]] and brings all the relevant options into scope. + * This serves as a helper trait for [[com.outworkers.phantom.dsl]] and brings all the relevant options into scope. */ private[phantom] trait TablePropertyClauses extends CompactionStrategies with CompressionStrategies { object Storage { @@ -57,7 +42,7 @@ private[phantom] trait TablePropertyClauses extends CompactionStrategies with Co * A simple way to define a strategy is by using the {{eqs}} method. * * {{{ - * import com.websudos.phantom.dsl._ + * import com.outworkers.phantom.dsl._ * * SomeTable.create.with(compression eqs SnappyCompressor) * @@ -66,7 +51,7 @@ private[phantom] trait TablePropertyClauses extends CompactionStrategies with Co * Using a compression strategy also allows using the API methods of controlling compressor behaviour: * * {{{ - * import com.websudos.phantom.dsl._ + * import com.outworkers.phantom.dsl._ * import com.twitter.conversions.storage._ * * SomeTable.create.`with`(compression eqs SnappyCompressor.chunk_length_kb(50.kilobytes)) @@ -85,7 +70,7 @@ private[phantom] trait TablePropertyClauses extends CompactionStrategies with Co * * * {{{ - * import com.websudos.phantom.dsl._ + * import com.outworkers.phantom.dsl._ * * SomeTable.create.`with`(compaction eqs SnappyCompressor) * }}} diff --git a/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/query/TruncateQuery.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/query/TruncateQuery.scala new file mode 100644 index 000000000..4b7f4ad02 --- /dev/null +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/query/TruncateQuery.scala @@ -0,0 +1,51 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.builder.query + +import com.datastax.driver.core.{ConsistencyLevel, Session} +import com.outworkers.phantom.CassandraTable +import com.outworkers.phantom.builder.{ConsistencyBound, QueryBuilder, Specified, Unspecified} +import com.outworkers.phantom.connectors.KeySpace + +class TruncateQuery[ + Table <: CassandraTable[Table, _], + Record, + Status <: ConsistencyBound +](table: Table, val qb: CQLQuery, override val options: QueryOptions) extends ExecutableStatement { + + def consistencyLevel_=(level: ConsistencyLevel)(implicit session: Session): TruncateQuery[Table, Record, Specified] = { + if (session.protocolConsistency) { + new TruncateQuery(table, qb, options.consistencyLevel_=(level)) + } else { + new TruncateQuery(table, QueryBuilder.consistencyLevel(qb, level.toString), options) + } + } +} + + +object TruncateQuery { + + type Default[T <: CassandraTable[T, _], R] = TruncateQuery[T, R, Unspecified] + + def apply[T <: CassandraTable[T, _], R](table: T)(implicit keySpace: KeySpace): TruncateQuery.Default[T, R] = { + new TruncateQuery( + table, + QueryBuilder.truncate(QueryBuilder.keyspace(keySpace.name, table.tableName).queryString), + QueryOptions.empty + ) + } + +} diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/query/UpdateQuery.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/query/UpdateQuery.scala similarity index 87% rename from phantom-dsl/src/main/scala/com/websudos/phantom/builder/query/UpdateQuery.scala rename to phantom-dsl/src/main/scala/com/outworkers/phantom/builder/query/UpdateQuery.scala index 8f15eca98..b22de2b5f 100644 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/query/UpdateQuery.scala +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/query/UpdateQuery.scala @@ -1,41 +1,27 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.query +package com.outworkers.phantom.builder.query import com.datastax.driver.core.{ConsistencyLevel, Row, Session} -import com.websudos.phantom.CassandraTable -import com.websudos.phantom.builder._ -import com.websudos.phantom.builder.clauses._ -import com.websudos.phantom.builder.query.prepared.{PrepareMark, PreparedBlock} -import com.websudos.phantom.connectors.KeySpace -import com.websudos.phantom.dsl.DateTime +import com.outworkers.phantom.CassandraTable +import com.outworkers.phantom.builder._ +import com.outworkers.phantom.builder.clauses._ +import com.outworkers.phantom.builder.query.prepared.{PrepareMark, PreparedBlock} +import com.outworkers.phantom.connectors.KeySpace +import com.outworkers.phantom.dsl.DateTime import shapeless.ops.hlist.{Prepend, Reverse} import shapeless.{::, =:!=, HList, HNil} diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/query/options/Caching.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/query/options/Caching.scala similarity index 69% rename from phantom-dsl/src/main/scala/com/websudos/phantom/builder/query/options/Caching.scala rename to phantom-dsl/src/main/scala/com/outworkers/phantom/builder/query/options/Caching.scala index 36b7da836..4c10b5b48 100644 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/query/options/Caching.scala +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/query/options/Caching.scala @@ -1,40 +1,25 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.query.options +package com.outworkers.phantom.builder.query.options import com.datastax.driver.core.Session -import com.websudos.phantom.builder.QueryBuilder -import com.websudos.phantom.builder.query.CQLQuery -import com.websudos.phantom.builder.syntax.CQLSyntax -import com.websudos.phantom.connectors.SessionAugmenterImplicits - +import com.outworkers.phantom.builder.QueryBuilder +import com.outworkers.phantom.builder.query.CQLQuery +import com.outworkers.phantom.builder.syntax.CQLSyntax +import com.outworkers.phantom.connectors.SessionAugmenterImplicits sealed abstract class CacheProperty(val qb: CQLQuery) extends TablePropertyClause @@ -43,7 +28,7 @@ private[phantom] trait CachingStrategies { private[this] def caching(strategy: String) = { CQLQuery(CQLSyntax.Symbols.`{`).forcePad .appendSingleQuote(CQLSyntax.CacheStrategies.Caching) - .forcePad.append(CQLSyntax.Symbols.`:`) + .forcePad.append(CQLSyntax.Symbols.colon) .forcePad.appendSingleQuote(strategy) } diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/query/options/Compaction.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/query/options/Compaction.scala similarity index 53% rename from phantom-dsl/src/main/scala/com/websudos/phantom/builder/query/options/Compaction.scala rename to phantom-dsl/src/main/scala/com/outworkers/phantom/builder/query/options/Compaction.scala index 5f1eb0406..766814dc8 100644 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/query/options/Compaction.scala +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/query/options/Compaction.scala @@ -1,37 +1,25 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.query.options +package com.outworkers.phantom.builder.query.options + +import com.outworkers.phantom.builder.QueryBuilder +import com.outworkers.phantom.builder.query.{CQLQuery, OptionPart} +import com.outworkers.phantom.builder.syntax.CQLSyntax -import com.websudos.phantom.builder.QueryBuilder -import com.websudos.phantom.builder.query.{CQLQuery, OptionPart} -import com.websudos.phantom.builder.syntax.CQLSyntax +import scala.concurrent.duration.TimeUnit sealed abstract class CompactionProperties[ T <: CompactionProperties[T] @@ -66,7 +54,7 @@ private[phantom] trait CompactionStrategies { private[this] def strategy(strategy: String): OptionPart = { OptionPart( CQLQuery.empty - .appendSingleQuote(CQLSyntax.CompactionOptions.`class`) + .appendSingleQuote(CQLSyntax.CompactionOptions.clz) .append(CQLSyntax.Symbols.colon) .forcePad.appendSingleQuote(strategy) ) @@ -137,6 +125,50 @@ private[phantom] trait CompactionStrategies { } } + sealed class TimeWindowCompactionStrategy(options: OptionPart) + extends CompactionProperties[TimeWindowCompactionStrategy](options) { + override protected[this] def instance(opts: OptionPart): TimeWindowCompactionStrategy = { + new TimeWindowCompactionStrategy(opts) + } + + /** + * Declares the time unit to write with. + * This will default to microseconds as per [[http://cassandra.apache.org/doc/latest/operating/compaction.html?highlight=time%20window%20compaction#time-window-compactionstrategy/ the official Cassandra Docs]] + * + * The only two valid options are [[java.util.concurrent.TimeUnit.MILLISECONDS]] and + * [[java.util.concurrent.TimeUnit.MILLISECONDS]]. + * + * @param unit The [[java.util.concurrent.TimeUnit]] to use, defaults to [[java.util.concurrent.TimeUnit.MICROSECONDS]]. + * @return A compaction strategy builder with a time unit specified. + */ + def timestamp_resolution(unit: TimeUnit): TimeWindowCompactionStrategy = { + option( + CQLSyntax.CompactionOptions.timestamp_resolution, + CQLQuery.escape(unit.name()) + ) + } + + def compaction_window_size(value: Long): TimeWindowCompactionStrategy = { + option( + CQLSyntax.CompactionOptions.compaction_window_size, + value.toString + ) + } + + /** + * Declares the time unit to use with this compaction strategy. + * This will default to days as per [[http://cassandra.apache.org/doc/latest/operating/compaction.html?highlight=time%20window%20compaction#time-window-compactionstrategy/ the official Cassandra Docs]] + * @param unit The [[java.util.concurrent.TimeUnit]] to use, defaults to [[java.util.concurrent.TimeUnit.DAYS]]. + * @return A compaction strategy builder with a time unit specified. + */ + def compaction_window_unit(unit: TimeUnit): TimeWindowCompactionStrategy = { + option( + CQLSyntax.CompactionOptions.compaction_window_unit, + CQLQuery.escape(unit.name()) + ) + } + } + sealed class DateTieredCompactionStrategy(options: OptionPart) extends CompactionProperties[DateTieredCompactionStrategy](options) { @@ -144,6 +176,23 @@ private[phantom] trait CompactionStrategies { new DateTieredCompactionStrategy(opts) } + /** + * Declares the time unit to write with. + * This will default to microseconds as per [[http://cassandra.apache.org/doc/latest/operating/compaction.html?highlight=time%20window%20compaction#time-window-compactionstrategy/ the official Cassandra Docs]] + * + * The only two valid options are [[java.util.concurrent.TimeUnit.MILLISECONDS]] and + * [[java.util.concurrent.TimeUnit.MILLISECONDS]]. + * + * @param unit The [[java.util.concurrent.TimeUnit]] to use, defaults to [[java.util.concurrent.TimeUnit.MICROSECONDS]]. + * @return A compaction strategy builder with a time unit specified. + */ + def timestamp_resolution(unit: TimeUnit): DateTieredCompactionStrategy = { + option( + CQLSyntax.CompactionOptions.timestamp_resolution, + CQLQuery.escape(unit.name()) + ) + } + def base_time_seconds(value: Long): DateTieredCompactionStrategy = { option( CQLSyntax.CompactionOptions.base_time_seconds, @@ -184,6 +233,10 @@ private[phantom] trait CompactionStrategies { case object DateTieredCompactionStrategy extends DateTieredCompactionStrategy( strategy(CQLSyntax.CompactionStrategies.dateTiered) ) + + case object TimeWindowCompactionStrategy extends TimeWindowCompactionStrategy( + strategy(CQLSyntax.CompactionStrategies.timeWindow) + ) } private[phantom] class CompactionBuilder extends TableProperty { diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/query/options/Compression.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/query/options/Compression.scala similarity index 54% rename from phantom-dsl/src/main/scala/com/websudos/phantom/builder/query/options/Compression.scala rename to phantom-dsl/src/main/scala/com/outworkers/phantom/builder/query/options/Compression.scala index f7c66ba3c..a4f171e13 100644 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/query/options/Compression.scala +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/query/options/Compression.scala @@ -1,37 +1,23 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.query.options +package com.outworkers.phantom.builder.query.options -import com.websudos.phantom.builder.QueryBuilder -import com.websudos.phantom.builder.query.{CQLQuery, OptionPart} -import com.websudos.phantom.builder.syntax.CQLSyntax +import com.outworkers.phantom.builder.QueryBuilder +import com.outworkers.phantom.builder.query.{CQLQuery, OptionPart} +import com.outworkers.phantom.builder.syntax.CQLSyntax sealed abstract class CompressionStrategy[ CS <: CompressionStrategy[CS] diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/query/options/TableProperty.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/query/options/TableProperty.scala similarity index 64% rename from phantom-dsl/src/main/scala/com/websudos/phantom/builder/query/options/TableProperty.scala rename to phantom-dsl/src/main/scala/com/outworkers/phantom/builder/query/options/TableProperty.scala index 1883d5c2d..c03bc37ae 100644 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/query/options/TableProperty.scala +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/query/options/TableProperty.scala @@ -1,37 +1,23 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.query.options +package com.outworkers.phantom.builder.query.options -import com.websudos.phantom.builder.QueryBuilder -import com.websudos.phantom.builder.query.{CQLQuery, OptionPart} -import com.websudos.phantom.builder.syntax.CQLSyntax +import com.outworkers.phantom.builder.QueryBuilder +import com.outworkers.phantom.builder.query.{CQLQuery, OptionPart} +import com.outworkers.phantom.builder.syntax.CQLSyntax import org.joda.time.Seconds import scala.concurrent.duration.FiniteDuration @@ -57,7 +43,9 @@ trait ClauseBuilder[T] extends TablePropertyClause { protected[this] def instance(opts: OptionPart): T - protected[this] def instance(qb: CQLQuery): T = instance(options append qb) + protected[this] def instance(qb: CQLQuery): T = { + instance(options append qb) + } def option(key: String, value: String): T = { val qb = QueryBuilder.Utils.option( diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/query/prepared/PreparedBuilder.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/query/prepared/PreparedBuilder.scala similarity index 78% rename from phantom-dsl/src/main/scala/com/websudos/phantom/builder/query/prepared/PreparedBuilder.scala rename to phantom-dsl/src/main/scala/com/outworkers/phantom/builder/query/prepared/PreparedBuilder.scala index 1c761ad26..cc354d41c 100644 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/query/prepared/PreparedBuilder.scala +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/query/prepared/PreparedBuilder.scala @@ -1,39 +1,25 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.query.prepared +package com.outworkers.phantom.builder.query.prepared import com.datastax.driver.core.{QueryOptions => _, _} -import com.websudos.phantom.CassandraTable -import com.websudos.phantom.builder.query._ -import com.websudos.phantom.builder.{LimitBound, Unlimited} -import com.websudos.phantom.connectors.KeySpace +import com.outworkers.phantom.CassandraTable +import com.outworkers.phantom.builder.query._ +import com.outworkers.phantom.builder.{LimitBound, Unlimited} +import com.outworkers.phantom.connectors.KeySpace import org.joda.time.DateTime import shapeless.{Generic, HList} import shapeless.ops.hlist.Tupler @@ -77,8 +63,8 @@ Limit <: LimitBound /** * Returns the first row from the select ignoring everything else - * @param session The implicit session provided by a [[com.websudos.phantom.connectors.Connector]]. - * @param keySpace The implicit keySpace definition provided by a [[com.websudos.phantom.connectors.Connector]]. + * @param session The implicit session provided by a [[com.outworkers.phantom.connectors.Connector]]. + * @param keySpace The implicit keySpace definition provided by a [[com.outworkers.phantom.connectors.Connector]]. * @param ev The implicit limit for the query. * @param ec The implicit Scala execution context. * @return A Scala future guaranteed to contain a single result wrapped as an Option. diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/serializers/AlterQueryBuilder.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/serializers/AlterQueryBuilder.scala similarity index 69% rename from phantom-dsl/src/main/scala/com/websudos/phantom/builder/serializers/AlterQueryBuilder.scala rename to phantom-dsl/src/main/scala/com/outworkers/phantom/builder/serializers/AlterQueryBuilder.scala index 5bca3f32a..245c60444 100644 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/serializers/AlterQueryBuilder.scala +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/serializers/AlterQueryBuilder.scala @@ -1,37 +1,23 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.serializers +package com.outworkers.phantom.builder.serializers -import com.websudos.phantom.builder.QueryBuilder -import com.websudos.phantom.builder.query.CQLQuery -import com.websudos.phantom.builder.syntax.CQLSyntax +import com.outworkers.phantom.builder.QueryBuilder +import com.outworkers.phantom.builder.query.CQLQuery +import com.outworkers.phantom.builder.syntax.CQLSyntax private[phantom] trait AlterQueryBuilder { @@ -117,7 +103,7 @@ private[phantom] trait AlterQueryBuilder { * @param clause The clause or option to append to the root query. * @return A new CQL query, where the underlying query contains an option clause. */ - def `with`(qb: CQLQuery, clause: CQLQuery): CQLQuery = { + def option(qb: CQLQuery, clause: CQLQuery): CQLQuery = { qb.pad.append(CQLSyntax.With).pad.append(clause) } @@ -146,7 +132,6 @@ private[phantom] trait AlterQueryBuilder { .forcePad.append(QueryBuilder.keyspace(keyspace, table)) } - def alter(tableName: String): CQLQuery = { CQLQuery(CQLSyntax.alter) .forcePad.append(CQLSyntax.table) diff --git a/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/serializers/BaseModifiers.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/serializers/BaseModifiers.scala new file mode 100644 index 000000000..de0b00250 --- /dev/null +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/serializers/BaseModifiers.scala @@ -0,0 +1,37 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.builder.serializers + +import com.outworkers.phantom.builder.query.CQLQuery + +private[builder] trait BaseModifiers { + + protected[this] def modifier(column: String, op: String, value: String): CQLQuery = { + CQLQuery(column).forcePad.append(op).forcePad.append(value) + } + + protected[this] def modifier(column: String, op: String, value: CQLQuery): CQLQuery = { + modifier(column, op, value.queryString) + } + + protected[this] def collectionModifier(left: String, op: String, right: CQLQuery): CQLQuery = { + CQLQuery(left).forcePad.append(op).forcePad.append(right) + } + + protected[this] def collectionModifier(left: String, op: String, right: String): CQLQuery = { + CQLQuery(left).forcePad.append(op).forcePad.append(right) + } +} diff --git a/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/serializers/BatchQueryBuilder.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/serializers/BatchQueryBuilder.scala new file mode 100644 index 000000000..40f5ecc23 --- /dev/null +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/serializers/BatchQueryBuilder.scala @@ -0,0 +1,30 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.builder.serializers + +import com.outworkers.phantom.builder.query.CQLQuery +import com.outworkers.phantom.builder.syntax.CQLSyntax + +private[phantom] class BatchQueryBuilder { + + def batch(batchType: String): CQLQuery = { + CQLQuery(CQLSyntax.Batch.begin).pad.append(batchType).pad.append(CQLSyntax.Batch.batch) + } + + def applyBatch(qb: CQLQuery): CQLQuery = { + qb.forcePad.append(CQLSyntax.Batch.apply).forcePad.append(CQLSyntax.Batch.batch).append(CQLSyntax.Symbols.`;`) + } +} \ No newline at end of file diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/serializers/CollectionModifiers.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/serializers/CollectionModifiers.scala similarity index 65% rename from phantom-dsl/src/main/scala/com/websudos/phantom/builder/serializers/CollectionModifiers.scala rename to phantom-dsl/src/main/scala/com/outworkers/phantom/builder/serializers/CollectionModifiers.scala index b4bf7cd12..166aacca9 100644 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/serializers/CollectionModifiers.scala +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/serializers/CollectionModifiers.scala @@ -1,42 +1,28 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.serializers +package com.outworkers.phantom.builder.serializers -import com.websudos.phantom.builder.QueryBuilder -import com.websudos.phantom.builder.query.CQLQuery -import com.websudos.phantom.builder.syntax.CQLSyntax +import com.outworkers.phantom.builder.QueryBuilder +import com.outworkers.phantom.builder.query.CQLQuery +import com.outworkers.phantom.builder.syntax.CQLSyntax private[builder] abstract class CollectionModifiers(queryBuilder: QueryBuilder) extends BaseModifiers { - def tupled(name: String, tuples: String*): CQLQuery = { - CQLQuery(name).wrap(queryBuilder.Utils.join(tuples)) + def tupled(tuples: String*): CQLQuery = { + queryBuilder.Utils.join(tuples) } def tuple(name: String, tuples: String*): CQLQuery = { @@ -71,9 +57,9 @@ private[builder] abstract class CollectionModifiers(queryBuilder: QueryBuilder) } def prepend(column: String, values: String*): CQLQuery = { - CQLQuery(column).forcePad.append(CQLSyntax.Symbols.`=`).forcePad.append( + CQLQuery(column).forcePad.append(CQLSyntax.Symbols.eqs).forcePad.append( collectionModifier( - queryBuilder.Utils.collection(values).queryString, + queryBuilder.Collections.serialize(values).queryString, CQLSyntax.Symbols.plus, column ) @@ -81,44 +67,44 @@ private[builder] abstract class CollectionModifiers(queryBuilder: QueryBuilder) } def prepend(column: String, valueDef: String): CQLQuery = { - CQLQuery(column).forcePad.append(CQLSyntax.Symbols.`=`).forcePad.append( + CQLQuery(column).forcePad.append(CQLSyntax.Symbols.eqs).forcePad.append( collectionModifier(valueDef, CQLSyntax.Symbols.plus, column) ) } def append(column: String, values: String*): CQLQuery = { - CQLQuery(column).forcePad.append(CQLSyntax.Symbols.`=`).forcePad.append( + CQLQuery(column).forcePad.append(CQLSyntax.Symbols.eqs).forcePad.append( collectionModifier( column, CQLSyntax.Symbols.plus, - queryBuilder.Utils.collection(values).queryString + queryBuilder.Collections.serialize(values).queryString ) ) } def append(column: String, valueDef: String): CQLQuery = { - CQLQuery(column).forcePad.append(CQLSyntax.Symbols.`=`).forcePad.append( + CQLQuery(column).forcePad.append(CQLSyntax.Symbols.eqs).forcePad.append( collectionModifier(column, CQLSyntax.Symbols.plus, valueDef) ) } def discard(column: String, values: String*): CQLQuery = { - CQLQuery(column).forcePad.append(CQLSyntax.Symbols.`=`).forcePad.append( + CQLQuery(column).forcePad.append(CQLSyntax.Symbols.eqs).forcePad.append( collectionModifier( column, CQLSyntax.Symbols.-, - queryBuilder.Utils.collection(values).queryString + queryBuilder.Collections.serialize(values).queryString ) ) } def discard(column: String, valueDef: String): CQLQuery = { - CQLQuery(column).forcePad.append(CQLSyntax.Symbols.`=`).forcePad.append( + CQLQuery(column).forcePad.append(CQLSyntax.Symbols.eqs).forcePad.append( collectionModifier(column, CQLSyntax.Symbols.-, valueDef) ) } def add(column: String, values: Set[String]): CQLQuery = { - CQLQuery(column).forcePad.append(CQLSyntax.Symbols.`=`).forcePad.append( + CQLQuery(column).forcePad.append(CQLSyntax.Symbols.eqs).forcePad.append( collectionModifier( column, CQLSyntax.Symbols.plus, @@ -140,7 +126,7 @@ private[builder] abstract class CollectionModifiers(queryBuilder: QueryBuilder) * @return A CQLQuery set remove query as described above. */ def remove(column: String, values: Set[String]): CQLQuery = { - CQLQuery(column).forcePad.append(CQLSyntax.Symbols.`=`).forcePad.append( + CQLQuery(column).forcePad.append(CQLSyntax.Symbols.eqs).forcePad.append( collectionModifier( column, CQLSyntax.Symbols.-, @@ -164,7 +150,7 @@ private[builder] abstract class CollectionModifiers(queryBuilder: QueryBuilder) } def put(column: String, pairs: (String, String)*): CQLQuery = { - CQLQuery(column).forcePad.append(CQLSyntax.Symbols.`=`).forcePad.append( + CQLQuery(column).forcePad.append(CQLSyntax.Symbols.eqs).forcePad.append( collectionModifier( column, CQLSyntax.Symbols.plus, @@ -173,6 +159,12 @@ private[builder] abstract class CollectionModifiers(queryBuilder: QueryBuilder) ) } + def serialize(list: Seq[String]): CQLQuery = { + CQLQuery(CQLSyntax.Symbols.`[`) + .append(list.mkString(", ")) + .append(CQLSyntax.Symbols.`]`) + } + def serialize(set: Set[String]): CQLQuery = { CQLQuery(CQLSyntax.Symbols.`{`) .forcePad.append(CQLQuery(set)) @@ -202,6 +194,21 @@ private[builder] abstract class CollectionModifiers(queryBuilder: QueryBuilder) .append(key).append(CQLSyntax.Symbols.`]`) } + def tupleType(types: String*): CQLQuery = { + CQLQuery(CQLSyntax.Collections.tuple) + .append(CQLSyntax.Symbols.`<`) + .append(types) + .append(CQLSyntax.Symbols.`>`) + } + + def frozen(cassandraType: String): CQLQuery = { + diamond(CQLSyntax.Collections.frozen, cassandraType) + } + + def frozen(cassandraType: CQLQuery): CQLQuery = { + frozen(cassandraType.queryString) + } + def frozen(name: String, cassandraType: CQLQuery): CQLQuery = { CQLQuery(name).forcePad.append( diamond(CQLSyntax.Collections.frozen, cassandraType.queryString) diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/serializers/CreateQueryBuilder.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/serializers/CreateQueryBuilder.scala similarity index 69% rename from phantom-dsl/src/main/scala/com/websudos/phantom/builder/serializers/CreateQueryBuilder.scala rename to phantom-dsl/src/main/scala/com/outworkers/phantom/builder/serializers/CreateQueryBuilder.scala index e9258b6bc..d0cbaae4e 100644 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/serializers/CreateQueryBuilder.scala +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/serializers/CreateQueryBuilder.scala @@ -1,39 +1,25 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.serializers +package com.outworkers.phantom.builder.serializers -import com.websudos.phantom.builder.QueryBuilder -import com.websudos.phantom.builder.QueryBuilder.Utils -import com.websudos.phantom.builder.query.CQLQuery -import com.websudos.phantom.builder.syntax.CQLSyntax -import com.websudos.phantom.connectors.KeySpace +import com.outworkers.phantom.builder.QueryBuilder +import com.outworkers.phantom.builder.QueryBuilder.Utils +import com.outworkers.phantom.builder.query.CQLQuery +import com.outworkers.phantom.builder.syntax.CQLSyntax +import com.outworkers.phantom.connectors.KeySpace sealed trait CreateOptionsBuilder { protected[this] def quotedValue(qb: CQLQuery, option: String, value: String): CQLQuery = { @@ -76,6 +62,73 @@ private[builder] class CreateTableBuilder { object Caching extends CachingQueryBuilder + def partitionKey(keys: List[String]): CQLQuery = { + keys match { + case head :: Nil => CQLQuery(head) + case head :: tail => CQLQuery.empty.wrapn(keys) + case _ => CQLQuery.empty + } + } + + /** + * This method will filter the columns from a Clustering Order definition. + * It is used to define TimeSeries tables, using the ClusteringOrder trait + * combined with a directional trait, either Ascending or Descending. + * + * This method will simply add to the trailing of a query. + * @return The clustering key, defined as a string or the empty string. + */ + def clusteringKey(keys: List[String]): CQLQuery = { + keys match { + case head :: tail => CQLQuery.empty.pad.append("WITH CLUSTERING ORDER BY").wrap(keys) + case _ => CQLQuery.empty + } + } + + /** + * This method will define the PRIMARY_KEY of the table. + * + * @return A string value representing the primary key of the table. + */ + def primaryKey( + partitions: List[String], + primaries: List[String] = Nil, + clusteringKeys: List[String] = Nil + ): CQLQuery = { + val root = CQLQuery("PRIMARY KEY").forcePad + .append(CQLSyntax.`(`) + .append(partitionKey(partitions)) + + val stage2 = if (primaries.nonEmpty) { + // This only works because the macro prevents the user from defining both primaries and clustering keys + // in the same table. + val finalKeys = primaries.toSet + root.append(CQLSyntax.comma) + .forcePad + .append(finalKeys) + .append(CQLSyntax.`)`) + } else { + root.append(CQLSyntax.`)`) + } + + clusteringKeys match { + case head :: tail => stage2.append(clusteringKey(clusteringKeys)) + case _ => stage2 + } + } + def read_repair_chance(st: String): CQLQuery = { Utils.tableOption(CQLSyntax.CreateOptions.read_repair_chance, st) } @@ -194,7 +247,7 @@ private[builder] class CreateTableBuilder { } def clusteringOrder(orderings: List[(String, String)]): CQLQuery = { - val list = orderings.foldRight(List.empty[String]){ case ((key, value), l) => + val list = orderings.foldRight(List.empty[String]) { case ((key, value), l) => (key + " " + value) :: l } diff --git a/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/serializers/DeleteQueryBuilder.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/serializers/DeleteQueryBuilder.scala new file mode 100644 index 000000000..24ba638e7 --- /dev/null +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/serializers/DeleteQueryBuilder.scala @@ -0,0 +1,55 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.builder.serializers + +import com.outworkers.phantom.builder.query.CQLQuery +import com.outworkers.phantom.builder.syntax.CQLSyntax + +private[builder] class DeleteQueryBuilder { + def delete(table: String): CQLQuery = { + CQLQuery(CQLSyntax.delete) + .forcePad.append(CQLSyntax.from) + .forcePad.append(table) + } + + def delete(table: String, cond: CQLQuery): CQLQuery = { + CQLQuery(CQLSyntax.delete) + .forcePad.append(cond) + .forcePad.append(CQLSyntax.from) + .forcePad.append(table) + } + + def delete(table: String, conds: Seq[CQLQuery]): CQLQuery = { + CQLQuery(CQLSyntax.delete) + .forcePad.append(conds.map(_.queryString)) + .forcePad.append(CQLSyntax.from) + .forcePad.append(table) + } + + def deleteColumn(table: String, column: String): CQLQuery = { + CQLQuery(CQLSyntax.delete) + .forcePad.append(column) + .forcePad.append(CQLSyntax.from) + .forcePad.append(table) + } + + def deleteMapColumn(table: String, column: String, key: String): CQLQuery = { + CQLQuery(CQLSyntax.delete) + .forcePad.append(qUtils.mapKey(column, key)) + .forcePad.append(CQLSyntax.from) + .forcePad.append(table) + } +} diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/serializers/IndexModifiers.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/serializers/IndexModifiers.scala similarity index 62% rename from phantom-dsl/src/main/scala/com/websudos/phantom/builder/serializers/IndexModifiers.scala rename to phantom-dsl/src/main/scala/com/outworkers/phantom/builder/serializers/IndexModifiers.scala index 18c516c7f..c3b401e8b 100644 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/serializers/IndexModifiers.scala +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/serializers/IndexModifiers.scala @@ -1,38 +1,24 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.serializers +package com.outworkers.phantom.builder.serializers -import com.websudos.phantom.builder.QueryBuilder -import com.websudos.phantom.builder.QueryBuilder.Utils -import com.websudos.phantom.builder.query.CQLQuery -import com.websudos.phantom.builder.syntax.CQLSyntax +import com.outworkers.phantom.builder.QueryBuilder +import com.outworkers.phantom.builder.QueryBuilder.Utils +import com.outworkers.phantom.builder.query.CQLQuery +import com.outworkers.phantom.builder.syntax.CQLSyntax private[builder] class IndexModifiers extends BaseModifiers { diff --git a/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/serializers/InsertQueryBuilder.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/serializers/InsertQueryBuilder.scala new file mode 100644 index 000000000..410f12560 --- /dev/null +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/serializers/InsertQueryBuilder.scala @@ -0,0 +1,50 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.builder.serializers + +import com.outworkers.phantom.builder.query.CQLQuery +import com.outworkers.phantom.builder.syntax.CQLSyntax + +private[phantom] trait InsertQueryBuilder { + def insert(table: String): CQLQuery = { + CQLQuery(CQLSyntax.insert) + .forcePad.append(CQLSyntax.into) + .forcePad.append(table) + } + + def insert(table: CQLQuery): CQLQuery = { + insert(table.queryString) + } + + /** + * Creates a CQL 2.2 JSON insert clause using a pre-serialized JSON string. + * @param init The initialization query of the Insert clause, generally comprising the "INSERT INTO tableName" part. + * @param jsonString The pre-serialized JSON string to insert into the Cassandra table. + * @return A CQL query with the JSON prefix appended to the insert. + */ + def json(init: CQLQuery, jsonString: String): CQLQuery = { + init.pad.append("JSON").pad.append(CQLQuery.escape(jsonString)) + } + + def columns(list: List[CQLQuery]): CQLQuery = { + CQLQuery.empty.wrapn(list.map(_.queryString)) + } + + def values(list: List[CQLQuery]): CQLQuery = { + CQLQuery(CQLSyntax.values).wrapn(list.map(_.queryString)) + } + +} diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/serializers/KeySpaceQuerySerializer.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/serializers/KeySpaceQuerySerializer.scala similarity index 68% rename from phantom-dsl/src/main/scala/com/websudos/phantom/builder/serializers/KeySpaceQuerySerializer.scala rename to phantom-dsl/src/main/scala/com/outworkers/phantom/builder/serializers/KeySpaceQuerySerializer.scala index c383a3dd6..ea33a3bdd 100644 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/serializers/KeySpaceQuerySerializer.scala +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/serializers/KeySpaceQuerySerializer.scala @@ -1,39 +1,25 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.serializers +package com.outworkers.phantom.builder.serializers -import com.websudos.phantom.builder.QueryBuilder -import com.websudos.phantom.builder.QueryBuilder.Utils -import com.websudos.phantom.builder.query.{CQLQuery, OptionPart} -import com.websudos.phantom.builder.syntax.CQLSyntax -import com.websudos.phantom.connectors.KeySpace +import com.outworkers.phantom.builder.QueryBuilder +import com.outworkers.phantom.builder.QueryBuilder.Utils +import com.outworkers.phantom.builder.query.{CQLQuery, OptionPart} +import com.outworkers.phantom.builder.syntax.CQLSyntax +import com.outworkers.phantom.connectors.KeySpace private object Strategies { final val networkTopology = "NetworkTopologyStrategy" @@ -66,7 +52,7 @@ sealed trait TopologyStrategies { private[this] def strategy(name: String): CQLQuery = { CQLQuery.empty - .appendSingleQuote(CQLSyntax.CompactionOptions.`class`) + .appendSingleQuote(CQLSyntax.CompactionOptions.clz) .append(CQLSyntax.Symbols.colon).forcePad.appendSingleQuote(name) } @@ -133,7 +119,7 @@ sealed trait TopologyStrategies { sealed class KeySpaceSerializer(val keySpace: KeySpace, val qb: CQLQuery = CQLQuery.empty) { def `with`(clause: BuilderClause): KeySpaceSerializer = { - new KeySpaceSerializer(keySpace, QueryBuilder.Alter.`with`(qb, clause.qb)) + new KeySpaceSerializer(keySpace, QueryBuilder.Alter.option(qb, clause.qb)) } def and(clause: BuilderClause): KeySpaceSerializer = { diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/serializers/SelectQueryBuilder.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/serializers/SelectQueryBuilder.scala similarity index 83% rename from phantom-dsl/src/main/scala/com/websudos/phantom/builder/serializers/SelectQueryBuilder.scala rename to phantom-dsl/src/main/scala/com/outworkers/phantom/builder/serializers/SelectQueryBuilder.scala index 196cb60b3..95c1b0e1c 100644 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/serializers/SelectQueryBuilder.scala +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/serializers/SelectQueryBuilder.scala @@ -1,37 +1,23 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.serializers +package com.outworkers.phantom.builder.serializers -import com.websudos.phantom.builder.QueryBuilder -import com.websudos.phantom.builder.query.CQLQuery -import com.websudos.phantom.builder.syntax.CQLSyntax +import com.outworkers.phantom.builder.QueryBuilder +import com.outworkers.phantom.builder.query.CQLQuery +import com.outworkers.phantom.builder.syntax.CQLSyntax sealed class OrderingModifier { diff --git a/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/serializers/UpdateQueryBuilder.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/serializers/UpdateQueryBuilder.scala new file mode 100644 index 000000000..6a8f767f8 --- /dev/null +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/serializers/UpdateQueryBuilder.scala @@ -0,0 +1,87 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.builder.serializers + +import com.outworkers.phantom.builder.QueryBuilder.Utils +import com.outworkers.phantom.builder.query.CQLQuery +import com.outworkers.phantom.builder.syntax.CQLSyntax + +private[builder] class UpdateQueryBuilder { + + def onlyIf(clause: CQLQuery): CQLQuery = { + CQLQuery(CQLSyntax.IF).forcePad.append(clause) + } + + val ifExists: CQLQuery = CQLQuery(CQLSyntax.ifExists) + + private[this] def counterSetter(column: String, op: String, value: String): CQLQuery = { + CQLQuery(column).forcePad.append(CQLSyntax.Symbols.eqs) + .forcePad.append(column) + .forcePad.append(op) + .forcePad.append(value) + } + + def increment(column: String, value: String): CQLQuery = { + counterSetter(column, CQLSyntax.Symbols.plus, value) + } + + def decrement(column: String, value: String): CQLQuery = { + counterSetter(column, CQLSyntax.Symbols.-, value) + } + + def setTo(column: String, value: String): CQLQuery = { + Utils.concat(column, CQLSyntax.Symbols.eqs, value) + } + + def set(clause: CQLQuery): CQLQuery = { + CQLQuery(CQLSyntax.set).forcePad.append(clause) + } + + def where(condition: CQLQuery): CQLQuery = { + Utils.operator(CQLSyntax.where, condition) + } + + def and(condition: CQLQuery): CQLQuery = { + Utils.operator(CQLSyntax.and, condition) + } + + def clauses(clauses: List[CQLQuery], sep: String = " "): CQLQuery = { + CQLQuery.empty.append(clauses.map(_.queryString).mkString(sep)) + } + + def chain(clauses: List[CQLQuery]): CQLQuery = { + CQLQuery.empty.append(clauses.map(_.queryString).mkString(", ")) + } + + def usingPart(queries: List[CQLQuery]): CQLQuery = { + CQLQuery(CQLSyntax.using) + .forcePad + .append(clauses(queries, " " + CQLSyntax.And + " ")) + + } + + def update(tableName: String): CQLQuery = { + CQLQuery(CQLSyntax.update) + .forcePad.append(tableName) + } + + def updateMapColumn(column: String, key: String, value: String): CQLQuery = { + qUtils.mapKey(column, key) + .forcePad.append(CQLSyntax.Symbols.eqs) + .forcePad.append(value) + } +} + diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/serializers/Utils.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/serializers/Utils.scala similarity index 61% rename from phantom-dsl/src/main/scala/com/websudos/phantom/builder/serializers/Utils.scala rename to phantom-dsl/src/main/scala/com/outworkers/phantom/builder/serializers/Utils.scala index ee9e2eda9..aaeef302b 100644 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/serializers/Utils.scala +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/serializers/Utils.scala @@ -1,37 +1,23 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.serializers +package com.outworkers.phantom.builder.serializers -import com.websudos.phantom.builder.QueryBuilder.Utils -import com.websudos.phantom.builder.query.CQLQuery -import com.websudos.phantom.builder.syntax.CQLSyntax +import com.outworkers.phantom.builder.QueryBuilder.Utils +import com.outworkers.phantom.builder.query.CQLQuery +import com.outworkers.phantom.builder.syntax.CQLSyntax private[builder] trait Utils { @@ -67,10 +53,6 @@ private[builder] trait Utils { CQLQuery(qbs.map(_.queryString).mkString(", ")) } - def collection(list: TraversableOnce[String]): CQLQuery = { - CQLQuery(CQLSyntax.Symbols.`[`).append(list.mkString(", ")).append(CQLSyntax.Symbols.`]`) - } - def set(list: Set[String]): CQLQuery = { CQLQuery(CQLSyntax.Symbols.`{`).append(list.mkString(", ")).append(CQLSyntax.Symbols.`}`) } @@ -117,7 +99,7 @@ private[builder] trait Utils { } def tableOption(option: String, value: String): CQLQuery = { - Utils.concat(option, CQLSyntax.Symbols.`=`, value) + Utils.concat(option, CQLSyntax.Symbols.eqs, value) } def tableOption(option: String, value: CQLQuery): CQLQuery = { diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/syntax/CQLSyntax.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/syntax/CQLSyntax.scala similarity index 77% rename from phantom-dsl/src/main/scala/com/websudos/phantom/builder/syntax/CQLSyntax.scala rename to phantom-dsl/src/main/scala/com/outworkers/phantom/builder/syntax/CQLSyntax.scala index fda5f04e9..09fcec38d 100644 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/syntax/CQLSyntax.scala +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/builder/syntax/CQLSyntax.scala @@ -1,33 +1,19 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.syntax +package com.outworkers.phantom.builder.syntax object CQLSyntax { val Select = "SELECT" @@ -121,7 +107,6 @@ object CQLSyntax { val `]` = "]" val dot = "." - val `:` = ":" val colon = ":" val `;` = ";" val `(` = "(" @@ -129,7 +114,7 @@ object CQLSyntax { val `,` = "," val `<` = "<" val `>` = ">" - val `=` = "=" + val eqs = "=" val + = "+" val plus = "+" val - = "-" @@ -221,7 +206,7 @@ object CQLSyntax { } object CompactionOptions { - val `class` = "class" + val clz = "class" val enabled = "enabled" val max_threshold = "max_threshold" val min_threshold = "min_threshold" @@ -236,6 +221,8 @@ object CQLSyntax { val base_time_seconds = "base_time_seconds" val max_sstable_age_days = "max_sstable_age_days" val timestamp_resolution = "timestamp_resolution" + val compaction_window_size = "compaction_window_size" + val compaction_window_unit = "compaction_window_unit" } object CompactionStrategies { diff --git a/phantom-dsl/src/main/scala/com/outworkers/phantom/codec/JodaLocalDateCodec.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/codec/JodaLocalDateCodec.scala new file mode 100644 index 000000000..38a38ce63 --- /dev/null +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/codec/JodaLocalDateCodec.scala @@ -0,0 +1,38 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.codec + +import com.datastax.driver.core._ +import com.datastax.driver.extras.codecs.MappingCodec + +class JodaLocalDateCodec extends MappingCodec(TypeCodec.date(), classOf[org.joda.time.LocalDate]) { + + override def serialize(value: org.joda.time.LocalDate): LocalDate = { + LocalDate.fromYearMonthDay( + value.getYear, + value.getMonthOfYear, + value.getDayOfMonth + ) + } + + override def deserialize(value: LocalDate): org.joda.time.LocalDate = { + new org.joda.time.LocalDate( + value.getYear, + value.getMonth, + value.getDay + ) + } +} \ No newline at end of file diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/column/AbstractColumn.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/column/AbstractColumn.scala similarity index 56% rename from phantom-dsl/src/main/scala/com/websudos/phantom/column/AbstractColumn.scala rename to phantom-dsl/src/main/scala/com/outworkers/phantom/column/AbstractColumn.scala index dbe6eb375..19a99fead 100644 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/column/AbstractColumn.scala +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/column/AbstractColumn.scala @@ -1,35 +1,21 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.column +package com.outworkers.phantom.column -import com.websudos.phantom.builder.query.CQLQuery +import com.outworkers.phantom.builder.query.CQLQuery import scala.reflect.runtime.{currentMirror => cm} @@ -87,7 +73,7 @@ trait AbstractColumn[@specialized(Int, Double, Float, Long, Boolean, Short) T] { * * @return A boolean that says whether or not this type should be frozen. */ - def shouldFreeze: Boolean = false + def shouldFreeze: Boolean = isPrimary } diff --git a/phantom-dsl/src/main/scala/com/outworkers/phantom/column/CollectionValueDefinition.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/column/CollectionValueDefinition.scala new file mode 100644 index 000000000..dd854a3bc --- /dev/null +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/column/CollectionValueDefinition.scala @@ -0,0 +1,23 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.column + +trait CollectionValueDefinition[RR] { + + def valueAsCql(v: RR): String + + def fromString(c: String): RR +} diff --git a/phantom-dsl/src/main/scala/com/outworkers/phantom/column/Column.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/column/Column.scala new file mode 100644 index 000000000..af6e76570 --- /dev/null +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/column/Column.scala @@ -0,0 +1,39 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.column + +import com.datastax.driver.core.Row +import com.outworkers.phantom.CassandraTable + +import scala.util.{Failure, Success, Try} + + +abstract class Column[ + Owner <: CassandraTable[Owner, Record], + Record, + T +](val table: CassandraTable[Owner, Record]) extends AbstractColumn[T] { + + def parse(r: Row): Try[T] + + def apply(r: Row): T = parse(r) match { + case Success(value) => value + case Failure(ex) => + table.logger.error(s"Unable to parse value for column $name from row", ex) + throw ex + } + +} diff --git a/phantom-dsl/src/main/scala/com/outworkers/phantom/column/CounterColumn.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/column/CounterColumn.scala new file mode 100644 index 000000000..11bdf638b --- /dev/null +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/column/CounterColumn.scala @@ -0,0 +1,44 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.column + +import com.datastax.driver.core.Row +import com.outworkers.phantom.CassandraTable +import com.outworkers.phantom.builder.primitives.Primitive +import com.outworkers.phantom.builder.query.CQLQuery +import com.outworkers.phantom.builder.syntax.CQLSyntax +import com.outworkers.phantom.keys.Unmodifiable + +import scala.util.Try + +private[phantom] trait CounterRestriction[T] + +class CounterColumn[ + Owner <: CassandraTable[Owner, Record], + Record +](table: CassandraTable[Owner, Record])(implicit primitive: Primitive[Long]) + extends Column[Owner, Record, Long](table) with CounterRestriction[Long] with Unmodifiable { + + val cassandraType = CQLSyntax.Types.Counter + + override val isCounterColumn = true + + def parse(r: Row): Try[Long] = primitive.fromRow(name, r) + + override def qb: CQLQuery = CQLQuery(name).forcePad.append(cassandraType) + + override def asCql(v: Long): String = primitive.asCql(v) +} diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/column/JsonColumn.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/column/JsonColumn.scala similarity index 63% rename from phantom-dsl/src/main/scala/com/websudos/phantom/column/JsonColumn.scala rename to phantom-dsl/src/main/scala/com/outworkers/phantom/column/JsonColumn.scala index eccce1383..9090bbf67 100644 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/column/JsonColumn.scala +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/column/JsonColumn.scala @@ -1,43 +1,28 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.column +package com.outworkers.phantom.column import scala.collection.JavaConverters._ import scala.util.{Success, Try} - import com.datastax.driver.core.Row -import com.websudos.phantom.CassandraTable -import com.websudos.phantom.builder.QueryBuilder -import com.websudos.phantom.builder.primitives.Primitive -import com.websudos.phantom.builder.query.CQLQuery -import com.websudos.phantom.builder.syntax.CQLSyntax +import com.outworkers.phantom.CassandraTable +import com.outworkers.phantom.builder.QueryBuilder +import com.outworkers.phantom.builder.primitives.Primitive +import com.outworkers.phantom.builder.query.CQLQuery +import com.outworkers.phantom.builder.syntax.CQLSyntax sealed trait JsonDefinition[T] { diff --git a/phantom-dsl/src/main/scala/com/outworkers/phantom/column/ListColumn.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/column/ListColumn.scala new file mode 100644 index 000000000..17774918e --- /dev/null +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/column/ListColumn.scala @@ -0,0 +1,79 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.column + +import com.datastax.driver.core.Row +import com.outworkers.phantom.CassandraTable +import com.outworkers.phantom.builder.QueryBuilder +import com.outworkers.phantom.builder.QueryBuilder.Utils +import com.outworkers.phantom.builder.primitives.Primitive +import com.outworkers.phantom.builder.query.CQLQuery + +import scala.collection.JavaConverters._ +import scala.util.{Success, Try} + +abstract class AbstractListColumn[ + Owner <: CassandraTable[Owner, Record], + Record, + RR +](table: CassandraTable[Owner, Record]) extends Column[Owner, Record, List[RR]](table) + with CollectionValueDefinition[RR] { + + override def asCql(v: List[RR]): String = { + QueryBuilder.Collections.serialize(v.map(valueAsCql)).queryString + } + + override def apply(r: Row): List[RR] = parse(r).getOrElse(Nil) +} + +class ListColumn[ + Owner <: CassandraTable[Owner, Record], + Record, + RR : Primitive +](table: CassandraTable[Owner, Record]) + extends AbstractListColumn[Owner, Record, RR](table) + with PrimitiveCollectionValue[RR] { + + override val valuePrimitive = Primitive[RR] + + override val cassandraType = QueryBuilder.Collections.listType(valuePrimitive.cassandraType).queryString + + override def qb: CQLQuery = { + if (shouldFreeze) { + QueryBuilder.Collections.frozen(name, cassandraType) + } else if (valuePrimitive.frozen) { + CQLQuery(name).forcePad.append( + QueryBuilder.Collections.listType( + QueryBuilder.Collections.frozen(valuePrimitive.cassandraType).queryString + ) + ) + } else { + CQLQuery(name).forcePad.append(cassandraType) + } + } + + override def valueAsCql(v: RR): String = valuePrimitive.asCql(v) + + override def fromString(value: String): RR = valuePrimitive.fromString(value) + + override def parse(r: Row): Try[List[RR]] = { + if (r.isNull(name)) { + Success(Nil) + } else { + Try(r.getList(name, valuePrimitive.clz).asScala.map(valuePrimitive.extract).toList) + } + } +} diff --git a/phantom-dsl/src/main/scala/com/outworkers/phantom/column/MapColumn.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/column/MapColumn.scala new file mode 100644 index 000000000..887113a80 --- /dev/null +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/column/MapColumn.scala @@ -0,0 +1,104 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.column + +import com.datastax.driver.core.Row +import com.outworkers.phantom.CassandraTable +import com.outworkers.phantom.builder.QueryBuilder +import com.outworkers.phantom.builder.ops.MapKeyUpdateClause +import com.outworkers.phantom.builder.primitives.Primitive +import com.outworkers.phantom.builder.query.CQLQuery + +import scala.annotation.implicitNotFound +import scala.collection.JavaConverters._ +import scala.util.{Failure, Success, Try} + +private[phantom] abstract class AbstractMapColumn[ + Owner <: CassandraTable[Owner, Record], + Record, + K, + V +](table: CassandraTable[Owner, Record]) extends Column[Owner, Record, Map[K, V]](table) + with CollectionValueDefinition[V] { + + def keyAsCql(v: K): String + + def keyFromCql(c: String): K + + override def fromString(c: String): V + + def asCql(v: Map[K, V]): String = QueryBuilder.Collections.serialize(v.map { + case (a, b) => (keyAsCql(a), valueAsCql(b)) + }).queryString + + override def apply(r: Row): Map[K, V] = { + parse(r) match { + case Success(map) => map + + // Note null rows will not result in a failure, we return an empty map for those. + case Failure(ex) => { + table.logger.error(ex.getMessage) + throw ex + } + } + } +} + +@implicitNotFound(msg = "Type ${K} and ${V} must be Cassandra primitives") +class MapColumn[Owner <: CassandraTable[Owner, Record], Record, K : Primitive, V : Primitive](table: CassandraTable[Owner, Record]) + extends AbstractMapColumn[Owner, Record, K, V](table) with PrimitiveCollectionValue[V] { + + val keyPrimitive = Primitive[K] + + override def keyAsCql(v: K): String = keyPrimitive.asCql(v) + + override val valuePrimitive = Primitive[V] + + override val cassandraType = QueryBuilder.Collections.mapType( + keyPrimitive.cassandraType, + valuePrimitive.cassandraType + ).queryString + + override def qb: CQLQuery = { + if (shouldFreeze) { + QueryBuilder.Collections.frozen(name, cassandraType) + } else { + CQLQuery(name).forcePad.append(cassandraType) + } + } + + override def keyFromCql(c: String): K = keyPrimitive.fromString(c) + + override def valueAsCql(v: V): String = valuePrimitive.asCql(v) + + override def fromString(c: String): V = valuePrimitive.fromString(c) + + override def parse(r: Row): Try[Map[K, V]] = { + if (r.isNull(name)) { + Success(Map.empty[K, V]) + } else { + Try( + r.getMap(name, keyPrimitive.clz, valuePrimitive.clz).asScala.toMap map { + case (k, v) => keyPrimitive.extract(k) -> valuePrimitive.extract(v) + } + ) + } + } + + def apply(k: K): MapKeyUpdateClause[K, V] = { + new MapKeyUpdateClause[K, V](name, k) + } +} diff --git a/phantom-dsl/src/main/scala/com/outworkers/phantom/column/OptionalColumn.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/column/OptionalColumn.scala new file mode 100644 index 000000000..ff026b9ce --- /dev/null +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/column/OptionalColumn.scala @@ -0,0 +1,36 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.column + +import com.datastax.driver.core.Row +import com.outworkers.phantom.CassandraTable + +import scala.util.Try + +abstract class OptionalColumn[ + Owner <: CassandraTable[Owner, Record], + Record, + T +]( + table: CassandraTable[Owner, Record] +) extends AbstractColumn[Option[T]] { + + def apply(r: Row): Option[T] = optional(r).toOption + + def cassandraType: String + + def optional(r: Row): Try[T] +} diff --git a/phantom-dsl/src/main/scala/com/outworkers/phantom/column/OptionalPrimitiveColumn.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/column/OptionalPrimitiveColumn.scala new file mode 100644 index 000000000..cb46a95d8 --- /dev/null +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/column/OptionalPrimitiveColumn.scala @@ -0,0 +1,50 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.column + +import com.outworkers.phantom.builder.syntax.CQLSyntax + +import scala.annotation.implicitNotFound +import com.datastax.driver.core.Row +import com.outworkers.phantom.CassandraTable +import com.outworkers.phantom.builder.primitives.Primitive +import com.outworkers.phantom.builder.query.CQLQuery + +import scala.util.Try + +@implicitNotFound(msg = "Type ${T} must be a Cassandra primitive") +class OptionalPrimitiveColumn[ + Owner <: CassandraTable[Owner, Record], + Record, @specialized(Int, Double, Float, Long, Boolean, Short) T : Primitive +](table: CassandraTable[Owner, Record]) extends OptionalColumn[Owner, Record, T](table) { + + def cassandraType: String = Primitive[T].cassandraType + + def optional(r: Row): Try[T] = implicitly[Primitive[T]].fromRow(name, r) + + override def qb: CQLQuery = { + val root = CQLQuery(name).forcePad.append(cassandraType) + if (isStaticColumn) { + root.forcePad.append(CQLSyntax.static) + } else { + root + } + } + + override def asCql(v: Option[T]): String = { + v.map(Primitive[T].asCql).getOrElse(None.orNull.asInstanceOf[String]) + } +} diff --git a/phantom-dsl/src/main/scala/com/outworkers/phantom/column/OptionalTimeUUIDColumn.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/column/OptionalTimeUUIDColumn.scala new file mode 100644 index 000000000..5a2c5a2c6 --- /dev/null +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/column/OptionalTimeUUIDColumn.scala @@ -0,0 +1,31 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.column + +import java.util.UUID + +import com.outworkers.phantom.CassandraTable +import com.outworkers.phantom.builder.primitives.Primitive +import com.outworkers.phantom.builder.syntax.CQLSyntax + +class OptionalTimeUUIDColumn[ + Owner <: CassandraTable[Owner, Record], + Record +](table: CassandraTable[Owner, Record])( + implicit primitive: Primitive[UUID] +) extends OptionalPrimitiveColumn[Owner, Record, UUID](table) { + override val cassandraType = CQLSyntax.Types.TimeUUID +} diff --git a/phantom-dsl/src/main/scala/com/outworkers/phantom/column/PrimitiveCollectionValue.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/column/PrimitiveCollectionValue.scala new file mode 100644 index 000000000..ef3c32e52 --- /dev/null +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/column/PrimitiveCollectionValue.scala @@ -0,0 +1,28 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.column + +import com.outworkers.phantom.builder.primitives.Primitive + + +trait PrimitiveCollectionValue[R] extends CollectionValueDefinition[R] { + + def valuePrimitive: Primitive[R] + + def valueAsCql(v: R): String = valuePrimitive.asCql(v) + + def fromString(c: String): R = valuePrimitive.fromString(c) +} diff --git a/phantom-dsl/src/main/scala/com/outworkers/phantom/column/PrimitiveColumn.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/column/PrimitiveColumn.scala new file mode 100644 index 000000000..dae25f0ff --- /dev/null +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/column/PrimitiveColumn.scala @@ -0,0 +1,46 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.column + +import com.datastax.driver.core.Row +import com.outworkers.phantom.CassandraTable +import com.outworkers.phantom.builder.primitives.Primitive +import com.outworkers.phantom.builder.query.CQLQuery +import com.outworkers.phantom.builder.syntax.CQLSyntax + +import scala.annotation.implicitNotFound +import scala.util.Try + +@implicitNotFound(msg = "Type ${RR} must be a Cassandra primitive") +class PrimitiveColumn[T <: CassandraTable[T, R], R, @specialized(Int, Double, Float, Long) RR : Primitive](t: CassandraTable[T, R]) + extends Column[T, R, RR](t) { + + def cassandraType: String = Primitive[RR].cassandraType + + def asCql(v: RR): String = Primitive[RR].asCql(v) + + def parse(r: Row): Try[RR] = implicitly[Primitive[RR]].fromRow(name, r) + + override def qb: CQLQuery = { + val root = CQLQuery(name).forcePad.append(cassandraType) + + if (isStaticColumn) { + root.forcePad.append(CQLSyntax.static) + } else { + root + } + } +} \ No newline at end of file diff --git a/phantom-dsl/src/main/scala/com/outworkers/phantom/column/SetColumn.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/column/SetColumn.scala new file mode 100644 index 000000000..9b1b7737c --- /dev/null +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/column/SetColumn.scala @@ -0,0 +1,79 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.column + +import scala.collection.JavaConverters._ +import com.datastax.driver.core.Row +import com.outworkers.phantom.CassandraTable +import com.outworkers.phantom.builder.QueryBuilder +import com.outworkers.phantom.builder.primitives.Primitive +import com.outworkers.phantom.builder.query.CQLQuery + +import scala.annotation.implicitNotFound +import scala.util.{Failure, Success, Try} + +abstract class AbstractSetColumn[Owner <: CassandraTable[Owner, Record], Record, RR](table: CassandraTable[Owner, Record]) + extends Column[Owner, Record, Set[RR]](table) with CollectionValueDefinition[RR] { + + def valuesToCType(values: Iterable[RR]): Set[String] = values.map(valueAsCql).toSet + + override def apply(r: Row): Set[RR] = { + parse(r) match { + case Success(set) => set + + // Note null sets are considered successful, we simply return an empty set instead of null. + case Failure(ex) => { + table.logger.error(ex.getMessage) + throw ex + } + } + } + + override def asCql(v: Set[RR]): String = QueryBuilder.Collections.serialize(valuesToCType(v)).queryString +} + + +@implicitNotFound(msg = "Type ${RR} must be a Cassandra primitive") +class SetColumn[Owner <: CassandraTable[Owner, Record], Record, RR : Primitive](table: CassandraTable[Owner, Record]) + extends AbstractSetColumn[Owner, Record, RR](table) with PrimitiveCollectionValue[RR] { + + override val valuePrimitive: Primitive[RR] = Primitive[RR] + + val cassandraType: String = QueryBuilder.Collections.setType(valuePrimitive.cassandraType).queryString + + override def qb: CQLQuery = { + if (shouldFreeze) { + QueryBuilder.Collections.frozen(name, cassandraType) + } else if (valuePrimitive.frozen) { + CQLQuery(name).forcePad.append(QueryBuilder.Collections.frozen(valuePrimitive.cassandraType)) + } else { + CQLQuery(name).forcePad.append(cassandraType) + } + } + + override def valueAsCql(v: RR): String = Primitive[RR].asCql(v) + + override def fromString(c: String): RR = Primitive[RR].fromString(c) + + override def parse(r: Row): Try[Set[RR]] = { + if (r.isNull(name)) { + Success(Set.empty[RR]) + } else { + Success(r.getSet(name, Primitive[RR].clz.asInstanceOf[Class[RR]]).asScala.toSet[RR]) + } + } + +} diff --git a/phantom-dsl/src/main/scala/com/outworkers/phantom/column/TimeUUIDColumn.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/column/TimeUUIDColumn.scala new file mode 100644 index 000000000..fd8a962e2 --- /dev/null +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/column/TimeUUIDColumn.scala @@ -0,0 +1,29 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.column + +import java.util.UUID + +import com.outworkers.phantom.CassandraTable +import com.outworkers.phantom.builder.primitives.Primitive +import com.outworkers.phantom.builder.syntax.CQLSyntax + +class TimeUUIDColumn[ + Owner <: CassandraTable[Owner, Record], + Record](table: CassandraTable[Owner, Record] +)(implicit primitive: Primitive[UUID]) extends PrimitiveColumn[Owner, Record, UUID](table) { + override val cassandraType = CQLSyntax.Types.TimeUUID +} diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/database/Database.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/database/Database.scala similarity index 66% rename from phantom-dsl/src/main/scala/com/websudos/phantom/database/Database.scala rename to phantom-dsl/src/main/scala/com/outworkers/phantom/database/Database.scala index cd458065c..62f8c1a25 100644 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/database/Database.scala +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/database/Database.scala @@ -1,39 +1,26 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.database +package com.outworkers.phantom.database import com.datastax.driver.core.{ResultSet, Session} -import com.outworkers.diesel.reflection.EarlyInit -import com.websudos.phantom.CassandraTable -import com.websudos.phantom.builder.query.{CQLQuery, ExecutableStatementList} -import com.websudos.phantom.connectors.{KeySpace, KeySpaceDef} +import com.outworkers.phantom.{CassandraTable, Manager} +import com.outworkers.phantom.CassandraTable +import com.outworkers.phantom.builder.query.{CQLQuery, CreateQuery, ExecutableStatementList} +import com.outworkers.phantom.connectors.{KeySpace, CassandraConnection} +import com.outworkers.phantom.macros.DatabaseHelper import scala.concurrent.duration._ import scala.concurrent.{Await, ExecutionContextExecutor, Future, blocking} @@ -42,17 +29,19 @@ private object Lock abstract class Database[ DB <: Database[DB] -](val connector: KeySpaceDef) extends EarlyInit[CassandraTable[_, _]] { +](val connector: CassandraConnection)(implicit helper: DatabaseHelper[DB]) { + + trait Connector extends connector.Connector implicit val space: KeySpace = KeySpace(connector.name) implicit lazy val session: Session = connector.session - lazy val tables: Set[CassandraTable[_, _]] = initialize().toSet + val tables: Set[CassandraTable[_, _]] = helper.tables(this.asInstanceOf[DB]) def shutdown(): Unit = { blocking { - com.websudos.phantom.Manager.shutdown() + Manager.shutdown() session.getCluster.close() session.close() } @@ -72,14 +61,14 @@ abstract class Database[ * @return An executable statement list that can be used with Scala or Twitter futures to simultaneously * execute an entire sequence of queries. */ - def autocreate(): ExecutableCreateStatementsList = new ExecutableCreateStatementsList(tables) + private[phantom] def autocreate(): ExecutableCreateStatementsList = helper.createQueries(this.asInstanceOf[DB]) /** * A blocking method that will create all the tables. This is designed to prevent the * requirement of the implicit session to escape the enclosure of the database object. * * @param timeout The timeout for the initialisation call. - * Defaults to [[com.websudos.phantom.database.Database#defaultTimeout]] + * Defaults to [[com.outworkers.phantom.database.Database#defaultTimeout]] * @return A sequence of result sets, where every result is the result of a single create operation. */ def create(timeout: FiniteDuration = defaultTimeout)(implicit ex: ExecutionContextExecutor): Seq[ResultSet] = { @@ -108,7 +97,7 @@ abstract class Database[ * @return An executable statement list that can be used with Scala or Twitter futures to simultaneously * execute an entire sequence of queries. */ - def autodrop(): ExecutableStatementList = { + private[phantom] def autodrop(): ExecutableStatementList = { new ExecutableStatementList(tables.toSeq.map { table => table.alter().drop().qb }) @@ -129,7 +118,7 @@ abstract class Database[ * requirement of the implicit session to escape the enclosure of the database object. * * @param timeout The timeout for the initialisation call. - * Defaults to [[com.websudos.phantom.database.Database#defaultTimeout]] + * Defaults to [[com.outworkers.phantom.database.Database#defaultTimeout]] * @return A sequence of result sets, where every result is the result of a single drop operation. */ def drop(timeout: FiniteDuration = defaultTimeout)(implicit ex: ExecutionContextExecutor): Seq[ResultSet] = { @@ -148,10 +137,8 @@ abstract class Database[ * @return An executable statement list that can be used with Scala or Twitter futures to simultaneously * execute an entire sequence of queries. */ - def autotruncate(): ExecutableStatementList = { - new ExecutableStatementList(tables.toSeq.map { - table => table.truncate().qb - }) + private[phantom] def autotruncate(): ExecutableStatementList = { + new ExecutableStatementList(tables.toSeq.map(_.truncate().qb)) } /** @@ -159,7 +146,7 @@ abstract class Database[ * requirement of the implicit session to escape the enclosure of the database object. * * @param timeout The timeout for the initialisation call. - * Defaults to [[com.websudos.phantom.database.Database#defaultTimeout]] + * Defaults to [[com.outworkers.phantom.database.Database#defaultTimeout]] * @return A sequence of result sets, where every result is the result of a single truncate operation. */ def truncate(timeout: FiniteDuration = defaultTimeout)(implicit ex: ExecutionContextExecutor): Seq[ResultSet] = { @@ -177,17 +164,12 @@ abstract class Database[ } } -sealed class ExecutableCreateStatementsList(val tables: Set[CassandraTable[_, _]]) { - - private[phantom] def queries()(implicit keySpace: KeySpace): Seq[CQLQuery] = { - tables.toSeq.map(_.autocreate(keySpace).qb) - } - +sealed class ExecutableCreateStatementsList(val queries: KeySpace => Seq[CreateQuery[_, _, _]]) { def future()( implicit session: Session, keySpace: KeySpace, ec: ExecutionContextExecutor ): Future[Seq[ResultSet]] = { - Future.sequence(tables.toSeq.map(_.autocreate(keySpace).future())) + Future.sequence(queries(keySpace).map(_.future())) } -} \ No newline at end of file +} diff --git a/phantom-dsl/src/main/scala/com/outworkers/phantom/database/DatabaseProvider.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/database/DatabaseProvider.scala new file mode 100644 index 000000000..ec302ed4d --- /dev/null +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/database/DatabaseProvider.scala @@ -0,0 +1,20 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.database + +trait DatabaseProvider[T <: Database[T]] { + def database: T +} diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/dsl/package.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/dsl/package.scala similarity index 51% rename from phantom-dsl/src/main/scala/com/websudos/phantom/dsl/package.scala rename to phantom-dsl/src/main/scala/com/outworkers/phantom/dsl/package.scala index 687d72577..86b536731 100644 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/dsl/package.scala +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/dsl/package.scala @@ -1,33 +1,19 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom +package com.outworkers.phantom import java.net.InetAddress import java.nio.ByteBuffer @@ -35,18 +21,18 @@ import java.util.{Date, Random} import com.datastax.driver.core.utils.UUIDs import com.datastax.driver.core.{VersionNumber, ConsistencyLevel => CLevel} -import com.websudos.phantom.batch.Batcher -import com.websudos.phantom.builder.QueryBuilder -import com.websudos.phantom.builder.clauses.{UpdateClause, UsingClauseOperations, WhereClause} -import com.websudos.phantom.builder.ops._ -import com.websudos.phantom.builder.primitives.Primitive -import com.websudos.phantom.builder.query.prepared.PrepareMark -import com.websudos.phantom.builder.query.{CQLQuery, CreateImplicits, DeleteImplicits, SelectImplicits} -import com.websudos.phantom.builder.serializers.KeySpaceConstruction -import com.websudos.phantom.builder.syntax.CQLSyntax -import com.websudos.phantom.column.AbstractColumn -import com.websudos.phantom.column.extractors.FromRow.RowParser -import com.websudos.phantom.database.Database +import com.outworkers.phantom +import com.outworkers.phantom.batch.Batcher +import com.outworkers.phantom.builder.QueryBuilder +import com.outworkers.phantom.builder.clauses.{UpdateClause, UsingClauseOperations, WhereClause} +import com.outworkers.phantom.builder.ops._ +import com.outworkers.phantom.builder.primitives.Primitive +import com.outworkers.phantom.builder.query.prepared.PrepareMark +import com.outworkers.phantom.builder.query.{CQLQuery, CreateImplicits, DeleteImplicits, SelectImplicits} +import com.outworkers.phantom.builder.serializers.KeySpaceConstruction +import com.outworkers.phantom.builder.syntax.CQLSyntax +import com.outworkers.phantom.column.AbstractColumn +import com.outworkers.phantom.connectors.DefaultVersions import org.joda.time.DateTimeZone import shapeless.{::, HNil} @@ -59,63 +45,63 @@ package object dsl extends ImplicitMechanism with CreateImplicits with KeySpaceConstruction with DeleteImplicits { - type CassandraTable[Owner <: CassandraTable[Owner, Record], Record] = com.websudos.phantom.CassandraTable[Owner, Record] - - type Column[Owner <: CassandraTable[Owner, Record], Record, T] = com.websudos.phantom.column.Column[Owner, Record, T] - type PrimitiveColumn[Owner <: CassandraTable[Owner, Record], Record, T] = com.websudos.phantom.column.PrimitiveColumn[Owner, Record, T] - type OptionalColumn[Owner <: CassandraTable[Owner, Record], Record, T] = com.websudos.phantom.column.OptionalColumn[Owner, Record, T] - - type OptionalPrimitiveColumn[Owner <: CassandraTable[Owner, Record], Record, T] = com.websudos.phantom.column.OptionalPrimitiveColumn[Owner, Record, T] - type BigDecimalColumn[Owner <: CassandraTable[Owner, Record], Record] = com.websudos.phantom.column.PrimitiveColumn[Owner, Record, BigDecimal] - - type BlobColumn[Owner <: CassandraTable[Owner, Record], Record, T] = com.websudos.phantom.column.PrimitiveColumn[Owner, Record, ByteBuffer] - type BigIntColumn[Owner <: CassandraTable[Owner, Record], Record] = com.websudos.phantom.column.PrimitiveColumn[Owner, Record, BigInt] - type BooleanColumn[Owner <: CassandraTable[Owner, Record], Record] = com.websudos.phantom.column.PrimitiveColumn[Owner, Record, Boolean] - type DateColumn[Owner <: CassandraTable[Owner, Record], Record] = com.websudos.phantom.column.PrimitiveColumn[Owner, Record, Date] - type DateTimeColumn[Owner <: CassandraTable[Owner, Record], Record] = com.websudos.phantom.column.PrimitiveColumn[Owner, Record, DateTime] - type LocalDateColumn[Owner <: CassandraTable[Owner, Record], Record] = com.websudos.phantom.column.PrimitiveColumn[Owner, Record, LocalDate] - type DoubleColumn[Owner <: CassandraTable[Owner, Record], Record] = com.websudos.phantom.column.PrimitiveColumn[Owner, Record, Double] - type FloatColumn[Owner <: CassandraTable[Owner, Record], Record] = com.websudos.phantom.column.PrimitiveColumn[Owner, Record, Float] - type IntColumn[Owner <: CassandraTable[Owner, Record], Record] = com.websudos.phantom.column.PrimitiveColumn[Owner, Record, Int] - type SmallIntColumn[Owner <: CassandraTable[Owner, Record], Record] = com.websudos.phantom.column.PrimitiveColumn[Owner, Record, Short] - type TinyIntColumn[Owner <: CassandraTable[Owner, Record], Record] = com.websudos.phantom.column.PrimitiveColumn[Owner, Record, Byte] - type InetAddressColumn[Owner <: CassandraTable[Owner, Record], Record] = com.websudos.phantom.column.PrimitiveColumn[Owner, Record, InetAddress] - type LongColumn[Owner <: CassandraTable[Owner, Record], Record] = com.websudos.phantom.column.PrimitiveColumn[Owner, Record, Long] - type StringColumn[Owner <: CassandraTable[Owner, Record], Record] = com.websudos.phantom.column.PrimitiveColumn[Owner, Record, String] - type UUIDColumn[Owner <: CassandraTable[Owner, Record], Record] = com.websudos.phantom.column.PrimitiveColumn[Owner, Record, UUID] - type CounterColumn[Owner <: CassandraTable[Owner, Record], Record] = com.websudos.phantom.column.CounterColumn[Owner, Record] - type TimeUUIDColumn[Owner <: CassandraTable[Owner, Record], Record] = com.websudos.phantom.column.TimeUUIDColumn[Owner, Record] - - type OptionalBlobColumn[Owner <: CassandraTable[Owner, Record], Record, T] = com.websudos.phantom.column.OptionalPrimitiveColumn[Owner, Record, ByteBuffer] - type OptionalBigDecimalColumn[Owner <: CassandraTable[Owner, Record], Record] = com.websudos.phantom.column.OptionalPrimitiveColumn[Owner, Record, BigDecimal] - type OptionalBigIntColumn[Owner <: CassandraTable[Owner, Record], Record] = com.websudos.phantom.column.OptionalPrimitiveColumn[Owner, Record, BigInt] - type OptionalBooleanColumn[Owner <: CassandraTable[Owner, Record], Record] = com.websudos.phantom.column.OptionalPrimitiveColumn[Owner, Record, Boolean] - type OptionalDateColumn[Owner <: CassandraTable[Owner, Record], Record] = com.websudos.phantom.column.OptionalPrimitiveColumn[Owner, Record, Date] - type OptionalDateTimeColumn[Owner <: CassandraTable[Owner, Record], Record] = com.websudos.phantom.column.OptionalPrimitiveColumn[Owner, Record, DateTime] - type OptionalLocalDateColumn[Owner <: CassandraTable[Owner, Record], Record] = com.websudos.phantom.column.OptionalPrimitiveColumn[Owner, Record, LocalDate] - type OptionalDoubleColumn[Owner <: CassandraTable[Owner, Record], Record] = com.websudos.phantom.column.OptionalPrimitiveColumn[Owner, Record, Double] - type OptionalFloatColumn[Owner <: CassandraTable[Owner, Record], Record] = com.websudos.phantom.column.OptionalPrimitiveColumn[Owner, Record, Float] - type OptionalIntColumn[Owner <: CassandraTable[Owner, Record], Record] = com.websudos.phantom.column.OptionalPrimitiveColumn[Owner, Record, Int] - type OptionalSmallIntColumn[Owner <: CassandraTable[Owner, Record], Record] = com.websudos.phantom.column.OptionalPrimitiveColumn[Owner, Record, Short] - type OptionalTinyIntColumn[Owner <: CassandraTable[Owner, Record], Record] = com.websudos.phantom.column.OptionalPrimitiveColumn[Owner, Record, Byte] - type OptionalInetAddressColumn[Owner <: CassandraTable[Owner, Record], Record] = com.websudos.phantom.column.OptionalPrimitiveColumn[Owner, Record, InetAddress] - type OptionalLongColumn[Owner <: CassandraTable[Owner, Record], Record] = com.websudos.phantom.column.OptionalPrimitiveColumn[Owner, Record, Long] - type OptionalStringColumn[Owner <: CassandraTable[Owner, Record], Record] = com.websudos.phantom.column.OptionalPrimitiveColumn[Owner, Record, String] - type OptionalUUIDColumn[Owner <: CassandraTable[Owner, Record], Record] = com.websudos.phantom.column.OptionalPrimitiveColumn[Owner, Record, UUID] - type OptionalTimeUUIDColumn[Owner <: CassandraTable[Owner, Record], Record] = com.websudos.phantom.column.OptionalTimeUUIDColumn[Owner, Record] - - type ClusteringOrder[ValueType] = com.websudos.phantom.keys.ClusteringOrder[ValueType] - type Ascending = com.websudos.phantom.keys.Ascending - type Descending = com.websudos.phantom.keys.Descending - type PartitionKey[ValueType] = com.websudos.phantom.keys.PartitionKey[ValueType] - type PrimaryKey[ValueType] = com.websudos.phantom.keys.PrimaryKey[ValueType] - type Index[ValueType] = com.websudos.phantom.keys.Index[ValueType] - type Keys = com.websudos.phantom.keys.Keys - type Entries = com.websudos.phantom.keys.Entries - type StaticColumn[ValueType] = com.websudos.phantom.keys.StaticColumn[ValueType] - - type Database[DB <: Database[DB]] = com.websudos.phantom.database.Database[DB] - type DatabaseProvider[DB <: Database[DB]] = com.websudos.phantom.database.DatabaseProvider[DB] + type CassandraTable[Owner <: CassandraTable[Owner, Record], Record] = phantom.CassandraTable[Owner, Record] + + type Column[Owner <: CassandraTable[Owner, Record], Record, T] = com.outworkers.phantom.column.Column[Owner, Record, T] + type PrimitiveColumn[Owner <: CassandraTable[Owner, Record], Record, T] = com.outworkers.phantom.column.PrimitiveColumn[Owner, Record, T] + type OptionalColumn[Owner <: CassandraTable[Owner, Record], Record, T] = com.outworkers.phantom.column.OptionalColumn[Owner, Record, T] + + type OptionalPrimitiveColumn[Owner <: CassandraTable[Owner, Record], Record, T] = com.outworkers.phantom.column.OptionalPrimitiveColumn[Owner, Record, T] + type BigDecimalColumn[Owner <: CassandraTable[Owner, Record], Record] = com.outworkers.phantom.column.PrimitiveColumn[Owner, Record, BigDecimal] + + type BlobColumn[Owner <: CassandraTable[Owner, Record], Record, T] = com.outworkers.phantom.column.PrimitiveColumn[Owner, Record, ByteBuffer] + type BigIntColumn[Owner <: CassandraTable[Owner, Record], Record] = com.outworkers.phantom.column.PrimitiveColumn[Owner, Record, BigInt] + type BooleanColumn[Owner <: CassandraTable[Owner, Record], Record] = com.outworkers.phantom.column.PrimitiveColumn[Owner, Record, Boolean] + type DateColumn[Owner <: CassandraTable[Owner, Record], Record] = com.outworkers.phantom.column.PrimitiveColumn[Owner, Record, Date] + type DateTimeColumn[Owner <: CassandraTable[Owner, Record], Record] = com.outworkers.phantom.column.PrimitiveColumn[Owner, Record, DateTime] + type LocalDateColumn[Owner <: CassandraTable[Owner, Record], Record] = com.outworkers.phantom.column.PrimitiveColumn[Owner, Record, LocalDate] + type DoubleColumn[Owner <: CassandraTable[Owner, Record], Record] = com.outworkers.phantom.column.PrimitiveColumn[Owner, Record, Double] + type FloatColumn[Owner <: CassandraTable[Owner, Record], Record] = com.outworkers.phantom.column.PrimitiveColumn[Owner, Record, Float] + type IntColumn[Owner <: CassandraTable[Owner, Record], Record] = com.outworkers.phantom.column.PrimitiveColumn[Owner, Record, Int] + type SmallIntColumn[Owner <: CassandraTable[Owner, Record], Record] = com.outworkers.phantom.column.PrimitiveColumn[Owner, Record, Short] + type TinyIntColumn[Owner <: CassandraTable[Owner, Record], Record] = com.outworkers.phantom.column.PrimitiveColumn[Owner, Record, Byte] + type InetAddressColumn[Owner <: CassandraTable[Owner, Record], Record] = com.outworkers.phantom.column.PrimitiveColumn[Owner, Record, InetAddress] + type LongColumn[Owner <: CassandraTable[Owner, Record], Record] = com.outworkers.phantom.column.PrimitiveColumn[Owner, Record, Long] + type StringColumn[Owner <: CassandraTable[Owner, Record], Record] = com.outworkers.phantom.column.PrimitiveColumn[Owner, Record, String] + type UUIDColumn[Owner <: CassandraTable[Owner, Record], Record] = com.outworkers.phantom.column.PrimitiveColumn[Owner, Record, UUID] + type CounterColumn[Owner <: CassandraTable[Owner, Record], Record] = com.outworkers.phantom.column.CounterColumn[Owner, Record] + type TimeUUIDColumn[Owner <: CassandraTable[Owner, Record], Record] = com.outworkers.phantom.column.TimeUUIDColumn[Owner, Record] + + type OptionalBlobColumn[Owner <: CassandraTable[Owner, Record], Record, T] = com.outworkers.phantom.column.OptionalPrimitiveColumn[Owner, Record, ByteBuffer] + type OptionalBigDecimalColumn[Owner <: CassandraTable[Owner, Record], Record] = com.outworkers.phantom.column.OptionalPrimitiveColumn[Owner, Record, BigDecimal] + type OptionalBigIntColumn[Owner <: CassandraTable[Owner, Record], Record] = com.outworkers.phantom.column.OptionalPrimitiveColumn[Owner, Record, BigInt] + type OptionalBooleanColumn[Owner <: CassandraTable[Owner, Record], Record] = com.outworkers.phantom.column.OptionalPrimitiveColumn[Owner, Record, Boolean] + type OptionalDateColumn[Owner <: CassandraTable[Owner, Record], Record] = com.outworkers.phantom.column.OptionalPrimitiveColumn[Owner, Record, Date] + type OptionalDateTimeColumn[Owner <: CassandraTable[Owner, Record], Record] = com.outworkers.phantom.column.OptionalPrimitiveColumn[Owner, Record, DateTime] + type OptionalLocalDateColumn[Owner <: CassandraTable[Owner, Record], Record] = com.outworkers.phantom.column.OptionalPrimitiveColumn[Owner, Record, LocalDate] + type OptionalDoubleColumn[Owner <: CassandraTable[Owner, Record], Record] = com.outworkers.phantom.column.OptionalPrimitiveColumn[Owner, Record, Double] + type OptionalFloatColumn[Owner <: CassandraTable[Owner, Record], Record] = com.outworkers.phantom.column.OptionalPrimitiveColumn[Owner, Record, Float] + type OptionalIntColumn[Owner <: CassandraTable[Owner, Record], Record] = com.outworkers.phantom.column.OptionalPrimitiveColumn[Owner, Record, Int] + type OptionalSmallIntColumn[Owner <: CassandraTable[Owner, Record], Record] = com.outworkers.phantom.column.OptionalPrimitiveColumn[Owner, Record, Short] + type OptionalTinyIntColumn[Owner <: CassandraTable[Owner, Record], Record] = com.outworkers.phantom.column.OptionalPrimitiveColumn[Owner, Record, Byte] + type OptionalInetAddressColumn[Owner <: CassandraTable[Owner, Record], Record] = com.outworkers.phantom.column.OptionalPrimitiveColumn[Owner, Record, InetAddress] + type OptionalLongColumn[Owner <: CassandraTable[Owner, Record], Record] = com.outworkers.phantom.column.OptionalPrimitiveColumn[Owner, Record, Long] + type OptionalStringColumn[Owner <: CassandraTable[Owner, Record], Record] = com.outworkers.phantom.column.OptionalPrimitiveColumn[Owner, Record, String] + type OptionalUUIDColumn[Owner <: CassandraTable[Owner, Record], Record] = com.outworkers.phantom.column.OptionalPrimitiveColumn[Owner, Record, UUID] + type OptionalTimeUUIDColumn[Owner <: CassandraTable[Owner, Record], Record] = com.outworkers.phantom.column.OptionalTimeUUIDColumn[Owner, Record] + + type ClusteringOrder = com.outworkers.phantom.keys.ClusteringOrder + type Ascending = com.outworkers.phantom.keys.Ascending + type Descending = com.outworkers.phantom.keys.Descending + type PartitionKey = com.outworkers.phantom.keys.PartitionKey + type PrimaryKey = com.outworkers.phantom.keys.PrimaryKey + type Index = com.outworkers.phantom.keys.Index + type Keys = com.outworkers.phantom.keys.Keys + type Entries = com.outworkers.phantom.keys.Entries + type StaticColumn = com.outworkers.phantom.keys.StaticColumn + + type Database[DB <: Database[DB]] = com.outworkers.phantom.database.Database[DB] + type DatabaseProvider[DB <: Database[DB]] = com.outworkers.phantom.database.DatabaseProvider[DB] type DateTime = org.joda.time.DateTime type LocalDate = org.joda.time.LocalDate @@ -124,15 +110,15 @@ package object dsl extends ImplicitMechanism with CreateImplicits type Row = com.datastax.driver.core.Row type ResultSet = com.datastax.driver.core.ResultSet type Session = com.datastax.driver.core.Session - type KeySpace = com.websudos.phantom.connectors.KeySpace - val KeySpace = com.websudos.phantom.connectors.KeySpace - type RootConnector = com.websudos.phantom.connectors.RootConnector + type KeySpace = com.outworkers.phantom.connectors.KeySpace + val KeySpace = com.outworkers.phantom.connectors.KeySpace + type RootConnector = com.outworkers.phantom.connectors.RootConnector - val Version = com.websudos.phantom.connectors.DefaultVersions + val Version = DefaultVersions - type ListResult[R] = com.websudos.phantom.builder.query.ListResult[R] - type IteratorResult[R] = com.websudos.phantom.builder.query.IteratorResult[R] - type RecordResult[R] = com.websudos.phantom.builder.query.RecordResult[R] + type ListResult[R] = com.outworkers.phantom.builder.query.ListResult[R] + type IteratorResult[R] = com.outworkers.phantom.builder.query.IteratorResult[R] + type RecordResult[R] = com.outworkers.phantom.builder.query.RecordResult[R] object ? extends PrepareMark @@ -152,9 +138,9 @@ package object dsl extends ImplicitMechanism with CreateImplicits val SERIAL = CLevel.SERIAL } - type KeySpaceDef = com.websudos.phantom.connectors.KeySpaceDef - val ContactPoint = com.websudos.phantom.connectors.ContactPoint - val ContactPoints = com.websudos.phantom.connectors.ContactPoints + type KeySpaceDef = com.outworkers.phantom.connectors.CassandraConnection + val ContactPoint = com.outworkers.phantom.connectors.ContactPoint + val ContactPoints = com.outworkers.phantom.connectors.ContactPoints implicit class RichNumber(val percent: Int) extends AnyVal { def percentile: CQLQuery = CQLQuery(percent.toString).append(CQLSyntax.CreateOptions.percentile) @@ -166,7 +152,7 @@ package object dsl extends ImplicitMechanism with CreateImplicits implicit lazy val context: ExecutionContextExecutor = Manager.scalaExecutor - implicit class PartitionTokenHelper[T](val col: AbstractColumn[T] with PartitionKey[T]) extends AnyVal { + implicit class PartitionTokenHelper[T](val col: AbstractColumn[T] with PartitionKey) extends AnyVal { def ltToken(value: T): WhereClause.Condition = { new WhereClause.Condition( @@ -257,7 +243,4 @@ package object dsl extends ImplicitMechanism with CreateImplicits implicit class UUIDAugmenter(val uid: UUID) extends AnyVal { def datetime: DateTime = new DateTime(UUIDs.unixTimestamp(uid), DateTimeZone.UTC) } - - def extract[R]: RowParser[R] = new RowParser[R] {} - } diff --git a/phantom-dsl/src/main/scala/com/outworkers/phantom/exceptions/exceptions.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/exceptions/exceptions.scala new file mode 100644 index 000000000..3913d696e --- /dev/null +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/exceptions/exceptions.scala @@ -0,0 +1,29 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.exceptions + +import scala.util.control.NoStackTrace + +case class InvalidClusteringKeyException(table: String) extends + RuntimeException(s"Table $table: When using CLUSTERING ORDER all PrimaryKey" + + s" definitions must become a ClusteringKey definition and specify order." + ) with NoStackTrace + +case class InvalidPrimaryKeyException( + table: String +) extends RuntimeException(s"You need to define at least one PartitionKey for the table $table") with NoStackTrace + +case class InvalidTableException(msg: String) extends RuntimeException(msg) with NoStackTrace diff --git a/phantom-dsl/src/main/scala/com/outworkers/phantom/keys/ClusteringOrder.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/keys/ClusteringOrder.scala new file mode 100644 index 000000000..e858f3d79 --- /dev/null +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/keys/ClusteringOrder.scala @@ -0,0 +1,36 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.keys + +import com.outworkers.phantom.column.AbstractColumn + +/** + * A trait mixable into a Column to allow clustering order. + */ +trait ClusteringOrder extends PrimaryKey { + self: AbstractColumn[_] => + override val isClusteringKey = true + +} + +trait Ascending { + self: AbstractColumn[_] with ClusteringOrder => + override val isAscending = true +} + +trait Descending { + self: AbstractColumn[_] with ClusteringOrder => +} diff --git a/phantom-dsl/src/main/scala/com/outworkers/phantom/keys/PrimaryKey.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/keys/PrimaryKey.scala new file mode 100644 index 000000000..a05693f51 --- /dev/null +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/keys/PrimaryKey.scala @@ -0,0 +1,58 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.keys + +import com.outworkers.phantom.column.AbstractColumn + +private[phantom] trait Undroppable +private[phantom] trait Unmodifiable +private[phantom] trait Indexed + +private[phantom] trait Key[KeyType <: Key[KeyType]] { + self: AbstractColumn[_] => +} + +trait PrimaryKey extends Key[PrimaryKey] with Unmodifiable with Indexed with Undroppable { + self: AbstractColumn[_] => + override val isPrimary = true +} + +trait PartitionKey extends Key[PartitionKey] with Unmodifiable with Indexed with Undroppable { + self: AbstractColumn[_] => + override val isPartitionKey = true + override val isPrimary = true +} + +/** + * A trait mixable into Column definitions to allow storing them as keys. + */ +trait Index extends Indexed with Undroppable { + self: AbstractColumn[_] => + + override val isSecondaryKey = true +} + +trait Keys { + self : Index with AbstractColumn[_] => + + override private[phantom] val isMapKeyIndex = true +} + +trait Entries { + self: Index with AbstractColumn[_] => + + override private[phantom] val isMapEntryIndex = true +} \ No newline at end of file diff --git a/phantom-dsl/src/main/scala/com/outworkers/phantom/keys/StaticColumn.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/keys/StaticColumn.scala new file mode 100644 index 000000000..a56c15f65 --- /dev/null +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/keys/StaticColumn.scala @@ -0,0 +1,23 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.keys + +import com.outworkers.phantom.column.AbstractColumn + +trait StaticColumn extends Key[StaticColumn] { + self: AbstractColumn[_] => + override val isStaticColumn = true +} diff --git a/phantom-dsl/src/main/scala/com/outworkers/phantom/macros/DatabaseHelper.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/macros/DatabaseHelper.scala new file mode 100644 index 000000000..a2aa8aa35 --- /dev/null +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/macros/DatabaseHelper.scala @@ -0,0 +1,72 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.macros + +import com.outworkers.phantom.CassandraTable +import com.outworkers.phantom.database.{Database, ExecutableCreateStatementsList} +import com.outworkers.phantom.builder.query.CreateQuery +import com.outworkers.phantom.connectors.KeySpace + +import scala.reflect.macros.blackbox + +trait DatabaseHelper[T <: Database[T]] { + def tables(db: T): Set[CassandraTable[_ ,_]] + + def createQueries(db: T)(implicit keySpace: KeySpace): ExecutableCreateStatementsList +} + +object DatabaseHelper { + implicit def macroMaterialise[T <: Database[T]]: DatabaseHelper[T] = macro DatabaseHelperMacro.macroImpl[T] +} + +@macrocompat.bundle +class DatabaseHelperMacro(override val c: blackbox.Context) extends MacroUtils(c) { + import c.universe._ + + val keySpaceTpe = tq"com.outworkers.phantom.connectors.KeySpace" + + def macroImpl[T <: Database[T] : WeakTypeTag]: Tree = { + val tpe = weakTypeOf[T] + val tableSymbol = tq"com.outworkers.phantom.CassandraTable[_, _]" + + val accessors = filterMembers[T, CassandraTable[_, _]]() + + val prefix = q"com.outworkers.phantom.database" + + val tableList = accessors.map(sym => { + val name = sym.asTerm.name.toTermName + q"""db.$name""" + }) + + val queryList = tableList.map { tb => q"""$tb.autocreate(space)""" } + + val listType = tq"$prefix.ExecutableCreateStatementsList" + + q""" + new com.outworkers.phantom.macros.DatabaseHelper[$tpe] { + def tables(db: $tpe): scala.collection.immutable.Set[$tableSymbol] = { + scala.collection.immutable.Set.apply[$tableSymbol](..$tableList) + } + + def createQueries(db: $tpe)(implicit space: $keySpaceTpe): $listType = { + new $prefix.ExecutableCreateStatementsList( + space => scala.collection.immutable.Seq.apply(..$queryList) + ) + } + } + """ + } +} diff --git a/phantom-dsl/src/main/scala/com/outworkers/phantom/macros/MacroUtils.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/macros/MacroUtils.scala new file mode 100644 index 000000000..ca4936c9e --- /dev/null +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/macros/MacroUtils.scala @@ -0,0 +1,78 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.macros +import scala.reflect.macros.blackbox + +@macrocompat.bundle +class MacroUtils(val c: blackbox.Context) { + import c.universe._ + + def caseFields(tpe: Type): Iterable[(Name, Type)] = { + object CaseField { + def unapply(arg: TermSymbol): Option[(Name, Type)] = { + if (arg.isVal && arg.isCaseAccessor) { + Some(TermName(arg.name.toString.trim) -> arg.typeSignature) + } else { + None + } + } + } + + tpe.decls.collect { case CaseField(name, fType) => name -> fType } + } + + def baseType(sym: Symbol): Set[Symbol] = { + if (sym.isClass) { + val clz = sym.asClass + val base = clz.baseClasses.toSet - clz //`baseClasses` contains `a` itself + val basebase = base.flatMap { + case x: ClassSymbol => x.baseClasses.toSet - x + } + base -- basebase + } else { + c.abort(c.enclosingPosition, s"Expected a class, but the symbol was different") + } + } + + def filterMembers[Filter : TypeTag]( + tag: Type, + exclusions: Symbol => Option[Symbol] + ): Seq[Symbol] = { + val tpe = tag.typeSymbol.typeSignature + + ( + for { + baseClass <- tpe.baseClasses.reverse.flatMap(exclusions(_)) + symbol <- baseClass.typeSignature.members.sorted + if symbol.typeSignature <:< typeOf[Filter] + } yield symbol + )(collection.breakOut) distinct + } + + def filterMembers[T : WeakTypeTag, Filter : TypeTag]( + exclusions: Symbol => Option[Symbol] = { s: Symbol => Some(s) } + ): Seq[Symbol] = { + val tpe = weakTypeOf[T].typeSymbol.typeSignature + + ( + for { + baseClass <- tpe.baseClasses.reverse.flatMap(exclusions(_)) + symbol <- baseClass.typeSignature.members.sorted + if symbol.typeSignature <:< typeOf[Filter] + } yield symbol + )(collection.breakOut) distinct + } +} diff --git a/phantom-dsl/src/main/scala/com/outworkers/phantom/macros/TableHelper.scala b/phantom-dsl/src/main/scala/com/outworkers/phantom/macros/TableHelper.scala new file mode 100644 index 000000000..d9922f0a2 --- /dev/null +++ b/phantom-dsl/src/main/scala/com/outworkers/phantom/macros/TableHelper.scala @@ -0,0 +1,333 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.macros + +import com.datastax.driver.core.Row +import com.outworkers.phantom.builder.query.InsertQuery +import com.outworkers.phantom.{CassandraTable, SelectTable} +import com.outworkers.phantom.column.AbstractColumn +import com.outworkers.phantom.dsl.KeySpace +import com.outworkers.phantom.keys.{ClusteringOrder, PartitionKey, PrimaryKey} + +import scala.reflect.macros.blackbox + +trait TableHelper[T <: CassandraTable[T, R], R] { + + def tableName: String + + def fromRow(table: T, row: Row): R + + def tableKey(table: T): String + + def fields(table: CassandraTable[T, R]): Set[AbstractColumn[_]] + + def store(table: T)(implicit space: KeySpace): InsertQuery.Default[T, R] +} + +object TableHelper { + implicit def fieldsMacro[T <: CassandraTable[T, R], R]: TableHelper[T, R] = macro TableHelperMacro.macroImpl[T, R] +} + + +@macrocompat.bundle +class TableHelperMacro(override val c: blackbox.Context) extends MacroUtils(c) { + + + import c.universe._ + + case class ColumnMember( + name: TermName, + tpe: Type + ) { + def symbol: Symbol = tpe.typeSymbol + } + + private[this] val rowType = tq"com.datastax.driver.core.Row" + private[this] val builder = q"com.outworkers.phantom.builder.QueryBuilder" + private[this] val strTpe = tq"java.lang.String" + private[this] val colType = tq"com.outworkers.phantom.column.AbstractColumn[_]" + private[this] val collections = q"scala.collection.immutable" + private[this] val rowTerm = TermName("row") + private[this] val tableTerm = TermName("table") + private[this] val keyspaceType = tq"com.outworkers.phantom.connectors.KeySpace" + + val knownList = List("Any", "Object", "RootConnector") + + val tableSym: Symbol = typeOf[CassandraTable[_, _]].typeSymbol + val selectTable: Symbol = typeOf[SelectTable[_, _]].typeSymbol + val rootConn: Symbol = typeOf[SelectTable[_, _]].typeSymbol + val colSymbol: Symbol = typeOf[AbstractColumn[_]].typeSymbol + + val exclusions: Symbol => Option[Symbol] = s => { + val sig = s.typeSignature.typeSymbol + + if (sig == tableSym || sig == selectTable || sig == rootConn) { + None + } else { + Some(s) + } + } + + def filterColumns[Filter : TypeTag](columns: Seq[Type]): Seq[Type] = { + columns.filter(_.baseClasses.exists(typeOf[Filter].typeSymbol == )) + } + + def insertQueryType(table: Type, record: Type): Tree = { + tq"com.outworkers.phantom.builder.query.InsertQuery.Default[$table, $record]" + } + + /** + * This method will check for common Cassandra anti-patterns during the intialisation of a schema. + * If the Schema definition violates valid CQL standard, this function will throw an error. + * + * A perfect example is using a mixture of Primary keys and Clustering keys in the same schema. + * While a Clustering key is also a primary key, when defining a clustering key all other keys must become clustering keys and specify their order. + * + * We could auto-generate this order but we wouldn't be making false assumptions about the desired ordering. + */ + def inferPrimaryKey(tableName: String, table: Type, columns: Seq[Type]): Tree = { + val partitionKeys = filterColumns[PartitionKey](columns) + .map(_.typeSymbol.typeSignatureIn(table).typeSymbol.name.toTermName) + .map(name => q"$tableTerm.$name") + + if (partitionKeys.isEmpty) { + c.abort( + c.enclosingPosition, + s"Table $tableName needs to have at least one partition key" + ) + } + + val primaries = filterColumns[PrimaryKey](columns) + .map(_.typeSymbol.typeSignatureIn(table).typeSymbol.name.toTermName) + .map(name => q"$tableTerm.$name") + + val clusteringKeys = filterColumns[ClusteringOrder](columns) + .map(_.typeSymbol.typeSignatureIn(table).typeSymbol.name.toTermName) + .map(name => q"$tableTerm.$name") + + if (clusteringKeys.nonEmpty && (clusteringKeys.size != primaries.size)) { + c.abort( + c.enclosingPosition, + "Using clustering order on one primary key part " + + "means all primary key parts must explicitly define clustering. " + + s"Table $tableName still has ${primaries.size} primary keys defined" + ) + } else { + q""" + $builder.Create.primaryKey( + $collections.List[$colType](..$partitionKeys).map(_.name), + $collections.List[$colType](..$primaries).map(_.name) + ).queryString + """ + } + + } + + trait TableMatchResult + + case class Match( + results: List[ColumnMember], + partition: Boolean + ) extends TableMatchResult + + case object NoMatch extends TableMatchResult + + def show(list: List[Type]): String = { + list map(tpe => showCode(tq"$tpe")) mkString ", " + } + + def show(list: Iterable[Type]): String = { + list map(tpe => showCode(tq"$tpe")) mkString ", " + } + + /** + * Finds a matching subset of columns inside a table definition where the extracted + * type from a table does not need to include all of the columns inside a table. + * + * This addresses [[https://websudos.atlassian.net/browse/PHANTOM-237]]. + * + * @param recordMembers The type members of the record type. + * @param members The type members of the table. + * @return + */ + def findMatchingSubset( + tableName: Name, + members: List[ColumnMember], + recordMembers: Iterable[ColumnMember] + ): TableMatchResult = { + if (members.isEmpty) { + NoMatch + } else { + + if (members.size >= recordMembers.size && members.zip(recordMembers).forall { case (rec, col) => + rec.tpe =:= col.tpe + }) { + Console.println(s"Successfully derived extractor for $tableName using columns: ${members.map(_.name.decodedName.toString).mkString(", ")}") + Match(members, recordMembers.size != members.size) + } else { + findMatchingSubset(tableName, members.tail, recordMembers) + } + } + } + + def extractColumnMembers(table: Type, columns: List[Symbol]): List[ColumnMember] = { + /** + * We filter for the members of the table type that + * directly subclass [[AbstractColumn[_]]. For every one of those methods, we + * are going to look at what type argument was passed by the specific column definition + * when extending [[AbstractColumn[_]] as this will tell us the Scala output type + * of the given column. + * We create a list of these types and if they match the case class types expected, + * it means we can auto-generate a fromRow implementation. + */ + columns.map { member => + val memberType = member.typeSignatureIn(table) + + memberType.baseClasses.find(colSymbol ==) match { + case Some(root) => + // Here we expect to have a single type argument or type param + // because we know root here will point to an AbstractColumn[_] symbol. + root.typeSignature.typeParams match { + // We use the special API to see what type was passed through to AbstractColumn[_] + // with special thanks to https://github.com/joroKr21 for helping me not rip + // the remainder of my hair off while uncovering this marvelous macro API method. + case head :: Nil => ColumnMember( + member.asModule.name.toTermName, + head.asType.toType.asSeenFrom(memberType, colSymbol) + ) + case _ => c.abort(c.enclosingPosition, "Expected exactly one type parameter provided for root column type") + } + case None => c.abort(c.enclosingPosition, s"Could not find root column type for ${member.asModule.name}") + } + } + } + + /** + * Materializes an extractor method for a table, the so called "fromRow" method. + * + * This will only work if the types of the record type match the types + * inferred by the return types of the columns inside the table. + * + * If the implementation could not be inferred, the output of this method will be the unimplemented + * method exception and the user will have to manually override the fromRow definition and create one + * themselves. + * + * {{{ + * def fromRow(row: Row): R = ??? + * }}} + * + * Not only that but they also have to be in the same order. For example: + * {{{ + * case class MyRecord( + * id: UUID, + * email: String, + * date: DateTime + * ) + * + * class MyTable extends CassandraTable[MyTable, MyRecord] { + * object id extends UUIDColumn(this) with PartitionKey + * object email extends StringColumn(this) + * object date extends DateTimeColumn(this) + * } + * }}} + * + * @return An interpolated tree that will contain the automatically generated implementation + * of the fromRow method in a Cassandra Table. + * Alternatively, this will return an unimplemented ??? method, provided a correct + * definition could not be inferred. + */ + def materializeExtractor[T](tableTpe: Type, recordTpe: Type, columns: List[Symbol]): Option[Tree] = { + /** + * First we create a set of ordered types corresponding to the type signatures + * found in the case class arguments. + */ + val recordMembers = caseFields(recordTpe) map { case (nm, tp) => ColumnMember(nm.toTermName, tp) } + + val colMembers = extractColumnMembers(tableTpe, columns) + + val tableSymbolName = tableTpe.typeSymbol.name + + findMatchingSubset(tableSymbolName, colMembers, recordMembers) match { + case Match(results, _) if recordTpe.typeSymbol.isClass && recordTpe.typeSymbol.asClass.isCaseClass => { + val columnNames = results.map { member => + q"$tableTerm.${member.name}.apply($rowTerm)" + } + + Some(q"""new $recordTpe(..$columnNames)""") + } + case _ => { + Console.println(s"Couldn't automatically infer an extractor for $tableSymbolName") + None + } + } + } + + /** + * Finds the first type in the type hierarchy for which columns exist as direct members. + * @param tpe The type of the table. + * @return An optional symbol, if such a type was found in the type hierarchy. + */ + def determineReferenceTable(tpe: Type): Option[Symbol] = { + tpe.baseClasses.reverse.find(symbol => { + symbol.typeSignature.decls.exists(_.typeSignature <:< typeOf[AbstractColumn[_]]) + }) + } + + def extractTableName(source: Type): String = { + val value = source.typeSymbol.name.toTermName.decodedName.toString + value.charAt(0).toLower + value.drop(1) + } + + def macroImpl[T : WeakTypeTag, R : WeakTypeTag]: Tree = { + val tableType = weakTypeOf[T] + + val rTpe = weakTypeOf[R] + + val colTpe = tq"com.outworkers.phantom.column.AbstractColumn[_]" + val tableTpe = tq"com.outworkers.phantom.CassandraTable[$tableType, $rTpe]" + + val refTable = determineReferenceTable(tableType).map(_.typeSignature).getOrElse(tableType) + val referenceColumns = refTable.decls.sorted.filter(_.typeSignature <:< typeOf[AbstractColumn[_]]) + + val tableName = extractTableName(refTable) + + val columns = filterMembers[T, AbstractColumn[_]](exclusions) + + val fromRowDefinition = materializeExtractor(tableType, rTpe, referenceColumns) getOrElse q"???" + + val accessors = columns.map(_.asTerm.name).map(tm => q"table.instance.${tm.toTermName}") + + val tree = q""" + new com.outworkers.phantom.macros.TableHelper[$tableType, $rTpe] { + def tableName: $strTpe = $tableName + + def store($tableTerm: $tableType)(implicit space: $keyspaceType): ${insertQueryType(tableType, rTpe)} = { + $tableTerm.insert() + } + + def tableKey($tableTerm: $tableType): $strTpe = ${inferPrimaryKey(tableName, tableType, referenceColumns.map(_.typeSignature))} + + def fromRow($tableTerm: $tableType, $rowTerm: $rowType): $rTpe = $fromRowDefinition + + def fields($tableTerm: $tableTpe): scala.collection.immutable.Set[$colTpe] = { + scala.collection.immutable.Set.apply[$colTpe](..$accessors) + } + } + """ + tree + } + +} \ No newline at end of file diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/CassandraTable.scala b/phantom-dsl/src/main/scala/com/websudos/phantom/CassandraTable.scala deleted file mode 100644 index fbd31d906..000000000 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/CassandraTable.scala +++ /dev/null @@ -1,232 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom - -import com.datastax.driver.core.{Row, Session} -import com.websudos.phantom.builder.clauses.DeleteClause -import com.websudos.phantom.builder.query.{RootCreateQuery, _} -import com.websudos.phantom.column.AbstractColumn -import com.websudos.phantom.connectors.KeySpace -import com.websudos.phantom.exceptions.{InvalidClusteringKeyException, InvalidPrimaryKeyException} -import org.slf4j.LoggerFactory - -import scala.concurrent.duration._ -import scala.concurrent.{Await, ExecutionContextExecutor} -import scala.reflect.runtime.{currentMirror => cm, universe => ru} - -/** - * Main representation of a Cassandra table. - * @tparam T Type of this table. - * @tparam R Type of record. - */ -abstract class CassandraTable[T <: CassandraTable[T, R], R] extends SelectTable[T, R] { self => - - type ListColumn[RR] = com.websudos.phantom.column.ListColumn[T, R, RR] - type SetColumn[RR] = com.websudos.phantom.column.SetColumn[T, R, RR] - type MapColumn[KK, VV] = com.websudos.phantom.column.MapColumn[T, R, KK, VV] - type JsonColumn[RR] = com.websudos.phantom.column.JsonColumn[T, R, RR] - type EnumColumn[RR <: Enumeration] = com.websudos.phantom.column.EnumColumn[T, R, RR] - type OptionalEnumColumn[RR <: Enumeration] = com.websudos.phantom.column.OptionalEnumColumn[T, R, RR] - type JsonSetColumn[RR] = com.websudos.phantom.column.JsonSetColumn[T, R, RR] - type JsonListColumn[RR] = com.websudos.phantom.column.JsonListColumn[T, R, RR] - type JsonMapColumn[KK,VV] = com.websudos.phantom.column.JsonMapColumn[T, R, KK, VV] - - private[phantom] def insertSchema()( - implicit session: Session, - keySpace: KeySpace, - ec: ExecutionContextExecutor - ): Unit = { - Await.result(autocreate(keySpace).future(), 10.seconds) - } - - private[this] val instanceMirror = cm.reflect(this) - - protected[phantom] lazy val _name: String = { - instanceMirror.symbol.name.toTypeName.decodedName.toString - } - - lazy val logger = LoggerFactory.getLogger(getClass.getName.stripSuffix("$")) - - def tableName: String = _name - - def fromRow(r: Row): R - - /** - * The new create mechanism introduced in Phantom 1.6.0. - * This uses the phantom proprietary QueryBuilder instead of the already available one in the underlying Java Driver. - * @return A root create block, with full support for all CQL Create query options. - */ - final def create: RootCreateQuery[T, R] = new RootCreateQuery(this.asInstanceOf[T]) - - def autocreate(keySpace: KeySpace): CreateQuery.Default[T, R] = create.ifNotExists()(keySpace) - - final def alter()(implicit keySpace: KeySpace): AlterQuery.Default[T, R] = AlterQuery(this.asInstanceOf[T]) - - final def update()(implicit keySpace: KeySpace): UpdateQuery.Default[T, R] = UpdateQuery(this.asInstanceOf[T]) - - final def insert()(implicit keySpace: KeySpace): InsertQuery.Default[T, R] = InsertQuery(this.asInstanceOf[T]) - - final def delete()(implicit keySpace: KeySpace): DeleteQuery.Default[T, R] = DeleteQuery[T, R](this.asInstanceOf[T]) - - final def delete(conditions: (T => DeleteClause.Condition)*)(implicit keySpace: KeySpace): DeleteQuery.Default[T, R] = { - val tb = this.asInstanceOf[T] - - val queries = conditions.map(_(tb).qb) - - DeleteQuery[T, R](tb, queries: _*) - } - - final def truncate()(implicit keySpace: KeySpace): TruncateQuery.Default[T, R] = TruncateQuery[T, R](this.asInstanceOf[T]) - - def secondaryKeys: Seq[AbstractColumn[_]] = columns.filter(_.isSecondaryKey) - - def primaryKeys: Seq[AbstractColumn[_]] = columns.filter(_.isPrimary).filterNot(_.isPartitionKey) - - def partitionKeys: Seq[AbstractColumn[_]] = columns.filter(_.isPartitionKey) - - def clusteringColumns: Seq[AbstractColumn[_]] = columns.filter(_.isClusteringKey) - - def clustered: Boolean = clusteringColumns.nonEmpty - - /** - * This method will filter the columns from a Clustering Order definition. - * It is used to define TimeSeries tables, using the ClusteringOrder trait - * combined with a directional trait, either Ascending or Descending. - * - * This method will simply add to the trailing of a query. - * @return The clustering key, defined as a string or the empty string. - */ - private[phantom] def clusteringKey: String = { - if (clusteringColumns.nonEmpty) { - val key = clusteringColumns.map(col => { - val direction = if (col.isAscending) { - "ASC" - } else { - "DESC" - } - s"${col.name} $direction" - }) - s"WITH CLUSTERING ORDER BY (${key.mkString(", ")})" - } else { - "" - } - } - - /** - * This method will define the PRIMARY_KEY of the table. - * - * @return A string value representing the primary key of the table. - */ - @throws(classOf[InvalidPrimaryKeyException]) - private[phantom] def defineTableKey(): String = { - - preconditions() - - // Get the list of primary keys that are not partition keys. - val primaries = primaryKeys - val primaryString = primaryKeys.map(_.name).mkString(", ") - - // Get the list of partition keys that are not primary keys - // This is done to avoid including the same columns twice. - val partitions = partitionKeys.toList - val partitionString = s"(${partitions.map(_.name).mkString(", ")})" - - val operand = partitions.lengthCompare(1) - val key = if (operand < 0) { - throw InvalidPrimaryKeyException(tableName) - } else if (operand == 0) { - - val partitionKey = partitions.headOption.map(_.name).orNull - - if (primaries.isEmpty) { - partitionKey - } else { - s"$partitionKey, $primaryString" - } - } else { - if (primaries.isEmpty) { - partitionString - } else { - s"$partitionString, $primaryString" - } - } - s"PRIMARY KEY ($key)" - } - - /** - * This method will check for common Cassandra anti-patterns during the intialisation of a schema. - * If the Schema definition violates valid CQL standard, this function will throw an error. - * - * A perfect example is using a mixture of Primary keys and Clustering keys in the same schema. - * While a Clustering key is also a primary key, when defining a clustering key all other keys must become clustering keys and specify their order. - * - * We could auto-generate this order but we wouldn't be making false assumptions about the desired ordering. - */ - private[this] def preconditions(): Unit = { - if (clustered && primaryKeys.diff(clusteringColumns).nonEmpty) { - logger.error("When using CLUSTERING ORDER all PrimaryKey definitions" + - " must become a ClusteringKey definition and specify order.") - throw InvalidClusteringKeyException(tableName) - } - } - - val columns: Seq[AbstractColumn[_]] = Lock.synchronized { - val selfType = instanceMirror.symbol.toType - - val members: Seq[ru.Symbol] = (for { - baseClass <- selfType.baseClasses.reverse - symbol <- baseClass.typeSignature.members.sorted - if symbol.typeSignature <:< ru.typeOf[AbstractColumn[_]] - } yield symbol)(collection.breakOut) - - for { - symbol <- members.distinct - table = if (symbol.isModule) { - instanceMirror.reflectModule(symbol.asModule).instance - } else if (symbol.isTerm && symbol.asTerm.isVal) { - instanceMirror.reflectField(symbol.asTerm).get - } - } yield table.asInstanceOf[AbstractColumn[_]] - } -} - -private[phantom] case object Lock \ No newline at end of file diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/Manager.scala b/phantom-dsl/src/main/scala/com/websudos/phantom/Manager.scala deleted file mode 100644 index 803f98c2a..000000000 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/Manager.scala +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom - -import java.util.concurrent.Executors - -import org.slf4j.LoggerFactory - -import scala.concurrent.{ExecutionContext, ExecutionContextExecutor} - -object Manager { - - private[this] lazy val taskExecutor = Executors.newCachedThreadPool() - - implicit lazy val scalaExecutor: ExecutionContextExecutor = ExecutionContext.fromExecutor(taskExecutor) - - lazy val logger = LoggerFactory.getLogger("com.websudos.phantom") - - /** - * Shuts down the default task executors for Guava ListenableFutures and for Scala Futures. - * @deprecated ("Call shutdown on a [[com.websudos.phantom.database.Database]] instead", "1.15.0") - */ - def shutdown(): Unit = { - logger.info("Shutting down executors") - taskExecutor.shutdown() - } -} \ No newline at end of file diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/Bounds.scala b/phantom-dsl/src/main/scala/com/websudos/phantom/builder/Bounds.scala deleted file mode 100644 index 68bb7a43e..000000000 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/Bounds.scala +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.builder - -sealed trait LimitBound -trait Limited extends LimitBound -trait Unlimited extends LimitBound - -sealed trait OrderBound -trait Ordered extends OrderBound -trait Unordered extends OrderBound - -sealed trait ConsistencyBound -trait Specified extends ConsistencyBound -trait Unspecified extends ConsistencyBound - -sealed trait WhereBound -trait Chainned extends WhereBound -trait Unchainned extends WhereBound \ No newline at end of file diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/primitives/Primitive.scala b/phantom-dsl/src/main/scala/com/websudos/phantom/builder/primitives/Primitive.scala deleted file mode 100644 index df6d4974d..000000000 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/primitives/Primitive.scala +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.builder.primitives - -import java.util.Date - -import com.datastax.driver.core.{GettableData, LocalDate} -import org.joda.time.DateTime - -import scala.annotation.implicitNotFound -import scala.util.control.NoStackTrace -import scala.util.{Failure, Try} - -private[phantom] object DateSerializer { - - def asCql(date: Date): String = date.getTime.toString - - def asCql(date: LocalDate): String = date.getMillisSinceEpoch.toString - - def asCql(date: org.joda.time.LocalDate): String = date.toString - - def asCql(date: DateTime): String = date.getMillis.toString -} - -@implicitNotFound(msg = "Type ${RR} must be a pre-defined Cassandra primitive.") -abstract class Primitive[RR] { - - /** - * A way of maintaining compatibility with the underlying Java driver. - * The driver often type checks records before casting them and to do that - * it needs the correct Java Class obtained via classOf[] or .getClass in Java. - * - * We use this because the appropriate Scala type is often different than the - * Java equivalent. For instance, we don't want users to deal with [[java.util.List]], - * even if the Java Driver will attempt to look for one. - */ - type PrimitiveType - - protected[this] def nullCheck[T](column: String, row: GettableData)(fn: GettableData => T): Try[T] = { - if (Option(row).isEmpty || row.isNull(column)) { - Failure(new Exception(s"Column $column is null") with NoStackTrace) - } else { - Try(fn(row)) - } - } - - /** - * Converts the type to a CQL compatible string. - * The primitive is responsible for handling all aspects of adequate escaping as well. - * This is used to generate the final queries from domain objects. - * @param value The strongly typed value. - * @return The string representation of the value with respect to CQL standards. - */ - def asCql(value: RR): String - - def cassandraType: String - - def fromRow(column: String, row: GettableData): Try[RR] - - def fromString(value: String): RR - - def clz: Class[PrimitiveType] - - def extract(obj: PrimitiveType): RR = identity(obj).asInstanceOf[RR] -} - -object Primitive { - - /** - * !! Warning !! Black magic going on. This will use the excellent macro compat - * library to macro materialise an instance of the required primitive based on the type argument. - * If this does not highlight properly in your IDE, fear not, it works on my machine :) - * @tparam T The type parameter to materialise a primitive for. - * @return A concrete instance of a primitive, materialised via implicit blackbox macros. - */ - implicit def materializer[T]: Primitive[T] = macro PrimitiveMacro.materializer[T] - - /** - * Convenience method to materialise the context bound and return a reference to it. - * This is somewhat shorter syntax than using implicitly. - * @tparam RR The type of the primitive to retrieve. - * @return A reference to a concrete materialised implementation of a primitive for the given type. - */ - def apply[RR : Primitive]: Primitive[RR] = implicitly[Primitive[RR]] -} diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/query/CQLQuery.scala b/phantom-dsl/src/main/scala/com/websudos/phantom/builder/query/CQLQuery.scala deleted file mode 100644 index 9f2889c82..000000000 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/query/CQLQuery.scala +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.builder.query - -import com.outworkers.diesel.engine.query.AbstractQuery - -case class CQLQuery(override val queryString: String) extends AbstractQuery[CQLQuery](queryString) { - def create(str: String): CQLQuery = CQLQuery(str) - - override def toString: String = queryString -} - -object CQLQuery { - def empty: CQLQuery = CQLQuery("") - - def escape(str: String): String = "'" + str.replaceAll("'", "''") + "'" - - def escaped(str: String): CQLQuery = CQLQuery("'" + str.replaceAll("'", "''") + "'") - - def apply(collection: TraversableOnce[String]): CQLQuery = CQLQuery(collection.mkString(", ")) -} diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/query/ExecutableQuery.scala b/phantom-dsl/src/main/scala/com/websudos/phantom/builder/query/ExecutableQuery.scala deleted file mode 100644 index b6feef63b..000000000 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/query/ExecutableQuery.scala +++ /dev/null @@ -1,344 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.builder.query - -import java.util.{List => JavaList} - -import com.datastax.driver.core._ -import com.websudos.phantom.CassandraTable -import com.websudos.phantom.builder.{LimitBound, Unlimited} -import com.websudos.phantom.connectors.KeySpace - -import scala.collection.JavaConverters._ -import scala.concurrent.{ExecutionContextExecutor, Future => ScalaFuture} - -trait RecordResult[R] { - - def result: ResultSet - - def pagingState: PagingState = result.getExecutionInfo.getPagingState -} - -case class ListResult[R](records: List[R], result: ResultSet) extends RecordResult[R] - -case class IteratorResult[R](records: Iterator[R], result: ResultSet) extends RecordResult[R] - -trait ExecutableStatement extends CassandraOperations { - - type Modifier = Statement => Statement - - def options: QueryOptions - - def qb: CQLQuery - - def queryString: String = qb.terminate().queryString - - def statement()(implicit session: Session): Statement = { - new SimpleStatement(qb.terminate().queryString) - .setConsistencyLevel(options.consistencyLevel.orNull) - } - - /** - * Default asynchronous query execution method. This will convert the underlying - * call to Cassandra done with Google Guava ListenableFuture to a consumable - * Scala Future that will be completed once the operation is completed on the - * database end. - * - * The execution context of the transformation is provided by phantom via - * [[com.websudos.phantom.Manager.scalaExecutor]] and it is recommended to - * use [[com.websudos.phantom.dsl.context]] for operations that chain - * database calls. - * - * @param session The implicit session provided by a [[com.websudos.phantom.connectors.Connector]]. - * @param keySpace The implicit keySpace definition provided by a [[com.websudos.phantom.connectors.Connector]]. - * @param ec The implicit Scala execution context. - * @return An asynchronous Scala future wrapping the Datastax result set. - */ - def future()( - implicit session: Session, - keySpace: KeySpace, - ec: ExecutionContextExecutor - ): ScalaFuture[ResultSet] = { - scalaQueryStringExecuteToFuture(statement) - } - - /** - * This will convert the underlying call to Cassandra done with Google Guava ListenableFuture to a consumable - * Scala Future that will be completed once the operation is completed on the - * database end. - * - * The execution context of the transformation is provided by phantom via - * [[com.websudos.phantom.Manager.scalaExecutor]] and it is recommended to - * use [[com.websudos.phantom.dsl.context]] for operations that chain - * database calls. - * - * @param modifyStatement The function allowing to modify underlying [[Statement]] - * @param session The implicit session provided by a [[com.websudos.phantom.connectors.Connector]]. - * @param keySpace The implicit keySpace definition provided by a [[com.websudos.phantom.connectors.Connector]]. - * @param executor The implicit Scala executor. - * @return An asynchronous Scala future wrapping the Datastax result set. - */ - def future(modifyStatement: Modifier)( - implicit session: Session, - keySpace: KeySpace, - executor: ExecutionContextExecutor - ): ScalaFuture[ResultSet] = { - scalaQueryStringExecuteToFuture(modifyStatement(statement)) - } -} - -class ExecutableStatementList(val queries: Seq[CQLQuery]) extends CassandraOperations { - - /** - * Secondary constructor to allow passing in Sets instead of Sequences. - * Although this may appear to be fruitless and uninteresting it a necessary evil. - * - * The TwitterFuture.collect method does not support passing in arbitrary collections using the Scala API - * just as Scala.future does. Scala Futures can sequence over traversables and return a collection of the appropiate type. - * - * @param queries The list of CQL queries to execute. - * @return An instance of an ExecutableStatement with the matching sequence of CQL queries. - */ - def this(queries: Set[CQLQuery]) = this(queries.toSeq) - - def add(appendable: Seq[CQLQuery]): ExecutableStatementList = { - new ExecutableStatementList(queries ++ appendable) - } - - def ++(appendable: Seq[CQLQuery]): ExecutableStatementList = add(appendable) - - def ++(st: ExecutableStatementList): ExecutableStatementList = add(st.queries) - - def future()( - implicit session: Session, - keySpace: KeySpace, - ec: ExecutionContextExecutor - ): ScalaFuture[Seq[ResultSet]] = { - ScalaFuture.sequence(queries.map(item => { - scalaQueryStringExecuteToFuture(new SimpleStatement(item.terminate().queryString)) - })) - } -} - -private[phantom] trait RootExecutableQuery[R] { - - def fromRow(r: Row): R - - protected[this] def singleResult(row: Row): Option[R] = { - if (Option(row).isDefined) Some(fromRow(row)) else None - } - - protected[this] def directMapper(results: JavaList[Row]): List[R] = { - List.tabulate(results.size())(index => fromRow(results.get(index))) - } -} - -/** - * An ExecutableQuery implementation, meant to retrieve results from Cassandra. - * This provides the root implementation of a Select query. - * - * @tparam T The class owning the table. - * @tparam R The record type to store. - */ -trait ExecutableQuery[T <: CassandraTable[T, _], R, Limit <: LimitBound] - extends ExecutableStatement with RootExecutableQuery[R] { - - def fromRow(r: Row): R - - private[phantom] def singleFetch()( - implicit session: Session, - keySpace: KeySpace, - ec: ExecutionContextExecutor - ): ScalaFuture[Option[R]] = { - future() map { res => singleResult(res.one) } - } - - /** - * Returns the first row from the select ignoring everything else - * - * @param session The implicit session provided by a [[com.websudos.phantom.connectors.Connector]]. - * @param keySpace The implicit keySpace definition provided by a [[com.websudos.phantom.connectors.Connector]]. - * @param ev The implicit limit for the query. - * @param ec The implicit Scala execution context. - * @return A Scala future guaranteed to contain a single result wrapped as an Option. - */ - def one()( - implicit session: Session, - keySpace: KeySpace, - ev: Limit =:= Unlimited, - ec: ExecutionContextExecutor - ): ScalaFuture[Option[R]] - - /** - * Returns a parsed sequence of [R]ows - * This is not suitable for big results set - * - * @param session The implicit session provided by a [[com.websudos.phantom.connectors.Connector]]. - * @param keySpace The implicit keySpace definition provided by a [[com.websudos.phantom.connectors.Connector]]. - * @param ec The implicit Scala execution context. - * @return A Scala future wrapping a list of mapped results. - */ - def fetch()( - implicit session: Session, - keySpace: KeySpace, - ec: ExecutionContextExecutor - ): ScalaFuture[List[R]] = { - future() map { resultSet => directMapper(resultSet.all) } - } - - /** - * Returns a parsed sequence of [R]ows - * This is not suitable for big results set - * - * @param session The implicit session provided by a [[com.websudos.phantom.connectors.Connector]]. - * @param keySpace The implicit keySpace definition provided by a [[com.websudos.phantom.connectors.Connector]]. - * @param ec The implicit Scala execution context. - * @return A Scala future wrapping a list of mapped results. - */ - def fetch(state: PagingState)( - implicit session: Session, - keySpace: KeySpace, - ec: ExecutionContextExecutor - ): ScalaFuture[List[R]] = { - future(_.setPagingState(state)) map { - resultSet => directMapper(resultSet.all) - } - } - - /** - * Returns a parsed sequence of [R]ows - * This is not suitable for big results set - * - * @param session The implicit session provided by a [[com.websudos.phantom.connectors.Connector]]. - * @param keySpace The implicit keySpace definition provided by a [[com.websudos.phantom.connectors.Connector]]. - * @param ec The implicit Scala execution context. - * @return A Scala future wrapping a list of mapped results. - */ - def fetch(modifyStatement : Modifier)( - implicit session: Session, - keySpace: KeySpace, - ec: ExecutionContextExecutor - ): ScalaFuture[List[R]] = { - future(modifyStatement) map { - resultSet => directMapper(resultSet.all) - } - } - - /** - * Returns a parsed sequence of [R]ows - * This is not suitable for big results set - * - * @param session The implicit session provided by a [[com.websudos.phantom.connectors.Connector]]. - * @param keySpace The implicit keySpace definition provided by a [[com.websudos.phantom.connectors.Connector]]. - * @param ec The implicit Scala execution context. - * @return A Scala future wrapping a list of mapped results. - */ - def fetchRecord()( - implicit session: Session, - keySpace: KeySpace, - ec: ExecutionContextExecutor - ): ScalaFuture[ListResult[R]] = { - future() map (resultSet => ListResult(directMapper(resultSet.all), resultSet)) - } - - /** - * Returns a parsed sequence of [R]ows - * This is not suitable for big results set - * - * @param session The implicit session provided by a [[com.websudos.phantom.connectors.Connector]]. - * @param keySpace The implicit keySpace definition provided by a [[com.websudos.phantom.connectors.Connector]]. - * @param ec The implicit Scala execution context. - * @return A Scala future wrapping a list of mapped results. - */ - def fetchRecord(state: PagingState)( - implicit session: Session, - keySpace: KeySpace, - ec: ExecutionContextExecutor - ): ScalaFuture[ListResult[R]] = { - future(st => st.setPagingState(state)) map { - set => ListResult(directMapper(set.all), set) - } - } - - def fetchRecord(state: Option[PagingState])( - implicit session: Session, - keySpace: KeySpace, - ec: ExecutionContextExecutor - ): ScalaFuture[ListResult[R]] = { - state.fold(future().map { - set => ListResult(directMapper(set.all), set) - }) (state => future(_.setPagingState(state)) map { - set => ListResult(directMapper(set.all), set) - }) - } - - /** - * Returns a parsed sequence of [R]ows - * This is not suitable for big results set - * - * @param session The implicit session provided by a [[com.websudos.phantom.connectors.Connector]]. - * @param keySpace The implicit keySpace definition provided by a [[com.websudos.phantom.connectors.Connector]]. - * @param ec The implicit Scala execution context. - * @return A Scala future wrapping a list of mapped results. - */ - def fetchRecord(modifyStatement: Modifier)( - implicit session: Session, - keySpace: KeySpace, - ec: ExecutionContextExecutor - ): ScalaFuture[ListResult[R]] = { - future(modifyStatement) map { - set => ListResult(directMapper(set.all), set) - } - } - - /** - * Returns a parsed iterator of [R]ows - * - * @param session The implicit session provided by a [[com.websudos.phantom.connectors.Connector]]. - * @param keySpace The implicit keySpace definition provided by a [[com.websudos.phantom.connectors.Connector]]. - * @param ec The implicit Scala execution context. - * @return A Scala future wrapping scala iterator of mapped results. - */ - def iterator()( - implicit session: Session, - keySpace: KeySpace, - ec: ExecutionContextExecutor - ): ScalaFuture[Iterator[R]] = { - future() map { _.iterator().asScala.map(fromRow) } - } - - def iteratorRecord()( - implicit session: Session, - keySpace: KeySpace, - ec: ExecutionContextExecutor - ): ScalaFuture[IteratorResult[R]] = { - future() map { result => IteratorResult(result.iterator().asScala.map(fromRow), result) } - } -} diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/query/TruncateQuery.scala b/phantom-dsl/src/main/scala/com/websudos/phantom/builder/query/TruncateQuery.scala deleted file mode 100644 index 3a890ded3..000000000 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/query/TruncateQuery.scala +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.builder.query - -import com.datastax.driver.core.{ConsistencyLevel, Session} -import com.websudos.phantom.CassandraTable -import com.websudos.phantom.builder.{ConsistencyBound, QueryBuilder, Specified, Unspecified} -import com.websudos.phantom.connectors.KeySpace - -class TruncateQuery[ - Table <: CassandraTable[Table, _], - Record, - Status <: ConsistencyBound -](table: Table, val qb: CQLQuery, override val options: QueryOptions) extends ExecutableStatement { - - def consistencyLevel_=(level: ConsistencyLevel)(implicit session: Session): TruncateQuery[Table, Record, Specified] = { - if (session.protocolConsistency) { - new TruncateQuery(table, qb, options.consistencyLevel_=(level)) - } else { - new TruncateQuery(table, QueryBuilder.consistencyLevel(qb, level.toString), options) - } - } -} - - -object TruncateQuery { - - type Default[T <: CassandraTable[T, _], R] = TruncateQuery[T, R, Unspecified] - - def apply[T <: CassandraTable[T, _], R](table: T)(implicit keySpace: KeySpace): TruncateQuery.Default[T, R] = { - new TruncateQuery( - table, - QueryBuilder.truncate(QueryBuilder.keyspace(keySpace.name, table.tableName).queryString), - QueryOptions.empty - ) - } - -} diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/serializers/BaseModifiers.scala b/phantom-dsl/src/main/scala/com/websudos/phantom/builder/serializers/BaseModifiers.scala deleted file mode 100644 index e347abdd4..000000000 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/serializers/BaseModifiers.scala +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.builder.serializers - -import com.websudos.phantom.builder.query.CQLQuery - -private[builder] trait BaseModifiers { - - protected[this] def modifier(column: String, op: String, value: String): CQLQuery = { - CQLQuery(column).forcePad.append(op).forcePad.append(value) - } - - protected[this] def modifier(column: String, op: String, value: CQLQuery): CQLQuery = { - modifier(column, op, value.queryString) - } - - protected[this] def collectionModifier(left: String, op: String, right: CQLQuery): CQLQuery = { - CQLQuery(left).forcePad.append(op).forcePad.append(right) - } - - protected[this] def collectionModifier(left: String, op: String, right: String): CQLQuery = { - CQLQuery(left).forcePad.append(op).forcePad.append(right) - } -} diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/serializers/BatchQueryBuilder.scala b/phantom-dsl/src/main/scala/com/websudos/phantom/builder/serializers/BatchQueryBuilder.scala deleted file mode 100644 index 59037f4f4..000000000 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/serializers/BatchQueryBuilder.scala +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.builder.serializers - -import com.websudos.phantom.builder.query.CQLQuery -import com.websudos.phantom.builder.syntax.CQLSyntax - -private[phantom] class BatchQueryBuilder { - - def batch(batchType: String): CQLQuery = { - CQLQuery(CQLSyntax.Batch.begin).pad.append(batchType).pad.append(CQLSyntax.Batch.batch) - } - - def applyBatch(qb: CQLQuery): CQLQuery = { - qb.forcePad.append(CQLSyntax.Batch.apply).forcePad.append(CQLSyntax.Batch.batch).append(CQLSyntax.Symbols.`;`) - } -} \ No newline at end of file diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/serializers/DeleteQueryBuilder.scala b/phantom-dsl/src/main/scala/com/websudos/phantom/builder/serializers/DeleteQueryBuilder.scala deleted file mode 100644 index 2013ecb5d..000000000 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/serializers/DeleteQueryBuilder.scala +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.builder.serializers - -import com.websudos.phantom.builder.query.CQLQuery -import com.websudos.phantom.builder.syntax.CQLSyntax - -private[builder] class DeleteQueryBuilder { - def delete(table: String): CQLQuery = { - CQLQuery(CQLSyntax.delete) - .forcePad.append(CQLSyntax.from) - .forcePad.append(table) - } - - def delete(table: String, cond: CQLQuery): CQLQuery = { - CQLQuery(CQLSyntax.delete) - .forcePad.append(cond) - .forcePad.append(CQLSyntax.from) - .forcePad.append(table) - } - - def delete(table: String, conds: Seq[CQLQuery]): CQLQuery = { - CQLQuery(CQLSyntax.delete) - .forcePad.append(conds.map(_.queryString)) - .forcePad.append(CQLSyntax.from) - .forcePad.append(table) - } - - def deleteColumn(table: String, column: String): CQLQuery = { - CQLQuery(CQLSyntax.delete) - .forcePad.append(column) - .forcePad.append(CQLSyntax.from) - .forcePad.append(table) - } - - def deleteMapColumn(table: String, column: String, key: String): CQLQuery = { - CQLQuery(CQLSyntax.delete) - .forcePad.append(qUtils.mapKey(column, key)) - .forcePad.append(CQLSyntax.from) - .forcePad.append(table) - } -} diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/serializers/InsertQueryBuilder.scala b/phantom-dsl/src/main/scala/com/websudos/phantom/builder/serializers/InsertQueryBuilder.scala deleted file mode 100644 index 624f35c70..000000000 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/serializers/InsertQueryBuilder.scala +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.builder.serializers - -import com.websudos.phantom.builder.query.CQLQuery -import com.websudos.phantom.builder.syntax.CQLSyntax - -private[phantom] trait InsertQueryBuilder { - def insert(table: String): CQLQuery = { - CQLQuery(CQLSyntax.insert) - .forcePad.append(CQLSyntax.into) - .forcePad.append(table) - } - - def insert(table: CQLQuery): CQLQuery = { - insert(table.queryString) - } - - /** - * Creates a CQL 2.2 JSON insert clause using a pre-serialized JSON string. - * @param init The initialization query of the Insert clause, generally comprising the "INSERT INTO tableName" part. - * @param jsonString The pre-serialized JSON string to insert into the Cassandra table. - * @return A CQL query with the JSON prefix appended to the insert. - */ - def json(init: CQLQuery, jsonString: String): CQLQuery = { - init.pad.append("JSON").pad.append(CQLQuery.escape(jsonString)) - } - - def columns(list: List[CQLQuery]): CQLQuery = { - CQLQuery.empty.wrapn(list.map(_.queryString)) - } - - def values(list: List[CQLQuery]): CQLQuery = { - CQLQuery(CQLSyntax.values).wrapn(list.map(_.queryString)) - } - -} diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/serializers/UpdateQueryBuilder.scala b/phantom-dsl/src/main/scala/com/websudos/phantom/builder/serializers/UpdateQueryBuilder.scala deleted file mode 100644 index 61b51232c..000000000 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/builder/serializers/UpdateQueryBuilder.scala +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.builder.serializers - -import com.websudos.phantom.builder.QueryBuilder.Utils -import com.websudos.phantom.builder.query.CQLQuery -import com.websudos.phantom.builder.syntax.CQLSyntax - -private[builder] class UpdateQueryBuilder { - - def onlyIf(clause: CQLQuery): CQLQuery = { - CQLQuery(CQLSyntax.IF).forcePad.append(clause) - } - - val ifExists: CQLQuery = CQLQuery(CQLSyntax.ifExists) - - private[this] def counterSetter(column: String, op: String, value: String): CQLQuery = { - CQLQuery(column).forcePad.append(CQLSyntax.Symbols.`=`) - .forcePad.append(column) - .forcePad.append(op) - .forcePad.append(value) - } - - def increment(column: String, value: String): CQLQuery = { - counterSetter(column, CQLSyntax.Symbols.plus, value) - } - - def decrement(column: String, value: String): CQLQuery = { - counterSetter(column, CQLSyntax.Symbols.-, value) - } - - def setTo(column: String, value: String): CQLQuery = { - Utils.concat(column, CQLSyntax.Symbols.`=`, value) - } - - def set(clause: CQLQuery): CQLQuery = { - CQLQuery(CQLSyntax.set).forcePad.append(clause) - } - - def where(condition: CQLQuery): CQLQuery = { - Utils.operator(CQLSyntax.where, condition) - } - - def and(condition: CQLQuery): CQLQuery = { - Utils.operator(CQLSyntax.and, condition) - } - - def clauses(clauses: List[CQLQuery], sep: String = " "): CQLQuery = { - CQLQuery.empty.append(clauses.map(_.queryString).mkString(sep)) - } - - def chain(clauses: List[CQLQuery]): CQLQuery = { - CQLQuery.empty.append(clauses.map(_.queryString).mkString(", ")) - } - - def usingPart(queries: List[CQLQuery]): CQLQuery = { - CQLQuery(CQLSyntax.using) - .forcePad - .append(clauses(queries, " " + CQLSyntax.And + " ")) - - } - - def update(tableName: String): CQLQuery = { - CQLQuery(CQLSyntax.update) - .forcePad.append(tableName) - } - - def updateMapColumn(column: String, key: String, value: String): CQLQuery = { - qUtils.mapKey(column, key) - .forcePad.append(CQLSyntax.Symbols.`=`) - .forcePad.append(value) - } -} - diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/codec/JodaLocalDateCodec.scala b/phantom-dsl/src/main/scala/com/websudos/phantom/codec/JodaLocalDateCodec.scala deleted file mode 100644 index 799e6aba3..000000000 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/codec/JodaLocalDateCodec.scala +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.codec - -import com.datastax.driver.core._ -import com.datastax.driver.extras.codecs.MappingCodec - -class JodaLocalDateCodec extends MappingCodec(TypeCodec.date(), classOf[org.joda.time.LocalDate]) { - - override def serialize(value: org.joda.time.LocalDate): LocalDate = { - LocalDate.fromYearMonthDay( - value.getYear, - value.getMonthOfYear, - value.getDayOfMonth - ) - } - - override def deserialize(value: LocalDate): org.joda.time.LocalDate = { - new org.joda.time.LocalDate( - value.getYear, - value.getMonth, - value.getDay - ) - } -} \ No newline at end of file diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/column/CollectionValueDefinition.scala b/phantom-dsl/src/main/scala/com/websudos/phantom/column/CollectionValueDefinition.scala deleted file mode 100644 index c94ef65bc..000000000 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/column/CollectionValueDefinition.scala +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.column - -trait CollectionValueDefinition[RR] { - - def valueAsCql(v: RR): String - - def fromString(c: String): RR -} diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/column/Column.scala b/phantom-dsl/src/main/scala/com/websudos/phantom/column/Column.scala deleted file mode 100644 index 714819a54..000000000 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/column/Column.scala +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.column - -import com.datastax.driver.core.Row -import com.websudos.phantom.CassandraTable - -import scala.util.{Failure, Success, Try} - - -abstract class Column[ - Owner <: CassandraTable[Owner, Record], - Record, - T -](val table: CassandraTable[Owner, Record]) extends AbstractColumn[T] { - - def parse(r: Row): Try[T] - - def apply(r: Row): T = parse(r) match { - case Success(value) => value - case Failure(ex) => - table.logger.error(s"Unable to parse value for column $name from row", ex) - throw ex - } - -} diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/column/CounterColumn.scala b/phantom-dsl/src/main/scala/com/websudos/phantom/column/CounterColumn.scala deleted file mode 100644 index 40860da12..000000000 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/column/CounterColumn.scala +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.column - -import com.datastax.driver.core.Row -import com.websudos.phantom.CassandraTable -import com.websudos.phantom.builder.primitives.Primitive -import com.websudos.phantom.builder.query.CQLQuery -import com.websudos.phantom.builder.syntax.CQLSyntax -import com.websudos.phantom.keys.Unmodifiable - -import scala.util.Try - -private[phantom] trait CounterRestriction[T] - -class CounterColumn[ - Owner <: CassandraTable[Owner, Record], - Record -](table: CassandraTable[Owner, Record])(implicit primitive: Primitive[Long]) - extends Column[Owner, Record, Long](table) with CounterRestriction[Long] with Unmodifiable { - - val cassandraType = CQLSyntax.Types.Counter - - override val isCounterColumn = true - - def parse(r: Row): Try[Long] = primitive.fromRow(name, r) - - override def qb: CQLQuery = CQLQuery(name).forcePad.append(cassandraType) - - override def asCql(v: Long): String = primitive.asCql(v) -} diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/column/EnumColumn.scala b/phantom-dsl/src/main/scala/com/websudos/phantom/column/EnumColumn.scala deleted file mode 100644 index 3e63c74a5..000000000 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/column/EnumColumn.scala +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.column - -import com.datastax.driver.core.Row -import com.websudos.phantom.CassandraTable -import com.websudos.phantom.builder.query.CQLQuery -import com.websudos.phantom.builder.syntax.CQLSyntax - -import scala.util.{Failure, Success, Try} - -class EnumColumn[ - Owner <: CassandraTable[Owner, Record], - Record, - EnumType <: Enumeration -](table: CassandraTable[Owner, Record], enum: EnumType) - extends Column[Owner, Record, EnumType#Value](table) { - - def cassandraType: String = CQLSyntax.Types.Text - - def parse(r: Row): Try[EnumType#Value] = { - val enumConstant = r.getString(name) - - enum.values.find(_.toString == enumConstant) match { - case Some(value) => Success(value) - case None => Failure(new Exception(s"Enumeration ${enum.toString()} doesn't contain value $enumConstant")) - } - } - - override def asCql(v: EnumType#Value): String = CQLQuery.empty.singleQuote(v.toString) -} - -class OptionalEnumColumn[ - Owner <: CassandraTable[Owner, Record], - Record, - EnumType <: Enumeration -](table: CassandraTable[Owner, Record], enum: EnumType) - extends OptionalColumn[Owner, Record, EnumType#Value](table) { - - def cassandraType: String = CQLSyntax.Types.Text - - def optional(r: Row): Try[EnumType#Value] = { - - val enumConstant = r.getString(name) - - enum.values.find(_.toString == enumConstant) match { - case Some(value) => Success(value) - case None => Failure(new Exception(s"Enumeration ${enum.toString()} doesn't contain value $enumConstant")) - } - } - - override def asCql(v: Option[EnumType#Value]): String = { - v.map(item => CQLQuery.empty.singleQuote(item.toString)).orNull - } - -} diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/column/ListColumn.scala b/phantom-dsl/src/main/scala/com/websudos/phantom/column/ListColumn.scala deleted file mode 100644 index 44749da8c..000000000 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/column/ListColumn.scala +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.column - -import com.datastax.driver.core.Row -import com.websudos.phantom.CassandraTable -import com.websudos.phantom.builder.QueryBuilder -import com.websudos.phantom.builder.QueryBuilder.Utils -import com.websudos.phantom.builder.primitives.Primitive -import com.websudos.phantom.builder.query.CQLQuery - -import scala.annotation.implicitNotFound -import scala.collection.JavaConverters._ -import scala.util.{Success, Try} - - -abstract class AbstractListColumn[ - Owner <: CassandraTable[Owner, Record], - Record, - RR -](table: CassandraTable[Owner, Record]) extends Column[Owner, Record, List[RR]](table) - with CollectionValueDefinition[RR] { - - override def asCql(v: List[RR]): String = Utils.collection(v.map(valueAsCql)).queryString - - override def apply(r: Row): List[RR] = { - parse(r).getOrElse(Nil) - } -} - -class ListColumn[ - Owner <: CassandraTable[Owner, Record], - Record, - RR : Primitive -](table: CassandraTable[Owner, Record]) - extends AbstractListColumn[Owner, Record, RR](table) with PrimitiveCollectionValue[RR] { - - override val valuePrimitive = Primitive[RR] - - override val cassandraType = QueryBuilder.Collections.listType(valuePrimitive.cassandraType).queryString - - override def qb: CQLQuery = { - if (shouldFreeze) { - QueryBuilder.Collections.frozen(name, cassandraType) - } else { - CQLQuery(name).forcePad.append(cassandraType) - } - } - - override def valueAsCql(v: RR): String = valuePrimitive.asCql(v) - - override def fromString(value: String): RR = valuePrimitive.fromString(value) - - override def parse(r: Row): Try[List[RR]] = { - if (r.isNull(name)) { - Success(Nil) - } else { - Success(r.getList(name, Primitive[RR].clz.asInstanceOf[Class[RR]]).asScala.toList) - } - } -} diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/column/MapColumn.scala b/phantom-dsl/src/main/scala/com/websudos/phantom/column/MapColumn.scala deleted file mode 100644 index 80c7a12d5..000000000 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/column/MapColumn.scala +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.column - -import com.datastax.driver.core.Row -import com.websudos.phantom.CassandraTable -import com.websudos.phantom.builder.QueryBuilder -import com.websudos.phantom.builder.ops.MapKeyUpdateClause -import com.websudos.phantom.builder.primitives.Primitive -import com.websudos.phantom.builder.query.CQLQuery - -import scala.annotation.implicitNotFound -import scala.collection.JavaConverters._ -import scala.util.{Failure, Success, Try} - -private[phantom] abstract class AbstractMapColumn[Owner <: CassandraTable[Owner, Record], Record, K, V](table: CassandraTable[Owner, Record]) - extends Column[Owner, Record, Map[K, V]](table) with CollectionValueDefinition[V] { - - def keyAsCql(v: K): String - - def keyFromCql(c: String): K - - override def fromString(c: String): V - - def asCql(v: Map[K, V]): String = QueryBuilder.Collections.serialize(v.map { - case (a, b) => (keyAsCql(a), valueAsCql(b)) - }).queryString - - override def apply(r: Row): Map[K, V] = { - parse(r) match { - case Success(map) => map - - // Note null rows will not result in a failure, we return an empty map for those. - case Failure(ex) => { - table.logger.error(ex.getMessage) - throw ex - } - } - } -} - -@implicitNotFound(msg = "Type ${K} and ${V} must be Cassandra primitives") -class MapColumn[Owner <: CassandraTable[Owner, Record], Record, K : Primitive, V : Primitive](table: CassandraTable[Owner, Record]) - extends AbstractMapColumn[Owner, Record, K, V](table) with PrimitiveCollectionValue[V] { - - val keyPrimitive = Primitive[K] - - override def keyAsCql(v: K): String = keyPrimitive.asCql(v) - - override val valuePrimitive = Primitive[V] - - override val cassandraType = QueryBuilder.Collections.mapType( - keyPrimitive.cassandraType, - valuePrimitive.cassandraType - ).queryString - - override def qb: CQLQuery = { - if (shouldFreeze) { - QueryBuilder.Collections.frozen(name, cassandraType) - } else { - CQLQuery(name).forcePad.append(cassandraType) - } - } - - override def keyFromCql(c: String): K = keyPrimitive.fromString(c) - - override def valueAsCql(v: V): String = valuePrimitive.asCql(v) - - override def fromString(c: String): V = valuePrimitive.fromString(c) - - override def parse(r: Row): Try[Map[K, V]] = { - if (r.isNull(name)) { - Success(Map.empty[K, V]) - } else { - Try( - r.getMap(name, keyPrimitive.clz, valuePrimitive.clz).asScala.toMap map { - case (k, v) => (keyPrimitive.extract(k), valuePrimitive.extract(v)) - } - ) - } - } - - def apply(k: K): MapKeyUpdateClause[K, V] = { - new MapKeyUpdateClause[K, V](name, k) - } -} diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/column/OptionalColumn.scala b/phantom-dsl/src/main/scala/com/websudos/phantom/column/OptionalColumn.scala deleted file mode 100644 index 4a124030b..000000000 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/column/OptionalColumn.scala +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.column - -import com.datastax.driver.core.Row -import com.websudos.phantom.CassandraTable - -import scala.util.Try - -abstract class OptionalColumn[Owner <: CassandraTable[Owner, Record], Record, T](table: CassandraTable[Owner, Record]) extends AbstractColumn[Option[T]] { - - def apply(r: Row): Option[T] = optional(r).toOption - - def cassandraType: String - - def optional(r: Row): Try[T] -} diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/column/OptionalPrimitiveColumn.scala b/phantom-dsl/src/main/scala/com/websudos/phantom/column/OptionalPrimitiveColumn.scala deleted file mode 100644 index 31b7c0164..000000000 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/column/OptionalPrimitiveColumn.scala +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.column - -import com.websudos.phantom.builder.syntax.CQLSyntax - -import scala.annotation.implicitNotFound -import com.datastax.driver.core.Row -import com.websudos.phantom.CassandraTable -import com.websudos.phantom.builder.primitives.Primitive -import com.websudos.phantom.builder.query.CQLQuery - -import scala.util.Try - - -@implicitNotFound(msg = "Type ${T} must be a Cassandra primitive") -class OptionalPrimitiveColumn[Owner <: CassandraTable[Owner, Record], Record, @specialized(Int, Double, Float, Long, Boolean, - Short) T : Primitive](t: CassandraTable[Owner, Record]) extends OptionalColumn[Owner, Record, T](t) { - - def cassandraType: String = Primitive[T].cassandraType - - def optional(r: Row): Try[T] = implicitly[Primitive[T]].fromRow(name, r) - - override def qb: CQLQuery = { - val root = CQLQuery(name).forcePad.append(cassandraType) - if (isStaticColumn) { - root.forcePad.append(CQLSyntax.static) - } else { - root - } - } - - override def asCql(v: Option[T]): String = { - v.map(Primitive[T].asCql).getOrElse(None.orNull.asInstanceOf[String]) - } -} diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/column/OptionalTimeUUIDColumn.scala b/phantom-dsl/src/main/scala/com/websudos/phantom/column/OptionalTimeUUIDColumn.scala deleted file mode 100644 index 2197628de..000000000 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/column/OptionalTimeUUIDColumn.scala +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.column - -import java.util.UUID - -import com.websudos.phantom.CassandraTable -import com.websudos.phantom.builder.primitives.Primitive -import com.websudos.phantom.builder.syntax.CQLSyntax - -class OptionalTimeUUIDColumn[ - Owner <: CassandraTable[Owner, Record], - Record -](table: CassandraTable[Owner, Record])( - implicit primitive: Primitive[UUID] -) extends OptionalPrimitiveColumn[Owner, Record, UUID](table) { - override val cassandraType = CQLSyntax.Types.TimeUUID -} diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/column/PrimitiveCollectionValue.scala b/phantom-dsl/src/main/scala/com/websudos/phantom/column/PrimitiveCollectionValue.scala deleted file mode 100644 index 8a224acc8..000000000 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/column/PrimitiveCollectionValue.scala +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.column - -import com.websudos.phantom.builder.primitives.Primitive - - -trait PrimitiveCollectionValue[R] extends CollectionValueDefinition[R] { - - def valuePrimitive: Primitive[R] - - def valueAsCql(v: R): String = valuePrimitive.asCql(v) - - def fromString(c: String): R = valuePrimitive.fromString(c) -} diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/column/PrimitiveColumn.scala b/phantom-dsl/src/main/scala/com/websudos/phantom/column/PrimitiveColumn.scala deleted file mode 100644 index 8b244fab1..000000000 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/column/PrimitiveColumn.scala +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.column - -import java.util.Date - -import com.datastax.driver.core.Row -import com.websudos.phantom.CassandraTable -import com.websudos.phantom.builder.primitives.Primitive -import com.websudos.phantom.builder.query.CQLQuery -import com.websudos.phantom.builder.syntax.CQLSyntax -import org.joda.time.{LocalDate, DateTime} - -import scala.annotation.implicitNotFound -import scala.util.Try - -@implicitNotFound(msg = "Type ${RR} must be a Cassandra primitive") -class PrimitiveColumn[T <: CassandraTable[T, R], R, @specialized(Int, Double, Float, Long) RR : Primitive](t: CassandraTable[T, R]) - extends Column[T, R, RR](t) { - - def cassandraType: String = Primitive[RR].cassandraType - - def asCql(v: RR): String = Primitive[RR].asCql(v) - - def parse(r: Row): Try[RR] = implicitly[Primitive[RR]].fromRow(name, r) - - override def qb: CQLQuery = { - val root = CQLQuery(name).forcePad.append(cassandraType) - - if (isStaticColumn) { - root.forcePad.append(CQLSyntax.static) - } else { - root - } - } -} - -/* -class Tuple2Column[Owner <: CassandraTable[Owner, Record], Record, K1 : Primitive, K2 : Primitive](table: Owner) - extends Column[Owner, Record, (K1, K2)](table) { - - val p1 = implicitly[Primitive[K1]] - val p2 = implicitly[Primitive[K2]] - - override def optional(r: Row): Option[(K1, K2)] = Option(r.getTupleValue(name)).map(value => { - p1.fromRow(name, value.getTupleValue() - p2.fromRow(name, value) - }) match { - case Tuple2(Success(tp1, tp2)) => Some(Tuple2(tp1, tp2)) - case _ => None - } - - override def cassandraType: String = { - QueryBuilder.Collections.tuple( - name, - implicitly[Primitive[K1]].cassandraType, - implicitly[Primitive[K2]].cassandraType - ).queryString - } - - /** - * Provides the serialisation mechanism of a value to a CQL string. - * The vast majority of serializers are fed in via the Primitives mechanism. - * - * Primitive columns will automatically override and define "asCql" based on the - * serialization of specific primitives. When T is context bounded by a primitive: - * - * {{{ - * def asCql(v: T): String = implicitly[Primitive[T]].asCql(value) - * }}} - * - * @param v The value of the object to convert to a string. - * @return A string that can be directly appended to a CQL query. - */ - override def asCql(v: (K1, K2)): String = { - QueryBuilder.Collections - .tupled(name, implicitly[Primitive[K1]].asCql(v._1), implicitly[Primitive[K2]].asCql(v._2)) - .queryString - } -}*/ \ No newline at end of file diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/column/SetColumn.scala b/phantom-dsl/src/main/scala/com/websudos/phantom/column/SetColumn.scala deleted file mode 100644 index c74895c09..000000000 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/column/SetColumn.scala +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.column - -import scala.collection.JavaConverters._ -import com.datastax.driver.core.Row -import com.websudos.phantom.CassandraTable -import com.websudos.phantom.builder.QueryBuilder -import com.websudos.phantom.builder.primitives.Primitive -import com.websudos.phantom.builder.query.CQLQuery - -import scala.annotation.implicitNotFound -import scala.util.{Try, Failure, Success} - - -abstract class AbstractSetColumn[Owner <: CassandraTable[Owner, Record], Record, RR](table: CassandraTable[Owner, Record]) - extends Column[Owner, Record, Set[RR]](table) with CollectionValueDefinition[RR] { - - def valuesToCType(values: Iterable[RR]): Set[String] = values.map(valueAsCql).toSet - - override def apply(r: Row): Set[RR] = { - parse(r) match { - case Success(set) => set - - // Note null sets are considered successful, we simply return an empty set instead of null. - case Failure(ex) => { - table.logger.error(ex.getMessage) - throw ex - } - } - } - - override def asCql(v: Set[RR]): String = QueryBuilder.Collections.serialize(valuesToCType(v)).queryString -} - - -@implicitNotFound(msg = "Type ${RR} must be a Cassandra primitive") -class SetColumn[Owner <: CassandraTable[Owner, Record], Record, RR : Primitive](table: CassandraTable[Owner, Record]) - extends AbstractSetColumn[Owner, Record, RR](table) with PrimitiveCollectionValue[RR] { - - override val valuePrimitive = Primitive[RR] - - val cassandraType = QueryBuilder.Collections.setType(valuePrimitive.cassandraType).queryString - - override def qb: CQLQuery = { - if (shouldFreeze) { - QueryBuilder.Collections.frozen(name, cassandraType) - } else { - CQLQuery(name).forcePad.append(cassandraType) - } - } - - override def valueAsCql(v: RR): String = Primitive[RR].asCql(v) - - override def fromString(c: String): RR = Primitive[RR].fromString(c) - - override def parse(r: Row): Try[Set[RR]] = { - if (r.isNull(name)) { - Success(Set.empty[RR]) - } else { - Success(r.getSet(name, Primitive[RR].clz.asInstanceOf[Class[RR]]).asScala.toSet[RR]) - } - } - -} diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/column/TimeUUIDColumn.scala b/phantom-dsl/src/main/scala/com/websudos/phantom/column/TimeUUIDColumn.scala deleted file mode 100644 index b48df4945..000000000 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/column/TimeUUIDColumn.scala +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.column - -import java.util.UUID - -import com.websudos.phantom.CassandraTable -import com.websudos.phantom.builder.primitives.Primitive -import com.websudos.phantom.builder.syntax.CQLSyntax - -class TimeUUIDColumn[ - Owner <: CassandraTable[Owner, Record], - Record](table: CassandraTable[Owner, Record] -)(implicit primitive: Primitive[UUID]) extends PrimitiveColumn[Owner, Record, UUID](table) { - override val cassandraType = CQLSyntax.Types.TimeUUID -} diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/column/extractors/FromRow.scala b/phantom-dsl/src/main/scala/com/websudos/phantom/column/extractors/FromRow.scala deleted file mode 100644 index 49105cd2b..000000000 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/column/extractors/FromRow.scala +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.column.extractors - -import com.datastax.driver.core.Row -import com.websudos.phantom.Manager -import com.websudos.phantom.builder.primitives.Primitive -import shapeless.{HList, HNil, Generic, :: => #:} -import scala.util.{Failure, Success, Try} -import scala.reflect.runtime.universe._ - -trait FromRow[L <: HList] { def apply(row: List[(String, Row)]): Try[L] } - -object FromRow { - - def classAccessors[T : TypeTag]: List[String] = { - typeOf[T].members.collect { - case m: MethodSymbol if m.isCaseAccessor => m.name.decodedName.toString - }.toList.reverse - } - - def apply[L <: HList](implicit fromRow: FromRow[L]): FromRow[L] = fromRow - - def fromFunc[L <: HList](f: List[(String, Row)] => Try[L]): FromRow[L] = new FromRow[L] { - def apply(row: List[(String, Row)]) = f(row) - } - - implicit val hnilExtractor: FromRow[HNil] = fromFunc { - case Nil => Success(HNil) - case _ => Failure(new RuntimeException("No more rows expected")) - } - - implicit def hconsExtractor[H : Primitive, T <: HList : FromRow]: FromRow[H #: T] = - fromFunc { - case (field, row) :: t => for { - hv <- Primitive[H].fromRow(field, row) - tv <- FromRow[T].apply(t) - } yield hv +: tv - case Nil => Failure(new RuntimeException("Expected more columns to extract")) - } - - - trait RowParser[A] { - - def apply[L <: HList](row: Row)(implicit - tag: scala.reflect.runtime.universe.TypeTag[A], - gen: Generic.Aux[A, L], - fromRow: FromRow[L] - ): A = { - val applier = new RowParser[A] {} - val accessors = classAccessors[A] - - applier.apply(accessors zip List.tabulate(accessors.size)(_ => row)) match { - case Success(value) => value - case Failure(ex) => - Manager.logger.error(s"Unable to parse value for from row", ex) - throw ex - } - } - - def apply[L <: HList](row: List[(String, Row)])(implicit - gen: Generic.Aux[A, L], - fromRow: FromRow[L] - ): Try[A] = fromRow(row).map(gen.from) - } -} diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/database/DatabaseProvider.scala b/phantom-dsl/src/main/scala/com/websudos/phantom/database/DatabaseProvider.scala deleted file mode 100644 index 74bd7583a..000000000 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/database/DatabaseProvider.scala +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright 2013-2016 Outworkers, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.database - -trait DatabaseProvider[T <: Database[T]] { - def database: T -} diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/exceptions/exceptions.scala b/phantom-dsl/src/main/scala/com/websudos/phantom/exceptions/exceptions.scala deleted file mode 100644 index bdded95c5..000000000 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/exceptions/exceptions.scala +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.exceptions - -import scala.util.control.NoStackTrace - -case class InvalidClusteringKeyException(table: String) extends - RuntimeException(s"Table $table: When using CLUSTERING ORDER all PrimaryKey" + - s" definitions must become a ClusteringKey definition and specify order." - ) with NoStackTrace - -case class InvalidPrimaryKeyException( - table: String -) extends RuntimeException(s"You need to define at least one PartitionKey for the table $table") with NoStackTrace - -case class InvalidTableException(msg: String) extends RuntimeException(msg) with NoStackTrace diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/keys/ClusteringOrder.scala b/phantom-dsl/src/main/scala/com/websudos/phantom/keys/ClusteringOrder.scala deleted file mode 100644 index 1410ba617..000000000 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/keys/ClusteringOrder.scala +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.keys - -import com.websudos.phantom.column.AbstractColumn - -/** - * A trait mixable into a Column to allow clustering order. - * @tparam ValueType The value stored in the column. - */ -trait ClusteringOrder[ValueType] extends PrimaryKey[ValueType]{ - self: AbstractColumn[ValueType] => - override val isClusteringKey = true - -} - -trait Ascending { - self: AbstractColumn[_] with ClusteringOrder[_] => - override val isAscending = true -} - -trait Descending { - self: AbstractColumn[_] with ClusteringOrder[_] => -} diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/keys/PrimaryKey.scala b/phantom-dsl/src/main/scala/com/websudos/phantom/keys/PrimaryKey.scala deleted file mode 100644 index 028ae5e22..000000000 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/keys/PrimaryKey.scala +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.keys - -import com.websudos.phantom.column.AbstractColumn - -private[phantom] trait Undroppable -private[phantom] trait Unmodifiable -private[phantom] trait Indexed - -private[phantom] trait Key[ValueType, KeyType <: Key[ValueType, KeyType]] { - self: AbstractColumn[ValueType] => -} - -trait PrimaryKey[ValueType] extends Key[ValueType, PrimaryKey[ValueType]] with Unmodifiable with Indexed with Undroppable { - self: AbstractColumn[ValueType] => - override val isPrimary = true - - override val shouldFreeze: Boolean = true -} - -trait PartitionKey[ValueType] extends Key[ValueType, PartitionKey[ValueType]] with Unmodifiable with Indexed with Undroppable { - self: AbstractColumn[ValueType] => - override val isPartitionKey = true - override val isPrimary = true - - override val shouldFreeze: Boolean = true -} - -/** - * A trait mixable into Column definitions to allow storing them as keys. - */ -trait Index[ValueType] extends Indexed with Undroppable { - self: AbstractColumn[ValueType] => - - override val isSecondaryKey = true -} - -trait Keys { - self : Index[_] with AbstractColumn[_] => - - override private[phantom] val isMapKeyIndex = true -} - -trait Entries { - self: Index[_] with AbstractColumn[_] => - - override private[phantom] val isMapEntryIndex = true -} \ No newline at end of file diff --git a/phantom-dsl/src/main/scala/com/websudos/phantom/keys/StaticColumn.scala b/phantom-dsl/src/main/scala/com/websudos/phantom/keys/StaticColumn.scala deleted file mode 100644 index 27a889914..000000000 --- a/phantom-dsl/src/main/scala/com/websudos/phantom/keys/StaticColumn.scala +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.keys - -import com.websudos.phantom.column.AbstractColumn - -trait StaticColumn[ValueType] extends Key[ValueType, PartitionKey[ValueType]] { - self: AbstractColumn[ValueType] => - override val isStaticColumn = true -} diff --git a/phantom-dsl/src/test/resources/logback-test.xml b/phantom-dsl/src/test/resources/logback-test.xml index a37754b30..833eabd52 100644 --- a/phantom-dsl/src/test/resources/logback-test.xml +++ b/phantom-dsl/src/test/resources/logback-test.xml @@ -12,7 +12,7 @@ - + diff --git a/phantom-dsl/src/test/scala/com/outworkers/phantom/BasicTableMethods.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/BasicTableMethods.scala new file mode 100644 index 000000000..06221cc5a --- /dev/null +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/BasicTableMethods.scala @@ -0,0 +1,39 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom + +import com.outworkers.phantom.tables._ +import org.scalatest.{FlatSpec, Matchers} + +class BasicTableMethods extends FlatSpec with Matchers { + + it should "retrieve the correct number of columns in a simple table" in { + TestDatabase.basicTable.columns.size shouldEqual 4 + } + + it should "retrieve the correct number of columns in a big table" in { + TestDatabase.complexCompoundKeyTable.columns.size shouldEqual 10 + } + + it should "retrieve the correct number of primary keys for a table" in { + TestDatabase.simpleCompoundKeyTable.primaryKeys.size shouldEqual 2 + TestDatabase.simpleCompoundKeyTable.partitionKeys.size shouldEqual 1 + } + + it should "retrieve the correct number of clustering keys for a table" in { + TestDatabase.clusteringTable.clusteringColumns.size shouldEqual 2 + } +} diff --git a/phantom-dsl/src/test/scala/com/outworkers/phantom/JsonFormats.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/JsonFormats.scala new file mode 100644 index 000000000..74ebc498f --- /dev/null +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/JsonFormats.scala @@ -0,0 +1,89 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom + +import java.util.UUID + +import org.joda.time.{DateTime, DateTimeZone} +import org.json4s.JsonAST.{JInt, JString} +import org.json4s.{Formats, JValue, MappingException, Serializer, TypeInfo} + +import scala.reflect.ClassTag +import scala.util.{Failure, Success, Try} +import scala.util.control.NonFatal + +trait JsonFormats { + + class UUIDSerializer extends Serializer[UUID] { + private[this] val Class = classOf[UUID] + + def deserialize(implicit format: Formats): PartialFunction[(TypeInfo, JValue), UUID] = { + case (TypeInfo(Class, _), json) => json match { + case JString(value) => try { + UUID.fromString(value) + } catch { + case NonFatal(err) => { + val exception = new MappingException(s"Couldn't extract an UUID from $value") + exception.initCause(err) + throw exception + } + } + case x => throw new MappingException("Can't convert " + x + " to UUID") + } + } + + def serialize(implicit format: Formats): PartialFunction[Any, JValue] = { + case x: UUID => JString(x.toString) + } + } + + sealed class DateTimeSerializer extends Serializer[DateTime] { + + val DateTimeClass = classOf[DateTime] + + def deserialize(implicit format: Formats): PartialFunction[(TypeInfo, JValue), DateTime] = { + case (TypeInfo(DateTimeClass, _), json) => json match { + case JString(value) => + Try { + new DateTime(value.toLong, DateTimeZone.UTC) + } match { + case Success(dt) => dt + case Failure(err) => { + val exception = new MappingException(s"Couldn't extract a DateTime from $value") + exception.initCause(err) + throw exception + } + } + case JInt(value) => { + Try(new DateTime(value.toLong, DateTimeZone.UTC)) match { + case Success(dt) => dt + case Failure(err) => { + val exception = new MappingException(s"Couldn't extract a DateTime from $value") + exception.initCause(err) + throw exception + } + } + } + case x => throw new MappingException("Can't convert " + x + " to DateTime") + } + } + + def serialize(implicit format: Formats): PartialFunction[Any, JValue] = { + case x: DateTime => JInt(x.getMillis) + } + } + +} diff --git a/phantom-dsl/src/test/scala/com/outworkers/phantom/PhantomSuite.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/PhantomSuite.scala new file mode 100644 index 000000000..ae5ac0118 --- /dev/null +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/PhantomSuite.scala @@ -0,0 +1,67 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom + +import java.util.concurrent.TimeUnit + +import com.datastax.driver.core.VersionNumber +import com.outworkers.phantom.connectors.RootConnector +import com.outworkers.phantom.tables.TestDatabase +import org.scalatest._ +import org.scalatest.concurrent.{PatienceConfiguration, ScalaFutures} +import org.scalatest.time.{Millis, Seconds, Span} + +trait PhantomBaseSuite extends Suite with Matchers + with BeforeAndAfterAll + with RootConnector + with ScalaFutures + with JsonFormats + with OptionValues { + + implicit val formats = org.json4s.DefaultFormats + new DateTimeSerializer + new UUIDSerializer + + protected[this] val defaultScalaTimeoutSeconds = 25 + + private[this] val defaultScalaInterval = 50L + + implicit val defaultScalaTimeout = scala.concurrent.duration.Duration(defaultScalaTimeoutSeconds, TimeUnit.SECONDS) + + private[this] val defaultTimeoutSpan = Span(defaultScalaTimeoutSeconds, Seconds) + + implicit val defaultTimeout: PatienceConfiguration.Timeout = timeout(defaultTimeoutSpan) + + override implicit val patienceConfig = PatienceConfig( + timeout = defaultTimeoutSpan, + interval = Span(defaultScalaInterval, Millis) + ) + + implicit class CqlConverter[T](val obj: T) { + def asCql()(implicit primitive: com.outworkers.phantom.builder.primitives.Primitive[T]): String = { + primitive.asCql(obj) + } + } +} + +trait PhantomSuite extends FlatSpec with PhantomBaseSuite with TestDatabase.connector.Connector { + val database = TestDatabase + + def requireVersion[T](v: VersionNumber)(fn: => T): Unit = if (cassandraVersion.value.compareTo(v) >= 0) fn else () +} + + +trait PhantomFreeSuite extends FreeSpec with PhantomBaseSuite with TestDatabase.connector.Connector { + val database = TestDatabase +} \ No newline at end of file diff --git a/phantom-dsl/src/test/scala/com/outworkers/phantom/TableKeyGenerationTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/TableKeyGenerationTest.scala new file mode 100644 index 000000000..756c15e1f --- /dev/null +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/TableKeyGenerationTest.scala @@ -0,0 +1,58 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom + +import com.outworkers.phantom.tables._ +import org.scalatest.{FlatSpec, Matchers, ParallelTestExecution} + +class TableKeyGenerationTest extends FlatSpec with Matchers with ParallelTestExecution { + + it should "correctly create a Compound key from a table with a single Partition key" in { + TestDatabase.tableWithSingleKey.tableKey shouldEqual s"PRIMARY KEY (id)" + } + + it should "correctly create a Compound key from a table with a single Partition key and one Primary key" in { + TestDatabase.tableWithCompoundKey.tableKey shouldEqual s"PRIMARY KEY (id, second)" + } + + it should "correctly create a Composite key from a table with a two Partition keys and one Primary key" in { + TestDatabase.tableWithCompositeKey.tableKey shouldEqual s"PRIMARY KEY ((id, second_part), second)" + } + + it should "throw an error if the schema has no PartitionKey" in { + """ + |abstract class TableWithNoKey extends CassandraTable[TableWithNoKey, StubRecord] { + | object id extends UUIDColumn(this) + | object name extends StringColumn(this) + |} + """.stripMargin shouldNot compile + } + + it should "throw an error if the table uses a ClusteringColumn with PrimaryKeys" in { + """ + |sealed class BrokenClusteringTable extends CassandraTable[BrokenClusteringTable, String] { + | object id extends UUIDColumn(this) with PartitionKey + | + | object id2 extends UUIDColumn(this) with PrimaryKey + | object id3 extends UUIDColumn(this) with ClusteringOrder with Descending + | object placeholder extends StringColumn(this) with ClusteringOrder with Descending + | + | override def fromRow(r: Row): String = placeholder(r) + |} + | + """.stripMargin shouldNot compile + } +} diff --git a/phantom-dsl/src/test/scala/com/outworkers/phantom/base/ClassNameExtraction.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/base/ClassNameExtraction.scala new file mode 100644 index 000000000..66620ffcd --- /dev/null +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/base/ClassNameExtraction.scala @@ -0,0 +1,62 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.base + +import org.scalatest.{FlatSpec, Matchers} +import com.outworkers.phantom.dsl._ + +case class CustomRecord(name: String, mp: Map[String, String]) + +trait TestTableNames extends CassandraTable[TestTableNames, CustomRecord] { + object rec extends StringColumn(this) with PartitionKey + object sampleLongTextColumnDefinition extends MapColumn[String, String](this) + + override def fromRow(r: Row): CustomRecord = { + CustomRecord( + rec(r), + sampleLongTextColumnDefinition(r) + ) + } +} + +object TestTableNames extends TestTableNames + +object Test extends PrimitiveColumn[TestTableNames, CustomRecord, String](TestTableNames) + +trait TestNames extends TestTableNames + +class Parent extends TestNames +class Parent2 extends Parent + +class ClassNameExtraction extends FlatSpec with Matchers { + + + it should "correctly name objects inside record classes " in { + TestTableNames.rec.name shouldEqual "rec" + } + + it should "correctly extract long object name definitions in nested record classes" in { + TestTableNames.sampleLongTextColumnDefinition.name shouldEqual "sampleLongTextColumnDefinition" + } + + it should "correctly name Cassandra Tables" in { + TestTableNames.tableName shouldEqual "testTableNames" + } + + it should "correctly extract the object name " in { + Test.name shouldEqual "Test" + } +} diff --git a/phantom-dsl/src/test/scala/com/outworkers/phantom/base/FieldCollectionTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/base/FieldCollectionTest.scala new file mode 100644 index 000000000..70630e322 --- /dev/null +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/base/FieldCollectionTest.scala @@ -0,0 +1,37 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.base + +import com.outworkers.phantom.tables.TestDatabase +import org.scalatest.{FlatSpec, Matchers, ParallelTestExecution} + +class FieldCollectionTest extends FlatSpec with Matchers with ParallelTestExecution { + + it should "collect objects in the same order they are written" in { + val collected = TestDatabase.articles.columns.map(_.name).mkString(" ") + val expected = s"${TestDatabase.articles.id.name} ${TestDatabase.articles.name.name} ${TestDatabase.articles.orderId.name}" + collected shouldEqual expected + } + + + it should "correctly reference the same table" in { + TestDatabase.primitives.pkey.table shouldEqual TestDatabase.primitives + } + + it should "initialise fields by default" in { + TestDatabase.articles.columns.size shouldEqual 3 + } +} diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/base/SkipRecordsByToken.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/base/SkipRecordsByToken.scala similarity index 67% rename from phantom-dsl/src/test/scala/com/websudos/phantom/base/SkipRecordsByToken.scala rename to phantom-dsl/src/test/scala/com/outworkers/phantom/base/SkipRecordsByToken.scala index 002754996..5b3e324af 100644 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/base/SkipRecordsByToken.scala +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/base/SkipRecordsByToken.scala @@ -1,37 +1,23 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.base +package com.outworkers.phantom.base -import com.websudos.phantom.PhantomSuite -import com.websudos.phantom.dsl._ -import com.websudos.phantom.tables.{Article, TestDatabase} +import com.outworkers.phantom.PhantomSuite +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.tables.{Article, TestDatabase} import com.outworkers.util.testing._ import scala.concurrent.{Future, blocking} diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/batch/BatchQuerySerialisationTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/batch/BatchQuerySerialisationTest.scala similarity index 51% rename from phantom-dsl/src/test/scala/com/websudos/phantom/builder/batch/BatchQuerySerialisationTest.scala rename to phantom-dsl/src/test/scala/com/outworkers/phantom/builder/batch/BatchQuerySerialisationTest.scala index b6c75c280..55d8398ba 100644 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/batch/BatchQuerySerialisationTest.scala +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/batch/BatchQuerySerialisationTest.scala @@ -1,37 +1,23 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.batch +package com.outworkers.phantom.builder.batch -import com.websudos.phantom.builder.query.SerializationTest -import com.websudos.phantom.dsl._ -import com.websudos.phantom.tables.{JodaRow, TestDatabase} +import com.outworkers.phantom.builder.query.SerializationTest +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.tables.{JodaRow, TestDatabase} import com.outworkers.util.testing._ import org.scalatest.FlatSpec diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/batch/BatchQueryTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/batch/BatchQueryTest.scala similarity index 78% rename from phantom-dsl/src/test/scala/com/websudos/phantom/builder/batch/BatchQueryTest.scala rename to phantom-dsl/src/test/scala/com/outworkers/phantom/builder/batch/BatchQueryTest.scala index 2873dbe31..e55c93abc 100644 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/batch/BatchQueryTest.scala +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/batch/BatchQueryTest.scala @@ -1,37 +1,23 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.batch +package com.outworkers.phantom.builder.batch -import com.websudos.phantom.PhantomSuite -import com.websudos.phantom.dsl._ -import com.websudos.phantom.tables.{JodaRow, TestDatabase} +import com.outworkers.phantom.PhantomSuite +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.tables.{JodaRow, TestDatabase} import com.outworkers.util.testing._ import org.joda.time.DateTime diff --git a/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/primitives/DerivedPrimitivesTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/primitives/DerivedPrimitivesTest.scala new file mode 100644 index 000000000..b84732224 --- /dev/null +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/primitives/DerivedPrimitivesTest.scala @@ -0,0 +1,35 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.builder.primitives + +import com.outworkers.phantom.PhantomSuite +import com.outworkers.phantom.builder.query.CQLQuery +import com.outworkers.util.testing._ + +case class Record(value: String) + +object Record { + implicit val recordPrimitive: Primitive[Record] = Primitive.derive[Record, String](_.value)(Record.apply) +} + +class DerivedPrimitivesTest extends PhantomSuite { + + it should "derive a primitive for a custom wrapper type" in { + val str = gen[String] + + Primitive[Record].asCql(Record(str)) shouldEqual CQLQuery.escape(str) + } +} diff --git a/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/primitives/PrimitivesTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/primitives/PrimitivesTest.scala new file mode 100644 index 000000000..f86dae169 --- /dev/null +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/primitives/PrimitivesTest.scala @@ -0,0 +1,74 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.builder.primitives + +import java.nio.ByteBuffer + +import com.outworkers.phantom.builder.QueryBuilder +import org.joda.time.{DateTime, DateTimeZone} +import org.scalatest.{FlatSpec, Matchers} +import com.outworkers.util.testing._ + +class PrimitivesTest extends FlatSpec with Matchers { + + it should "coerce a DateTime into a valid timezone string" in { + val date = new DateTime(2014, 6, 2, 10, 5, DateTimeZone.UTC) + + DateSerializer.asCql(date) shouldEqual date.getMillis.toString + } + + it should "convert ByteBuffers to valid hex bytes" in { + val buf = ByteBuffer.wrap(Array[Byte](1, 2, 3, 4, 5)) + Primitive[ByteBuffer].asCql(buf) shouldEqual "0x0102030405" + + buf.position(2) // Non-zero position + Primitive[ByteBuffer].asCql(buf) shouldEqual "0x030405" + + val slice = buf.slice() // Slice with non-zero arrayOffset + Primitive[ByteBuffer].asCql(slice) shouldEqual "0x030405" + } + + it should "autogenerate list primitives for List types" in { + val test = Primitive[List[String]] + val input = genList[String]() + val expected = QueryBuilder.Collections.serialize(input.map(Primitive[String].asCql)).queryString + + test.asCql(input) shouldEqual expected + } + + it should "correctly serialize a tuple using a primitive" in { + val primitive = implicitly[Primitive[(String, Long)]] + QueryBuilder.Collections.tupled("'test'", "5").queryString shouldEqual "('test', 5)" + primitive.asCql("test" -> 5) shouldEqual "('test', 5)" + } + + it should "autogenerate set primitives for Set types" in { + """val test = Primitive[Set[String]]""" should compile + } + + it should "generate a primitive for a collection of tuples" in { + val primitive = Primitive[List[(String, Int)]] + val strPrimitive = Primitive[List[String]] + + val samples = genList[Int]() map (i => gen[String] -> i) + val strSamples = genList[String]() + } + + it should "autogenerate set primitives for Map types" in { + """val test = Primitive[Map[String, String]]""" should compile + } + +} diff --git a/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/CQLQueryTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/CQLQueryTest.scala new file mode 100644 index 000000000..aff25739d --- /dev/null +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/CQLQueryTest.scala @@ -0,0 +1,43 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.builder.query + +import org.scalatest.{Matchers, FlatSpec} +import com.outworkers.util.testing._ + +class CQLQueryTest extends FlatSpec with Matchers { + + it should "create an empty CQL query using the empty method on the companion object" in { + CQLQuery.empty.queryString shouldEqual "" + } + + it should "automatically serialize a list of strings using the apply method from the companion object" in { + val list = List("test", "test2") + + CQLQuery(list).queryString shouldEqual "test, test2" + } + + it should "escape strings without single quotes inside them by wrapping the string in single quotes" in { + val test = gen[String] + CQLQuery.escape(test) shouldEqual s"'$test'" + } + + it should "escape single quotes inside a string using the scape method of the companion" in { + val test = "test'" + CQLQuery.escape(test) shouldEqual "'test'''" + } + +} diff --git a/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/KeySpaceSuite.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/KeySpaceSuite.scala new file mode 100644 index 000000000..5f2a0500c --- /dev/null +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/KeySpaceSuite.scala @@ -0,0 +1,34 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.builder.query + +import com.outworkers.phantom.PhantomBaseSuite +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.tables.TestDatabase +import org.scalatest.{FreeSpec, Matchers, Suite} + +trait KeySpaceSuite { + + self: Suite => + + implicit val keySpace = KeySpace("phantom") +} + +trait SerializationTest extends Matchers with TestDatabase.connector.Connector { + self: Suite => +} + +trait QueryBuilderTest extends FreeSpec with PhantomBaseSuite with TestDatabase.connector.Connector \ No newline at end of file diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/compilation/BatchRestrictionTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/compilation/BatchRestrictionTest.scala similarity index 66% rename from phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/compilation/BatchRestrictionTest.scala rename to phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/compilation/BatchRestrictionTest.scala index e10ef6a01..87b5523eb 100644 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/compilation/BatchRestrictionTest.scala +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/compilation/BatchRestrictionTest.scala @@ -1,37 +1,23 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.query.compilation +package com.outworkers.phantom.builder.query.compilation -import com.websudos.phantom.builder.query.SerializationTest -import com.websudos.phantom.dsl._ -import com.websudos.phantom.tables.{Recipe, TestDatabase} +import com.outworkers.phantom.builder.query.SerializationTest +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.tables.{Recipe, TestDatabase} import com.outworkers.util.testing._ import org.joda.time.DateTime import org.scalatest.FlatSpec diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/compilation/CompareAndSetRestrictionsTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/compilation/CompareAndSetRestrictionsTest.scala similarity index 63% rename from phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/compilation/CompareAndSetRestrictionsTest.scala rename to phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/compilation/CompareAndSetRestrictionsTest.scala index d4e7d9c16..f8899ff37 100644 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/compilation/CompareAndSetRestrictionsTest.scala +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/compilation/CompareAndSetRestrictionsTest.scala @@ -1,37 +1,23 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.query.compilation +package com.outworkers.phantom.builder.query.compilation -import com.websudos.phantom.builder.query.KeySpaceSuite -import com.websudos.phantom.dsl._ -import com.websudos.phantom.tables.TestDatabase +import com.outworkers.phantom.builder.query.KeySpaceSuite +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.tables.TestDatabase import com.outworkers.util.testing._ import org.scalatest.{FlatSpec, Matchers} diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/compilation/IndexOperatorsRestrictionTests.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/compilation/IndexOperatorsRestrictionTests.scala similarity index 54% rename from phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/compilation/IndexOperatorsRestrictionTests.scala rename to phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/compilation/IndexOperatorsRestrictionTests.scala index b279ee74d..b3e63cb7e 100644 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/compilation/IndexOperatorsRestrictionTests.scala +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/compilation/IndexOperatorsRestrictionTests.scala @@ -1,37 +1,23 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.query.compilation +package com.outworkers.phantom.builder.query.compilation -import com.websudos.phantom.builder.query.KeySpaceSuite -import com.websudos.phantom.dsl._ -import com.websudos.phantom.tables.TestDatabase +import com.outworkers.phantom.builder.query.KeySpaceSuite +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.tables.TestDatabase import com.outworkers.util.testing._ import org.scalatest.{FlatSpec, Matchers} diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/compilation/ModifyOperatorRestrictions.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/compilation/ModifyOperatorRestrictions.scala similarity index 55% rename from phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/compilation/ModifyOperatorRestrictions.scala rename to phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/compilation/ModifyOperatorRestrictions.scala index 1321366e3..4837e1125 100644 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/compilation/ModifyOperatorRestrictions.scala +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/compilation/ModifyOperatorRestrictions.scala @@ -1,43 +1,29 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.query.compilation +package com.outworkers.phantom.builder.query.compilation -import com.websudos.phantom.connectors.KeySpace -import com.websudos.phantom.dsl._ -import com.websudos.phantom.tables.TestDatabase +import com.outworkers.phantom.connectors.KeySpace +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.tables.TestDatabase import com.outworkers.util.testing._ import org.scalatest.{FlatSpec, Matchers, ParallelTestExecution} class ModifyOperatorRestrictions extends FlatSpec with Matchers with ParallelTestExecution { - implicit val keySpace: KeySpace = new KeySpace("phantom") + implicit val keySpace: KeySpace = KeySpace("phantom") val TimeSeriesTable = TestDatabase.timeSeriesTable val CounterTableTest = TestDatabase.counterTableTest diff --git a/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/compilation/TypeRestrictionsTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/compilation/TypeRestrictionsTest.scala new file mode 100644 index 000000000..09a33aea6 --- /dev/null +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/compilation/TypeRestrictionsTest.scala @@ -0,0 +1,56 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.builder.query.compilation + +import com.outworkers.phantom.builder.query.SerializationTest +import com.outworkers.phantom.dsl.UUID +import com.outworkers.phantom.tables.TestDatabase +import com.outworkers.util.testing._ +import org.scalatest.FlatSpec + +class TypeRestrictionsTest extends FlatSpec with SerializationTest { + + val Primitives = TestDatabase.primitives + val tsTable = TestDatabase.timeSeriesTable + + + it should "allow using a correct type for a value method" in { + "Primitives.insert.value(_.boolean, true)" should compile + } + + it should "not allow using a wrong type for a value method" in { + "Primitives.insert.value(_.boolean, 5)" shouldNot compile + } + + it should "not allow chaining 2 limit clauses on the same query" in { + "Primitives.select.all().limit(5).limit(5)" shouldNot compile + } + + it should "not allow chaining multiple order by clauses on the same query" in { + val user = gen[UUID] + """tsTable.select.where(_.id eqs user).orderBy(_.timestamp.desc).orderBy(_.timestamp.desc)""" shouldNot compile + } + + it should "not allow chaining where clauses on the same query, it should only allow where .. and constructs" in { + val user = gen[UUID] + """tsTable.select.where(_.id eqs user).where(_.id eqs user)""" shouldNot compile + } + + it should "not allow specifying multiple consistency bounds on the same query" in { + val user = gen[UUID] + """tsTable.select.where(_.id eqs user).consistencyLevel_=(ConsistencyLevel.ONE).consistencyLevel_=(ConsistencyLevel.ONE)""" shouldNot compile + } +} diff --git a/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/compilation/WhereClauseRestrictionsTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/compilation/WhereClauseRestrictionsTest.scala new file mode 100644 index 000000000..b8194543e --- /dev/null +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/compilation/WhereClauseRestrictionsTest.scala @@ -0,0 +1,52 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.builder.query.compilation + +import com.outworkers.phantom.builder.query.KeySpaceSuite +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.tables.TestDatabase +import com.outworkers.util.testing._ +import org.scalatest.{FlatSpec, Matchers} + +class WhereClauseRestrictionsTest extends FlatSpec with Matchers with KeySpaceSuite { + + val s = gen[String] + val Primitives = TestDatabase.primitives + + it should "allow using a Select.Where clause" in { + "Primitives.select.where(_.pkey eqs gen[String])" should compile + } + + it should "allow using a Select.Where clause with AND chain" in { + "Primitives.select.where(_.pkey eqs gen[String]).and(_.pkey eqs gen[String])" should compile + } + + it should "not allow chaining two Select.Where clauses" in { + "Primitives.select.where(_.pkey eqs gen[String]).where(_.pkey eqs gen[String])" shouldNot compile + } + + it should "not allow re-using a Where clause after an WHERE/AND chain" in { + "Primitives.select.where(_.pkey eqs gen[String]).and(_.pkey eqs gen[String]).where(_.pkey eqs gen[String])" shouldNot compile + } + + it should "Should not allow chaining two Update.Where clauses" in { + "Primitives.update.where(_.pkey eqs gen[String]).where(_.pkey eqs gen[String])" shouldNot compile + } + + it should "not allow chaining two Delete.Where clauses" in { + "Primitives.update.where(_.pkey eqs gen[String]).where(_.pkey eqs gen[String])" shouldNot compile + } +} diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/batch/BatchTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/batch/BatchTest.scala similarity index 82% rename from phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/batch/BatchTest.scala rename to phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/batch/BatchTest.scala index 0f001ae1c..9b5238661 100644 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/batch/BatchTest.scala +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/batch/BatchTest.scala @@ -1,38 +1,24 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.query.db.batch +package com.outworkers.phantom.builder.query.db.batch +import com.outworkers.phantom.PhantomSuite import com.outworkers.util.testing._ -import com.websudos.phantom.PhantomSuite -import com.websudos.phantom.dsl._ -import com.websudos.phantom.tables.JodaRow +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.tables.JodaRow import org.joda.time.DateTime class BatchTest extends PhantomSuite { diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/batch/CounterBatchTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/batch/CounterBatchTest.scala similarity index 75% rename from phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/batch/CounterBatchTest.scala rename to phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/batch/CounterBatchTest.scala index 215eab5d9..434d070d4 100644 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/batch/CounterBatchTest.scala +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/batch/CounterBatchTest.scala @@ -1,38 +1,24 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.query.db.batch +package com.outworkers.phantom.builder.query.db.batch import com.datastax.driver.core.utils.UUIDs -import com.websudos.phantom.PhantomSuite -import com.websudos.phantom.dsl._ -import com.websudos.phantom.tables.TestDatabase +import com.outworkers.phantom.PhantomSuite +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.tables.TestDatabase class CounterBatchTest extends PhantomSuite { diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/batch/UnloggedBatchTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/batch/UnloggedBatchTest.scala similarity index 81% rename from phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/batch/UnloggedBatchTest.scala rename to phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/batch/UnloggedBatchTest.scala index 73f6b5c56..597c3ce46 100644 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/batch/UnloggedBatchTest.scala +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/batch/UnloggedBatchTest.scala @@ -1,37 +1,23 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.query.db.batch +package com.outworkers.phantom.builder.query.db.batch -import com.websudos.phantom.PhantomSuite -import com.websudos.phantom.dsl._ -import com.websudos.phantom.tables.{JodaRow, TestDatabase} +import com.outworkers.phantom.PhantomSuite +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.tables.{JodaRow, TestDatabase} import com.outworkers.util.testing._ import org.joda.time.DateTime import org.scalatest.time.SpanSugar._ diff --git a/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/crud/CountTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/crud/CountTest.scala new file mode 100644 index 000000000..fb9b86581 --- /dev/null +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/crud/CountTest.scala @@ -0,0 +1,68 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.builder.query.db.crud + +import com.outworkers.phantom.PhantomSuite +import com.outworkers.phantom.dsl.Batch +import com.outworkers.phantom.tables._ +import com.outworkers.util.testing._ + +import com.outworkers.phantom.dsl._ + +class CountTest extends PhantomSuite { + + override def beforeAll(): Unit = { + super.beforeAll() + TestDatabase.primitivesJoda.insertSchema() + } + + + it should "retrieve a count of 0 if the table has been truncated" in { + + val chain = for { + truncate <- TestDatabase.primitivesJoda.truncate.future() + count <- TestDatabase.primitivesJoda.select.count.one() + } yield count + + chain successful { + res => { + res.value shouldEqual 0L + } + } + } + + it should "correctly retrieve a count of 1000" in { + val limit = 100 + + val rows = genList[JodaRow](limit) + + val batch = rows.foldLeft(Batch.unlogged)((b, row) => { + b.add(TestDatabase.primitivesJoda.store(row)) + }) + + val chain = for { + truncate <- TestDatabase.primitivesJoda.truncate.future() + batch <- batch.future() + count <- TestDatabase.primitivesJoda.select.count.one() + } yield count + + chain successful { + res => { + res.value shouldEqual limit.toLong + } + } + } +} diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/crud/CreateTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/crud/CreateTest.scala similarity index 59% rename from phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/crud/CreateTest.scala rename to phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/crud/CreateTest.scala index 56d8169bf..ed2430081 100644 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/crud/CreateTest.scala +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/crud/CreateTest.scala @@ -1,37 +1,23 @@ /* - * Copyright 2013-2016 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.query.db.crud +package com.outworkers.phantom.builder.query.db.crud -import com.websudos.phantom.PhantomFreeSuite -import com.websudos.phantom.tables.TestDatabase -import com.websudos.phantom.dsl._ +import com.outworkers.phantom.PhantomFreeSuite +import com.outworkers.phantom.tables.TestDatabase +import com.outworkers.phantom.dsl._ class CreateTest extends PhantomFreeSuite { diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/crud/DeleteQueryTests.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/crud/DeleteQueryTests.scala similarity index 72% rename from phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/crud/DeleteQueryTests.scala rename to phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/crud/DeleteQueryTests.scala index 2fa4360f6..55f685827 100644 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/crud/DeleteQueryTests.scala +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/crud/DeleteQueryTests.scala @@ -1,37 +1,23 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.query.db.crud +package com.outworkers.phantom.builder.query.db.crud -import com.websudos.phantom.PhantomSuite -import com.websudos.phantom.dsl._ -import com.websudos.phantom.tables._ +import com.outworkers.phantom.PhantomSuite +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.tables._ import com.outworkers.util.testing._ class DeleteQueryTests extends PhantomSuite { diff --git a/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/crud/DistinctTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/crud/DistinctTest.scala new file mode 100644 index 000000000..9a7362587 --- /dev/null +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/crud/DistinctTest.scala @@ -0,0 +1,63 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.builder.query.db.crud + +import java.util.UUID + +import com.outworkers.phantom.PhantomSuite +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.tables._ +import org.joda.time.DateTime + +class DistinctTest extends PhantomSuite { + + override def beforeAll(): Unit = { + super.beforeAll() + database.tableWithCompoundKey.insertSchema() + } + + it should "return distinct primary keys" in { + val rows = List( + StubRecord(UUID.nameUUIDFromBytes("1".getBytes), "a"), + StubRecord(UUID.nameUUIDFromBytes("1".getBytes), "b"), + StubRecord(UUID.nameUUIDFromBytes("2".getBytes), "c"), + StubRecord(UUID.nameUUIDFromBytes("3".getBytes), "d") + ) + + val batch = rows.foldLeft(Batch.unlogged)((batch, row) => { + batch.add( + database.tableWithCompoundKey.insert + .value(_.id, row.id) + .value(_.second, UUID.nameUUIDFromBytes(row.name.getBytes)) + .value(_.name, row.name) + ) + }) + + val chain = for { + truncate <- TestDatabase.tableWithCompoundKey.truncate.future() + batch <- batch.future() + list <- TestDatabase.tableWithCompoundKey.select(_.id).distinct.fetch + } yield list + + val expectedResult = rows.filter(_.name != "b").map(_.id) + + whenReady(chain) { + res => res should contain only (expectedResult: _*) + } + } + + private[this] implicit def string2date(date: String): DateTime = new DateTime(date) +} diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/crud/InsertCasTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/crud/InsertCasTest.scala similarity index 61% rename from phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/crud/InsertCasTest.scala rename to phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/crud/InsertCasTest.scala index b956499e9..816c96f14 100644 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/crud/InsertCasTest.scala +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/crud/InsertCasTest.scala @@ -1,38 +1,24 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.query.db.crud +package com.outworkers.phantom.builder.query.db.crud -import com.websudos.phantom.PhantomSuite -import com.websudos.phantom.builder.query.ExecutableStatementList -import com.websudos.phantom.dsl._ -import com.websudos.phantom.tables._ +import com.outworkers.phantom.PhantomSuite +import com.outworkers.phantom.builder.query.ExecutableStatementList +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.tables._ import com.outworkers.util.testing._ class InsertCasTest extends PhantomSuite { diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/crud/InsertTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/crud/InsertTest.scala similarity index 69% rename from phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/crud/InsertTest.scala rename to phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/crud/InsertTest.scala index da1faa8f7..414e8f7e0 100644 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/crud/InsertTest.scala +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/crud/InsertTest.scala @@ -1,39 +1,26 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.query.db.crud +package com.outworkers.phantom.builder.query.db.crud -import com.websudos.phantom.PhantomSuite -import com.websudos.phantom.dsl._ -import com.websudos.phantom.tables._ +import com.outworkers.phantom.PhantomSuite +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.tables._ import com.outworkers.util.testing._ -import net.liftweb.json._ +import org.json4s.Extraction +import org.json4s.native._ class InsertTest extends PhantomSuite { @@ -164,7 +151,7 @@ class InsertTest extends PhantomSuite { val sample = gen[Recipe] val chain = for { - store <- TestDatabase.recipes.insert.json(compactRender(Extraction.decompose(sample))).future() + store <- TestDatabase.recipes.insert.json(compactJson(renderJValue(Extraction.decompose(sample)))).future() get <- TestDatabase.recipes.select.where(_.url eqs sample.url).one() } yield get diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/crud/ListOperatorsTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/crud/ListOperatorsTest.scala similarity index 77% rename from phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/crud/ListOperatorsTest.scala rename to phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/crud/ListOperatorsTest.scala index fad44ee61..205dd352d 100644 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/crud/ListOperatorsTest.scala +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/crud/ListOperatorsTest.scala @@ -1,37 +1,23 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.query.db.crud +package com.outworkers.phantom.builder.query.db.crud -import com.websudos.phantom.PhantomSuite -import com.websudos.phantom.dsl._ -import com.websudos.phantom.tables._ +import com.outworkers.phantom.PhantomSuite +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.tables._ import com.outworkers.util.testing._ class ListOperatorsTest extends PhantomSuite { diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/crud/MapOperationsTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/crud/MapOperationsTest.scala similarity index 66% rename from phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/crud/MapOperationsTest.scala rename to phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/crud/MapOperationsTest.scala index e337ba727..89fb15d7c 100644 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/crud/MapOperationsTest.scala +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/crud/MapOperationsTest.scala @@ -1,38 +1,24 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.query.db.crud +package com.outworkers.phantom.builder.query.db.crud +import com.outworkers.phantom.PhantomSuite import com.outworkers.util.testing._ -import com.websudos.phantom.PhantomSuite -import com.websudos.phantom.dsl._ -import com.websudos.phantom.tables.{Recipe, SampleEvent, ScalaPrimitiveMapRecord} +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.tables.{Recipe, SampleEvent, ScalaPrimitiveMapRecord} import org.joda.time.DateTime class MapOperationsTest extends PhantomSuite { diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/crud/RelationalOperatorsTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/crud/RelationalOperatorsTest.scala similarity index 76% rename from phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/crud/RelationalOperatorsTest.scala rename to phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/crud/RelationalOperatorsTest.scala index 569d84780..1e0dc5db4 100644 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/crud/RelationalOperatorsTest.scala +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/crud/RelationalOperatorsTest.scala @@ -1,42 +1,29 @@ /* - * Copyright 2013-2016 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.query.db.crud +package com.outworkers.phantom.builder.query.db.crud +import com.outworkers.phantom.PhantomSuite import com.twitter.util.{Future => TwitterFuture} -import com.websudos.phantom.PhantomSuite -import com.websudos.phantom.builder.query.db.ordering.TimeSeriesTest -import com.websudos.phantom.builder.query.prepared._ -import com.websudos.phantom.dsl._ -import com.websudos.phantom.tables._ +import com.outworkers.phantom.builder.query.db.ordering.TimeSeriesTest +import com.outworkers.phantom.builder.query.prepared._ +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.tables._ import com.outworkers.util.testing._ import org.slf4j.LoggerFactory + import scala.concurrent.{Future => ScalaFuture} class RelationalOperatorsTest extends PhantomSuite { diff --git a/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/crud/SelectJsonTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/crud/SelectJsonTest.scala new file mode 100644 index 000000000..06964f0a2 --- /dev/null +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/crud/SelectJsonTest.scala @@ -0,0 +1,76 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.builder.query.db.crud + +import com.datastax.driver.core.exceptions.SyntaxError +import com.outworkers.phantom.PhantomSuite +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.tables._ +import com.outworkers.util.testing._ +import org.json4s.native.JsonParser + +class SelectJsonTest extends PhantomSuite { + override def beforeAll(): Unit = { + super.beforeAll() + TestDatabase.primitives.insertSchema() + } + + "A JSON selection clause" should "select an entire row as JSON" in { + val row = gen[Primitive] + + val chain = for { + store <- TestDatabase.primitives.store(row).future() + b <- TestDatabase.primitives.select.json().where(_.pkey eqs row.pkey).one + } yield b + + + if (cassandraVersion.value >= Version.`2.2.0`) { + chain successful { + res => { + res shouldBe defined + val parsed = JsonParser.parse(res.value) + parsed.children.size shouldEqual row.productArity + } + } + } else { + chain.failing[SyntaxError] + } + } + + "A JSON selection clause" should "8 columns as JSON" in { + val row = gen[Primitive] + val expected = (row.pkey, row.long, row.boolean, row.bDecimal, row.double, row.float, row.inet, row.int) + + val chain = for { + store <- TestDatabase.primitives.store(row).future() + get <- TestDatabase.primitives.select(_.pkey, _.long, _.boolean, _.bDecimal, _.double, _.float, _.inet, _.int) + .json() + .where(_.pkey eqs row.pkey).one() + } yield get + + if (cassandraVersion.value >= Version.`2.2.0`) { + chain successful { + res => { + res shouldBe defined + val parsed = JsonParser.parse(res.value) + parsed.children.size shouldEqual expected.productArity + } + } + } else { + chain.failing[SyntaxError] + } + } +} \ No newline at end of file diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/crud/SelectOptionalTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/crud/SelectOptionalTest.scala similarity index 57% rename from phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/crud/SelectOptionalTest.scala rename to phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/crud/SelectOptionalTest.scala index ccb719f72..d04789bc9 100644 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/crud/SelectOptionalTest.scala +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/crud/SelectOptionalTest.scala @@ -1,37 +1,23 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.query.db.crud +package com.outworkers.phantom.builder.query.db.crud -import com.websudos.phantom.PhantomSuite -import com.websudos.phantom.dsl._ -import com.websudos.phantom.tables._ +import com.outworkers.phantom.PhantomSuite +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.tables._ import com.outworkers.util.testing._ class SelectOptionalTest extends PhantomSuite { diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/crud/SelectTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/crud/SelectTest.scala similarity index 68% rename from phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/crud/SelectTest.scala rename to phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/crud/SelectTest.scala index e8acb36f0..a73d26b06 100644 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/crud/SelectTest.scala +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/crud/SelectTest.scala @@ -1,40 +1,24 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.query.db.crud +package com.outworkers.phantom.builder.query.db.crud -import com.websudos.phantom.PhantomSuite -import com.websudos.phantom.dsl._ -import com.websudos.phantom.tables._ +import com.outworkers.phantom.PhantomSuite +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.tables._ import com.outworkers.util.testing._ -import net.liftweb.http.js.JsObj -import net.liftweb.json.JsonParser class SelectTest extends PhantomSuite { diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/crud/SetOperationsTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/crud/SetOperationsTest.scala similarity index 60% rename from phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/crud/SetOperationsTest.scala rename to phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/crud/SetOperationsTest.scala index cb9f6e79b..2725025cf 100644 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/crud/SetOperationsTest.scala +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/crud/SetOperationsTest.scala @@ -1,37 +1,23 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.query.db.crud +package com.outworkers.phantom.builder.query.db.crud -import com.websudos.phantom.PhantomSuite -import com.websudos.phantom.dsl._ -import com.websudos.phantom.tables._ +import com.outworkers.phantom.PhantomSuite +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.tables._ import com.outworkers.util.testing._ class SetOperationsTest extends PhantomSuite { diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/crud/TTLTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/crud/TTLTest.scala similarity index 59% rename from phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/crud/TTLTest.scala rename to phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/crud/TTLTest.scala index 32133681f..e1de385f2 100644 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/crud/TTLTest.scala +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/crud/TTLTest.scala @@ -1,38 +1,24 @@ /* - * Copyright 2013-2016 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.query.db.crud +package com.outworkers.phantom.builder.query.db.crud -import com.websudos.phantom.PhantomSuite -import com.websudos.phantom.builder.query.prepared._ -import com.websudos.phantom.dsl._ -import com.websudos.phantom.tables.{Primitive, TestDatabase} +import com.outworkers.phantom.PhantomSuite +import com.outworkers.phantom.builder.query.prepared._ +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.tables.{Primitive, TestDatabase} import com.outworkers.util.testing._ import org.scalatest.{Outcome, Retries} import org.scalatest.concurrent.Eventually diff --git a/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/crud/TruncateTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/crud/TruncateTest.scala new file mode 100644 index 000000000..77c3c56ac --- /dev/null +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/crud/TruncateTest.scala @@ -0,0 +1,59 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.builder.query.db.crud + +import com.outworkers.phantom.PhantomSuite +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.tables._ +import com.outworkers.util.testing._ + +class TruncateTest extends PhantomSuite { + + override def beforeAll(): Unit = { + super.beforeAll() + TestDatabase.articles.insertSchema() + } + + it should "truncate all records in a table" in { + val article1 = gen[Article] + val article2 = gen[Article] + val article3 = gen[Article] + val article4 = gen[Article] + + val result = for { + truncateBefore <- TestDatabase.articles.truncate.future() + i1 <- TestDatabase.articles.store(article1).future() + i2 <- TestDatabase.articles.store(article2).future() + i3 <- TestDatabase.articles.store(article3).future() + i4 <- TestDatabase.articles.store(article4).future() + + records <- TestDatabase.articles.select.fetch + truncate <- TestDatabase.articles.truncate.future() + records1 <- TestDatabase.articles.select.fetch + } yield (records, records1) + + + result successful { + case (init, updated) => { + init should have size 4 + info (s"inserted exactly ${init.size} records") + + updated should have size 0 + info (s"got exactly ${updated.size} records") + } + } + } +} diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/crud/UpdateQueryTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/crud/UpdateQueryTest.scala similarity index 86% rename from phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/crud/UpdateQueryTest.scala rename to phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/crud/UpdateQueryTest.scala index c678d001f..429a035d7 100644 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/crud/UpdateQueryTest.scala +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/crud/UpdateQueryTest.scala @@ -1,44 +1,30 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.query.db.crud +package com.outworkers.phantom.builder.query.db.crud -import com.websudos.phantom.PhantomSuite -import com.websudos.phantom.dsl._ -import com.websudos.phantom.tables._ +import com.outworkers.phantom.PhantomSuite +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.tables._ import com.outworkers.util.testing._ -import com.websudos.phantom.builder.QueryBuilder +import com.outworkers.phantom.builder.QueryBuilder import org.joda.time.{DateTime, DateTimeZone} -import org.scalatest.concurrent.AsyncAssertions +import org.scalatest.concurrent.{AsyncAssertions, Waiters} import org.scalatest.{Assertions, Inside, Matchers} -class UpdateQueryTest extends PhantomSuite with Matchers with Assertions with AsyncAssertions with Inside { +class UpdateQueryTest extends PhantomSuite with Matchers with Assertions with Waiters with Inside { override def beforeAll(): Unit = { super.beforeAll() diff --git a/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/ordering/OrderByTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/ordering/OrderByTest.scala new file mode 100644 index 000000000..75187871c --- /dev/null +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/ordering/OrderByTest.scala @@ -0,0 +1,75 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.builder.query.db.ordering + +import java.util.UUID + +import com.datastax.driver.core.utils.UUIDs +import com.outworkers.phantom.PhantomSuite +import com.outworkers.phantom.tables.{TestDatabase, TimeUUIDRecord} +import com.outworkers.util.testing._ +import com.outworkers.phantom.dsl._ + +import scala.concurrent.Future + +class OrderByTest extends PhantomSuite { + + override def beforeAll(): Unit = { + super.beforeAll() + database.timeuuidTable.insertSchema() + } + + it should "store a series of records and retrieve them in the right order" in { + + val user = gen[UUID] + + info(s"Generating a list of records with the same partition key value: $user") + val records = genList[TimeUUIDRecord]().map(_.copy(user = user)) + + val chain = for { + store <- Future.sequence(records.map(database.timeuuidTable.store(_).future())) + get <- database.timeuuidTable.retrieve(user) + desc <- database.timeuuidTable.retrieveDescending(user) + } yield (get, desc) + + + whenReady(chain) { + case (asc, desc) => { + val orderedAsc = records.sortWith((a, b) => { a.id.compareTo(b.id) <= 0 }) + + info("The ascending results retrieved from the DB") + info(asc.mkString("\n")) + + info("The ascending results expected") + info(orderedAsc.mkString("\n")) + + asc shouldEqual orderedAsc + + val orderedDesc = records.sortWith((a, b) => { a.id.compareTo(b.id) >= 0 }) + + info("The ascending results retrieved from the DB") + info(desc.mkString("\n")) + + info("The ascending results expected") + info(orderedDesc.mkString("\n")) + + desc shouldEqual orderedDesc + + } + } + } + +} diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/ordering/TimeSeriesTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/ordering/TimeSeriesTest.scala similarity index 70% rename from phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/ordering/TimeSeriesTest.scala rename to phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/ordering/TimeSeriesTest.scala index 58132e74d..0398b46b7 100644 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/ordering/TimeSeriesTest.scala +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/ordering/TimeSeriesTest.scala @@ -1,42 +1,28 @@ /* - * Copyright 2013-2016 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.query.db.ordering +package com.outworkers.phantom.builder.query.db.ordering import com.datastax.driver.core.Session +import com.outworkers.phantom.PhantomSuite import com.twitter.util.{Future => TwitterFuture} -import com.websudos.phantom.PhantomSuite -import com.websudos.phantom.builder.query.db.ordering.TimeSeriesTest._ -import com.websudos.phantom.builder.query.prepared._ -import com.websudos.phantom.connectors.KeySpace -import com.websudos.phantom.dsl._ -import com.websudos.phantom.tables._ +import com.outworkers.phantom.builder.query.db.ordering.TimeSeriesTest._ +import com.outworkers.phantom.builder.query.prepared._ +import com.outworkers.phantom.connectors.KeySpace +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.tables._ import com.outworkers.util.testing._ import scala.concurrent.{Future => ScalaFuture} diff --git a/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/select/PartialSelectTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/select/PartialSelectTest.scala new file mode 100644 index 000000000..4f3a9e679 --- /dev/null +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/select/PartialSelectTest.scala @@ -0,0 +1,48 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.builder.query.db.select + +import com.outworkers.phantom.PhantomSuite +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.tables._ +import com.outworkers.util.testing._ + + +class PartialSelectTest extends PhantomSuite { + + override def beforeAll(): Unit = { + super.beforeAll() + TestDatabase.primitives.insertSchema() + } + + "Partially selecting 2 fields" should "correctly select the fields" in { + val row = gen[Primitive] + + val chain = for { + truncate <- TestDatabase.primitives.truncate.future() + insertDone <- TestDatabase.primitives.store(row).future() + listSelect <- TestDatabase.primitives.select(_.pkey).fetch + oneSelect <- TestDatabase.primitives.select(_.long, _.boolean).where(_.pkey eqs row.pkey).one + } yield (listSelect, oneSelect) + + chain successful { + case (res, res2) => { + res shouldEqual List(row.pkey) + res2.value shouldEqual Tuple2(row.long, row.boolean) + } + } + } +} diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/specialized/ConditionalQueriesTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/specialized/ConditionalQueriesTest.scala similarity index 84% rename from phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/specialized/ConditionalQueriesTest.scala rename to phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/specialized/ConditionalQueriesTest.scala index 7f1d96394..df239389a 100644 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/specialized/ConditionalQueriesTest.scala +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/specialized/ConditionalQueriesTest.scala @@ -1,38 +1,25 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.query.db.specialized +package com.outworkers.phantom.builder.query.db.specialized -import com.websudos.phantom.PhantomSuite -import com.websudos.phantom.dsl._ -import com.websudos.phantom.tables.{ Recipe, TestDatabase } +import com.outworkers.phantom.PhantomSuite +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.tables.{Recipe, TestDatabase} import com.outworkers.util.testing._ + import scala.concurrent.duration._ class ConditionalQueriesTest extends PhantomSuite { diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/specialized/ConsistencyLevelTests.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/specialized/ConsistencyLevelTests.scala similarity index 63% rename from phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/specialized/ConsistencyLevelTests.scala rename to phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/specialized/ConsistencyLevelTests.scala index 6894ebd1f..701ee6aea 100644 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/specialized/ConsistencyLevelTests.scala +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/specialized/ConsistencyLevelTests.scala @@ -1,37 +1,23 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.query.db.specialized +package com.outworkers.phantom.builder.query.db.specialized -import com.websudos.phantom.PhantomSuite -import com.websudos.phantom.dsl._ -import com.websudos.phantom.tables.{Primitive, TestDatabase} +import com.outworkers.phantom.PhantomSuite +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.tables.{Primitive, TestDatabase} import com.outworkers.util.testing._ class ConsistencyLevelTests extends PhantomSuite { diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/specialized/CounterColumnTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/specialized/CounterColumnTest.scala similarity index 69% rename from phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/specialized/CounterColumnTest.scala rename to phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/specialized/CounterColumnTest.scala index c7a239d71..8baa481ce 100644 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/specialized/CounterColumnTest.scala +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/specialized/CounterColumnTest.scala @@ -1,40 +1,25 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.query.db.specialized +package com.outworkers.phantom.builder.query.db.specialized -import com.websudos.phantom.PhantomSuite +import com.outworkers.phantom.PhantomSuite import org.scalatest.concurrent.PatienceConfiguration import org.scalatest.time.SpanSugar._ - -import com.websudos.phantom.dsl._ -import com.websudos.phantom.tables._ +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.tables._ import com.outworkers.util.testing._ class CounterColumnTest extends PhantomSuite { diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/specialized/EnumColumnTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/specialized/EnumColumnTest.scala similarity index 65% rename from phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/specialized/EnumColumnTest.scala rename to phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/specialized/EnumColumnTest.scala index 50f24e83d..9c728677e 100644 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/specialized/EnumColumnTest.scala +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/specialized/EnumColumnTest.scala @@ -1,38 +1,24 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.query.db.specialized +package com.outworkers.phantom.builder.query.db.specialized import com.datastax.driver.core.utils.UUIDs -import com.websudos.phantom.PhantomSuite -import com.websudos.phantom.dsl._ -import com.websudos.phantom.tables._ +import com.outworkers.phantom.PhantomSuite +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.tables._ import scala.concurrent.Await diff --git a/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/specialized/InOperatorTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/specialized/InOperatorTest.scala new file mode 100644 index 000000000..a52e827a4 --- /dev/null +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/specialized/InOperatorTest.scala @@ -0,0 +1,60 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.builder.query.db.specialized + +import com.outworkers.phantom.PhantomSuite +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.tables.{Recipe, TestDatabase} +import com.outworkers.util.testing._ + +class InOperatorTest extends PhantomSuite { + + override def beforeAll(): Unit = { + super.beforeAll() + TestDatabase.recipes.insertSchema() + } + + it should "find a record with a in operator if the record exists" in { + val recipe = gen[Recipe] + + val chain = for { + done <- TestDatabase.recipes.store(recipe).future() + select <- TestDatabase.recipes.select.where(_.url in List(recipe.url, gen[EmailAddress].value)).one() + } yield select + + chain.successful { + res => { + res.value.url shouldEqual recipe.url + } + } + } + + it should "not find a record with a in operator if the record doesn't exists" in { + val recipe = gen[Recipe] + + val chain = for { + done <- TestDatabase.recipes.store(recipe).future() + select <- TestDatabase.recipes.select.where(_.url in List(gen[EmailAddress].value)).one() + } yield select + + chain.successful { + res => { + res shouldBe empty + } + } + } + +} diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/specialized/IndexedCollectionsTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/specialized/IndexedCollectionsTest.scala similarity index 64% rename from phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/specialized/IndexedCollectionsTest.scala rename to phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/specialized/IndexedCollectionsTest.scala index b58c64ecf..64f81fdaa 100644 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/specialized/IndexedCollectionsTest.scala +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/specialized/IndexedCollectionsTest.scala @@ -1,38 +1,24 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.query.db.specialized +package com.outworkers.phantom.builder.query.db.specialized import com.datastax.driver.core.exceptions.{InvalidQueryException, SyntaxError} -import com.websudos.phantom.PhantomSuite -import com.websudos.phantom.dsl._ -import com.websudos.phantom.tables.{TestDatabase, TestRow} +import com.outworkers.phantom.PhantomSuite +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.tables.{TestDatabase, TestRow} import com.outworkers.util.testing._ class IndexedCollectionsTest extends PhantomSuite { diff --git a/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/specialized/JodaDateTimeColumnTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/specialized/JodaDateTimeColumnTest.scala new file mode 100644 index 000000000..acf76c4e4 --- /dev/null +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/specialized/JodaDateTimeColumnTest.scala @@ -0,0 +1,46 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.builder.query.db.specialized + +import com.outworkers.phantom.PhantomSuite +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.tables._ +import com.outworkers.util.testing._ + +class JodaDateTimeColumnTest extends PhantomSuite { + + override def beforeAll(): Unit = { + super.beforeAll() + database.primitivesJoda.insertSchema() + } + + it should "correctly insert and extract a JodaTime date" in { + val row = gen[JodaRow] + + val chain = for { + store <- TestDatabase.primitivesJoda.store(row).future() + select <- TestDatabase.primitivesJoda.select.where(_.pkey eqs row.pkey).one() + } yield select + + chain successful { + res => { + res.value.pkey shouldEqual row.pkey + res.value.intColumn shouldEqual row.intColumn + res.value.timestamp shouldEqual row.timestamp + } + } + } +} diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/specialized/JsonColumnTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/specialized/JsonColumnTest.scala similarity index 61% rename from phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/specialized/JsonColumnTest.scala rename to phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/specialized/JsonColumnTest.scala index 067063266..18acda8f3 100644 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/specialized/JsonColumnTest.scala +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/specialized/JsonColumnTest.scala @@ -1,38 +1,23 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ +package com.outworkers.phantom.builder.query.db.specialized -package com.websudos.phantom.builder.query.db.specialized - -import com.websudos.phantom.PhantomSuite -import com.websudos.phantom.dsl._ -import com.websudos.phantom.tables._ +import com.outworkers.phantom.PhantomSuite +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.tables._ import com.outworkers.util.testing._ class JsonColumnTest extends PhantomSuite { diff --git a/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/specialized/OptionalIndexesTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/specialized/OptionalIndexesTest.scala new file mode 100644 index 000000000..fa7fdb0da --- /dev/null +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/specialized/OptionalIndexesTest.scala @@ -0,0 +1,70 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.builder.query.db.specialized + +import com.datastax.driver.core.exceptions.InvalidQueryException +import com.outworkers.phantom.PhantomSuite +import com.outworkers.phantom.tables.OptionalSecondaryRecord +import com.outworkers.phantom.dsl._ +import com.outworkers.util.testing._ + +class OptionalIndexesTest extends PhantomSuite { + + override def beforeAll(): Unit = { + super.beforeAll() + database.optionalIndexesTable.insertSchema() + } + + it should "store a record and then retrieve it using an optional index" in { + val sample = OptionalSecondaryRecord( + gen[UUID], + genOpt[Int] + ) + + val chain = for { + store <- database.optionalIndexesTable.store(sample) + get <- database.optionalIndexesTable.findById(sample.id) + get2 <- database.optionalIndexesTable.findByOptionalSecondary(sample.secondary.value) + } yield (get, get2) + + whenReady(chain) { + case (byId, byIndex) => { + byId shouldBe defined + byId.value shouldEqual sample + + byIndex shouldBe defined + byIndex.value shouldEqual sample + } + } + } + + it should "not be able to delete records by their secondary index" in { + val sample = OptionalSecondaryRecord( + gen[UUID], + genOpt[Int] + ) + + val chain = for { + store <- database.optionalIndexesTable.store(sample) + get <- database.optionalIndexesTable.findByOptionalSecondary(sample.secondary.value) + delete <- database.optionalIndexesTable.delete.where(_.secondary eqs sample.secondary.value).future() + get2 <- database.optionalIndexesTable.findByOptionalSecondary(sample.secondary.value) + } yield (get, get2) + + chain.failing[InvalidQueryException] + } + +} diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/specialized/SecondaryIndexTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/specialized/SecondaryIndexTest.scala similarity index 69% rename from phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/specialized/SecondaryIndexTest.scala rename to phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/specialized/SecondaryIndexTest.scala index 07f5fa6e0..b0edf5df8 100644 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/specialized/SecondaryIndexTest.scala +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/specialized/SecondaryIndexTest.scala @@ -1,38 +1,24 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.query.db.specialized +package com.outworkers.phantom.builder.query.db.specialized import com.datastax.driver.core.exceptions.InvalidQueryException -import com.websudos.phantom.PhantomSuite -import com.websudos.phantom.dsl._ -import com.websudos.phantom.tables._ +import com.outworkers.phantom.PhantomSuite +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.tables._ import com.outworkers.util.testing._ class SecondaryIndexTest extends PhantomSuite { diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/specialized/SelectFunctionsTesting.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/specialized/SelectFunctionsTesting.scala similarity index 59% rename from phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/specialized/SelectFunctionsTesting.scala rename to phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/specialized/SelectFunctionsTesting.scala index fbb0899cb..a63182e44 100644 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/specialized/SelectFunctionsTesting.scala +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/specialized/SelectFunctionsTesting.scala @@ -1,37 +1,23 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.query.db.specialized +package com.outworkers.phantom.builder.query.db.specialized -import com.websudos.phantom.PhantomSuite -import com.websudos.phantom.tables.{TimeUUIDRecord, Recipe} -import com.websudos.phantom.dsl._ +import com.outworkers.phantom.PhantomSuite +import com.outworkers.phantom.tables.{Recipe, TimeUUIDRecord} +import com.outworkers.phantom.dsl._ import com.outworkers.util.testing._ import com.twitter.conversions.time._ diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/specialized/StaticColumnTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/specialized/StaticColumnTest.scala similarity index 63% rename from phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/specialized/StaticColumnTest.scala rename to phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/specialized/StaticColumnTest.scala index a3567034c..76b710475 100644 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/specialized/StaticColumnTest.scala +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/specialized/StaticColumnTest.scala @@ -1,38 +1,24 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.query.db.specialized +package com.outworkers.phantom.builder.query.db.specialized import com.datastax.driver.core.utils.UUIDs -import com.websudos.phantom.PhantomSuite -import com.websudos.phantom.dsl._ -import com.websudos.phantom.tables.StaticCollectionRecord +import com.outworkers.phantom.PhantomSuite +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.tables.StaticCollectionRecord import com.outworkers.util.testing._ class StaticColumnTest extends PhantomSuite { diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/specialized/TimeUuidTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/specialized/TimeUuidTest.scala similarity index 69% rename from phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/specialized/TimeUuidTest.scala rename to phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/specialized/TimeUuidTest.scala index 17a23cf9a..257f89476 100644 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/specialized/TimeUuidTest.scala +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/specialized/TimeUuidTest.scala @@ -1,40 +1,26 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.query.db.specialized +package com.outworkers.phantom.builder.query.db.specialized import com.datastax.driver.core.utils.UUIDs -import com.websudos.phantom.{PhantomSuite, dsl} -import com.websudos.phantom.tables.{TestDatabase, TimeUUIDRecord} +import com.outworkers.phantom.PhantomSuite +import com.outworkers.phantom.tables.{TestDatabase, TimeUUIDRecord} import org.joda.time.{DateTime, DateTimeZone} import com.outworkers.util.testing._ -import com.websudos.phantom.dsl._ +import com.outworkers.phantom.dsl._ class TimeUuidTest extends PhantomSuite { @@ -58,6 +44,18 @@ class TimeUuidTest extends PhantomSuite { new DateTime(UUIDs.unixTimestamp(id), DateTimeZone.UTC) ) + /** + * Cassandra sometimes skews the timestamp of this date by exactly 1 milliseconds + * for reasons beyond our understanding, which means the test is flaky unless this + * list is added to make sure at least one of t, t minus 1 millisecond, or t plus 1 millisecond + * is found in the expected list of records. + */ + val recordList = List( + record, + record.copy(timestamp = record.timestamp.plusMillis(1)), + record.copy(timestamp = record.timestamp.plusMillis(-1)) + ) + val minuteOffset = start.plusMinutes(-1).timeuuid() val secondOffset = start.plusSeconds(-15).timeuuid() @@ -96,7 +94,8 @@ class TimeUuidTest extends PhantomSuite { whenReady(chain) { case (res, res2) => { - res should contain(record) + info("At least one timestamp value, including potential time skewes, should be included here") + recordList exists(res contains) shouldEqual true info("Should not contain record with a timestamp 1 minute before the selection window") res should not contain record1 diff --git a/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/specialized/TupleColumnTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/specialized/TupleColumnTest.scala new file mode 100644 index 000000000..61f5c7812 --- /dev/null +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/db/specialized/TupleColumnTest.scala @@ -0,0 +1,161 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.builder.query.db.specialized + +import com.outworkers.phantom.PhantomSuite +import com.outworkers.phantom.tables.{NestedTupleRecord, TupleCollectionRecord, TupleRecord} +import com.outworkers.util.testing._ +import com.outworkers.phantom.dsl._ + +class TupleColumnTest extends PhantomSuite { + override def beforeAll(): Unit = { + super.beforeAll() + database.tuple2Table.insertSchema() + database.nestedTupleTable.insertSchema() + database.tupleCollectionsTable.insertSchema() + } + + it should "store and retrieve a record with a tuple column" in { + val sample = gen[TupleRecord] + + val insert = database.tuple2Table.store(sample) + + val chain = for { + store <- insert.future() + rec <- database.tuple2Table.findById(sample.id) + } yield rec + + whenReady(chain) { + res => { + res shouldBe defined + res.value shouldEqual sample + } + } + } + + it should "update the value of a tuple column" in { + val sample = gen[TupleRecord] + val sample2 = gen[TupleRecord].copy(id = sample.id) + + val insert = database.tuple2Table.store(sample) + + val chain = for { + store <- insert.future() + rec <- database.tuple2Table.findById(sample.id) + update <- database.tuple2Table.update.where(_.id eqs sample.id).modify(_.tp setTo sample2.tp).future() + rec2 <- database.tuple2Table.findById(sample.id) + } yield (rec, rec2) + + whenReady(chain) { + case (beforeUpdate, afterUpdate) => { + beforeUpdate shouldBe defined + beforeUpdate.value shouldEqual sample + + afterUpdate shouldBe defined + afterUpdate.value.tp shouldEqual sample2.tp + } + } + } + + it should "store and retrieve a record with a nested tuple column" in { + val sample = gen[NestedTupleRecord] + + val insert = database.nestedTupleTable.store(sample) + + val chain = for { + store <- insert.future() + rec <- database.nestedTupleTable.findById(sample.id) + } yield rec + + whenReady(chain) { + res => { + res shouldBe defined + res.value shouldEqual sample + } + } + } + + it should "update the value of a nested tuple column" in { + val sample = gen[NestedTupleRecord] + val sample2 = gen[NestedTupleRecord].copy(id = sample.id) + + val insert = database.nestedTupleTable.store(sample) + + val chain = for { + store <- insert.future() + rec <- database.nestedTupleTable.findById(sample.id) + update <- database.nestedTupleTable.update.where(_.id eqs sample.id).modify(_.tp setTo sample2.tp).future() + rec2 <- database.nestedTupleTable.findById(sample.id) + } yield (rec, rec2) + + whenReady(chain) { + case (beforeUpdate, afterUpdate) => { + beforeUpdate shouldBe defined + beforeUpdate.value shouldEqual sample + + afterUpdate shouldBe defined + afterUpdate.value.tp shouldEqual sample2.tp + } + } + } + + + it should "store and retrieve a record with a collection tuple column" in { + val sample = gen[TupleCollectionRecord] + + val insert = database.tupleCollectionsTable.store(sample) + + val chain = for { + store <- insert.future() + rec <- database.tupleCollectionsTable.findById(sample.id) + } yield rec + + whenReady(chain) { + res => { + res shouldBe defined + res.value.id shouldEqual sample.id + res.value.tuples should contain theSameElementsAs sample.tuples + } + } + } + + it should "update the value of a collection tuple column" in { + val sample = gen[TupleCollectionRecord] + + val appended = gen[Int] -> gen[String] + + val insert = database.tupleCollectionsTable.store(sample) + + val chain = for { + store <- insert.future() + rec <- database.tupleCollectionsTable.findById(sample.id) + update <- database.tupleCollectionsTable.update.where(_.id eqs sample.id).modify(_.tuples append appended).future() + rec2 <- database.tupleCollectionsTable.findById(sample.id) + } yield (rec, rec2) + + whenReady(chain) { + case (beforeUpdate, afterUpdate) => { + + beforeUpdate shouldBe defined + beforeUpdate.value.id shouldEqual sample.id + beforeUpdate.value.tuples should contain theSameElementsAs sample.tuples + + afterUpdate shouldBe defined + afterUpdate.value.tuples should contain (appended) + } + } + } +} diff --git a/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/prepared/BatchablePreparedInsertQueryTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/prepared/BatchablePreparedInsertQueryTest.scala new file mode 100644 index 000000000..d7af836f8 --- /dev/null +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/prepared/BatchablePreparedInsertQueryTest.scala @@ -0,0 +1,69 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.builder.query.prepared + +import com.outworkers.phantom.PhantomSuite +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.tables.{Recipe, TestDatabase} +import com.outworkers.util.testing._ + +class BatchablePreparedInsertQueryTest extends PhantomSuite { + + override def beforeAll(): Unit = { + super.beforeAll() + TestDatabase.recipes.insertSchema() + } + + it should "serialize an prepared batch query" in { + val sample1 = gen[Recipe] + val sample2 = gen[Recipe] + + val query = TestDatabase.recipes.insert + .p_value(_.uid, ?) + .p_value(_.url, ?) + .p_value(_.servings, ?) + .p_value(_.ingredients, ?) + .p_value(_.description, ?) + .p_value(_.lastcheckedat, ?) + .p_value(_.props, ?) + .prepare() + + def bind(recipe: Recipe): ExecutablePreparedQuery = query.bind( + recipe.uid, + recipe.url, + recipe.servings, + recipe.ingredients, + recipe.description, + recipe.lastCheckedAt, + recipe.props + ) + + val exec1 = bind(sample1) + val exec2 = bind(sample2) + + val chain = for { + truncate <- TestDatabase.recipes.truncate.future() + store <- Batch.unlogged.add(exec1, exec2).future() + get <- TestDatabase.recipes.select.fetch() + } yield get + + whenReady(chain) { + res => { + res should contain theSameElementsAs Seq(sample1, sample2) + } + } + } +} diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/prepared/PreparedDeleteQueryTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/prepared/PreparedDeleteQueryTest.scala similarity index 52% rename from phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/prepared/PreparedDeleteQueryTest.scala rename to phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/prepared/PreparedDeleteQueryTest.scala index d04622900..79649a3a5 100644 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/prepared/PreparedDeleteQueryTest.scala +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/prepared/PreparedDeleteQueryTest.scala @@ -1,37 +1,23 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.query.prepared +package com.outworkers.phantom.builder.query.prepared -import com.websudos.phantom.PhantomSuite -import com.websudos.phantom.tables.{Article, Recipe} -import com.websudos.phantom.dsl._ +import com.outworkers.phantom.PhantomSuite +import com.outworkers.phantom.tables.{Article, Recipe} +import com.outworkers.phantom.dsl._ import com.outworkers.util.testing._ class PreparedDeleteQueryTest extends PhantomSuite { diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/prepared/PreparedInsertQueryTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/prepared/PreparedInsertQueryTest.scala similarity index 72% rename from phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/prepared/PreparedInsertQueryTest.scala rename to phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/prepared/PreparedInsertQueryTest.scala index 7d8597fea..8102745c9 100644 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/prepared/PreparedInsertQueryTest.scala +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/prepared/PreparedInsertQueryTest.scala @@ -1,39 +1,25 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.query.prepared +package com.outworkers.phantom.builder.query.prepared import com.datastax.driver.core.{BoundStatement, PreparedStatement} -import com.websudos.phantom.PhantomSuite -import com.websudos.phantom.codec.JodaLocalDateCodec -import com.websudos.phantom.dsl._ -import com.websudos.phantom.tables.{Primitive, PrimitiveCassandra22, Recipe, TestDatabase} +import com.outworkers.phantom.PhantomSuite +import com.outworkers.phantom.codec.JodaLocalDateCodec +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.tables.{Primitive, PrimitiveCassandra22, Recipe, TestDatabase} import com.outworkers.util.testing._ class PreparedInsertQueryTest extends PhantomSuite { diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/prepared/PreparedSelectQueryTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/prepared/PreparedSelectQueryTest.scala similarity index 70% rename from phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/prepared/PreparedSelectQueryTest.scala rename to phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/prepared/PreparedSelectQueryTest.scala index b1390f3a1..6659a6991 100644 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/prepared/PreparedSelectQueryTest.scala +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/prepared/PreparedSelectQueryTest.scala @@ -1,37 +1,23 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.query.prepared +package com.outworkers.phantom.builder.query.prepared -import com.websudos.phantom.PhantomSuite -import com.websudos.phantom.dsl._ -import com.websudos.phantom.tables._ +import com.outworkers.phantom.PhantomSuite +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.tables._ import com.outworkers.util.testing._ class PreparedSelectQueryTest extends PhantomSuite { diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/prepared/PreparedUpdateQueryTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/prepared/PreparedUpdateQueryTest.scala similarity index 61% rename from phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/prepared/PreparedUpdateQueryTest.scala rename to phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/prepared/PreparedUpdateQueryTest.scala index adebeac50..75f9d866c 100644 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/prepared/PreparedUpdateQueryTest.scala +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/query/prepared/PreparedUpdateQueryTest.scala @@ -1,37 +1,23 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.query.prepared +package com.outworkers.phantom.builder.query.prepared -import com.websudos.phantom.PhantomSuite -import com.websudos.phantom.tables.Recipe -import com.websudos.phantom.dsl._ +import com.outworkers.phantom.PhantomSuite +import com.outworkers.phantom.tables.Recipe +import com.outworkers.phantom.dsl._ import com.outworkers.util.testing._ class PreparedUpdateQueryTest extends PhantomSuite { diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/serializers/AlterQueryBuilderTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/serializers/AlterQueryBuilderTest.scala similarity index 71% rename from phantom-dsl/src/test/scala/com/websudos/phantom/builder/serializers/AlterQueryBuilderTest.scala rename to phantom-dsl/src/test/scala/com/outworkers/phantom/builder/serializers/AlterQueryBuilderTest.scala index 9ce745f01..3d5722d3d 100644 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/serializers/AlterQueryBuilderTest.scala +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/serializers/AlterQueryBuilderTest.scala @@ -1,42 +1,28 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.serializers +package com.outworkers.phantom.builder.serializers import java.util.concurrent.TimeUnit import com.twitter.conversions.storage._ import com.twitter.util.{Duration => TwitterDuration} -import com.websudos.phantom.builder.query.QueryBuilderTest -import com.websudos.phantom.builder.syntax.CQLSyntax -import com.websudos.phantom.dsl._ -import com.websudos.phantom.tables.TestDatabase +import com.outworkers.phantom.builder.query.QueryBuilderTest +import com.outworkers.phantom.builder.syntax.CQLSyntax +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.tables.TestDatabase import org.joda.time.Seconds import scala.concurrent.duration._ @@ -101,14 +87,14 @@ class AlterQueryBuilderTest extends QueryBuilderTest { "serialise a simple create query with a SizeTieredCompactionStrategy and no compaction strategy options set" in { - val qb = BasicTable.alter.`with`(compaction eqs SizeTieredCompactionStrategy).qb.queryString + val qb = BasicTable.alter.option(compaction eqs SizeTieredCompactionStrategy).qb.queryString qb shouldEqual "ALTER TABLE phantom.basicTable WITH compaction = {'class': 'SizeTieredCompactionStrategy'}" } "serialise a simple create query with a SizeTieredCompactionStrategy and 1 compaction strategy options set" in { - val qb = BasicTable.alter.`with`(compaction eqs LeveledCompactionStrategy.sstable_size_in_mb(50)).qb.queryString + val qb = BasicTable.alter.option(compaction eqs LeveledCompactionStrategy.sstable_size_in_mb(50)).qb.queryString qb shouldEqual "ALTER TABLE phantom.basicTable WITH compaction = {'class': 'LeveledCompactionStrategy', 'sstable_size_in_mb': 50}" } @@ -116,7 +102,7 @@ class AlterQueryBuilderTest extends QueryBuilderTest { "serialise a simple create query with a SizeTieredCompactionStrategy and 1 compaction strategy options set and a compression strategy set" in { val qb = BasicTable.alter - .`with`(compaction eqs LeveledCompactionStrategy.sstable_size_in_mb(50)) + .option(compaction eqs LeveledCompactionStrategy.sstable_size_in_mb(50)) .and(compression eqs LZ4Compressor.crc_check_chance(0.5)) .qb.queryString @@ -125,44 +111,44 @@ class AlterQueryBuilderTest extends QueryBuilderTest { "add a comment option to a create query" in { val qb = BasicTable.alter - .`with`(comment eqs "testing") + .option(comment eqs "testing") .qb.queryString qb shouldEqual "ALTER TABLE phantom.basicTable WITH comment = 'testing'" } "allow specifying a read_repair_chance clause" in { - val qb = BasicTable.alter.`with`(read_repair_chance eqs 5D).qb.queryString + val qb = BasicTable.alter.option(read_repair_chance eqs 5D).qb.queryString qb shouldEqual "ALTER TABLE phantom.basicTable WITH read_repair_chance = 5.0" } "allow specifying a dclocal_read_repair_chance clause" in { - val qb = BasicTable.alter.`with`(dclocal_read_repair_chance eqs 5D).qb.queryString + val qb = BasicTable.alter.option(dclocal_read_repair_chance eqs 5D).qb.queryString qb shouldEqual "ALTER TABLE phantom.basicTable WITH dclocal_read_repair_chance = 5.0" } "allow specifying a replicate_on_write clause" in { - val qb = BasicTable.alter.`with`(replicate_on_write eqs true).qb.queryString + val qb = BasicTable.alter.option(replicate_on_write eqs true).qb.queryString qb shouldEqual "ALTER TABLE phantom.basicTable WITH replicate_on_write = true" } "allow specifying a custom gc_grace_seconds clause" in { - val qb = BasicTable.alter.`with`(gc_grace_seconds eqs 5.seconds).qb.queryString + val qb = BasicTable.alter.option(gc_grace_seconds eqs 5.seconds).qb.queryString qb shouldEqual "ALTER TABLE phantom.basicTable WITH gc_grace_seconds = 5" } "allow specifying larger custom units as gc_grace_seconds" in { - val qb = BasicTable.alter.`with`(gc_grace_seconds eqs 1.day).qb.queryString + val qb = BasicTable.alter.option(gc_grace_seconds eqs 1.day).qb.queryString qb shouldEqual "ALTER TABLE phantom.basicTable WITH gc_grace_seconds = 86400" } "allow specifying custom gc_grade_seconds using the Joda Time ReadableInstant and Second API" in { - val qb = BasicTable.alter.`with`(gc_grace_seconds eqs Seconds.seconds(OneDay)).qb.queryString + val qb = BasicTable.alter.option(gc_grace_seconds eqs Seconds.seconds(OneDay)).qb.queryString qb shouldEqual "ALTER TABLE phantom.basicTable WITH gc_grace_seconds = 86400" } "allow specifying a bloom_filter_fp_chance using a Double param value" in { - val qb = BasicTable.alter.`with`(bloom_filter_fp_chance eqs 5D).qb.queryString + val qb = BasicTable.alter.option(bloom_filter_fp_chance eqs 5D).qb.queryString qb shouldEqual "ALTER TABLE phantom.basicTable WITH " + "bloom_filter_fp_chance = 5.0" } @@ -170,7 +156,7 @@ class AlterQueryBuilderTest extends QueryBuilderTest { "should allow specifying cache strategies " - { "specify Cache.None as a cache strategy" in { - val qb = BasicTable.alter.`with`(caching eqs Cache.None()).qb.queryString + val qb = BasicTable.alter.option(caching eqs Cache.None()).qb.queryString if (session.v4orNewer) { qb shouldEqual "ALTER TABLE phantom.basicTable WITH caching = {'keys': 'none', 'rows_per_partition': 'none'}" @@ -180,7 +166,7 @@ class AlterQueryBuilderTest extends QueryBuilderTest { } "specify Cache.KeysOnly as a caching strategy" in { - val qb = BasicTable.alter.`with`(caching eqs Cache.KeysOnly()).qb.queryString + val qb = BasicTable.alter.option(caching eqs Cache.KeysOnly()).qb.queryString if (session.v4orNewer) { qb shouldEqual "ALTER TABLE phantom.basicTable WITH caching = {'keys': 'all', 'rows_per_partition': 'none'}" @@ -192,17 +178,17 @@ class AlterQueryBuilderTest extends QueryBuilderTest { "should allow specifying a default_time_to_live" - { "specify a default time to live using a Long value" in { - val qb = BasicTable.alter.`with`(default_time_to_live eqs DefaultTtl).qb.queryString + val qb = BasicTable.alter.option(default_time_to_live eqs DefaultTtl).qb.queryString qb shouldEqual "ALTER TABLE phantom.basicTable WITH default_time_to_live = 500" } "specify a default time to live using a org.joda.time.Seconds value" in { - val qb = BasicTable.alter.`with`(default_time_to_live eqs Seconds.seconds(DefaultTtl)).qb.queryString + val qb = BasicTable.alter.option(default_time_to_live eqs Seconds.seconds(DefaultTtl)).qb.queryString qb shouldEqual "ALTER TABLE phantom.basicTable WITH default_time_to_live = 500" } "specify a default time to live using a scala.concurrent.duration.FiniteDuration value" in { - val qb = BasicTable.alter.`with`(default_time_to_live eqs FiniteDuration(DefaultTtl, TimeUnit.SECONDS)).qb.queryString + val qb = BasicTable.alter.option(default_time_to_live eqs FiniteDuration(DefaultTtl, TimeUnit.SECONDS)).qb.queryString qb shouldEqual "ALTER TABLE phantom.basicTable WITH default_time_to_live = 500" } } diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/serializers/BasicQueryBuilderTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/serializers/BasicQueryBuilderTest.scala similarity index 51% rename from phantom-dsl/src/test/scala/com/websudos/phantom/builder/serializers/BasicQueryBuilderTest.scala rename to phantom-dsl/src/test/scala/com/outworkers/phantom/builder/serializers/BasicQueryBuilderTest.scala index 67bba7775..642b07a93 100644 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/serializers/BasicQueryBuilderTest.scala +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/serializers/BasicQueryBuilderTest.scala @@ -1,36 +1,22 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.serializers +package com.outworkers.phantom.builder.serializers -import com.websudos.phantom.builder.QueryBuilder -import com.websudos.phantom.builder.query.{CQLQuery, QueryBuilderTest} +import com.outworkers.phantom.builder.QueryBuilder +import com.outworkers.phantom.builder.query.{CQLQuery, QueryBuilderTest} class BasicQueryBuilderTest extends QueryBuilderTest { "The QueryBuilder should perform basic operations" - { diff --git a/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/serializers/CollectionModifiersSerialisationTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/serializers/CollectionModifiersSerialisationTest.scala new file mode 100644 index 000000000..6c73c3d4a --- /dev/null +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/serializers/CollectionModifiersSerialisationTest.scala @@ -0,0 +1,51 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.builder.serializers + +import com.outworkers.phantom.builder.QueryBuilder +import org.scalatest.{FreeSpec, Matchers} + +class CollectionModifiersSerialisationTest extends FreeSpec with Matchers { + + "The collection modifier query builder" - { + + "should append a pre-serialized list as a collection" in { + QueryBuilder.Collections.append("test", QueryBuilder.Collections.serialize(List("test1", "test2")).queryString) + .queryString shouldEqual "test = test + [test1, test2]" + } + + "should append a single element to a list collection" in { + QueryBuilder.Collections.append("test", "test1", "test2").queryString shouldEqual "test = test + [test1, test2]" + } + + "should append elements to a list collection" in { + QueryBuilder.Collections.append("test", "test1", "test2", "test3").queryString shouldEqual "test = test + [test1, test2, test3]" + } + + "should prepend a pre-serialized list as a collection" in { + QueryBuilder.Collections.prepend("test", QueryBuilder.Collections.serialize(List("test1", "test2")).queryString) + .queryString shouldEqual "test = [test1, test2] + test" + } + + "should prepend a single element to a list collection" in { + QueryBuilder.Collections.prepend("test", "test1", "test2").queryString shouldEqual "test = [test1, test2] + test" + } + + "should prepend multiple elements to a list collection" in { + QueryBuilder.Collections.prepend("test", "test1", "test2", "test3").queryString shouldEqual "test = [test1, test2, test3] + test" + } + } +} diff --git a/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/serializers/CreateQueryBuilderTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/serializers/CreateQueryBuilderTest.scala new file mode 100644 index 000000000..2af2a5a8c --- /dev/null +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/serializers/CreateQueryBuilderTest.scala @@ -0,0 +1,362 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.builder.serializers + +import java.util.concurrent.TimeUnit + +import com.twitter.conversions.storage._ +import com.twitter.util.{Duration => TwitterDuration} +import com.outworkers.phantom.builder.QueryBuilder +import com.outworkers.phantom.builder.query.SerializationTest +import com.outworkers.phantom.builder.syntax.CQLSyntax +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.tables.TestDatabase +import org.joda.time.Seconds +import org.scalatest.{FreeSpec, Matchers} + +import scala.concurrent.duration._ + +class CreateQueryBuilderTest extends FreeSpec with Matchers with SerializationTest { + + val BasicTable = TestDatabase.basicTable + final val DefaultTtl = 500 + final val OneDay = 86400 + + val root = BasicTable.create.qb.queryString + + "The CREATE query builder" - { + + "should correctly serialise primary key definitions" - { + "a simple single partition key definition" in { + val cols = List("test") + QueryBuilder.Create.primaryKey(cols).queryString shouldEqual "PRIMARY KEY (test)" + } + + "a single partition key and a primary key" in { + val partitions = List("test") + val primaries = List("test2") + QueryBuilder.Create.primaryKey(partitions, primaries).queryString shouldEqual "PRIMARY KEY (test, test2)" + } + + "a composite partition key" in { + val partitions = List("partition1", "partition2") + val primaries = List("primary1") + val key = QueryBuilder.Create.primaryKey(partitions, primaries).queryString + + key shouldEqual "PRIMARY KEY ((partition1, partition2), primary1)" + } + + "a compound primary key" in { + val partitions = List("partition1") + val primaries = List("primary1", "primary2") + val key = QueryBuilder.Create.primaryKey(partitions, primaries).queryString + + key shouldEqual "PRIMARY KEY (partition1, primary1, primary2)" + } + + "a composite and compound primary key" in { + val partitions = List("partition1", "partition2") + val primaries = List("primary1", "primary2") + val key = QueryBuilder.Create.primaryKey(partitions, primaries).queryString + + key shouldEqual "PRIMARY KEY ((partition1, partition2), primary1, primary2)" + } + + "a composite with clustering order" in { + val partitions = List("partition1", "partition2") + val primaries = List("primary1", "primary2") + val clustering = List("primary1 ASC", "primary2 ASC") + val key = QueryBuilder.Create.primaryKey(partitions, primaries, clustering).queryString + + key shouldEqual "PRIMARY KEY ((partition1, partition2), primary1, primary2) WITH CLUSTERING ORDER BY (primary1 ASC, primary2 ASC)" + } + } + + "should allow using DateTieredCompactionStrategy and its options" - { + "serialise a create query with a DateTieredCompactionStrategy" in { + val qb = BasicTable.create.`with`( + compaction eqs DateTieredCompactionStrategy + ).qb.queryString + + qb shouldEqual s"$root WITH compaction = {'class': 'DateTieredCompactionStrategy'}" + } + + "allow setting base_time_seconds" in { + val qb = BasicTable.create.`with`( + compaction eqs DateTieredCompactionStrategy.base_time_seconds(5L) + ).qb.queryString + + qb shouldEqual s"$root WITH compaction = {'class': 'DateTieredCompactionStrategy', 'base_time_seconds': 5}" + } + + "allow setting max_threshold" in { + val qb = BasicTable.create.`with`( + compaction eqs DateTieredCompactionStrategy.max_threshold(5) + ).qb.queryString + + qb shouldEqual s"$root WITH compaction = {'class': 'DateTieredCompactionStrategy', 'max_threshold': 5}" + } + + "allow setting min_threshold" in { + val qb = BasicTable.create.`with`( + compaction eqs DateTieredCompactionStrategy.min_threshold(5) + ).qb.queryString + + qb shouldEqual s"$root WITH compaction = {'class': 'DateTieredCompactionStrategy', 'min_threshold': 5}" + } + + "allow setting timestamp_resolution" in { + val qb = BasicTable.create.`with`( + compaction eqs DateTieredCompactionStrategy.timestamp_resolution(TimeUnit.MILLISECONDS) + ).qb.queryString + + qb shouldEqual s"$root WITH compaction = {'class': 'DateTieredCompactionStrategy', 'timestamp_resolution': 'MILLISECONDS'}" + } + } + + "should allow using TimeWindowCompactionStrategy and its options" - { + + "serialise a create query with a TimeWindowCompactionStrategy" in { + val qb = BasicTable.create.`with`(compaction eqs TimeWindowCompactionStrategy).qb.queryString + + qb shouldEqual s"$root WITH compaction = {'class': 'TimeWindowCompactionStrategy'}" + } + + "serialise a create query with a TimeWindowCompactionStrategy and an option set" in { + val qb = BasicTable.create.`with`(compaction eqs TimeWindowCompactionStrategy.compaction_window_unit(TimeUnit.DAYS) + ).qb.queryString + + qb shouldEqual s"$root WITH compaction = {'class': 'TimeWindowCompactionStrategy', 'compaction_window_unit': 'DAYS'}" + } + + "serialise a create query with a TimeWindowCompactionStrategy and two options set" in { + val qb = BasicTable.create.`with`(compaction eqs TimeWindowCompactionStrategy + .compaction_window_unit(TimeUnit.DAYS) + .compaction_window_size(5) + ).qb.queryString + + qb shouldEqual s"$root WITH compaction = {'class'" + + ": 'TimeWindowCompactionStrategy', 'compaction_window_unit': 'DAYS', 'compaction_window_size': 5}" + } + + "serialise a create query with a TimeWindowCompactionStrategy and three options set" in { + val qb = BasicTable.create.`with`(compaction eqs TimeWindowCompactionStrategy + .compaction_window_unit(TimeUnit.DAYS) + .compaction_window_size(5) + .timestamp_resolution(TimeUnit.MILLISECONDS) + ).qb.queryString + + qb shouldEqual s"$root WITH compaction = {'class'" + + ": 'TimeWindowCompactionStrategy', 'compaction_window_unit': 'DAYS', 'compaction_window_size': 5, 'timestamp_resolution': 'MILLISECONDS'}" + } + } + + "should allow specifying table creation options" - { + + "serialise a simple create query with a SizeTieredCompactionStrategy and no compaction strategy options set" in { + + val qb = BasicTable.create.`with`(compaction eqs SizeTieredCompactionStrategy).qb.queryString + + qb shouldEqual s"$root WITH compaction = {'class': 'SizeTieredCompactionStrategy'}" + } + + "serialise a create query with a TimeWindowCompactionStrategy" in { + val qb = BasicTable.create.`with`(compaction eqs TimeWindowCompactionStrategy).qb.queryString + + qb shouldEqual s"$root WITH compaction = {'class': 'TimeWindowCompactionStrategy'}" + } + + "serialise a create query with a TimeWindowCompactionStrategy and an option set" in { + val qb = BasicTable.create.`with`(compaction eqs TimeWindowCompactionStrategy.compaction_window_unit(TimeUnit.DAYS) + ).qb.queryString + + qb shouldEqual s"$root WITH compaction = {'class': 'TimeWindowCompactionStrategy', 'compaction_window_unit': 'DAYS'}" + } + + + "serialise a create query with a TimeWindowCompactionStrategy and both options set" in { + val qb = BasicTable.create.`with`(compaction eqs TimeWindowCompactionStrategy + .compaction_window_unit(TimeUnit.DAYS) + .compaction_window_size(5) + ).qb.queryString + + qb shouldEqual s"$root WITH compaction = {'class': 'TimeWindowCompactionStrategy', 'compaction_window_unit': 'DAYS', 'compaction_window_size': 5}" + } + + "serialise a simple create query with a SizeTieredCompactionStrategy and 1 compaction strategy options set" in { + + val qb = BasicTable.create.`with`(compaction eqs LeveledCompactionStrategy.sstable_size_in_mb(50)).qb.queryString + + qb shouldEqual "CREATE TABLE phantom.basicTable (id uuid, id2 uuid, id3 uuid, placeholder text, PRIMARY KEY (id, id2, id3)) WITH compaction = {'class': 'LeveledCompactionStrategy', 'sstable_size_in_mb': 50}" + } + + "serialise a simple create query with a SizeTieredCompactionStrategy and 1 compaction strategy options set and a compression strategy set" in { + val qb = BasicTable.create + .`with`(compaction eqs LeveledCompactionStrategy.sstable_size_in_mb(50)) + .and(compression eqs LZ4Compressor.crc_check_chance(0.5)) + .qb.queryString + + qb shouldEqual s"""$root WITH compaction = {'class': 'LeveledCompactionStrategy', 'sstable_size_in_mb': 50} AND compression = {'sstable_compression': 'LZ4Compressor', 'crc_check_chance': 0.5}""" + } + + "add a comment option to a create query" in { + val qb = BasicTable.create + .`with`(comment eqs "testing") + .qb.queryString + + qb shouldEqual s"$root WITH comment = 'testing'" + } + + "allow specifying a read_repair_chance clause" in { + val qb = BasicTable.create.`with`(read_repair_chance eqs 5D).qb.queryString + qb shouldEqual s"$root WITH read_repair_chance = 5.0" + } + + "allow specifying a dclocal_read_repair_chance clause" in { + val qb = BasicTable.create.`with`(dclocal_read_repair_chance eqs 5D).qb.queryString + qb shouldEqual s"$root WITH dclocal_read_repair_chance = 5.0" + } + + "allow specifying a replicate_on_write clause" in { + val qb = BasicTable.create.`with`(replicate_on_write eqs true).qb.queryString + qb shouldEqual s"$root WITH replicate_on_write = true" + } + + "allow specifying a custom gc_grace_seconds clause" in { + val qb = BasicTable.create.`with`(gc_grace_seconds eqs 5.seconds).qb.queryString + qb shouldEqual s"$root WITH gc_grace_seconds = 5" + } + + "allow specifying larger custom units as gc_grace_seconds" in { + val qb = BasicTable.create.`with`(gc_grace_seconds eqs 1.day).qb.queryString + qb shouldEqual s"$root WITH gc_grace_seconds = 86400" + } + + "allow specifying custom gc_grade_seconds using the Joda Time ReadableInstant and Second API" in { + val qb = BasicTable.create.`with`(gc_grace_seconds eqs Seconds.seconds(OneDay)).qb.queryString + qb shouldEqual s"$root WITH gc_grace_seconds = 86400" + } + + "allow specifying a bloom_filter_fp_chance using a Double param value" in { + val qb = BasicTable.create.`with`(bloom_filter_fp_chance eqs 5D).qb.queryString + qb shouldEqual s"$root WITH bloom_filter_fp_chance = 5.0" + } + } + + "should allow specifying cache strategies " - { + "specify Cache.None as a cache strategy" in { + val qb = BasicTable.create.`with`(caching eqs Cache.None()).qb.queryString + + if (session.v4orNewer) { + qb shouldEqual s"$root WITH caching = {'keys': 'none', 'rows_per_partition': 'none'}" + } else { + qb shouldEqual s"$root WITH caching = 'none'" + } + } + + "specify Cache.KeysOnly as a caching strategy" in { + val qb = BasicTable.create.`with`(caching eqs Cache.KeysOnly()).qb.queryString + + if (session.v4orNewer) { + qb shouldEqual s"$root WITH caching = {'keys': 'all', 'rows_per_partition': 'none'}" + } else { + qb shouldEqual s"$root WITH caching = 'keys_only'" + } + } + + "specify Cache.RowsOnly as a caching strategy" in { + val qb = BasicTable.create.`with`(caching eqs Cache.RowsOnly()).qb.queryString + + if (session.v4orNewer) { + qb shouldEqual s"$root WITH caching = {'rows_per_partition': 'all'}" + } else { + qb shouldEqual s"$root WITH caching = 'rows_only'" + } + } + + "specify Cache.All as a caching strategy" in { + val qb = BasicTable.create.`with`(caching eqs Cache.All()).qb.queryString + if (session.v4orNewer) { + qb shouldEqual s"$root WITH caching = {'keys': 'all', 'rows_per_partition': 'all'}" + } else { + qb shouldEqual s"$root WITH caching = 'all'" + } + + } + } + + "should allow specifying a default_time_to_live" - { + "specify a default time to live using a Long value" in { + val qb = BasicTable.create.`with`(default_time_to_live eqs DefaultTtl.toLong).qb.queryString + qb shouldEqual s"$root WITH default_time_to_live = 500" + } + + "specify a default time to live using a org.joda.time.Seconds value" in { + val qb = BasicTable.create.`with`(default_time_to_live eqs Seconds.seconds(DefaultTtl)).qb.queryString + qb shouldEqual s"$root WITH default_time_to_live = 500" + } + + "specify a default time to live using a scala.concurrent.duration.FiniteDuration value" in { + val qb = BasicTable.create.`with`(default_time_to_live eqs FiniteDuration(DefaultTtl, TimeUnit.SECONDS)).qb.queryString + qb shouldEqual s"$root WITH default_time_to_live = 500" + } + } + + "should allow specifying a clustering order" - { + "specify a single column clustering order with ascending ordering" in { + val column = ("test", CQLSyntax.Ordering.asc) :: Nil + + val qb = QueryBuilder.Create.clusteringOrder(column).queryString + + qb shouldEqual "CLUSTERING ORDER BY (test ASC)" + } + + "specify a single column clustering order with descending ordering" in { + val column = ("test", CQLSyntax.Ordering.desc) :: Nil + + val qb = QueryBuilder.Create.clusteringOrder(column).queryString + + qb shouldEqual "CLUSTERING ORDER BY (test DESC)" + } + + "specify multiple columns and preserve ordering" in { + val column1 = ("test", CQLSyntax.Ordering.asc) + val column2 = ("test2", CQLSyntax.Ordering.desc) + + val columns = List(column1, column2) + + val qb = QueryBuilder.Create.clusteringOrder(columns).queryString + + qb shouldEqual "CLUSTERING ORDER BY (test ASC, test2 DESC)" + } + } + + "should allow generating secondary indexes based on trait mixins" - { + "specify a secondary index on a non-map column" in { + val qb = QueryBuilder.Create.index("t", "k", "col").queryString + + qb shouldEqual "CREATE INDEX IF NOT EXISTS t_col_idx ON k.t(col)" + } + + "specify a secondary index on a map column for the keys of a map column" in { + val qb = QueryBuilder.Create.mapIndex("t", "k", "col").queryString + + qb shouldEqual "CREATE INDEX IF NOT EXISTS t_col_idx ON k.t(keys(col))" + } + } + + } +} diff --git a/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/serializers/CreateQuerySerialisationTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/serializers/CreateQuerySerialisationTest.scala new file mode 100644 index 000000000..d5cb26740 --- /dev/null +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/serializers/CreateQuerySerialisationTest.scala @@ -0,0 +1,34 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.builder.serializers + +import com.outworkers.phantom.builder.query.QueryBuilderTest +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.tables.TestDatabase + +class CreateQuerySerialisationTest extends QueryBuilderTest { + + "The CREATE query builder" - { + "should generate clustering keys for a schema queries" - { + "generate a descending order clustering key on a table with a single clustering key" in { + val qb = TestDatabase.timeSeriesTable.create.qb.queryString + + qb shouldEqual "CREATE TABLE phantom.timeSeriesTable (id uuid, name text, unixTimestamp timestamp, " + + "PRIMARY KEY (id, unixTimestamp)) WITH CLUSTERING ORDER BY (unixTimestamp DESC)" + } + } + } +} diff --git a/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/serializers/DeleteQueryBuilderTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/serializers/DeleteQueryBuilderTest.scala new file mode 100644 index 000000000..396a94056 --- /dev/null +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/serializers/DeleteQueryBuilderTest.scala @@ -0,0 +1,36 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.builder.serializers + +import com.outworkers.phantom.builder.QueryBuilder +import com.outworkers.phantom.builder.query.QueryBuilderTest + +class DeleteQueryBuilderTest extends QueryBuilderTest { + + "The DELETE query builder" - { + + "should allow specifying column delete queries" - { + val qb = QueryBuilder.Delete.deleteColumn("table", "col").queryString + qb shouldEqual "DELETE col FROM table" + } + + "should allow specifying full delete queries" - { + val qb = QueryBuilder.Delete.delete("table").queryString + qb shouldEqual "DELETE FROM table" + } + + } +} diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/serializers/DeleteQuerySerialisationTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/serializers/DeleteQuerySerialisationTest.scala similarity index 72% rename from phantom-dsl/src/test/scala/com/websudos/phantom/builder/serializers/DeleteQuerySerialisationTest.scala rename to phantom-dsl/src/test/scala/com/outworkers/phantom/builder/serializers/DeleteQuerySerialisationTest.scala index 18891b36b..07efeb04a 100644 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/serializers/DeleteQuerySerialisationTest.scala +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/serializers/DeleteQuerySerialisationTest.scala @@ -1,37 +1,23 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.serializers +package com.outworkers.phantom.builder.serializers -import com.websudos.phantom.builder.query.QueryBuilderTest -import com.websudos.phantom.dsl._ -import com.websudos.phantom.tables.TestDatabase +import com.outworkers.phantom.builder.query.QueryBuilderTest +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.tables.TestDatabase import com.outworkers.util.testing._ class DeleteQuerySerialisationTest extends QueryBuilderTest { diff --git a/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/serializers/InsertQueryBuilderTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/serializers/InsertQueryBuilderTest.scala new file mode 100644 index 000000000..913191b45 --- /dev/null +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/serializers/InsertQueryBuilderTest.scala @@ -0,0 +1,40 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.builder.serializers + +import com.outworkers.phantom.builder.QueryBuilder +import com.outworkers.phantom.builder.query.{CQLQuery, QueryBuilderTest} + +class InsertQueryBuilderTest extends QueryBuilderTest { + + "The INSERT query builder" - { + + "should allow appending columns and values to a query" - { + + "should serialize a sequence of appended values" in { + val query = QueryBuilder.Insert.values(List(CQLQuery("a"), CQLQuery("b"))).queryString + + query shouldEqual "VALUES(a, b)" + } + + "should serialize a sequence of column definitions" in { + val query = QueryBuilder.Insert.columns(List(CQLQuery("a"), CQLQuery("b"))).queryString + query shouldEqual "(a, b)" + } + + } + } +} diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/serializers/InsertQuerySerializationTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/serializers/InsertQuerySerializationTest.scala similarity index 70% rename from phantom-dsl/src/test/scala/com/websudos/phantom/builder/serializers/InsertQuerySerializationTest.scala rename to phantom-dsl/src/test/scala/com/outworkers/phantom/builder/serializers/InsertQuerySerializationTest.scala index 40c113dd7..b9c14b717 100644 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/serializers/InsertQuerySerializationTest.scala +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/serializers/InsertQuerySerializationTest.scala @@ -1,39 +1,26 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.serializers +package com.outworkers.phantom.builder.serializers -import com.websudos.phantom.builder.query.QueryBuilderTest -import com.websudos.phantom.tables.{Recipe, TestDatabase} +import com.outworkers.phantom.builder.query.QueryBuilderTest +import com.outworkers.phantom.tables.{Recipe, TestDatabase} import com.outworkers.util.testing._ -import com.websudos.phantom.dsl._ -import net.liftweb.json.{ compactRender, Extraction } +import com.outworkers.phantom.dsl._ +import org.json4s.Extraction +import org.json4s.native._ class InsertQuerySerializationTest extends QueryBuilderTest { @@ -121,7 +108,8 @@ class InsertQuerySerializationTest extends QueryBuilderTest { "should serialize a JSON clause as the insert part" in { val sample = gen[Recipe] - val query = TestDatabase.recipes.insert.json(compactRender(Extraction.decompose(sample))).queryString + val json = compactJson(renderJValue(Extraction.decompose(sample))) + val query = TestDatabase.recipes.insert.json(json).queryString } diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/serializers/KeySpaceSerializerTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/serializers/KeySpaceSerializerTest.scala similarity index 54% rename from phantom-dsl/src/test/scala/com/websudos/phantom/builder/serializers/KeySpaceSerializerTest.scala rename to phantom-dsl/src/test/scala/com/outworkers/phantom/builder/serializers/KeySpaceSerializerTest.scala index 4daad9a3a..1bafb69fa 100644 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/serializers/KeySpaceSerializerTest.scala +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/serializers/KeySpaceSerializerTest.scala @@ -1,36 +1,22 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.serializers +package com.outworkers.phantom.builder.serializers -import com.websudos.phantom.builder.QueryBuilder -import com.websudos.phantom.dsl._ +import com.outworkers.phantom.builder.QueryBuilder +import com.outworkers.phantom.dsl._ import shapeless.{Generic, HList, HNil, LabelledGeneric} import scala.util.{Failure, Success, Try} @@ -38,7 +24,7 @@ import scala.util.{Failure, Success, Try} class KeySpaceSerializerTest extends QuerySerializationTest { it should "create a simple keyspace creation query" in { - val query = QueryBuilder.keyspace("test").ifNotExists() + val query = KeySpaceSerializer("test").ifNotExists() .`with`(replication eqs NetworkTopologyStrategy) .and(durable_writes eqs true) .qb.queryString diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/serializers/PartsSerializationTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/serializers/PartsSerializationTest.scala similarity index 76% rename from phantom-dsl/src/test/scala/com/websudos/phantom/builder/serializers/PartsSerializationTest.scala rename to phantom-dsl/src/test/scala/com/outworkers/phantom/builder/serializers/PartsSerializationTest.scala index 08781db44..7f1c1e474 100644 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/serializers/PartsSerializationTest.scala +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/serializers/PartsSerializationTest.scala @@ -1,36 +1,22 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.serializers +package com.outworkers.phantom.builder.serializers -import com.websudos.phantom.builder.QueryBuilder -import com.websudos.phantom.builder.query._ +import com.outworkers.phantom.builder.QueryBuilder +import com.outworkers.phantom.builder.query._ import org.scalatest.FreeSpec class PartsSerializationTest extends FreeSpec with SerializationTest { diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/serializers/QuerySerializationTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/serializers/QuerySerializationTest.scala similarity index 72% rename from phantom-dsl/src/test/scala/com/websudos/phantom/builder/serializers/QuerySerializationTest.scala rename to phantom-dsl/src/test/scala/com/outworkers/phantom/builder/serializers/QuerySerializationTest.scala index ba882d4f7..88148c7c1 100644 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/serializers/QuerySerializationTest.scala +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/serializers/QuerySerializationTest.scala @@ -1,39 +1,25 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.serializers +package com.outworkers.phantom.builder.serializers import java.util.UUID -import com.websudos.phantom.builder.query.KeySpaceSuite -import com.websudos.phantom.dsl._ -import com.websudos.phantom.tables.TestDatabase +import com.outworkers.phantom.builder.query.KeySpaceSuite +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.tables.TestDatabase import com.outworkers.util.testing._ import org.scalatest.{FlatSpec, Matchers} diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/serializers/SelectQueryBuilderTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/serializers/SelectQueryBuilderTest.scala similarity index 65% rename from phantom-dsl/src/test/scala/com/websudos/phantom/builder/serializers/SelectQueryBuilderTest.scala rename to phantom-dsl/src/test/scala/com/outworkers/phantom/builder/serializers/SelectQueryBuilderTest.scala index 4b68c09f2..1a5e63022 100644 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/serializers/SelectQueryBuilderTest.scala +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/serializers/SelectQueryBuilderTest.scala @@ -1,37 +1,23 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.serializers +package com.outworkers.phantom.builder.serializers -import com.websudos.phantom.builder.QueryBuilder -import com.websudos.phantom.builder.query.{CQLQuery, QueryBuilderTest} -import com.websudos.phantom.tables.TestDatabase +import com.outworkers.phantom.builder.QueryBuilder +import com.outworkers.phantom.builder.query.{CQLQuery, QueryBuilderTest} +import com.outworkers.phantom.tables.TestDatabase class SelectQueryBuilderTest extends QueryBuilderTest { diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/serializers/SelectQuerySerialisationTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/serializers/SelectQuerySerialisationTest.scala similarity index 75% rename from phantom-dsl/src/test/scala/com/websudos/phantom/builder/serializers/SelectQuerySerialisationTest.scala rename to phantom-dsl/src/test/scala/com/outworkers/phantom/builder/serializers/SelectQuerySerialisationTest.scala index 64d9f5998..e76687c1c 100644 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/serializers/SelectQuerySerialisationTest.scala +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/serializers/SelectQuerySerialisationTest.scala @@ -1,40 +1,26 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.serializers +package com.outworkers.phantom.builder.serializers import java.util.Date import com.datastax.driver.core.utils.UUIDs -import com.websudos.phantom.builder.query.QueryBuilderTest -import com.websudos.phantom.dsl._ -import com.websudos.phantom.tables.TestDatabase +import com.outworkers.phantom.builder.query.QueryBuilderTest +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.tables.TestDatabase import com.outworkers.util.testing._ import scala.collection.SeqLike @@ -61,7 +47,8 @@ class SelectQuerySerialisationTest extends QueryBuilderTest { "should correctly append a column selection to a distinct clause" in { val id = gen[UUID] - val qb = TestDatabase.tableWithCompositeKey.select(_.id, _.second_part) + val qb = TestDatabase.tableWithCompositeKey + .select(_.id, _.second_part) .distinct() .where(_.id eqs id) .limit(limit).queryString @@ -197,7 +184,7 @@ class SelectQuerySerialisationTest extends QueryBuilderTest { .where(_.id eqs id) .qb.queryString - qb shouldEqual s"SELECT dateOf(id) FROM phantom.timeuuidTable WHERE id = $id" + qb shouldEqual s"SELECT dateOf(id) FROM phantom.${TestDatabase.timeuuidTable.tableName} WHERE id = $id" } } } diff --git a/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/serializers/UpdateQueryBuilderTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/serializers/UpdateQueryBuilderTest.scala new file mode 100644 index 000000000..e0ad44c1f --- /dev/null +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/serializers/UpdateQueryBuilderTest.scala @@ -0,0 +1,64 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.builder.serializers + +import com.outworkers.phantom.builder.QueryBuilder +import com.outworkers.phantom.builder.query.QueryBuilderTest +import com.outworkers.util.testing._ + +class UpdateQueryBuilderTest extends QueryBuilderTest { + + "The UPDATE query builder" - { + + "should allow specifying SET options" - { + + "should allowing updating the value of a column with a setTo clause" in { + QueryBuilder.Update.setTo("a", "b").queryString shouldEqual "a = b" + } + + "should allow specifying a set clause in an UPDATE query" in { + QueryBuilder.Update + .set(QueryBuilder.Update.setTo("a", "b")) + .queryString shouldEqual "SET a = b" + } + + "should allow specifying multiple SET clauses and chaining them" in { + val c1 = QueryBuilder.Update.setTo("a", "b") + val c2 = QueryBuilder.Update.setTo("c", "d") + + QueryBuilder.Update.chain(List(c1, c2)).queryString shouldEqual "a = b, c = d" + } + } + + "should allow specifying USING clause options" - { + "should allow specifying a timestamp clause" in { + val str = gen[Long] + QueryBuilder.timestamp(str).queryString shouldEqual s"TIMESTAMP $str" + } + } + + "should allow specifying CAS options" - { + + "should allow specifying a single IF clause" in { + QueryBuilder.Update.onlyIf(QueryBuilder.Where.eqs("a", "b")).queryString shouldEqual "IF a = b" + } + + "should allow specifying an AND clause" in { + QueryBuilder.Update.and(QueryBuilder.Where.eqs("a", "b")).queryString shouldEqual "AND a = b" + } + } + } +} diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/serializers/UpdateQuerySerializationTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/serializers/UpdateQuerySerializationTest.scala similarity index 78% rename from phantom-dsl/src/test/scala/com/websudos/phantom/builder/serializers/UpdateQuerySerializationTest.scala rename to phantom-dsl/src/test/scala/com/outworkers/phantom/builder/serializers/UpdateQuerySerializationTest.scala index 40e44b81c..9b18c189a 100644 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/serializers/UpdateQuerySerializationTest.scala +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/serializers/UpdateQuerySerializationTest.scala @@ -1,37 +1,23 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.serializers +package com.outworkers.phantom.builder.serializers -import com.websudos.phantom.PhantomBaseSuite -import com.websudos.phantom.dsl._ -import com.websudos.phantom.tables.TestDatabase +import com.outworkers.phantom.PhantomBaseSuite +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.tables.TestDatabase import com.outworkers.util.testing._ import org.joda.time.{DateTime, DateTimeZone} diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/serializers/WhereClauseOperatorsSerializationTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/serializers/WhereClauseOperatorsSerializationTest.scala similarity index 60% rename from phantom-dsl/src/test/scala/com/websudos/phantom/builder/serializers/WhereClauseOperatorsSerializationTest.scala rename to phantom-dsl/src/test/scala/com/outworkers/phantom/builder/serializers/WhereClauseOperatorsSerializationTest.scala index 22dbf9b1d..a6df3c78e 100644 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/serializers/WhereClauseOperatorsSerializationTest.scala +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/builder/serializers/WhereClauseOperatorsSerializationTest.scala @@ -1,36 +1,22 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.builder.serializers +package com.outworkers.phantom.builder.serializers -import com.websudos.phantom.builder.QueryBuilder -import com.websudos.phantom.builder.syntax.CQLSyntax +import com.outworkers.phantom.builder.QueryBuilder +import com.outworkers.phantom.builder.syntax.CQLSyntax import com.outworkers.util.testing._ import org.scalatest.{FlatSpec, Matchers} diff --git a/phantom-dsl/src/test/scala/com/outworkers/phantom/database/DatabaseTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/database/DatabaseTest.scala new file mode 100644 index 000000000..a2a420f75 --- /dev/null +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/database/DatabaseTest.scala @@ -0,0 +1,44 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.database + +import com.outworkers.phantom.PhantomSuite +import com.outworkers.phantom.dsl._ +import com.outworkers.util.testing._ + +object db extends TestDatabase + +class DatabaseTest extends PhantomSuite { + + it should "instantiate a database and collect references to the tables" in { + db.tables.size shouldEqual 4 + } + + it should "automatically generate the CQL schema and initialise tables " in { + db.createAsync().successful { + res => res.nonEmpty shouldEqual true + } + } + + it should "respect any auto-creation options specified for the particular table" in { + val space = KeySpace("phantom_test") + val queries = db.autocreate().queries(space).map(_.qb) + + val target = db.recipes.autocreate(space).qb + + queries should contain (target) + } +} diff --git a/phantom-dsl/src/test/scala/com/outworkers/phantom/database/TestDatabase.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/database/TestDatabase.scala new file mode 100644 index 000000000..6634eb110 --- /dev/null +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/database/TestDatabase.scala @@ -0,0 +1,40 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.database + +import com.outworkers.phantom.connectors.ContactPoint +import com.outworkers.phantom.tables._ + +private[this] object DefaultKeyspace { + lazy val local = ContactPoint.local.keySpace("phantom") +} + +class TestDatabase extends Database[TestDatabase](DefaultKeyspace.local) { + object enumTable extends EnumTable with Connector + object basicTable extends BasicTable with Connector + object jsonTable extends JsonTable with Connector + object recipes extends Recipes with Connector +} + +object TestDatabase extends TestDatabase + +/* +class ValueInitDatabase extends Database[ValueInitDatabase](DefaultKeyspace.local) { + val basicTable = new BasicTable with connector.Connector + val enumTable = new EnumTable with connector.Connector + val jsonTable = new JsonTable with connector.Connector + val recipes = new Recipes with connector.Connector +}*/ \ No newline at end of file diff --git a/phantom-dsl/src/test/scala/com/outworkers/phantom/macros/TableHelperTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/macros/TableHelperTest.scala new file mode 100644 index 000000000..9bdcb0ca8 --- /dev/null +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/macros/TableHelperTest.scala @@ -0,0 +1,146 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.macros + +import com.outworkers.phantom.PhantomSuite +import com.outworkers.phantom.builder.primitives.Primitive +import org.joda.time.DateTime +import com.outworkers.phantom.dsl._ +import org.scalamock.scalatest.MockFactory +import com.outworkers.util.testing._ + +import scala.collection.JavaConverters._ + +case class Ev2( + id: UUID, + set: Set[String] +) + +class Events2 extends CassandraTable[Events2, Ev2] { + object partition extends UUIDColumn(this) with PartitionKey + object id extends UUIDColumn(this) with PartitionKey + object map extends SetColumn[String](this) +} + +class TableHelperTest extends PhantomSuite with MockFactory { + + it should "not generate a fromRow if a normal type is different" in { + + case class SampleEvent(id: String, map: Map[Long, DateTime]) + + class Events extends CassandraTable[Events, SampleEvent] { + object id extends UUIDColumn(this) with PartitionKey + object map extends MapColumn[Long, Long](this) + } + + val ev = new Events() + intercept[NotImplementedError] { + ev.fromRow(null.asInstanceOf[Row]) + } + } + + it should "not generate a fromRow if the columns match but are in the wrong order" in { + + case class Event( + id: UUID, + text: String, + length: Int, + map: Map[Long, DateTime] + ) + + class Events extends CassandraTable[Events, Event] { + object id extends UUIDColumn(this) with PartitionKey + object text extends StringColumn(this) + object map extends MapColumn[Long, Long](this) + object length extends IntColumn(this) + } + + val ev = new Events() + intercept[NotImplementedError] { + ev.fromRow(null.asInstanceOf[Row]) + } + } + + it should "not generate a fromRow if the argument passed to a map column is different" in { + + case class SampleEvent(id: UUID, map: Map[Long, DateTime]) + + class Events extends CassandraTable[Events, SampleEvent] { + object id extends UUIDColumn(this) with PartitionKey + object map extends MapColumn[Long, Long](this) + } + + val ev = new Events() + intercept[NotImplementedError] { + ev.fromRow(null.asInstanceOf[Row]) + } + } + + it should "not generate a fromRow if the collection type is different" in { + case class Ev(id: UUID, set: List[Int]) + + class Events extends CassandraTable[Events, Ev] { + object id extends UUIDColumn(this) with PartitionKey + object map extends SetColumn[Int](this) + } + + val ev = new Events() + intercept[NotImplementedError] { + ev.fromRow(null.asInstanceOf[Row]) + } + } + + it should "not generate a fromRow if the argument passed to a list column is different" in { + case class Ev(id: UUID, set: List[Int]) + + class Events extends CassandraTable[Events, Ev] { + object id extends UUIDColumn(this) with PartitionKey + object map extends ListColumn[String](this) + } + + val ev = new Events() + intercept[NotImplementedError] { + ev.fromRow(null.asInstanceOf[Row]) + } + } + + it should "not generate a fromRow if the argument passed to a set column is different" in { + case class Ev(id: UUID, set: Set[Int]) + + class Events extends CassandraTable[Events, Ev] { + object id extends UUIDColumn(this) with PartitionKey + object map extends SetColumn[String](this) + } + + val ev = new Events() + intercept[NotImplementedError] { + ev.fromRow(null.asInstanceOf[Row]) + } + } + + it should "generate a fromRow method from a partial table definition" in { + + val row = stub[Row] + + val instance = Ev2(gen[UUID], genList[String]().toSet) + + val ev = new Events2() + + intercept[NullPointerException] { + ev.fromRow(row) + } + } +} diff --git a/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/Articles.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/Articles.scala new file mode 100644 index 000000000..c2ad565a1 --- /dev/null +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/Articles.scala @@ -0,0 +1,78 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.tables + +import com.outworkers.phantom.connectors.RootConnector +import com.outworkers.util.testing.sample +import com.outworkers.phantom.builder.query.InsertQuery +import com.outworkers.phantom.dsl._ + +case class Article( + id: UUID, + name: String, + orderId: Long +) + +sealed class Articles extends CassandraTable[ConcreteArticles, Article] { + + object id extends UUIDColumn(this) with PartitionKey + object name extends StringColumn(this) + object orderId extends LongColumn(this) + + override def fromRow(row: Row): Article = Article(id(row), name(row), orderId(row)) +} + +abstract class ConcreteArticles extends Articles with RootConnector { + override def tableName: String = "articles" + + def store(article: Article): InsertQuery.Default[ConcreteArticles, Article] = { + insert + .value(_.id, article.id) + .value(_.name, article.name) + .value(_.orderId, article.orderId) + } +} + + +sealed class ArticlesByAuthor extends CassandraTable[ConcreteArticlesByAuthor, Article] { + + object author_id extends UUIDColumn(this) with PartitionKey + object category extends UUIDColumn(this) with PartitionKey + object id extends UUIDColumn(this) with PrimaryKey + + object name extends StringColumn(this) + object orderId extends LongColumn(this) + + override def fromRow(row: Row): Article = { + Article( + name = name(row), + id = id(row), + orderId = orderId(row) + ) + } +} + +abstract class ConcreteArticlesByAuthor extends ArticlesByAuthor with RootConnector { + + def store(author: UUID, category: UUID, article: Article): InsertQuery.Default[ConcreteArticlesByAuthor, Article] = { + insert + .value(_.author_id, author) + .value(_.category, category) + .value(_.id, article.id) + .value(_.name, article.name) + .value(_.orderId, article.orderId) + } +} diff --git a/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/BasicTable.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/BasicTable.scala new file mode 100644 index 000000000..343e759ed --- /dev/null +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/BasicTable.scala @@ -0,0 +1,161 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.tables + +import com.outworkers.phantom.connectors.RootConnector +import com.outworkers.phantom.builder.query.InsertQuery +import com.outworkers.phantom.dsl._ + +abstract class BasicTable extends CassandraTable[BasicTable, String] with RootConnector { + + object id extends UUIDColumn(this) with PartitionKey + object id2 extends UUIDColumn(this) with PrimaryKey + object id3 extends UUIDColumn(this) with PrimaryKey + object placeholder extends StringColumn(this) + + override def fromRow(r: Row): String = placeholder(r) +} + +trait Records extends Enumeration { + type Records = Value + val TypeOne, TypeTwo, TypeThree = Value +} + +object Records extends Records + +trait NamedRecords extends Enumeration { + type NamedRecords = Value + val One = Value("one") + val Two = Value("two") +} + +object NamedRecords extends NamedRecords + +case class EnumRecord( + name: String, + enum: Records#Value, + optEnum: Option[Records#Value] +) + +case class NamedEnumRecord( + name: String, + enum: NamedRecords#Value, + optEnum: Option[NamedRecords#Value] +) + +case class NamedPartitionRecord( + enum: NamedRecords#Value, + id: UUID +) + +abstract class EnumTable extends CassandraTable[EnumTable, EnumRecord] with RootConnector { + object id extends StringColumn(this) with PartitionKey + object enum extends EnumColumn[Records#Value](this) + object optEnum extends OptionalEnumColumn[Records#Value](this) + + def store(sample: EnumRecord): InsertQuery.Default[EnumTable, EnumRecord] = { + insert + .value(_.id, sample.name) + .value(_.enum, sample.enum) + .value(_.optEnum, sample.optEnum) + } +} + + +sealed class NamedEnumTable extends CassandraTable[ConcreteNamedEnumTable, NamedEnumRecord] { + object id extends StringColumn(this) with PartitionKey + object enum extends EnumColumn[NamedRecords#Value](this) + object optEnum extends OptionalEnumColumn[NamedRecords#Value](this) +} + +abstract class ConcreteNamedEnumTable extends NamedEnumTable with RootConnector { + def store(sample: NamedEnumRecord): InsertQuery.Default[ConcreteNamedEnumTable, NamedEnumRecord] = { + insert + .value(_.id, sample.name) + .value(_.enum, sample.enum) + .value(_.optEnum, sample.optEnum) + } +} + + +sealed class NamedPartitionEnumTable extends CassandraTable[ConcreteNamedPartitionEnumTable, NamedPartitionRecord] { + object enum extends EnumColumn[NamedRecords#Value](this) with PartitionKey + object id extends UUIDColumn(this) with PrimaryKey +} + +abstract class ConcreteNamedPartitionEnumTable extends NamedPartitionEnumTable with RootConnector { + def store(sample: NamedPartitionRecord): InsertQuery.Default[ConcreteNamedPartitionEnumTable, NamedPartitionRecord] = { + insert + .value(_.id, sample.id) + .value(_.enum, sample.enum) + } +} + +sealed class ClusteringTable extends CassandraTable[ConcreteClusteringTable, String] { + + object id extends UUIDColumn(this) with PartitionKey + object id2 extends UUIDColumn(this) with ClusteringOrder with Ascending + object id3 extends UUIDColumn(this) with ClusteringOrder with Descending + object placeholder extends StringColumn(this) + + override def fromRow(r: Row): String = placeholder(r) +} + +abstract class ConcreteClusteringTable extends ClusteringTable with RootConnector + +sealed class ComplexClusteringTable extends CassandraTable[ConcreteComplexClusteringTable, String] { + + object id extends UUIDColumn(this) with PartitionKey + object id2 extends UUIDColumn(this) with ClusteringOrder with Ascending + object id3 extends UUIDColumn(this) with ClusteringOrder with Descending + object placeholder extends StringColumn(this) with ClusteringOrder with Descending + + override def fromRow(r: Row): String = placeholder(r) +} + +abstract class ConcreteComplexClusteringTable extends ComplexClusteringTable with RootConnector + +sealed class ComplexCompoundKeyTable extends CassandraTable[ConcreteComplexCompoundKeyTable, String] { + + object id extends UUIDColumn(this) with PartitionKey + object id2 extends UUIDColumn(this) with PrimaryKey + object id3 extends UUIDColumn(this) with PrimaryKey + object id4 extends UUIDColumn(this) with PrimaryKey + object id5 extends UUIDColumn(this) with PrimaryKey + object id6 extends UUIDColumn(this) with PrimaryKey + object id7 extends UUIDColumn(this) with PrimaryKey + object id8 extends UUIDColumn(this) with PrimaryKey + object id9 extends UUIDColumn(this) with PrimaryKey + object placeholder extends StringColumn(this) + + override def fromRow(r: Row): String = placeholder(r) +} + +abstract class ConcreteComplexCompoundKeyTable extends ComplexCompoundKeyTable with RootConnector + +sealed class SimpleCompoundKeyTable extends CassandraTable[ConcreteSimpleCompoundKeyTable, String] { + + object id extends UUIDColumn(this) with PartitionKey + object id2 extends UUIDColumn(this) with PrimaryKey + object id3 extends UUIDColumn(this) with PrimaryKey + object placeholder extends StringColumn(this) + + override def fromRow(r: Row): String = placeholder(r) +} + +abstract class ConcreteSimpleCompoundKeyTable extends SimpleCompoundKeyTable with RootConnector + + diff --git a/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/CounterTableTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/CounterTableTest.scala new file mode 100644 index 000000000..95e7ebd20 --- /dev/null +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/CounterTableTest.scala @@ -0,0 +1,53 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.tables + +import com.outworkers.phantom.connectors.RootConnector +import com.outworkers.util.testing.sample +import com.outworkers.phantom.dsl._ + +case class CounterRecord(id: UUID, count: Long) + +class CounterTableTest extends CassandraTable[ConcreteCounterTableTest, CounterRecord] { + + object id extends UUIDColumn(this) with PartitionKey + object count_entries extends CounterColumn(this) +} + +abstract class ConcreteCounterTableTest extends CounterTableTest with RootConnector { + override val tableName = "counter_column_tests" +} + +class SecondaryCounterTable extends CassandraTable[ConcreteSecondaryCounterTable, CounterRecord] { + object id extends UUIDColumn(this) with PartitionKey + object count_entries extends CounterColumn(this) +} + +abstract class ConcreteSecondaryCounterTable extends SecondaryCounterTable with RootConnector { + override val tableName = "secondary_column_tests" +} + +class BrokenCounterTableTest extends CassandraTable[ConcreteBrokenCounterTableTest, CounterRecord] { + + object id extends UUIDColumn(this) with PartitionKey + object count_entries extends CounterColumn(this) + +} + +abstract class ConcreteBrokenCounterTableTest extends BrokenCounterTableTest with RootConnector { + override val tableName = "counter_column_tests" +} + diff --git a/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/IndexedCollectionsTable.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/IndexedCollectionsTable.scala new file mode 100644 index 000000000..e76902b72 --- /dev/null +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/IndexedCollectionsTable.scala @@ -0,0 +1,92 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.tables + +import com.outworkers.phantom.CassandraTable +import com.outworkers.phantom.connectors.RootConnector +import com.outworkers.phantom.builder.query.InsertQuery +import com.outworkers.phantom.column.{ListColumn, MapColumn, SetColumn} +import com.outworkers.phantom.dsl._ + +sealed class IndexedCollectionsTable extends CassandraTable[ConcreteIndexedCollectionsTable, TestRow] { + + object key extends StringColumn(this) with PartitionKey + + object list extends ListColumn[String](this) + + object setText extends SetColumn[String](this) with Index + + object mapTextToText extends MapColumn[String, String](this) with Index + + object setInt extends SetColumn[Int](this) + + object mapIntToText extends MapColumn[Int, String](this) with Index with Keys + + object mapIntToInt extends MapColumn[Int, Int](this) +} + +abstract class ConcreteIndexedCollectionsTable extends IndexedCollectionsTable with RootConnector { + override val tableName = "indexed_collections" + + def store(row: TestRow): InsertQuery.Default[ConcreteIndexedCollectionsTable, TestRow] = { + insert + .value(_.key, row.key) + .value(_.list, row.list) + .value(_.setText, row.setText) + .value(_.mapTextToText, row.mapTextToText) + .value(_.setInt, row.setInt) + .value(_.mapIntToText, row.mapIntToText) + .value(_.mapIntToInt, row.mapIntToInt) + } + +} + + +sealed class IndexedEntriesTable extends CassandraTable[ConcreteIndexedEntriesTable, TestRow] { + + object key extends StringColumn(this) with PartitionKey + + object list extends ListColumn[String](this) + + object setText extends SetColumn[String](this) with Index + + object mapTextToText extends MapColumn[String, String](this) with Index + + object setInt extends SetColumn[Int](this) + + object mapIntToText extends MapColumn[Int, String](this) with Index with Keys + + object mapIntToInt extends MapColumn[Int, Int](this) with Index with Entries +} + +abstract class ConcreteIndexedEntriesTable extends IndexedEntriesTable with RootConnector { + override val tableName = "indexed_collections" + + def store(row: TestRow): InsertQuery.Default[ConcreteIndexedEntriesTable, TestRow] = { + insert + .value(_.key, row.key) + .value(_.list, row.list) + .value(_.setText, row.setText) + .value(_.mapTextToText, row.mapTextToText) + .value(_.setInt, row.setInt) + .value(_.mapIntToText, row.mapIntToText) + .value(_.mapIntToInt, row.mapIntToInt) + } + +} + + + diff --git a/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/JsonTable.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/JsonTable.scala new file mode 100644 index 000000000..b232d6719 --- /dev/null +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/JsonTable.scala @@ -0,0 +1,79 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.tables + +import com.outworkers.phantom.connectors.RootConnector +import com.outworkers.phantom.builder.query.InsertQuery +import com.outworkers.phantom.dsl._ +import org.json4s.Extraction +import org.json4s.native._ + +case class JsonTest(prop1: String, prop2: String) + +case class JsonClass( + id: UUID, + name: String, + json: JsonTest, + jsonList: List[JsonTest], + jsonSet: Set[JsonTest] +) + + +abstract class JsonTable extends CassandraTable[JsonTable, JsonClass] with RootConnector { + + implicit val formats = org.json4s.DefaultFormats + + object id extends UUIDColumn(this) with PartitionKey + + object name extends StringColumn(this) + + object json extends JsonColumn[JsonTest](this) { + override def fromJson(obj: String): JsonTest = { + JsonParser.parse(obj).extract[JsonTest] + } + + override def toJson(obj: JsonTest): String = compactJson(renderJValue(Extraction.decompose(obj))) + } + + object jsonList extends JsonListColumn[JsonTest](this) { + override def fromJson(obj: String): JsonTest = { + JsonParser.parse(obj).extract[JsonTest] + } + + override def toJson(obj: JsonTest): String = { + compactJson(renderJValue(Extraction.decompose(obj))) + } + } + + object jsonSet extends JsonSetColumn[JsonTest](this) { + override def fromJson(obj: String): JsonTest = { + JsonParser.parse(obj).extract[JsonTest] + } + + override def toJson(obj: JsonTest): String = { + compactJson(renderJValue(Extraction.decompose(obj))) + } + } + + def store(sample: JsonClass): InsertQuery.Default[JsonTable, JsonClass] = { + insert + .value(_.id, sample.id) + .value(_.name, sample.name) + .value(_.json, sample.json) + .value(_.jsonList, sample.jsonList) + .value(_.jsonSet, sample.jsonSet) + } +} diff --git a/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/ListCollectionTable.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/ListCollectionTable.scala new file mode 100644 index 000000000..6955760da --- /dev/null +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/ListCollectionTable.scala @@ -0,0 +1,50 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.tables + +import com.outworkers.phantom.connectors.RootConnector +import com.outworkers.util.testing.sample +import com.outworkers.phantom.builder.query.InsertQuery +import com.outworkers.phantom.dsl._ + +case class MyTestRow( + key: String, + optionA: Option[Int], + stringlist: List[String] +) + +sealed class ListCollectionTable extends CassandraTable[ConcreteListCollectionTable, MyTestRow] { + + object key extends StringColumn(this) with PartitionKey + + object optionA extends OptionalIntColumn(this) + + object stringlist extends ListColumn[String](this) +} + +abstract class ConcreteListCollectionTable extends ListCollectionTable with RootConnector { + + override val tableName = "mytest" + + def store(row: MyTestRow): InsertQuery.Default[ConcreteListCollectionTable, MyTestRow] = { + insert().value(_.key, row.key) + .value(_.stringlist, row.stringlist) + .value(_.optionA, row.optionA) + } + +} + + diff --git a/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/MultipleKeys.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/MultipleKeys.scala new file mode 100644 index 000000000..c59872fc6 --- /dev/null +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/MultipleKeys.scala @@ -0,0 +1,39 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.tables + +import com.datastax.driver.core.Row +import com.outworkers.phantom.connectors.RootConnector +import com.outworkers.phantom.dsl._ + +class MultipleKeys extends CassandraTable[ConcreteMultipleKeys, Option[MultipleKeys]] { + + object pkey extends StringColumn(this) with PartitionKey + object intColumn1 extends IntColumn(this) with PrimaryKey with Index + object intColumn2 extends IntColumn(this) with PrimaryKey + object intColumn3 extends IntColumn(this) with PrimaryKey + object intColumn4 extends IntColumn(this) with PrimaryKey + object intColumn5 extends IntColumn(this) with PrimaryKey + object intColumn6 extends IntColumn(this) with PrimaryKey + object intColumn7 extends IntColumn(this) with PrimaryKey + object timestamp8 extends DateTimeColumn(this) + + override def fromRow(r: Row): Option[MultipleKeys] = None +} + +abstract class ConcreteMultipleKeys extends MultipleKeys with RootConnector { + override val tableName = "AJ" +} diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/tables/OptionalPrimitives.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/OptionalPrimitives.scala similarity index 66% rename from phantom-dsl/src/test/scala/com/websudos/phantom/tables/OptionalPrimitives.scala rename to phantom-dsl/src/test/scala/com/outworkers/phantom/tables/OptionalPrimitives.scala index 0a9ac6eaa..69dd43fbf 100644 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/tables/OptionalPrimitives.scala +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/OptionalPrimitives.scala @@ -1,36 +1,23 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.tables +package com.outworkers.phantom.tables -import com.websudos.phantom.builder.query.{InsertQuery, UpdateQuery} -import com.websudos.phantom.dsl._ +import com.outworkers.phantom.connectors.RootConnector +import com.outworkers.phantom.builder.query.{InsertQuery, UpdateQuery} +import com.outworkers.phantom.dsl._ import com.outworkers.util.testing._ import scala.concurrent.Future @@ -73,7 +60,7 @@ object OptionalPrimitive { } sealed class OptionalPrimitives extends CassandraTable[ConcreteOptionalPrimitives, OptionalPrimitive] { - object pkey extends StringColumn(this) with PartitionKey[String] + object pkey extends StringColumn(this) with PartitionKey object string extends OptionalStringColumn(this) diff --git a/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/OptionalPrimitivesCassandra22.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/OptionalPrimitivesCassandra22.scala new file mode 100644 index 000000000..76c69b2ff --- /dev/null +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/OptionalPrimitivesCassandra22.scala @@ -0,0 +1,74 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.tables + +import com.outworkers.phantom.CassandraTable +import com.outworkers.phantom.connectors.RootConnector +import com.outworkers.phantom.builder.query.InsertQuery +import com.outworkers.phantom.dsl._ +import com.outworkers.util.testing._ + +case class OptionalPrimitiveCassandra22( + pkey: String, + short: Option[Short], + byte: Option[Byte], + localDate: Option[LocalDate] +) + +object OptionalPrimitiveCassandra22 { + + def none: OptionalPrimitiveCassandra22 = { + OptionalPrimitiveCassandra22( + pkey = gen[String], + short = None, + byte = None, + localDate = None + ) + } +} + +sealed class OptionalPrimitivesCassandra22 extends CassandraTable[ConcreteOptionalPrimitivesCassandra22, OptionalPrimitiveCassandra22] { + + object pkey extends StringColumn(this) with PartitionKey + + object short extends OptionalSmallIntColumn(this) + + object byte extends OptionalTinyIntColumn(this) + + object localDate extends OptionalLocalDateColumn(this) + + override def fromRow(r: Row): OptionalPrimitiveCassandra22 = { + OptionalPrimitiveCassandra22( + pkey = pkey(r), + short = short(r), + byte = byte(r), + localDate = localDate(r) + ) + } +} + +abstract class ConcreteOptionalPrimitivesCassandra22 extends OptionalPrimitivesCassandra22 with RootConnector { + + override val tableName = "OptionalPrimitivesCassandra22" + + def store(row: OptionalPrimitiveCassandra22): InsertQuery.Default[ConcreteOptionalPrimitivesCassandra22, OptionalPrimitiveCassandra22] = { + insert + .value(_.pkey, row.pkey) + .value(_.short, row.short) + .value(_.byte, row.byte) + .value(_.localDate, row.localDate) + } +} diff --git a/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/OptionalSecondaryIndexTable.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/OptionalSecondaryIndexTable.scala new file mode 100644 index 000000000..26ffbe95c --- /dev/null +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/OptionalSecondaryIndexTable.scala @@ -0,0 +1,57 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.tables + +import java.util.UUID + +import com.outworkers.phantom.connectors.RootConnector +import com.outworkers.phantom.dsl._ + +import scala.concurrent.Future + +case class OptionalSecondaryRecord( + id: UUID, + secondary: Option[Int] +) + +sealed class OptionalSecondaryIndexTable extends CassandraTable[ + ConcreteOptionalSecondaryIndexTable, + OptionalSecondaryRecord +] { + object id extends UUIDColumn(this) with PartitionKey + object secondary extends OptionalIntColumn(this) with Index +} + +abstract class ConcreteOptionalSecondaryIndexTable + extends OptionalSecondaryIndexTable with RootConnector { + + def store(rec: OptionalSecondaryRecord): Future[ResultSet] = { + insert.value(_.id, rec.id) + .value(_.secondary, rec.secondary) + .future() + } + + def findById(id: UUID): Future[Option[OptionalSecondaryRecord]] = { + select.where(_.id eqs id).one() + } + + def findByOptionalSecondary(sec: Int): Future[Option[OptionalSecondaryRecord]] = { + select.where(_.secondary eqs sec).one() + } + +} + + diff --git a/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/PrimaryCollectionTable.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/PrimaryCollectionTable.scala new file mode 100644 index 000000000..e83efed3a --- /dev/null +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/PrimaryCollectionTable.scala @@ -0,0 +1,49 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.tables + +import com.outworkers.phantom.connectors.RootConnector +import com.outworkers.phantom.dsl._ + +import scala.concurrent.Future + +case class PrimaryCollectionRecord( + index: List[String], + set: Set[String], + map: Map[String, String], + name: String, + value: Int +) + +class PrimaryCollectionTable extends CassandraTable[ConcretePrimaryCollectionTable, PrimaryCollectionRecord] { + object listIndex extends ListColumn[String](this) with PartitionKey + object setCol extends SetColumn[String](this) with PrimaryKey + object mapCol extends MapColumn[String, String](this) with PrimaryKey + object name extends StringColumn(this) with PrimaryKey + object value extends IntColumn(this) +} + +abstract class ConcretePrimaryCollectionTable extends PrimaryCollectionTable with RootConnector { + + def store(rec: PrimaryCollectionRecord): Future[ResultSet] = { + insert.value(_.listIndex, rec.index) + .value(_.setCol, rec.set) + .value(_.mapCol, rec.map) + .value(_.name, rec.name) + .value(_.value, rec.value) + .future() + } +} \ No newline at end of file diff --git a/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/Primitives.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/Primitives.scala new file mode 100644 index 000000000..2c9fef817 --- /dev/null +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/Primitives.scala @@ -0,0 +1,94 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.tables + +import com.outworkers.phantom.connectors.RootConnector +import com.outworkers.util.testing.sample +import com.outworkers.phantom.builder.query.InsertQuery +import com.outworkers.phantom.dsl._ + +case class Primitive( + pkey: String, + long: Long, + boolean: Boolean, + bDecimal: BigDecimal, + double: Double, + float: Float, + inet: java.net.InetAddress, + int: Int, + date: java.util.Date, + uuid: java.util.UUID, + bi: BigInt +) + +sealed class Primitives extends CassandraTable[ConcretePrimitives, Primitive] { + object pkey extends StringColumn(this) with PartitionKey + + object long extends LongColumn(this) + + object boolean extends BooleanColumn(this) + + object bDecimal extends BigDecimalColumn(this) + + object double extends DoubleColumn(this) + + object float extends FloatColumn(this) + + object inet extends InetAddressColumn(this) + + object int extends IntColumn(this) + + object date extends DateColumn(this) + + object uuid extends UUIDColumn(this) + + object bi extends BigIntColumn(this) + + override def fromRow(r: Row): Primitive = Primitive( + pkey(r), + long(r), + boolean(r), + bDecimal(r), + double(r), + float(r), + inet(r), + int(r), + date(r), + uuid(r), + bi(r) + ) +} + +abstract class ConcretePrimitives extends Primitives with RootConnector { + + override val tableName = "Primitives" + + def store(row: Primitive): InsertQuery.Default[ConcretePrimitives, Primitive] = { + insert + .value(_.pkey, row.pkey) + .value(_.long, row.long) + .value(_.boolean, row.boolean) + .value(_.bDecimal, row.bDecimal) + .value(_.double, row.double) + .value(_.float, row.float) + .value(_.inet, row.inet) + .value(_.int, row.int) + .value(_.date, row.date) + .value(_.uuid, row.uuid) + .value(_.bi, row.bi) + } + +} diff --git a/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/PrimitivesCassandra22.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/PrimitivesCassandra22.scala new file mode 100644 index 000000000..791af6a4f --- /dev/null +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/PrimitivesCassandra22.scala @@ -0,0 +1,61 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.tables + +import com.outworkers.phantom.connectors.RootConnector +import com.outworkers.phantom.builder.query.InsertQuery +import com.outworkers.phantom.dsl._ +import org.joda.time.LocalDate + +case class PrimitiveCassandra22( + pkey: String, + short: Short, + byte: Byte, + date: LocalDate +) + +sealed class PrimitivesCassandra22 extends CassandraTable[ConcretePrimitivesCassandra22, PrimitiveCassandra22] { + + object pkey extends StringColumn(this) with PartitionKey + + object short extends SmallIntColumn(this) + + object byte extends TinyIntColumn(this) + + object date extends LocalDateColumn(this) + + override def fromRow(r: Row): PrimitiveCassandra22 = { + PrimitiveCassandra22( + pkey = pkey(r), + short = short(r), + byte = byte(r), + date = date(r) + ) + } +} + +abstract class ConcretePrimitivesCassandra22 extends PrimitivesCassandra22 with RootConnector { + + override val tableName = "PrimitivesCassandra22" + + def store(row: PrimitiveCassandra22): InsertQuery.Default[ConcretePrimitivesCassandra22, PrimitiveCassandra22] = { + insert + .value(_.pkey, row.pkey) + .value(_.short, row.short) + .value(_.byte, row.byte) + .value(_.date, row.date) + } +} diff --git a/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/PrimitivesJoda.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/PrimitivesJoda.scala new file mode 100644 index 000000000..fa7f3bfb6 --- /dev/null +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/PrimitivesJoda.scala @@ -0,0 +1,56 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.tables + +import com.datastax.driver.core.PagingState +import com.outworkers.phantom.connectors.RootConnector +import com.outworkers.util.testing.sample +import com.outworkers.phantom.builder.query.InsertQuery +import com.outworkers.phantom.dsl._ +import org.joda.time.DateTime + +import scala.concurrent.Future + +case class JodaRow( + pkey: String, + intColumn: Int, + timestamp: DateTime +) + +sealed class PrimitivesJoda extends CassandraTable[ConcretePrimitivesJoda, JodaRow] { + object pkey extends StringColumn(this) with PartitionKey + object intColumn extends IntColumn(this) + object timestamp extends DateTimeColumn(this) + + override def fromRow(r: Row): JodaRow = JodaRow(pkey(r), intColumn(r), timestamp(r)) +} + +abstract class ConcretePrimitivesJoda extends PrimitivesJoda with RootConnector { + + def store(primitive: JodaRow): InsertQuery.Default[ConcretePrimitivesJoda, JodaRow] = { + insert.value(_.pkey, primitive.pkey) + .value(_.intColumn, primitive.intColumn) + .value(_.timestamp, primitive.timestamp) + } + + def fetchPage(limit: Int, paging: Option[PagingState]): Future[ListResult[JodaRow]] = { + select.limit(limit).paginateRecord(paging) + } + + override val tableName = "PrimitivesJoda" + +} + diff --git a/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/Recipes.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/Recipes.scala new file mode 100644 index 000000000..f90192fec --- /dev/null +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/Recipes.scala @@ -0,0 +1,80 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.tables + +import com.outworkers.phantom.connectors.RootConnector +import com.outworkers.phantom.builder.query.{CreateQuery, InsertQuery, SelectQuery} +import com.outworkers.phantom.dsl._ +import org.joda.time.DateTime + +import scala.concurrent.Future + +case class Recipe( + url: String, + description: Option[String], + ingredients: List[String], + servings: Option[Int], + lastCheckedAt: DateTime, + props: Map[String, String], + uid: UUID +) + +abstract class Recipes extends CassandraTable[Recipes, Recipe] with RootConnector { + + object url extends StringColumn(this) with PartitionKey + + object description extends OptionalStringColumn(this) + + object ingredients extends ListColumn[String](this) + + object servings extends OptionalIntColumn(this) + + object lastcheckedat extends DateTimeColumn(this) + + object props extends MapColumn[String, String](this) + + object uid extends UUIDColumn(this) + + def store(recipe: Recipe): InsertQuery.Default[Recipes, Recipe] = { + insert + .value(_.url, recipe.url) + .value(_.description, recipe.description) + .value(_.ingredients, recipe.ingredients) + .value(_.lastcheckedat, recipe.lastCheckedAt) + .value(_.props, recipe.props) + .value(_.uid, recipe.uid) + .value(_.servings, recipe.servings) + } +} + +case class SampleEvent(id: UUID, map: Map[Long, DateTime]) + +sealed class Events extends CassandraTable[ConcreteEvents, SampleEvent] { + object id extends UUIDColumn(this) with PartitionKey + object map extends MapColumn[Long, DateTime](this) +} + +abstract class ConcreteEvents extends Events with RootConnector { + + def store(event: SampleEvent): InsertQuery.Default[ConcreteEvents, SampleEvent] = { + insert.value(_.id, event.id) + .value(_.map, event.map) + } + + def findById(id: UUID): Future[Option[SampleEvent]] = { + select.where(_.id eqs id).one() + } +} diff --git a/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/ScalaTypesMapTable.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/ScalaTypesMapTable.scala new file mode 100644 index 000000000..f6731bc39 --- /dev/null +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/ScalaTypesMapTable.scala @@ -0,0 +1,47 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.tables + +import com.outworkers.phantom.connectors.RootConnector +import com.outworkers.phantom.builder.query.InsertQuery +import com.outworkers.phantom.dsl._ + +import scala.concurrent.Future + +case class ScalaPrimitiveMapRecord( + id: UUID, + map: Map[DateTime, BigDecimal] +) + +class ScalaTypesMapTable extends CassandraTable[ConcreteScalaTypesMapTable, ScalaPrimitiveMapRecord] { + + object id extends UUIDColumn(this) with PartitionKey + object map extends MapColumn[DateTime, BigDecimal](this) +} + +abstract class ConcreteScalaTypesMapTable extends ScalaTypesMapTable with RootConnector { + def store( + rec: ScalaPrimitiveMapRecord + ): InsertQuery.Default[ConcreteScalaTypesMapTable, ScalaPrimitiveMapRecord] = { + insert + .value(_.id, rec.id) + .value(_.map, rec.map) + } + + def findById(id: UUID): Future[Option[ScalaPrimitiveMapRecord]] = { + select.where(_.id eqs id).one() + } +} \ No newline at end of file diff --git a/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/SecondaryIndexTable.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/SecondaryIndexTable.scala new file mode 100644 index 000000000..29fba6bd7 --- /dev/null +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/SecondaryIndexTable.scala @@ -0,0 +1,43 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.tables + +import com.outworkers.phantom.connectors.RootConnector +import com.outworkers.phantom.builder.query.InsertQuery +import com.outworkers.phantom.dsl._ + + case class SecondaryIndexRecord( + primary: UUID, + secondary: UUID, + name: String +) + +sealed class SecondaryIndexTable extends CassandraTable[ConcreteSecondaryIndexTable, SecondaryIndexRecord] { + object id extends UUIDColumn(this) with PartitionKey + object secondary extends UUIDColumn(this) with Index + object name extends StringColumn(this) +} + +abstract class ConcreteSecondaryIndexTable extends SecondaryIndexTable with RootConnector { + + def store(sample: SecondaryIndexRecord): InsertQuery.Default[ConcreteSecondaryIndexTable, SecondaryIndexRecord] = { + insert + .value(_.id, sample.primary) + .value(_.secondary, sample.secondary) + .value(_.name, sample.name) + } + +} \ No newline at end of file diff --git a/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/StaticTableTest.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/StaticTableTest.scala new file mode 100644 index 000000000..ceb4c65f4 --- /dev/null +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/StaticTableTest.scala @@ -0,0 +1,53 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.tables + +import com.outworkers.phantom.connectors.RootConnector +import com.outworkers.phantom.builder.query.InsertQuery +import com.outworkers.phantom.dsl._ + +case class StaticCollectionSingle(id: UUID, clusteringId: UUID, static: String) + +sealed class StaticTableTest extends CassandraTable[ConcreteStaticTableTest, StaticCollectionSingle] { + + object id extends UUIDColumn(this) with PartitionKey + object clusteringId extends UUIDColumn(this) with PrimaryKey with ClusteringOrder with Descending + object staticTest extends StringColumn(this) with StaticColumn +} + +abstract class ConcreteStaticTableTest extends StaticTableTest with RootConnector + + +case class StaticCollectionRecord( + id: UUID, + clustering: UUID, + list: List[String] +) + +sealed class StaticCollectionTableTest extends CassandraTable[ConcreteStaticCollectionTableTest, StaticCollectionRecord] { + + object id extends UUIDColumn(this) with PartitionKey + object clusteringId extends UUIDColumn(this) with PrimaryKey with ClusteringOrder with Descending + object staticList extends ListColumn[String](this) with StaticColumn +} + +abstract class ConcreteStaticCollectionTableTest extends StaticCollectionTableTest with RootConnector { + def store(record: StaticCollectionRecord): InsertQuery.Default[ConcreteStaticCollectionTableTest, StaticCollectionRecord] = { + insert.value(_.id, record.id) + .value(_.clusteringId, record.clustering) + .value(_.staticList, record.list) + } +} diff --git a/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/TableKeyTests.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/TableKeyTests.scala new file mode 100644 index 000000000..6ce49e12b --- /dev/null +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/TableKeyTests.scala @@ -0,0 +1,63 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.tables + +import com.outworkers.phantom.connectors.RootConnector +import com.outworkers.phantom.dsl._ + +case class StubRecord( + id: UUID, + name: String +) + +sealed class TableWithSingleKey extends CassandraTable[ConcreteTableWithSingleKey, StubRecord] { + + object id extends UUIDColumn(this) with PartitionKey + object name extends StringColumn(this) +} + +abstract class ConcreteTableWithSingleKey extends TableWithSingleKey with RootConnector + +class TableWithCompoundKey extends CassandraTable[ConcreteTableWithCompoundKey, StubRecord] { + + object id extends UUIDColumn(this) with PartitionKey + object second extends UUIDColumn(this) with PrimaryKey + object name extends StringColumn(this) + + override def fromRow(r: Row): StubRecord = StubRecord(id(r), name(r)) +} + +abstract class ConcreteTableWithCompoundKey extends TableWithCompoundKey with RootConnector + + +sealed class TableWithCompositeKey extends CassandraTable[ConcreteTableWithCompositeKey, StubRecord] { + + object id extends UUIDColumn(this) with PartitionKey + object second_part extends UUIDColumn(this) with PartitionKey + object second extends UUIDColumn(this) with PrimaryKey + object name extends StringColumn(this) + + override def fromRow(r: Row): StubRecord = { + StubRecord( + id = id(r), + name = name(r) + ) + } +} + +abstract class ConcreteTableWithCompositeKey extends TableWithCompositeKey with RootConnector + + diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/tables/TestDatabase.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/TestDatabase.scala similarity index 60% rename from phantom-dsl/src/test/scala/com/websudos/phantom/tables/TestDatabase.scala rename to phantom-dsl/src/test/scala/com/outworkers/phantom/tables/TestDatabase.scala index 058693b6f..e9e9b14d5 100644 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/tables/TestDatabase.scala +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/TestDatabase.scala @@ -1,54 +1,40 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.tables +package com.outworkers.phantom.tables import java.util.UUID import com.datastax.driver.core.{PoolingOptions, SocketOptions} -import com.websudos.phantom.builder.query.CreateQuery -import com.websudos.phantom.connectors.{ContactPoint, KeySpaceDef} -import com.websudos.phantom.database.Database -import com.websudos.phantom.dsl._ +import com.outworkers.phantom.connectors +import com.outworkers.phantom.builder.query.CreateQuery +import com.outworkers.phantom.connectors.CassandraConnection +import com.outworkers.phantom.database.Database +import com.outworkers.phantom.dsl._ -class TestDatabase(override val connector: KeySpaceDef) extends Database[TestDatabase](connector) { +class TestDatabase(override val connector: CassandraConnection) extends Database[TestDatabase](connector) { object articles extends ConcreteArticles with connector.Connector object articlesByAuthor extends ConcreteArticlesByAuthor with connector.Connector - object basicTable extends ConcreteBasicTable with connector.Connector - object enumTable extends ConcreteEnumTable with connector.Connector + object basicTable extends BasicTable with connector.Connector + object enumTable extends EnumTable with connector.Connector object namedEnumTable extends ConcreteNamedEnumTable with connector.Connector object indexedEnumTable extends ConcreteNamedPartitionEnumTable with connector.Connector object clusteringTable extends ConcreteClusteringTable with connector.Connector object complexClusteringTable extends ConcreteComplexClusteringTable with connector.Connector - object brokenClusteringTable extends ConcreteBrokenClusteringTable with connector.Connector object simpleCompoundKeyTable extends ConcreteSimpleCompoundKeyTable with connector.Connector object complexCompoundKeyTable extends ConcreteComplexCompoundKeyTable with connector.Connector @@ -58,7 +44,7 @@ class TestDatabase(override val connector: KeySpaceDef) extends Database[TestDat object indexedCollectionsTable extends ConcreteIndexedCollectionsTable with connector.Connector object indexedEntriesTable extends ConcreteIndexedEntriesTable with connector.Connector - object jsonTable extends ConcreteJsonTable with connector.Connector + object jsonTable extends JsonTable with connector.Connector object listCollectionTable extends ConcreteListCollectionTable with connector.Connector object optionalPrimitives extends ConcreteOptionalPrimitives with connector.Connector object primitives extends ConcretePrimitives with connector.Connector @@ -68,8 +54,8 @@ class TestDatabase(override val connector: KeySpaceDef) extends Database[TestDat object primitivesCassandra22 extends ConcretePrimitivesCassandra22 with connector.Connector object optionalPrimitivesCassandra22 extends ConcreteOptionalPrimitivesCassandra22 with connector.Connector - object recipes extends ConcreteRecipes with connector.Connector { - override def autocreate(space: KeySpace): CreateQuery.Default[ConcreteRecipes, Recipe] = { + object recipes extends Recipes with connector.Connector { + override def autocreate(space: KeySpace): CreateQuery.Default[Recipes, Recipe] = { create.ifNotExists()(space).`with`(comment eqs "This is a test string") } } @@ -81,7 +67,6 @@ class TestDatabase(override val connector: KeySpaceDef) extends Database[TestDat object tableWithSingleKey extends ConcreteTableWithSingleKey with connector.Connector object tableWithCompoundKey extends ConcreteTableWithCompoundKey with connector.Connector object tableWithCompositeKey extends ConcreteTableWithCompositeKey with connector.Connector - object tableWithNoKey extends ConcreteTableWithNoKey with connector.Connector object testTable extends ConcreteTestTable with connector.Connector object timeSeriesTable extends ConcreteTimeSeriesTable with connector.Connector { @@ -99,10 +84,13 @@ class TestDatabase(override val connector: KeySpaceDef) extends Database[TestDat object scalaPrimitivesTable extends ConcreteScalaTypesMapTable with connector.Connector object optionalIndexesTable extends ConcreteOptionalSecondaryIndexTable with connector.Connector + object tuple2Table extends ConcreteTupleColumnTable with connector.Connector + object nestedTupleTable extends ConcreteNestedTupleColumnTable with connector.Connector + object tupleCollectionsTable extends ConcreteTupleCollectionsTable with connector.Connector } object Connector { - val default = ContactPoint.local + val default = connectors.ContactPoint.local .withClusterBuilder(_.withSocketOptions( new SocketOptions() .setConnectTimeoutMillis(20000) diff --git a/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/TestTable.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/TestTable.scala new file mode 100644 index 000000000..b91bab497 --- /dev/null +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/TestTable.scala @@ -0,0 +1,64 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.tables + +import com.outworkers.phantom.connectors.RootConnector +import com.outworkers.phantom.builder.query.InsertQuery +import com.outworkers.phantom.dsl._ + +case class TestRow( + key: String, + list: List[String], + setText: Set[String], + mapTextToText: Map[String, String], + setInt: Set[Int], + mapIntToText: Map[Int, String], + mapIntToInt: Map[Int, Int] +) + +sealed class TestTable extends CassandraTable[ConcreteTestTable, TestRow] { + + object key extends StringColumn(this) with PartitionKey + + object list extends ListColumn[String](this) + + object setText extends SetColumn[String](this) + + object mapTextToText extends MapColumn[String, String](this) + + object setInt extends SetColumn[Int](this) + + object mapIntToText extends MapColumn[Int, String](this) + + object mapIntToInt extends MapColumn[Int, Int](this) +} + +abstract class ConcreteTestTable extends TestTable with RootConnector { + override val tableName = "TestTable" + + def store(row: TestRow): InsertQuery.Default[ConcreteTestTable, TestRow] = { + insert + .value(_.key, row.key) + .value(_.list, row.list) + .value(_.setText, row.setText) + .value(_.mapTextToText, row.mapTextToText) + .value(_.setInt, row.setInt) + .value(_.mapIntToText, row.mapIntToText) + .value(_.mapIntToInt, row.mapIntToInt) + } + +} + diff --git a/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/TestTable2.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/TestTable2.scala new file mode 100644 index 000000000..b18cd2b71 --- /dev/null +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/TestTable2.scala @@ -0,0 +1,30 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.tables + +case class SimpleStringClass(something: String) + +case class SimpleMapOfStringsClass(something: Map[String, Int]) + +case class TestList(key: String, l: List[String]) + +case class TestRow2( + key: String, + optionalInt: Option[Int], + simpleMapOfString: SimpleMapOfStringsClass, + optionalSimpleMapOfString: Option[SimpleMapOfStringsClass], + mapOfStringToCaseClass: Map[String, SimpleMapOfStringsClass] +) \ No newline at end of file diff --git a/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/TimeSeriesTable.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/TimeSeriesTable.scala new file mode 100644 index 000000000..d18c5a884 --- /dev/null +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/TimeSeriesTable.scala @@ -0,0 +1,81 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.tables + +import com.datastax.driver.core.utils.UUIDs +import com.outworkers.phantom.connectors.RootConnector +import com.outworkers.phantom.builder.query.InsertQuery +import com.outworkers.phantom.dsl._ +import org.joda.time.{DateTime, DateTimeZone} + +import scala.concurrent.Future + +case class TimeSeriesRecord( + id: UUID, + name: String, + timestamp: DateTime +) + +case class TimeUUIDRecord( + user: UUID, + id: UUID, + name: String, + timestamp: DateTime +) + +sealed class TimeSeriesTable extends CassandraTable[ConcreteTimeSeriesTable, TimeSeriesRecord] { + object id extends UUIDColumn(this) with PartitionKey + object name extends StringColumn(this) + object timestamp extends DateTimeColumn(this) with ClusteringOrder with Descending { + override val name = "unixTimestamp" + } +} + +abstract class ConcreteTimeSeriesTable extends TimeSeriesTable with RootConnector + +sealed class TimeUUIDTable extends CassandraTable[ConcreteTimeUUIDTable, TimeUUIDRecord] { + + object user extends UUIDColumn(this) with PartitionKey + object id extends TimeUUIDColumn(this) with ClusteringOrder with Descending + object name extends StringColumn(this) + + override def fromRow(row: Row): TimeUUIDRecord = { + TimeUUIDRecord( + user(row), + id(row), + name(row), + id(row).datetime + ) + } +} + +abstract class ConcreteTimeUUIDTable extends TimeUUIDTable with RootConnector { + + def store(rec: TimeUUIDRecord): InsertQuery.Default[ConcreteTimeUUIDTable, TimeUUIDRecord] = { + insert + .value(_.user, rec.user) + .value(_.id, rec.id) + .value(_.name, rec.name) + } + + def retrieve(user: UUID): Future[List[TimeUUIDRecord]] = { + select.where(_.user eqs user).orderBy(_.id ascending).fetch() + } + + def retrieveDescending(user: UUID): Future[List[TimeUUIDRecord]] = { + select.where(_.user eqs user).orderBy(_.id descending).fetch() + } +} diff --git a/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/TimeSeriesTableWithTTL.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/TimeSeriesTableWithTTL.scala new file mode 100644 index 000000000..4db9b8be4 --- /dev/null +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/TimeSeriesTableWithTTL.scala @@ -0,0 +1,40 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.tables + +import com.outworkers.phantom.connectors.RootConnector +import com.outworkers.phantom.dsl._ +import com.outworkers.util.testing._ +import org.joda.time.DateTime + +sealed class TimeSeriesTableWithTTL extends CassandraTable[ConcreteTimeSeriesTableWithTTL, TimeSeriesRecord] { + object id extends UUIDColumn(this) with PartitionKey + object name extends StringColumn(this) + object timestamp extends DateTimeColumn(this) with ClusteringOrder with Descending +} + +abstract class ConcreteTimeSeriesTableWithTTL extends TimeSeriesTableWithTTL with RootConnector + +sealed class TimeSeriesTableWithTTL2 extends CassandraTable[ConcreteTimeSeriesTableWithTTL2, TimeSeriesRecord] { + object id extends UUIDColumn(this) with PartitionKey + object name extends StringColumn(this) + object timestamp extends DateTimeColumn(this) +} + +abstract class ConcreteTimeSeriesTableWithTTL2 extends TimeSeriesTableWithTTL2 with RootConnector { + val testUUID = gen[UUID] +} + diff --git a/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/TupleColumnTable.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/TupleColumnTable.scala new file mode 100644 index 000000000..3edb11c97 --- /dev/null +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/TupleColumnTable.scala @@ -0,0 +1,84 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.tables + +import java.util.UUID + +import com.outworkers.phantom.builder.query.InsertQuery +import com.outworkers.phantom.dsl._ + +import scala.concurrent.Future + +case class TupleRecord(id: UUID, tp: (String, Long)) + +class TupleColumnTable extends CassandraTable[ConcreteTupleColumnTable, TupleRecord] { + object id extends UUIDColumn(this) with PartitionKey + object tp extends TupleColumn[(String, Long)](this) +} + +abstract class ConcreteTupleColumnTable extends TupleColumnTable with RootConnector { + + def store(rec: TupleRecord): InsertQuery.Default[ConcreteTupleColumnTable, TupleRecord] = { + insert + .value(_.id, rec.id) + .value(_.tp, rec.tp) + } + + def findById(id: UUID): Future[Option[TupleRecord]] = { + select.where(_.id eqs id).one() + } +} + +case class NestedTupleRecord(id: UUID, tp: (String, (String, Long))) + +class NestedTupleColumnTable extends CassandraTable[ConcreteNestedTupleColumnTable, NestedTupleRecord] { + object id extends UUIDColumn(this) with PartitionKey + object tp extends TupleColumn[(String, (String, Long))](this) +} + +abstract class ConcreteNestedTupleColumnTable extends NestedTupleColumnTable with RootConnector { + + def store(rec: NestedTupleRecord): InsertQuery.Default[ConcreteNestedTupleColumnTable, NestedTupleRecord] = { + insert + .value(_.id, rec.id) + .value(_.tp, rec.tp) + } + + def findById(id: UUID): Future[Option[NestedTupleRecord]] = { + select.where(_.id eqs id).one() + } +} + + +case class TupleCollectionRecord(id: UUID, tuples: List[(Int, String)]) + +class TupleCollectionsTable extends CassandraTable[ConcreteTupleCollectionsTable, TupleCollectionRecord] { + object id extends UUIDColumn(this) with PartitionKey + object tuples extends ListColumn[(Int, String)](this) +} + +abstract class ConcreteTupleCollectionsTable extends TupleCollectionsTable with RootConnector { + + def store(rec: TupleCollectionRecord): InsertQuery.Default[ConcreteTupleCollectionsTable, TupleCollectionRecord] = { + insert + .value(_.id, rec.id) + .value(_.tuples, rec.tuples) + } + + def findById(id: UUID): Future[Option[TupleCollectionRecord]] = { + select.where(_.id eqs id).one() + } +} diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/tables/package.scala b/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/package.scala similarity index 78% rename from phantom-dsl/src/test/scala/com/websudos/phantom/tables/package.scala rename to phantom-dsl/src/test/scala/com/outworkers/phantom/tables/package.scala index 581ee6fbe..1b61cbc60 100644 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/tables/package.scala +++ b/phantom-dsl/src/test/scala/com/outworkers/phantom/tables/package.scala @@ -1,33 +1,19 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom +package com.outworkers.phantom import java.net.InetAddress import java.util.{Date, UUID} @@ -88,8 +74,8 @@ package object tables { implicit object ArticleSampler extends Sample[Article] { def sample: Article = Article( - gen[String], gen[UUID], + gen[String], gen[Long] ) } @@ -263,4 +249,20 @@ package object tables { implicit object SimpleStringClassSampler extends Sample[SimpleStringClass] { def sample: SimpleStringClass = SimpleStringClass(gen[String]) } + + implicit object TupleRecordSampler extends Sample[TupleRecord] { + override def sample: TupleRecord = TupleRecord(gen[UUID], gen[String] -> gen[Long]) + } + + implicit object NestedTupleRecordSampler extends Sample[NestedTupleRecord] { + override def sample: NestedTupleRecord = NestedTupleRecord( + gen[UUID], gen[String] -> (gen[String] -> gen[Long]) + ) + } + + implicit object TupleCollectionRecordSampler extends Sample[TupleCollectionRecord] { + override def sample: TupleCollectionRecord = TupleCollectionRecord( + gen[UUID], genList[Int]().map(_ -> gen[String]) + ) + } } diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/BasicTableMethods.scala b/phantom-dsl/src/test/scala/com/websudos/phantom/BasicTableMethods.scala deleted file mode 100644 index d84c0f0fb..000000000 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/BasicTableMethods.scala +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom - -import com.websudos.phantom.tables._ -import org.scalatest.{FlatSpec, Matchers} - -class BasicTableMethods extends FlatSpec with Matchers { - - it should "retrieve the correct number of columns in a simple table" in { - TestDatabase.basicTable.columns.size shouldEqual 4 - } - - it should "retrieve the correct number of columns in a big table" in { - TestDatabase.complexCompoundKeyTable.columns.size shouldEqual 10 - } - - it should "retrieve the correct number of primary keys for a table" in { - TestDatabase.simpleCompoundKeyTable.primaryKeys.size shouldEqual 2 - TestDatabase.simpleCompoundKeyTable.partitionKeys.size shouldEqual 1 - } - - it should "retrieve the correct number of clustering keys for a table" in { - TestDatabase.clusteringTable.clusteringColumns.size shouldEqual 2 - } - - it should "create the correct CLUSTERING_ORDER key for a 3 part clustering key" in { - val key = TestDatabase.clusteringTable.clusteringKey - key shouldEqual "WITH CLUSTERING ORDER BY (id2 ASC, id3 DESC)" - } - - it should "create the correct CLUSTERING_ORDER key for a 2 part clustering key" in { - val key = TestDatabase.complexClusteringTable.clusteringKey - key shouldEqual "WITH CLUSTERING ORDER BY (id2 ASC, id3 DESC, placeholder DESC)" - } -} diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/PhantomSuite.scala b/phantom-dsl/src/test/scala/com/websudos/phantom/PhantomSuite.scala deleted file mode 100644 index df4159426..000000000 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/PhantomSuite.scala +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom - -import java.util.concurrent.TimeUnit - -import com.websudos.phantom.connectors.{RootConnector, VersionNumber} -import com.websudos.phantom.tables.{Primitive, TestDatabase} -import com.outworkers.util.lift.{DateTimeSerializer, UUIDSerializer} -import org.scalatest._ -import org.scalatest.concurrent.{PatienceConfiguration, ScalaFutures} -import org.scalatest.time.{Millis, Seconds, Span} - -trait PhantomBaseSuite extends Suite with Matchers - with BeforeAndAfterAll - with RootConnector - with ScalaFutures - with OptionValues { - - protected[this] val defaultScalaTimeoutSeconds = 25 - - private[this] val defaultScalaInterval = 50L - - implicit val formats = net.liftweb.json.DefaultFormats + new UUIDSerializer + new DateTimeSerializer - - implicit val defaultScalaTimeout = scala.concurrent.duration.Duration(defaultScalaTimeoutSeconds, TimeUnit.SECONDS) - - private[this] val defaultTimeoutSpan = Span(defaultScalaTimeoutSeconds, Seconds) - - implicit val defaultTimeout: PatienceConfiguration.Timeout = timeout(defaultTimeoutSpan) - - override implicit val patienceConfig = PatienceConfig( - timeout = defaultTimeoutSpan, - interval = Span(defaultScalaInterval, Millis) - ) - - implicit class CqlConverter[T](val obj: T) { - def asCql()(implicit primitive: com.websudos.phantom.builder.primitives.Primitive[T]): String = { - primitive.asCql(obj) - } - } -} - -trait PhantomSuite extends FlatSpec with PhantomBaseSuite with TestDatabase.connector.Connector { - val database = TestDatabase - - def requireVersion[T](v: VersionNumber)(fn: => T): Unit = if (cassandraVersion.value.compareTo(v) >= 0) fn else () -} - - -trait PhantomFreeSuite extends FreeSpec with PhantomBaseSuite with TestDatabase.connector.Connector { - val database = TestDatabase -} \ No newline at end of file diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/RaceCondition.scala b/phantom-dsl/src/test/scala/com/websudos/phantom/RaceCondition.scala deleted file mode 100644 index 806d674ce..000000000 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/RaceCondition.scala +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom - -import java.util.concurrent.{Callable, Executors} - -import scala.collection.JavaConversions._ - -import org.scalatest.FunSuite - -import com.websudos.phantom.dsl._ - -class RaceCondition extends FunSuite { - - case class Group(id: UUID, name: String) - - class Groups extends CassandraTable[Groups, Group] { - object id extends UUIDColumn(this) with PartitionKey[UUID] - object name extends StringColumn(this) - - override def fromRow(row: Row) = Group(id(row), name(row)) - } - - case class User(id: UUID, name: String) - - class Users extends CassandraTable[Users, User] { - object id extends UUIDColumn(this) with PartitionKey[UUID] - object name extends StringColumn(this) - - override def fromRow(row: Row) = User(id(row), name(row)) - } - - test("parallel tables instantiation") { - val executor = Executors.newFixedThreadPool(2) - val futureResults = executor.invokeAll(List( - new Callable[AnyRef] { - override def call() = new Users - }, - new Callable[AnyRef] { - override def call() = new Groups - } - )) - futureResults.map(_.get()) - } - - test("sequential tables instantiation") { - new Groups - new Users - } -} diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/TableKeyGenerationTest.scala b/phantom-dsl/src/test/scala/com/websudos/phantom/TableKeyGenerationTest.scala deleted file mode 100644 index 0859353d0..000000000 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/TableKeyGenerationTest.scala +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom - -import com.websudos.phantom.exceptions.{InvalidClusteringKeyException, InvalidPrimaryKeyException} -import com.websudos.phantom.tables._ -import org.scalatest.{FlatSpec, Matchers, ParallelTestExecution} - -class TableKeyGenerationTest extends FlatSpec with Matchers with ParallelTestExecution { - - it should "correctly create a Compound key from a table with a single Partition key" in { - TestDatabase.tableWithSingleKey.defineTableKey() shouldEqual s"PRIMARY KEY (id)" - } - - it should "correctly create a Compound key from a table with a single Partition key and one Primary key" in { - TestDatabase.tableWithCompoundKey.defineTableKey() shouldEqual s"PRIMARY KEY (id, second)" - } - - it should "correctly create a Composite key from a table with a two Partition keys and one Primary key" in { - TestDatabase.tableWithCompositeKey.defineTableKey() shouldEqual s"PRIMARY KEY ((id, second_part), second)" - } - - it should "throw an error if the schema has no PartitionKey" in { - intercept[InvalidPrimaryKeyException] { - TestDatabase.tableWithNoKey.defineTableKey() - } - } - - it should "throw an error if the table uses a ClusteringColumn with PrimaryKeys" in { - intercept[InvalidClusteringKeyException] { - TestDatabase.brokenClusteringTable.defineTableKey() - } - } -} diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/base/ClassNameExtraction.scala b/phantom-dsl/src/test/scala/com/websudos/phantom/base/ClassNameExtraction.scala deleted file mode 100644 index cc8204180..000000000 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/base/ClassNameExtraction.scala +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.base - -import org.scalatest.{FlatSpec, Matchers} -import com.websudos.phantom.dsl._ - -case class CustomRecord(name: String, mp: Map[String, String]) - -trait TestTableNames extends CassandraTable[TestTableNames, CustomRecord] { - object rec extends StringColumn(this) with PartitionKey[String] - object sampleLongTextColumnDefinition extends MapColumn[String, String](this) - - override def fromRow(r: Row): CustomRecord = { - CustomRecord( - rec(r), - sampleLongTextColumnDefinition(r) - ) - } -} - -object TestTableNames extends TestTableNames - -object Test extends PrimitiveColumn[TestTableNames, CustomRecord, String](TestTableNames) - -trait TestNames extends TestTableNames - -class Parent extends TestNames -class Parent2 extends Parent - -class ClassNameExtraction extends FlatSpec with Matchers { - - - it should "correctly name objects inside record classes " in { - TestTableNames.rec.name shouldEqual "rec" - } - - it should "correctly extract long object name definitions in nested record classes" in { - TestTableNames.sampleLongTextColumnDefinition.name shouldEqual "sampleLongTextColumnDefinition" - } - - it should "correctly name Cassandra Tables" in { - TestTableNames.tableName shouldEqual "TestTableNames" - } - - it should "correctly extract the object name " in { - Test.name shouldEqual "Test" - } -} diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/base/FieldCollectionTest.scala b/phantom-dsl/src/test/scala/com/websudos/phantom/base/FieldCollectionTest.scala deleted file mode 100644 index cbda49562..000000000 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/base/FieldCollectionTest.scala +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.base - -import com.websudos.phantom.tables.TestDatabase -import org.scalatest.{FlatSpec, Matchers, ParallelTestExecution} - -class FieldCollectionTest extends FlatSpec with Matchers with ParallelTestExecution { - - it should "collect objects in the same order they are written" in { - val collected = TestDatabase.articles.columns.map(_.name).mkString(" ") - val expected = s"${TestDatabase.articles.id.name} ${TestDatabase.articles.name.name} ${TestDatabase.articles.orderId.name}" - collected shouldEqual expected - } - - - it should "correctly reference the same table" in { - TestDatabase.primitives.pkey.table shouldEqual TestDatabase.primitives - } - - it should "initialise fields by default" in { - TestDatabase.articles.columns.size shouldEqual 3 - } -} diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/primitives/PrimitivesTest.scala b/phantom-dsl/src/test/scala/com/websudos/phantom/builder/primitives/PrimitivesTest.scala deleted file mode 100644 index ea7cce5ca..000000000 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/primitives/PrimitivesTest.scala +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.builder.primitives - -import java.nio.ByteBuffer - -import com.websudos.phantom.builder.QueryBuilder -import org.joda.time.{DateTime, DateTimeZone} -import org.scalatest.{FlatSpec, Matchers} -import com.outworkers.util.testing._ - -class PrimitivesTest extends FlatSpec with Matchers { - - it should "coerce a DateTime into a valid timezone string" in { - val date = new DateTime(2014, 6, 2, 10, 5, DateTimeZone.UTC) - - DateSerializer.asCql(date) shouldEqual date.getMillis.toString - } - - it should "convert ByteBuffers to valid hex bytes" in { - val buf = ByteBuffer.wrap(Array[Byte](1, 2, 3, 4, 5)) - Primitive[ByteBuffer].asCql(buf) shouldEqual "0x0102030405" - - buf.position(2) // Non-zero position - Primitive[ByteBuffer].asCql(buf) shouldEqual "0x030405" - - val slice = buf.slice() // Slice with non-zero arrayOffset - Primitive[ByteBuffer].asCql(slice) shouldEqual "0x030405" - } - - it should "autogenerate list primitives for List types" in { - val test = Primitive[List[String]] - val input = genList[String]() - val expected = QueryBuilder.Utils.collection(input.map(Primitive[String].asCql)).queryString - - test.asCql(input) shouldEqual expected - - } - - it should "autogenerate set primitives for Set types" in { - val test = Primitive[Set[String]] - } - - - it should "autogenerate set primitives for Map types" in { - val test = Primitive[Map[String, String]] - } - -} diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/CQLQueryTest.scala b/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/CQLQueryTest.scala deleted file mode 100644 index 6a5cc4e5c..000000000 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/CQLQueryTest.scala +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.builder.query - -import org.scalatest.{Matchers, FlatSpec} -import com.outworkers.util.testing._ - -class CQLQueryTest extends FlatSpec with Matchers { - - it should "create an empty CQL query using the empty method on the companion object" in { - CQLQuery.empty.queryString shouldEqual "" - } - - it should "automatically serialize a list of strings using the apply method from the companion object" in { - val list = List("test", "test2") - - CQLQuery(list).queryString shouldEqual "test, test2" - } - - it should "escape strings without single quotes inside them by wrapping the string in single quotes" in { - val test = gen[String] - CQLQuery.escape(test) shouldEqual s"'$test'" - } - - it should "escape single quotes inside a string using the scape method of the companion" in { - val test = "test'" - CQLQuery.escape(test) shouldEqual "'test'''" - } - -} diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/KeySpaceSuite.scala b/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/KeySpaceSuite.scala deleted file mode 100644 index 7e9950e57..000000000 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/KeySpaceSuite.scala +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.builder.query - -import com.websudos.phantom.PhantomBaseSuite -import com.websudos.phantom.dsl._ -import com.websudos.phantom.tables.TestDatabase -import org.scalatest.{FreeSpec, Matchers, Suite} - -trait KeySpaceSuite { - - self: Suite => - - implicit val keySpace = KeySpace("phantom") -} - -trait SerializationTest extends Matchers with TestDatabase.connector.Connector { - self: Suite => -} - -trait QueryBuilderTest extends FreeSpec with PhantomBaseSuite with TestDatabase.connector.Connector \ No newline at end of file diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/compilation/TypeRestrictionsTest.scala b/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/compilation/TypeRestrictionsTest.scala deleted file mode 100644 index ecc0051d4..000000000 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/compilation/TypeRestrictionsTest.scala +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.builder.query.compilation - -import com.datastax.driver.core.ConsistencyLevel -import com.websudos.phantom.builder.query.SerializationTest -import com.websudos.phantom.dsl.UUID -import com.websudos.phantom.tables.TestDatabase -import org.scalatest.FlatSpec -import com.outworkers.util.testing._ - -class TypeRestrictionsTest extends FlatSpec with SerializationTest { - - val Primitives = TestDatabase.primitives - val tsTable = TestDatabase.timeSeriesTable - - - it should "allow using a correct type for a value method" in { - "Primitives.insert.value(_.boolean, true)" should compile - } - - it should "not allow using a wrong type for a value method" in { - "Primitives.insert.value(_.boolean, 5)" shouldNot compile - } - - it should "not allow chaining 2 limit clauses on the same query" in { - "Primitives.select.all().limit(5).limit(5)" shouldNot compile - } - - it should "not allow chaining multiple order by clauses on the same query" in { - val user = gen[UUID] - """tsTable.select.where(_.id eqs user).orderBy(_.timestamp.desc).orderBy(_.timestamp.desc)""" shouldNot compile - } - - it should "not allow chaining where clauses on the same query, it should only allow where .. and constructs" in { - val user = gen[UUID] - """tsTable.select.where(_.id eqs user).where(_.id eqs user)""" shouldNot compile - } - - it should "not allow specifying multiple consistency bounds on the same query" in { - val user = gen[UUID] - """tsTable.select.where(_.id eqs user).consistencyLevel_=(ConsistencyLevel.ONE).consistencyLevel_=(ConsistencyLevel.ONE)""" shouldNot compile - } -} diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/compilation/WhereClauseRestrictionsTest.scala b/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/compilation/WhereClauseRestrictionsTest.scala deleted file mode 100644 index 056a319f5..000000000 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/compilation/WhereClauseRestrictionsTest.scala +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.builder.query.compilation - -import com.websudos.phantom.builder.query.KeySpaceSuite -import com.websudos.phantom.dsl._ -import com.websudos.phantom.tables.TestDatabase -import com.outworkers.util.testing._ -import org.scalatest.{FlatSpec, Matchers} - -class WhereClauseRestrictionsTest extends FlatSpec with Matchers with KeySpaceSuite { - - val s = gen[String] - val Primitives = TestDatabase.primitives - - it should "allow using a Select.Where clause" in { - "Primitives.select.where(_.pkey eqs gen[String])" should compile - } - - it should "allow using a Select.Where clause with AND chain" in { - "Primitives.select.where(_.pkey eqs gen[String]).and(_.pkey eqs gen[String])" should compile - } - - it should "not allow chaining two Select.Where clauses" in { - "Primitives.select.where(_.pkey eqs gen[String]).where(_.pkey eqs gen[String])" shouldNot compile - } - - it should "not allow re-using a Where clause after an WHERE/AND chain" in { - "Primitives.select.where(_.pkey eqs gen[String]).and(_.pkey eqs gen[String]).where(_.pkey eqs gen[String])" shouldNot compile - } - - it should "Should not allow chaining two Update.Where clauses" in { - "Primitives.update.where(_.pkey eqs gen[String]).where(_.pkey eqs gen[String])" shouldNot compile - } - - it should "not allow chaining two Delete.Where clauses" in { - "Primitives.update.where(_.pkey eqs gen[String]).where(_.pkey eqs gen[String])" shouldNot compile - } -} diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/crud/CountTest.scala b/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/crud/CountTest.scala deleted file mode 100644 index 73c2c5e2e..000000000 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/crud/CountTest.scala +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.builder.query.db.crud - - -import com.websudos.phantom.PhantomSuite -import com.websudos.phantom.dsl.Batch -import com.websudos.phantom.tables._ -import com.outworkers.util.testing._ - -import scala.concurrent.ExecutionContext.Implicits.global - -class CountTest extends PhantomSuite { - - override def beforeAll(): Unit = { - super.beforeAll() - TestDatabase.primitivesJoda.insertSchema() - } - - - it should "retrieve a count of 0 if the table has been truncated" in { - - val chain = for { - truncate <- TestDatabase.primitivesJoda.truncate.future() - count <- TestDatabase.primitivesJoda.select.count.one() - } yield count - - chain successful { - res => { - res.value shouldEqual 0L - } - } - } - - it should "correctly retrieve a count of 1000" in { - val limit = 100 - - val rows = genList[JodaRow](limit) - - val batch = rows.foldLeft(Batch.unlogged)((b, row) => { - b.add(TestDatabase.primitivesJoda.store(row)) - }) - - val chain = for { - truncate <- TestDatabase.primitivesJoda.truncate.future() - batch <- batch.future() - count <- TestDatabase.primitivesJoda.select.count.one() - } yield count - - chain successful { - res => { - res.value shouldEqual limit.toLong - } - } - } -} diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/crud/DistinctTest.scala b/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/crud/DistinctTest.scala deleted file mode 100644 index fe4e0350c..000000000 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/crud/DistinctTest.scala +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.builder.query.db.crud - -import java.util.UUID - -import com.websudos.phantom.PhantomSuite -import com.websudos.phantom.dsl._ -import com.websudos.phantom.tables._ -import org.joda.time.DateTime - -class DistinctTest extends PhantomSuite { - - override def beforeAll(): Unit = { - super.beforeAll() - database.tableWithCompoundKey.insertSchema() - } - - it should "return distinct primary keys" in { - val rows = List( - StubRecord("a", UUID.nameUUIDFromBytes("1".getBytes)), - StubRecord("b", UUID.nameUUIDFromBytes("1".getBytes)), - StubRecord("c", UUID.nameUUIDFromBytes("2".getBytes)), - StubRecord("d", UUID.nameUUIDFromBytes("3".getBytes)) - ) - - val batch = rows.foldLeft(Batch.unlogged)((batch, row) => { - batch.add( - database.tableWithCompoundKey.insert - .value(_.id, row.id) - .value(_.second, UUID.nameUUIDFromBytes(row.name.getBytes)) - .value(_.name, row.name) - ) - }) - - val chain = for { - truncate <- TestDatabase.tableWithCompoundKey.truncate.future() - batch <- batch.future() - list <- TestDatabase.tableWithCompoundKey.select(_.id).distinct.fetch - } yield list - - val expectedResult = rows.filter(_.name != "b").map(_.id) - - whenReady(chain) { - res => res should contain only (expectedResult: _*) - } - } - - private[this] implicit def string2date(date: String): DateTime = new DateTime(date) -} diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/crud/SelectJsonTest.scala b/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/crud/SelectJsonTest.scala deleted file mode 100644 index 5f329c5b8..000000000 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/crud/SelectJsonTest.scala +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.builder.query.db.crud - -import com.datastax.driver.core.exceptions.SyntaxError -import com.websudos.phantom.PhantomSuite -import com.websudos.phantom.dsl._ -import com.websudos.phantom.tables._ -import com.outworkers.util.testing._ -import net.liftweb.json.JsonParser - -class SelectJsonTest extends PhantomSuite { - override def beforeAll(): Unit = { - super.beforeAll() - TestDatabase.primitives.insertSchema() - } - - "A JSON selection clause" should "select an entire row as JSON" in { - val row = gen[Primitive] - - val chain = for { - store <- TestDatabase.primitives.store(row).future() - b <- TestDatabase.primitives.select.json().where(_.pkey eqs row.pkey).one - } yield b - - - if (cassandraVersion.value >= Version.`2.2.0`) { - chain successful { - res => { - res shouldBe defined - val parsed = JsonParser.parse(res.value) - parsed.children.size shouldEqual row.productArity - } - } - } else { - chain.failing[SyntaxError] - } - } - - "A JSON selection clause" should "8 columns as JSON" in { - val row = gen[Primitive] - val expected = (row.pkey, row.long, row.boolean, row.bDecimal, row.double, row.float, row.inet, row.int) - - val chain = for { - store <- TestDatabase.primitives.store(row).future() - get <- TestDatabase.primitives.select(_.pkey, _.long, _.boolean, _.bDecimal, _.double, _.float, _.inet, _.int) - .json() - .where(_.pkey eqs row.pkey).one() - } yield get - - if (cassandraVersion.value >= Version.`2.2.0`) { - chain successful { - res => { - res shouldBe defined - val parsed = JsonParser.parse(res.value) - parsed.children.size shouldEqual expected.productArity - } - } - } else { - chain.failing[SyntaxError] - } - } -} \ No newline at end of file diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/crud/TruncateTest.scala b/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/crud/TruncateTest.scala deleted file mode 100644 index 4076c1258..000000000 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/crud/TruncateTest.scala +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.builder.query.db.crud - -import com.websudos.phantom.PhantomSuite -import com.websudos.phantom.dsl._ -import com.websudos.phantom.tables._ -import com.outworkers.util.testing._ - -class TruncateTest extends PhantomSuite { - - override def beforeAll(): Unit = { - super.beforeAll() - TestDatabase.articles.insertSchema() - } - - it should "truncate all records in a table" in { - val article1 = gen[Article] - val article2 = gen[Article] - val article3 = gen[Article] - val article4 = gen[Article] - - val result = for { - truncateBefore <- TestDatabase.articles.truncate.future() - i1 <- TestDatabase.articles.store(article1).future() - i2 <- TestDatabase.articles.store(article2).future() - i3 <- TestDatabase.articles.store(article3).future() - i4 <- TestDatabase.articles.store(article4).future() - - records <- TestDatabase.articles.select.fetch - truncate <- TestDatabase.articles.truncate.future() - records1 <- TestDatabase.articles.select.fetch - } yield (records, records1) - - - result successful { - case (init, updated) => { - init should have size 4 - info (s"inserted exactly ${init.size} records") - - updated should have size 0 - info (s"got exactly ${updated.size} records") - } - } - } -} diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/ordering/OrderByTest.scala b/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/ordering/OrderByTest.scala deleted file mode 100644 index 0a829ddef..000000000 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/ordering/OrderByTest.scala +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright 2013-2016 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.builder.query.db.ordering - -import java.util.UUID - -import com.datastax.driver.core.utils.UUIDs -import com.websudos.phantom.PhantomSuite -import com.websudos.phantom.tables.{TestDatabase, TimeUUIDRecord} -import com.outworkers.util.testing._ -import com.websudos.phantom.dsl._ - -import scala.concurrent.Future - -class OrderByTest extends PhantomSuite { - - override def beforeAll(): Unit = { - super.beforeAll() - database.timeuuidTable.insertSchema() - } - - it should "store a series of records and retrieve them in the right order" in { - - val user = gen[UUID] - - info(s"Generating a list of records with the same partition key value: $user") - val records = genList[TimeUUIDRecord]().map(_.copy(user = user)) - - val chain = for { - store <- Future.sequence(records.map(database.timeuuidTable.store(_).future())) - get <- database.timeuuidTable.retrieve(user) - desc <- database.timeuuidTable.retrieveDescending(user) - } yield (get, desc) - - - whenReady(chain) { - case (asc, desc) => { - val orderedAsc = records.sortWith((a, b) => { a.id.compareTo(b.id) <= 0 }) - - info("The ascending results retrieved from the DB") - info(asc.mkString("\n")) - - info("The ascending results expected") - info(orderedAsc.mkString("\n")) - - asc shouldEqual orderedAsc - - val orderedDesc = records.sortWith((a, b) => { a.id.compareTo(b.id) >= 0 }) - - info("The ascending results retrieved from the DB") - info(desc.mkString("\n")) - - info("The ascending results expected") - info(orderedDesc.mkString("\n")) - - desc shouldEqual orderedDesc - - } - } - } - -} diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/select/PartialSelectTest.scala b/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/select/PartialSelectTest.scala deleted file mode 100644 index dcddf99ed..000000000 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/select/PartialSelectTest.scala +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.builder.query.db.select - -import com.websudos.phantom.PhantomSuite -import com.websudos.phantom.dsl._ -import com.websudos.phantom.tables._ -import com.outworkers.util.testing._ - - -class PartialSelectTest extends PhantomSuite { - - override def beforeAll(): Unit = { - super.beforeAll() - TestDatabase.primitives.insertSchema() - } - - "Partially selecting 2 fields" should "correctly select the fields" in { - val row = gen[Primitive] - - val chain = for { - truncate <- TestDatabase.primitives.truncate.future() - insertDone <- TestDatabase.primitives.store(row).future() - listSelect <- TestDatabase.primitives.select(_.pkey).fetch - oneSelect <- TestDatabase.primitives.select(_.long, _.boolean).where(_.pkey eqs row.pkey).one - } yield (listSelect, oneSelect) - - chain successful { - case (res, res2) => { - res shouldEqual List(row.pkey) - res2.value shouldEqual Tuple2(row.long, row.boolean) - } - } - } -} diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/specialized/InOperatorTest.scala b/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/specialized/InOperatorTest.scala deleted file mode 100644 index 52414df38..000000000 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/specialized/InOperatorTest.scala +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.builder.query.db.specialized - -import com.websudos.phantom.PhantomSuite -import com.websudos.phantom.dsl._ -import com.websudos.phantom.tables.{ TestDatabase, Recipe } -import com.outworkers.util.testing._ - -class InOperatorTest extends PhantomSuite { - - override def beforeAll(): Unit = { - super.beforeAll() - TestDatabase.recipes.insertSchema() - } - - it should "find a record with a in operator if the record exists" in { - val recipe = gen[Recipe] - - val chain = for { - done <- TestDatabase.recipes.store(recipe).future() - select <- TestDatabase.recipes.select.where(_.url in List(recipe.url, gen[EmailAddress].value)).one() - } yield select - - chain.successful { - res => { - res.value.url shouldEqual recipe.url - } - } - } - - it should "not find a record with a in operator if the record doesn't exists" in { - val recipe = gen[Recipe] - - val chain = for { - done <- TestDatabase.recipes.store(recipe).future() - select <- TestDatabase.recipes.select.where(_.url in List(gen[EmailAddress].value)).one() - } yield select - - chain.successful { - res => { - res shouldBe empty - } - } - } - -} diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/specialized/JodaDateTimeColumnTest.scala b/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/specialized/JodaDateTimeColumnTest.scala deleted file mode 100644 index 3b79d1779..000000000 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/specialized/JodaDateTimeColumnTest.scala +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.builder.query.db.specialized - -import com.websudos.phantom.PhantomSuite -import com.websudos.phantom.dsl._ -import com.websudos.phantom.tables._ -import com.outworkers.util.testing._ - -class JodaDateTimeColumnTest extends PhantomSuite { - - override def beforeAll(): Unit = { - super.beforeAll() - database.primitivesJoda.insertSchema() - } - - it should "correctly insert and extract a JodaTime date" in { - val row = gen[JodaRow] - - val chain = for { - store <- TestDatabase.primitivesJoda.store(row).future() - select <- TestDatabase.primitivesJoda.select.where(_.pkey eqs row.pkey).one() - } yield select - - chain successful { - res => { - res.value.pkey shouldEqual row.pkey - res.value.intColumn shouldEqual row.intColumn - res.value.timestamp shouldEqual row.timestamp - } - } - } -} diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/specialized/OptionalIndexesTest.scala b/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/specialized/OptionalIndexesTest.scala deleted file mode 100644 index a35138190..000000000 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/db/specialized/OptionalIndexesTest.scala +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.builder.query.db.specialized - -import com.datastax.driver.core.exceptions.InvalidQueryException -import com.websudos.phantom.PhantomSuite -import com.websudos.phantom.tables.OptionalSecondaryRecord -import com.websudos.phantom.dsl._ -import com.outworkers.util.testing._ - -class OptionalIndexesTest extends PhantomSuite { - - override def beforeAll(): Unit = { - super.beforeAll() - database.optionalIndexesTable.insertSchema() - } - - it should "store a record and then retrieve it using an optional index" in { - val sample = OptionalSecondaryRecord( - gen[UUID], - genOpt[Int] - ) - - val chain = for { - store <- database.optionalIndexesTable.store(sample) - get <- database.optionalIndexesTable.findById(sample.id) - get2 <- database.optionalIndexesTable.findByOptionalSecondary(sample.secondary.value) - } yield (get, get2) - - whenReady(chain) { - case (byId, byIndex) => { - byId shouldBe defined - byId.value shouldEqual sample - - byIndex shouldBe defined - byIndex.value shouldEqual sample - } - } - } - - it should "not be able to delete records by their secondary index" in { - val sample = OptionalSecondaryRecord( - gen[UUID], - genOpt[Int] - ) - - val chain = for { - store <- database.optionalIndexesTable.store(sample) - get <- database.optionalIndexesTable.findByOptionalSecondary(sample.secondary.value) - delete <- database.optionalIndexesTable.delete.where(_.secondary eqs sample.secondary.value).future() - get2 <- database.optionalIndexesTable.findByOptionalSecondary(sample.secondary.value) - } yield (get, get2) - - chain.failing[InvalidQueryException] - } - -} diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/prepared/BatchablePreparedInsertQueryTest.scala b/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/prepared/BatchablePreparedInsertQueryTest.scala deleted file mode 100644 index cc18d72ae..000000000 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/query/prepared/BatchablePreparedInsertQueryTest.scala +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.builder.query.prepared - -import com.websudos.phantom.PhantomSuite -import com.websudos.phantom.dsl._ -import com.websudos.phantom.tables.{Recipe, TestDatabase} -import com.outworkers.util.testing._ - -class BatchablePreparedInsertQueryTest extends PhantomSuite { - - override def beforeAll(): Unit = { - super.beforeAll() - TestDatabase.recipes.insertSchema() - } - - it should "serialize an prepared batch query" in { - val sample1 = gen[Recipe] - val sample2 = gen[Recipe] - - val query = TestDatabase.recipes.insert - .p_value(_.uid, ?) - .p_value(_.url, ?) - .p_value(_.servings, ?) - .p_value(_.ingredients, ?) - .p_value(_.description, ?) - .p_value(_.lastcheckedat, ?) - .p_value(_.props, ?) - .prepare() - - def bind(recipe: Recipe): ExecutablePreparedQuery = query.bind( - recipe.uid, - recipe.url, - recipe.servings, - recipe.ingredients, - recipe.description, - recipe.lastCheckedAt, - recipe.props - ) - - val exec1 = bind(sample1) - val exec2 = bind(sample2) - - val chain = for { - truncate <- TestDatabase.recipes.truncate.future() - store <- Batch.unlogged.add(exec1, exec2).future() - get <- TestDatabase.recipes.select.fetch() - } yield get - - whenReady(chain) { - res => { - res should contain theSameElementsAs Seq(sample1, sample2) - } - } - } -} diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/serializers/CollectionModifiersSerialisationTest.scala b/phantom-dsl/src/test/scala/com/websudos/phantom/builder/serializers/CollectionModifiersSerialisationTest.scala deleted file mode 100644 index cbaa57a60..000000000 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/serializers/CollectionModifiersSerialisationTest.scala +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.builder.serializers - -import com.websudos.phantom.builder.QueryBuilder -import org.scalatest.{FreeSpec, Matchers} - -class CollectionModifiersSerialisationTest extends FreeSpec with Matchers { - - "The collection modifier query builder" - { - - "should append a pre-serialized list as a collection" in { - QueryBuilder.Collections.append("test", QueryBuilder.Utils.collection(List("test1", "test2")).queryString) - .queryString shouldEqual "test = test + [test1, test2]" - } - - "should append a single element to a list collection" in { - QueryBuilder.Collections.append("test", "test1", "test2").queryString shouldEqual "test = test + [test1, test2]" - } - - "should append elements to a list collection" in { - QueryBuilder.Collections.append("test", "test1", "test2", "test3").queryString shouldEqual "test = test + [test1, test2, test3]" - } - - "should prepend a pre-serialized list as a collection" in { - QueryBuilder.Collections.prepend("test", QueryBuilder.Utils.collection(List("test1", "test2")).queryString) - .queryString shouldEqual "test = [test1, test2] + test" - } - - "should prepend a single element to a list collection" in { - QueryBuilder.Collections.prepend("test", "test1", "test2").queryString shouldEqual "test = [test1, test2] + test" - } - - "should prepend multiple elements to a list collection" in { - QueryBuilder.Collections.prepend("test", "test1", "test2", "test3").queryString shouldEqual "test = [test1, test2, test3] + test" - } - } -} diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/serializers/CreateQueryBuilderTest.scala b/phantom-dsl/src/test/scala/com/websudos/phantom/builder/serializers/CreateQueryBuilderTest.scala deleted file mode 100644 index 50c2f7cc6..000000000 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/serializers/CreateQueryBuilderTest.scala +++ /dev/null @@ -1,235 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.builder.serializers - -import java.util.concurrent.TimeUnit - -import com.twitter.conversions.storage._ -import com.twitter.util.{Duration => TwitterDuration} -import com.websudos.phantom.builder.QueryBuilder -import com.websudos.phantom.builder.query.SerializationTest -import com.websudos.phantom.builder.syntax.CQLSyntax -import com.websudos.phantom.dsl._ -import com.websudos.phantom.tables.TestDatabase -import org.joda.time.Seconds -import org.scalatest.{FreeSpec, Matchers} - -import scala.concurrent.duration._ - -class CreateQueryBuilderTest extends FreeSpec with Matchers with SerializationTest { - - val BasicTable = TestDatabase.basicTable - final val DefaultTtl = 500 - final val OneDay = 86400 - - "The CREATE query builder" - { - "should allow specifying table creation options" - { - - "serialise a simple create query with a SizeTieredCompactionStrategy and no compaction strategy options set" in { - - val qb = BasicTable.create.`with`(compaction eqs SizeTieredCompactionStrategy).qb.queryString - - qb shouldEqual "CREATE TABLE phantom.basicTable (id uuid, id2 uuid, id3 uuid, placeholder text, PRIMARY KEY (id, id2, id3)) WITH compaction = {'class'" + - ": 'SizeTieredCompactionStrategy'}" - } - - "serialise a simple create query with a SizeTieredCompactionStrategy and 1 compaction strategy options set" in { - - val qb = BasicTable.create.`with`(compaction eqs LeveledCompactionStrategy.sstable_size_in_mb(50)).qb.queryString - - qb shouldEqual "CREATE TABLE phantom.basicTable (id uuid, id2 uuid, id3 uuid, placeholder text, PRIMARY KEY (id, id2, id3)) WITH compaction = {'class': 'LeveledCompactionStrategy', 'sstable_size_in_mb': 50}" - } - - "serialise a simple create query with a SizeTieredCompactionStrategy and 1 compaction strategy options set and a compression strategy set" in { - val qb = BasicTable.create - .`with`(compaction eqs LeveledCompactionStrategy.sstable_size_in_mb(50)) - .and(compression eqs LZ4Compressor.crc_check_chance(0.5)) - .qb.queryString - - qb shouldEqual """CREATE TABLE phantom.basicTable (id uuid, id2 uuid, id3 uuid, placeholder text, PRIMARY KEY (id, id2, id3)) WITH compaction = {'class': 'LeveledCompactionStrategy', 'sstable_size_in_mb': 50} AND compression = {'sstable_compression': 'LZ4Compressor', 'crc_check_chance': 0.5}""" - } - - "add a comment option to a create query" in { - val qb = BasicTable.create - .`with`(comment eqs "testing") - .qb.queryString - - qb shouldEqual "CREATE TABLE phantom.basicTable (id uuid, id2 uuid, id3 uuid, placeholder text, PRIMARY KEY (id, id2, id3)) WITH comment = 'testing'" - } - - "allow specifying a read_repair_chance clause" in { - val qb = BasicTable.create.`with`(read_repair_chance eqs 5D).qb.queryString - qb shouldEqual "CREATE TABLE phantom.basicTable (id uuid, id2 uuid, id3 uuid, placeholder text, PRIMARY KEY (id, id2, id3)) WITH read_repair_chance = 5.0" - } - - "allow specifying a dclocal_read_repair_chance clause" in { - val qb = BasicTable.create.`with`(dclocal_read_repair_chance eqs 5D).qb.queryString - qb shouldEqual "CREATE TABLE phantom.basicTable (id uuid, id2 uuid, id3 uuid, placeholder text, PRIMARY KEY (id, id2, id3)) WITH dclocal_read_repair_chance = 5.0" - } - - "allow specifying a replicate_on_write clause" in { - val qb = BasicTable.create.`with`(replicate_on_write eqs true).qb.queryString - qb shouldEqual "CREATE TABLE phantom.basicTable (id uuid, id2 uuid, id3 uuid, placeholder text, PRIMARY KEY (id, id2, id3)) WITH replicate_on_write = true" - } - - "allow specifying a custom gc_grace_seconds clause" in { - val qb = BasicTable.create.`with`(gc_grace_seconds eqs 5.seconds).qb.queryString - qb shouldEqual "CREATE TABLE phantom.basicTable (id uuid, id2 uuid, id3 uuid, placeholder text, PRIMARY KEY (id, id2, id3)) WITH gc_grace_seconds = 5" - } - - "allow specifying larger custom units as gc_grace_seconds" in { - val qb = BasicTable.create.`with`(gc_grace_seconds eqs 1.day).qb.queryString - qb shouldEqual "CREATE TABLE phantom.basicTable (id uuid, id2 uuid, id3 uuid, placeholder text, PRIMARY KEY (id, id2, id3)) WITH gc_grace_seconds = 86400" - } - - "allow specifying custom gc_grade_seconds using the Joda Time ReadableInstant and Second API" in { - val qb = BasicTable.create.`with`(gc_grace_seconds eqs Seconds.seconds(OneDay)).qb.queryString - qb shouldEqual "CREATE TABLE phantom.basicTable (id uuid, id2 uuid, id3 uuid, placeholder text, PRIMARY KEY (id, id2, id3)) WITH gc_grace_seconds = 86400" - } - - "allow specifying a bloom_filter_fp_chance using a Double param value" in { - val qb = BasicTable.create.`with`(bloom_filter_fp_chance eqs 5D).qb.queryString - qb shouldEqual "CREATE TABLE phantom.basicTable (id uuid, id2 uuid, id3 uuid, placeholder text, PRIMARY KEY (id, id2, id3)) WITH " + - "bloom_filter_fp_chance = 5.0" - } - } - - "should allow specifying cache strategies " - { - "specify Cache.None as a cache strategy" in { - val qb = BasicTable.create.`with`(caching eqs Cache.None()).qb.queryString - - val baseQuery = "CREATE TABLE phantom.basicTable (id uuid, id2 uuid, id3 uuid, placeholder text, PRIMARY KEY (id, id2, id3))" - - if (session.v4orNewer) { - qb shouldEqual s"$baseQuery WITH caching = {'keys': 'none', 'rows_per_partition': 'none'}" - } else { - qb shouldEqual s"$baseQuery WITH caching = 'none'" - } - } - - "specify Cache.KeysOnly as a caching strategy" in { - val qb = BasicTable.create.`with`(caching eqs Cache.KeysOnly()).qb.queryString - - if (session.v4orNewer) { - qb shouldEqual "CREATE TABLE phantom.basicTable (id uuid, id2 uuid, id3 uuid, placeholder text," + - " PRIMARY KEY (id, id2, id3)) WITH caching = {'keys': 'all', 'rows_per_partition': 'none'}" - } else { - qb shouldEqual "CREATE TABLE phantom.basicTable (id uuid, id2 uuid, id3 uuid, placeholder text," + - " PRIMARY KEY (id, id2, id3)) WITH caching = 'keys_only'" - } - } - - "specify Cache.RowsOnly as a caching strategy" in { - val qb = BasicTable.create.`with`(caching eqs Cache.RowsOnly()).qb.queryString - - if (session.v4orNewer) { - qb shouldEqual "CREATE TABLE phantom.basicTable (id uuid, id2 uuid, id3 uuid, placeholder text," + - " PRIMARY KEY (id, id2, id3)) WITH caching = {'rows_per_partition': 'all'}" - } else { - qb shouldEqual "CREATE TABLE phantom.basicTable (id uuid, id2 uuid, id3 uuid, placeholder text," + - " PRIMARY KEY (id, id2, id3)) WITH caching = 'rows_only'" - } - } - - "specify Cache.All as a caching strategy" in { - val qb = BasicTable.create.`with`(caching eqs Cache.All()).qb.queryString - val baseQuery = "CREATE TABLE phantom.basicTable (id uuid, id2 uuid, id3 uuid, placeholder text, PRIMARY KEY (id, id2, id3))" - - if (session.v4orNewer) { - qb shouldEqual s"$baseQuery WITH caching = {'keys': 'all', 'rows_per_partition': 'all'}" - } else { - qb shouldEqual s"$baseQuery WITH caching = 'all'" - } - - } - } - - "should allow specifying a default_time_to_live" - { - "specify a default time to live using a Long value" in { - val qb = BasicTable.create.`with`(default_time_to_live eqs DefaultTtl.toLong).qb.queryString - qb shouldEqual "CREATE TABLE phantom.basicTable (id uuid, id2 uuid, id3 uuid, placeholder text, PRIMARY KEY (id, id2, id3)) WITH default_time_to_live = 500" - } - - "specify a default time to live using a org.joda.time.Seconds value" in { - val qb = BasicTable.create.`with`(default_time_to_live eqs Seconds.seconds(DefaultTtl)).qb.queryString - qb shouldEqual "CREATE TABLE phantom.basicTable (id uuid, id2 uuid, id3 uuid, placeholder text, PRIMARY KEY (id, id2, id3)) WITH default_time_to_live = 500" - } - - "specify a default time to live using a scala.concurrent.duration.FiniteDuration value" in { - val qb = BasicTable.create.`with`(default_time_to_live eqs FiniteDuration(DefaultTtl, TimeUnit.SECONDS)).qb.queryString - qb shouldEqual "CREATE TABLE phantom.basicTable (id uuid, id2 uuid, id3 uuid, placeholder text, PRIMARY KEY (id, id2, id3)) WITH default_time_to_live = 500" - } - } - - "should allow specifying a clustering order" - { - "specify a single column clustering order with ascending ordering" in { - val column = ("test", CQLSyntax.Ordering.asc) :: Nil - - val qb = QueryBuilder.Create.clusteringOrder(column).queryString - - qb shouldEqual "CLUSTERING ORDER BY (test ASC)" - } - - "specify a single column clustering order with descending ordering" in { - val column = ("test", CQLSyntax.Ordering.desc) :: Nil - - val qb = QueryBuilder.Create.clusteringOrder(column).queryString - - qb shouldEqual "CLUSTERING ORDER BY (test DESC)" - } - - "specify multiple columns and preserve ordering" in { - val column1 = ("test", CQLSyntax.Ordering.asc) - val column2 = ("test2", CQLSyntax.Ordering.desc) - - val columns = List(column1, column2) - - val qb = QueryBuilder.Create.clusteringOrder(columns).queryString - - qb shouldEqual "CLUSTERING ORDER BY (test ASC, test2 DESC)" - } - } - - "should allow generating secondary indexes based on trait mixins" - { - "specify a secondary index on a non-map column" in { - val qb = QueryBuilder.Create.index("t", "k", "col").queryString - - qb shouldEqual "CREATE INDEX IF NOT EXISTS t_col_idx ON k.t(col)" - } - - "specify a secondary index on a map column for the keys of a map column" in { - val qb = QueryBuilder.Create.mapIndex("t", "k", "col").queryString - - qb shouldEqual "CREATE INDEX IF NOT EXISTS t_col_idx ON k.t(keys(col))" - } - } - - } -} diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/serializers/CreateQuerySerialisationTest.scala b/phantom-dsl/src/test/scala/com/websudos/phantom/builder/serializers/CreateQuerySerialisationTest.scala deleted file mode 100644 index 2f8d82a3b..000000000 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/serializers/CreateQuerySerialisationTest.scala +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.builder.serializers - -import com.websudos.phantom.builder.query.QueryBuilderTest -import com.websudos.phantom.dsl._ -import com.websudos.phantom.tables.TestDatabase - -class CreateQuerySerialisationTest extends QueryBuilderTest { - - "The CREATE query builder" - { - "should generate clustering keys for a schema queries" - { - "generate a descending order clustering key on a table with a single clustering key" in { - val qb = TestDatabase.timeSeriesTable.create.qb.queryString - - qb shouldEqual "CREATE TABLE phantom.timeSeriesTable (id uuid, name text, unixTimestamp timestamp, " + - "PRIMARY KEY (id, unixTimestamp)) WITH CLUSTERING ORDER BY (unixTimestamp DESC)" - } - } - } -} diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/serializers/DeleteQueryBuilderTest.scala b/phantom-dsl/src/test/scala/com/websudos/phantom/builder/serializers/DeleteQueryBuilderTest.scala deleted file mode 100644 index de92c7cd3..000000000 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/serializers/DeleteQueryBuilderTest.scala +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.builder.serializers - -import com.websudos.phantom.builder.QueryBuilder -import com.websudos.phantom.builder.query.QueryBuilderTest - -class DeleteQueryBuilderTest extends QueryBuilderTest { - - "The DELETE query builder" - { - - "should allow specifying column delete queries" - { - val qb = QueryBuilder.Delete.deleteColumn("table", "col").queryString - qb shouldEqual "DELETE col FROM table" - } - - "should allow specifying full delete queries" - { - val qb = QueryBuilder.Delete.delete("table").queryString - qb shouldEqual "DELETE FROM table" - } - - } -} diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/serializers/InsertQueryBuilderTest.scala b/phantom-dsl/src/test/scala/com/websudos/phantom/builder/serializers/InsertQueryBuilderTest.scala deleted file mode 100644 index 0229cafc7..000000000 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/serializers/InsertQueryBuilderTest.scala +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.builder.serializers - -import com.websudos.phantom.builder.QueryBuilder -import com.websudos.phantom.builder.query.{CQLQuery, QueryBuilderTest} - -class InsertQueryBuilderTest extends QueryBuilderTest { - - "The INSERT query builder" - { - - "should allow appending columns and values to a query" - { - - "should serialize a sequence of appended values" in { - val query = QueryBuilder.Insert.values(List(CQLQuery("a"), CQLQuery("b"))).queryString - - query shouldEqual "VALUES(a, b)" - } - - "should serialize a sequence of column definitions" in { - val query = QueryBuilder.Insert.columns(List(CQLQuery("a"), CQLQuery("b"))).queryString - query shouldEqual "(a, b)" - } - - } - } -} diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/serializers/UpdateQueryBuilderTest.scala b/phantom-dsl/src/test/scala/com/websudos/phantom/builder/serializers/UpdateQueryBuilderTest.scala deleted file mode 100644 index 8f0417256..000000000 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/builder/serializers/UpdateQueryBuilderTest.scala +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.builder.serializers - -import com.websudos.phantom.builder.QueryBuilder -import com.websudos.phantom.builder.query.QueryBuilderTest -import com.outworkers.util.testing._ - -class UpdateQueryBuilderTest extends QueryBuilderTest { - - "The UPDATE query builder" - { - - "should allow specifying SET options" - { - - "should allowing updating the value of a column with a setTo clause" in { - QueryBuilder.Update.setTo("a", "b").queryString shouldEqual "a = b" - } - - "should allow specifying a set clause in an UPDATE query" in { - QueryBuilder.Update - .set(QueryBuilder.Update.setTo("a", "b")) - .queryString shouldEqual "SET a = b" - } - - "should allow specifying multiple SET clauses and chaining them" in { - val c1 = QueryBuilder.Update.setTo("a", "b") - val c2 = QueryBuilder.Update.setTo("c", "d") - - QueryBuilder.Update.chain(List(c1, c2)).queryString shouldEqual "a = b, c = d" - } - } - - "should allow specifying USING clause options" - { - "should allow specifying a timestamp clause" in { - val str = gen[Long] - QueryBuilder.timestamp(str).queryString shouldEqual s"TIMESTAMP $str" - } - } - - "should allow specifying CAS options" - { - - "should allow specifying a single IF clause" in { - QueryBuilder.Update.onlyIf(QueryBuilder.Where.eqs("a", "b")).queryString shouldEqual "IF a = b" - } - - "should allow specifying an AND clause" in { - QueryBuilder.Update.and(QueryBuilder.Where.eqs("a", "b")).queryString shouldEqual "AND a = b" - } - } - } -} diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/database/DatabaseTest.scala b/phantom-dsl/src/test/scala/com/websudos/phantom/database/DatabaseTest.scala deleted file mode 100644 index 4adeaab02..000000000 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/database/DatabaseTest.scala +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.database - -import com.websudos.phantom.PhantomSuite -import com.websudos.phantom.dsl._ -import com.outworkers.util.testing._ - -class DatabaseTest extends PhantomSuite { - object db extends TestDatabase - - it should "instantiate a database and collect references to the tables" in { - db.tables.size shouldEqual 4 - } - - it should "automatically generate the CQL schema and initialise tables " in { - db.autocreate().future().successful { - res => res.nonEmpty shouldEqual true - } - } - - it should "respect any auto-creation options specified for the particular table" in { - val space = KeySpace("phantom_test") - val queries = db.autocreate().queries()(space) - - val target = db.recipes.autocreate(space).qb - - queries should contain (target) - } -} diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/database/TestDatabase.scala b/phantom-dsl/src/test/scala/com/websudos/phantom/database/TestDatabase.scala deleted file mode 100644 index 4a63be4c7..000000000 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/database/TestDatabase.scala +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.database - -import com.websudos.phantom.connectors.ContactPoint -import com.websudos.phantom.tables._ - - -private[this] object DefaultKeyspace { - lazy val local = ContactPoint.local.keySpace("phantom") -} - -class TestDatabase extends Database[TestDatabase](DefaultKeyspace.local) { - object enumTable extends EnumTable with connector.Connector - object basicTable extends BasicTable with connector.Connector - object jsonTable extends JsonTable with connector.Connector - object recipes extends Recipes with connector.Connector -} - -object TestDatabase extends TestDatabase - - -/* -class ValueInitDatabase extends Database[ValueInitDatabase](DefaultKeyspace.local) { - val basicTable = new BasicTable with connector.Connector - val enumTable = new EnumTable with connector.Connector - val jsonTable = new JsonTable with connector.Connector - val recipes = new Recipes with connector.Connector -}*/ \ No newline at end of file diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/tables/Articles.scala b/phantom-dsl/src/test/scala/com/websudos/phantom/tables/Articles.scala deleted file mode 100644 index 5ecd9658b..000000000 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/tables/Articles.scala +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.tables - -import com.outworkers.util.testing.sample -import com.websudos.phantom.builder.query.InsertQuery -import com.websudos.phantom.dsl._ - -case class Article( - name: String, - id: UUID, - orderId: Long -) - -sealed class Articles extends CassandraTable[ConcreteArticles, Article] { - - object id extends UUIDColumn(this) with PartitionKey[UUID] - object name extends StringColumn(this) - object orderId extends LongColumn(this) - - override def fromRow(row: Row): Article = extract[Article].apply(row) -} - -abstract class ConcreteArticles extends Articles with RootConnector { - override def tableName: String = "articles" - - def store(article: Article): InsertQuery.Default[ConcreteArticles, Article] = { - insert - .value(_.id, article.id) - .value(_.name, article.name) - .value(_.orderId, article.orderId) - } -} - - -sealed class ArticlesByAuthor extends CassandraTable[ConcreteArticlesByAuthor, Article] { - - object author_id extends UUIDColumn(this) with PartitionKey[UUID] - object category extends UUIDColumn(this) with PartitionKey[UUID] - object id extends UUIDColumn(this) with PrimaryKey[UUID] - - object name extends StringColumn(this) - object orderId extends LongColumn(this) - - override def fromRow(row: Row): Article = { - Article( - name = name(row), - id = id(row), - orderId = orderId(row) - ) - } -} - -abstract class ConcreteArticlesByAuthor extends ArticlesByAuthor with RootConnector { - - def store(author: UUID, category: UUID, article: Article): InsertQuery.Default[ConcreteArticlesByAuthor, Article] = { - insert - .value(_.author_id, author) - .value(_.category, category) - .value(_.id, article.id) - .value(_.name, article.name) - .value(_.orderId, article.orderId) - } -} diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/tables/BasicTable.scala b/phantom-dsl/src/test/scala/com/websudos/phantom/tables/BasicTable.scala deleted file mode 100644 index 17ed98da9..000000000 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/tables/BasicTable.scala +++ /dev/null @@ -1,226 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.tables - -import com.websudos.phantom.builder.query.InsertQuery -import com.websudos.phantom.dsl._ - -class BasicTable extends CassandraTable[ConcreteBasicTable, String] { - - object id extends UUIDColumn(this) with PartitionKey[UUID] - object id2 extends UUIDColumn(this) with PrimaryKey[UUID] - object id3 extends UUIDColumn(this) with PrimaryKey[UUID] - object placeholder extends StringColumn(this) - - def fromRow(r: Row): String = placeholder(r) -} - -abstract class ConcreteBasicTable extends BasicTable with RootConnector - - -object Records extends Enumeration { - type Records = Value - val TypeOne, TypeTwo, TypeThree = Value -} - -trait NamedRecords extends Enumeration { - type NamedRecords = Value - val One = Value("one") - val Two = Value("two") -} - -object NamedRecords extends NamedRecords - -case class EnumRecord( - name: String, - enum: Records.type#Value, - optEnum: Option[Records.type#Value] -) - -case class NamedEnumRecord( - name: String, - enum: NamedRecords.type#Value, - optEnum: Option[NamedRecords.type#Value] -) - -case class NamedPartitionRecord( - enum: NamedRecords#Value, - id: UUID -) - -abstract class EnumTable extends CassandraTable[ConcreteEnumTable, EnumRecord] { - object id extends StringColumn(this) with PartitionKey[String] - object enum extends EnumColumn[Records.type](this, Records) - object optEnum extends OptionalEnumColumn[Records.type](this, Records) - - def fromRow(row: Row): EnumRecord = { - EnumRecord( - name = id(row), - enum = enum(row), - optEnum = optEnum(row) - ) - } -} - -abstract class ConcreteEnumTable extends EnumTable with RootConnector { - def store(sample: EnumRecord): InsertQuery.Default[ConcreteEnumTable, EnumRecord] = { - insert - .value(_.id, sample.name) - .value(_.enum, sample.enum) - .value(_.optEnum, sample.optEnum) - } -} - - -sealed class NamedEnumTable extends CassandraTable[ConcreteNamedEnumTable, NamedEnumRecord] { - object id extends StringColumn(this) with PartitionKey[String] - object enum extends EnumColumn[NamedRecords.type](this, NamedRecords) - object optEnum extends OptionalEnumColumn[NamedRecords.type](this, NamedRecords) - - def fromRow(row: Row): NamedEnumRecord = { - NamedEnumRecord( - id(row), - enum(row), - optEnum(row) - ) - } -} - -abstract class ConcreteNamedEnumTable extends NamedEnumTable with RootConnector { - def store(sample: NamedEnumRecord): InsertQuery.Default[ConcreteNamedEnumTable, NamedEnumRecord] = { - insert - .value(_.id, sample.name) - .value(_.enum, sample.enum) - .value(_.optEnum, sample.optEnum) - } -} - - -sealed class NamedPartitionEnumTable extends CassandraTable[ConcreteNamedPartitionEnumTable, NamedPartitionRecord] { - object enum extends EnumColumn[NamedRecords](this, NamedRecords) with PartitionKey[NamedRecords#Value] - object id extends UUIDColumn(this) with PrimaryKey[UUID] - - def fromRow(row: Row): NamedPartitionRecord = { - NamedPartitionRecord( - enum = enum(row), - id = id(row) - ) - } -} - -abstract class ConcreteNamedPartitionEnumTable extends NamedPartitionEnumTable with RootConnector { - def store(sample: NamedPartitionRecord): InsertQuery.Default[ConcreteNamedPartitionEnumTable, NamedPartitionRecord] = { - insert - .value(_.id, sample.id) - .value(_.enum, sample.enum) - } -} - - - -sealed class ClusteringTable extends CassandraTable[ConcreteClusteringTable, String] { - - object id extends UUIDColumn(this) with PartitionKey[UUID] - object id2 extends UUIDColumn(this) with PrimaryKey[UUID] with ClusteringOrder[UUID] with Ascending - object id3 extends UUIDColumn(this) with PrimaryKey[UUID] with ClusteringOrder[UUID] with Descending - object placeholder extends StringColumn(this) - - def fromRow(r: Row): String = { - placeholder(r) - } -} - -abstract class ConcreteClusteringTable extends ClusteringTable with RootConnector - -sealed class ComplexClusteringTable extends CassandraTable[ConcreteComplexClusteringTable, String] { - - object id extends UUIDColumn(this) with PartitionKey[UUID] - object id2 extends UUIDColumn(this) with ClusteringOrder[UUID] with Ascending - object id3 extends UUIDColumn(this) with ClusteringOrder[UUID] with Descending - object placeholder extends StringColumn(this) with ClusteringOrder[String] with Descending - - def fromRow(r: Row): String = { - placeholder(r) - } -} - -abstract class ConcreteComplexClusteringTable extends ComplexClusteringTable with RootConnector - - -sealed class BrokenClusteringTable extends CassandraTable[ConcreteBrokenClusteringTable, String] { - object id extends UUIDColumn(this) with PartitionKey[UUID] - - object id2 extends UUIDColumn(this) with PrimaryKey[UUID] - object id3 extends UUIDColumn(this) with ClusteringOrder[UUID] with Descending - object placeholder extends StringColumn(this) with ClusteringOrder[String] with Descending - - def fromRow(r: Row): String = { - placeholder(r) - } -} - -abstract class ConcreteBrokenClusteringTable extends BrokenClusteringTable - - -sealed class ComplexCompoundKeyTable extends CassandraTable[ConcreteComplexCompoundKeyTable, String] { - - object id extends UUIDColumn(this) with PartitionKey[UUID] - object id2 extends UUIDColumn(this) with PrimaryKey[UUID] - object id3 extends UUIDColumn(this) with PrimaryKey[UUID] - object id4 extends UUIDColumn(this) with PrimaryKey[UUID] - object id5 extends UUIDColumn(this) with PrimaryKey[UUID] - object id6 extends UUIDColumn(this) with PrimaryKey[UUID] - object id7 extends UUIDColumn(this) with PrimaryKey[UUID] - object id8 extends UUIDColumn(this) with PrimaryKey[UUID] - object id9 extends UUIDColumn(this) with PrimaryKey[UUID] - object placeholder extends StringColumn(this) - - def fromRow(r: Row): String = { - placeholder(r) - } -} - -abstract class ConcreteComplexCompoundKeyTable extends ComplexCompoundKeyTable with RootConnector - -sealed class SimpleCompoundKeyTable extends CassandraTable[ConcreteSimpleCompoundKeyTable, String] { - - object id extends UUIDColumn(this) with PartitionKey[UUID] - object id2 extends UUIDColumn(this) with PrimaryKey[UUID] - object id3 extends UUIDColumn(this) with PrimaryKey[UUID] - object placeholder extends StringColumn(this) - - def fromRow(r: Row): String = { - placeholder(r) - } -} - -abstract class ConcreteSimpleCompoundKeyTable extends SimpleCompoundKeyTable with RootConnector - - diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/tables/CounterTableTest.scala b/phantom-dsl/src/test/scala/com/websudos/phantom/tables/CounterTableTest.scala deleted file mode 100644 index 14313aec3..000000000 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/tables/CounterTableTest.scala +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.tables - -import com.outworkers.util.testing.sample -import com.websudos.phantom.dsl._ - -case class CounterRecord(id: UUID, count: Long) - -class CounterTableTest extends CassandraTable[ConcreteCounterTableTest, CounterRecord] { - - object id extends UUIDColumn(this) with PartitionKey[UUID] - object count_entries extends CounterColumn(this) - - def fromRow(row: Row): CounterRecord = { - CounterRecord( - id = id(row), - count = count_entries(row) - ) - } -} - -abstract class ConcreteCounterTableTest extends CounterTableTest with RootConnector { - override val tableName = "counter_column_tests" -} - -class SecondaryCounterTable extends CassandraTable[ConcreteSecondaryCounterTable, CounterRecord] { - object id extends UUIDColumn(this) with PartitionKey[UUID] - object count_entries extends CounterColumn(this) - - def fromRow(row: Row): CounterRecord = { - CounterRecord( - id = id(row), - count = count_entries(row) - ) - } -} - -abstract class ConcreteSecondaryCounterTable extends SecondaryCounterTable with RootConnector { - override val tableName = "secondary_column_tests" -} - -class BrokenCounterTableTest extends CassandraTable[ConcreteBrokenCounterTableTest, CounterRecord] { - - object id extends UUIDColumn(this) with PartitionKey[UUID] - object count_entries extends CounterColumn(this) - - def fromRow(row: Row): CounterRecord = { - CounterRecord( - id = id(row), - count = count_entries(row) - ) - } - -} - -abstract class ConcreteBrokenCounterTableTest extends BrokenCounterTableTest with RootConnector { - override val tableName = "counter_column_tests" -} - diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/tables/IndexedCollectionsTable.scala b/phantom-dsl/src/test/scala/com/websudos/phantom/tables/IndexedCollectionsTable.scala deleted file mode 100644 index 9ab4ab85b..000000000 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/tables/IndexedCollectionsTable.scala +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.tables - -import com.websudos.phantom.CassandraTable -import com.websudos.phantom.builder.query.InsertQuery -import com.websudos.phantom.column.{ListColumn, MapColumn, SetColumn} -import com.websudos.phantom.dsl._ - -sealed class IndexedCollectionsTable extends CassandraTable[ConcreteIndexedCollectionsTable, TestRow] { - - object key extends StringColumn(this) with PartitionKey[String] - - object list extends ListColumn[String](this) - - object setText extends SetColumn[String](this) with Index[Set[String]] - - object mapTextToText extends MapColumn[String, String](this) with Index[Map[String, String]] - - object setInt extends SetColumn[Int](this) - - object mapIntToText extends MapColumn[Int, String](this) with Index[Map[Int, String]] with Keys - - object mapIntToInt extends MapColumn[Int, Int](this) - - def fromRow(r: Row): TestRow = { - TestRow( - key = key(r), - list = list(r), - setText = setText(r), - mapTextToText = mapTextToText(r), - setInt = setInt(r), - mapIntToText = mapIntToText(r), - mapIntToInt = mapIntToInt(r) - ) - } -} - -abstract class ConcreteIndexedCollectionsTable extends IndexedCollectionsTable with RootConnector { - override val tableName = "indexed_collections" - - def store(row: TestRow): InsertQuery.Default[ConcreteIndexedCollectionsTable, TestRow] = { - insert - .value(_.key, row.key) - .value(_.list, row.list) - .value(_.setText, row.setText) - .value(_.mapTextToText, row.mapTextToText) - .value(_.setInt, row.setInt) - .value(_.mapIntToText, row.mapIntToText) - .value(_.mapIntToInt, row.mapIntToInt) - } - -} - - -sealed class IndexedEntriesTable extends CassandraTable[ConcreteIndexedEntriesTable, TestRow] { - - object key extends StringColumn(this) with PartitionKey[String] - - object list extends ListColumn[String](this) - - object setText extends SetColumn[String](this) with Index[Set[String]] - - object mapTextToText extends MapColumn[String, String](this) with Index[Map[String, String]] - - object setInt extends SetColumn[Int](this) - - object mapIntToText extends MapColumn[Int, String](this) with Index[Map[Int, String]] with Keys - - object mapIntToInt extends MapColumn[Int, Int](this) with Index[Map[Int, Int]] with Entries - - def fromRow(r: Row): TestRow = { - TestRow( - key = key(r), - list = list(r), - setText = setText(r), - mapTextToText = mapTextToText(r), - setInt = setInt(r), - mapIntToText = mapIntToText(r), - mapIntToInt = mapIntToInt(r) - ) - } -} - -abstract class ConcreteIndexedEntriesTable extends IndexedEntriesTable with RootConnector { - override val tableName = "indexed_collections" - - def store(row: TestRow): InsertQuery.Default[ConcreteIndexedEntriesTable, TestRow] = { - insert - .value(_.key, row.key) - .value(_.list, row.list) - .value(_.setText, row.setText) - .value(_.mapTextToText, row.mapTextToText) - .value(_.setInt, row.setInt) - .value(_.mapIntToText, row.mapIntToText) - .value(_.mapIntToInt, row.mapIntToInt) - } - -} - - - diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/tables/JsonTable.scala b/phantom-dsl/src/test/scala/com/websudos/phantom/tables/JsonTable.scala deleted file mode 100644 index 0b93791b4..000000000 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/tables/JsonTable.scala +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.tables - -import com.outworkers.util.testing.sample -import com.websudos.phantom.builder.query.InsertQuery -import com.websudos.phantom.dsl._ -import net.liftweb.json.{DefaultFormats, Extraction, JsonParser, compactRender} - -case class JsonTest(prop1: String, prop2: String) - -case class JsonClass( - id: UUID, - name: String, - json: JsonTest, - jsonList: List[JsonTest], - jsonSet: Set[JsonTest] -) - - -class JsonTable extends CassandraTable[ConcreteJsonTable, JsonClass] { - - implicit val formats = DefaultFormats - - object id extends UUIDColumn(this) with PartitionKey[UUID] - - object name extends StringColumn(this) - - object json extends JsonColumn[JsonTest](this) { - override def fromJson(obj: String): JsonTest = { - JsonParser.parse(obj).extract[JsonTest] - } - - override def toJson(obj: JsonTest): String = { - compactRender(Extraction.decompose(obj)) - } - } - - object jsonList extends JsonListColumn[JsonTest](this) { - override def fromJson(obj: String): JsonTest = { - JsonParser.parse(obj).extract[JsonTest] - } - - override def toJson(obj: JsonTest): String = { - compactRender(Extraction.decompose(obj)) - } - } - - object jsonSet extends JsonSetColumn[JsonTest](this) { - override def fromJson(obj: String): JsonTest = { - JsonParser.parse(obj).extract[JsonTest] - } - - override def toJson(obj: JsonTest): String = { - compactRender(Extraction.decompose(obj)) - } - } - - def fromRow(row: Row): JsonClass = { - JsonClass( - id = id(row), - name = name(row), - json = json(row), - jsonList = jsonList(row), - jsonSet = jsonSet(row) - ) - } -} - -abstract class ConcreteJsonTable extends JsonTable with RootConnector { - def store(sample: JsonClass): InsertQuery.Default[ConcreteJsonTable, JsonClass] = { - insert - .value(_.id, sample.id) - .value(_.name, sample.name) - .value(_.json, sample.json) - .value(_.jsonList, sample.jsonList) - .value(_.jsonSet, sample.jsonSet) - } -} diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/tables/ListCollectionTable.scala b/phantom-dsl/src/test/scala/com/websudos/phantom/tables/ListCollectionTable.scala deleted file mode 100644 index f7f7389ee..000000000 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/tables/ListCollectionTable.scala +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.tables - -import com.outworkers.util.testing.sample -import com.websudos.phantom.builder.query.InsertQuery -import com.websudos.phantom.dsl._ - -case class MyTestRow( - key: String, - optionA: Option[Int], - stringlist: List[String] -) - - -sealed class ListCollectionTable extends CassandraTable[ConcreteListCollectionTable, MyTestRow] { - def fromRow(r: Row): MyTestRow = { - MyTestRow( - key(r), - optionA(r), - stringlist(r) - ) - } - - object key extends StringColumn(this) with PartitionKey[String] - - object stringlist extends ListColumn[String](this) - - object optionA extends OptionalIntColumn(this) - -} - -abstract class ConcreteListCollectionTable extends ListCollectionTable with RootConnector { - - override val tableName = "mytest" - - def store(row: MyTestRow): InsertQuery.Default[ConcreteListCollectionTable, MyTestRow] = { - insert().value(_.key, row.key) - .value(_.stringlist, row.stringlist) - .value(_.optionA, row.optionA) - } - -} - - diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/tables/MultipleKeys.scala b/phantom-dsl/src/test/scala/com/websudos/phantom/tables/MultipleKeys.scala deleted file mode 100644 index 2c3787367..000000000 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/tables/MultipleKeys.scala +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.tables - -import com.datastax.driver.core.Row -import com.websudos.phantom.dsl._ - -class MultipleKeys extends CassandraTable[ConcreteMultipleKeys, Option[MultipleKeys]] { - - object pkey extends StringColumn(this) with PartitionKey[String] - object intColumn1 extends IntColumn(this) with PrimaryKey[Int] with Index[Int] - object intColumn2 extends IntColumn(this) with PrimaryKey[Int] - object intColumn3 extends IntColumn(this) with PrimaryKey[Int] - object intColumn4 extends IntColumn(this) with PrimaryKey[Int] - object intColumn5 extends IntColumn(this) with PrimaryKey[Int] - object intColumn6 extends IntColumn(this) with PrimaryKey[Int] - object intColumn7 extends IntColumn(this) with PrimaryKey[Int] - object timestamp8 extends DateTimeColumn(this) - - def fromRow(r: Row): Option[MultipleKeys] = None -} - -abstract class ConcreteMultipleKeys extends MultipleKeys with RootConnector { - override val tableName = "AJ" -} diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/tables/OptionalPrimitivesCassandra22.scala b/phantom-dsl/src/test/scala/com/websudos/phantom/tables/OptionalPrimitivesCassandra22.scala deleted file mode 100644 index 7de442598..000000000 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/tables/OptionalPrimitivesCassandra22.scala +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.tables - -import com.websudos.phantom.CassandraTable -import com.websudos.phantom.builder.query.InsertQuery -import com.websudos.phantom.dsl._ -import com.outworkers.util.testing._ - -case class OptionalPrimitiveCassandra22( - pkey: String, - short: Option[Short], - byte: Option[Byte], - localDate: Option[LocalDate] -) - -object OptionalPrimitiveCassandra22 { - - def none: OptionalPrimitiveCassandra22 = { - OptionalPrimitiveCassandra22( - pkey = gen[String], - short = None, - byte = None, - localDate = None - ) - } -} - -sealed class OptionalPrimitivesCassandra22 extends CassandraTable[ConcreteOptionalPrimitivesCassandra22, OptionalPrimitiveCassandra22] { - - object pkey extends StringColumn(this) with PartitionKey[String] - - object short extends OptionalSmallIntColumn(this) - - object byte extends OptionalTinyIntColumn(this) - - object localDate extends OptionalLocalDateColumn(this) - - override def fromRow(r: Row): OptionalPrimitiveCassandra22 = { - OptionalPrimitiveCassandra22( - pkey = pkey(r), - short = short(r), - byte = byte(r), - localDate = localDate(r) - ) - } -} - -abstract class ConcreteOptionalPrimitivesCassandra22 extends OptionalPrimitivesCassandra22 with RootConnector { - - override val tableName = "OptionalPrimitivesCassandra22" - - def store(row: OptionalPrimitiveCassandra22): InsertQuery.Default[ConcreteOptionalPrimitivesCassandra22, OptionalPrimitiveCassandra22] = { - insert - .value(_.pkey, row.pkey) - .value(_.short, row.short) - .value(_.byte, row.byte) - .value(_.localDate, row.localDate) - } -} diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/tables/OptionalSecondaryIndexTable.scala b/phantom-dsl/src/test/scala/com/websudos/phantom/tables/OptionalSecondaryIndexTable.scala deleted file mode 100644 index 69114cebf..000000000 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/tables/OptionalSecondaryIndexTable.scala +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.tables - -import java.util.UUID - -import com.websudos.phantom.dsl._ - -import scala.concurrent.Future - -case class OptionalSecondaryRecord( - id: UUID, - secondary: Option[Int] -) - -sealed class OptionalSecondaryIndexTable extends - CassandraTable[ConcreteOptionalSecondaryIndexTable, OptionalSecondaryRecord] { - object id extends UUIDColumn(this) with PartitionKey[UUID] - object secondary extends OptionalIntColumn(this) with Index[Option[Int]] - - def fromRow(row: Row): OptionalSecondaryRecord = { - OptionalSecondaryRecord( - id(row), - secondary(row) - ) - } -} - -abstract class ConcreteOptionalSecondaryIndexTable - extends OptionalSecondaryIndexTable with RootConnector { - - def store(rec: OptionalSecondaryRecord): Future[ResultSet] = { - insert.value(_.id, rec.id) - .value(_.secondary, rec.secondary) - .future() - } - - def findById(id: UUID): Future[Option[OptionalSecondaryRecord]] = { - select.where(_.id eqs id).one() - } - - def findByOptionalSecondary(sec: Int): Future[Option[OptionalSecondaryRecord]] = { - select.where(_.secondary eqs sec).one() - } - -} - - diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/tables/PrimaryCollectionTable.scala b/phantom-dsl/src/test/scala/com/websudos/phantom/tables/PrimaryCollectionTable.scala deleted file mode 100644 index 7a138933e..000000000 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/tables/PrimaryCollectionTable.scala +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright 2013-2016 Outworkers, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.tables - -import com.websudos.phantom.dsl._ - -import scala.concurrent.Future - -case class PrimaryCollectionRecord( - index: List[String], - set: Set[String], - map: Map[String, String], - name: String, - value: Int -) - -class PrimaryCollectionTable extends CassandraTable[ConcretePrimaryCollectionTable, PrimaryCollectionRecord] { - object listIndex extends ListColumn[String](this) with PartitionKey[List[String]] - object setCol extends SetColumn[String](this) with PrimaryKey[Set[String]] - object mapCol extends MapColumn[String, String](this) with PrimaryKey[Map[String, String]] - object name extends StringColumn(this) with PrimaryKey[String] - object value extends IntColumn(this) - - def fromRow(row: Row): PrimaryCollectionRecord = { - PrimaryCollectionRecord( - listIndex(row), - setCol(row), - mapCol(row), - name(row), - value(row) - ) - } -} - -abstract class ConcretePrimaryCollectionTable extends PrimaryCollectionTable with RootConnector { - - def store(rec: PrimaryCollectionRecord): Future[ResultSet] = { - insert.value(_.listIndex, rec.index) - .value(_.setCol, rec.set) - .value(_.mapCol, rec.map) - .value(_.name, rec.name) - .value(_.value, rec.value) - .future() - } -} \ No newline at end of file diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/tables/Primitives.scala b/phantom-dsl/src/test/scala/com/websudos/phantom/tables/Primitives.scala deleted file mode 100644 index 233440e31..000000000 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/tables/Primitives.scala +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.tables - -import com.outworkers.util.testing.sample -import com.websudos.phantom.builder.query.InsertQuery -import com.websudos.phantom.dsl._ - -case class Primitive( - pkey: String, - long: Long, - boolean: Boolean, - bDecimal: BigDecimal, - double: Double, - float: Float, - inet: java.net.InetAddress, - int: Int, - date: java.util.Date, - uuid: java.util.UUID, - bi: BigInt -) - -sealed class Primitives extends CassandraTable[ConcretePrimitives, Primitive] { - object pkey extends StringColumn(this) with PartitionKey[String] - - object long extends LongColumn(this) - - object boolean extends BooleanColumn(this) - - object bDecimal extends BigDecimalColumn(this) - - object double extends DoubleColumn(this) - - object float extends FloatColumn(this) - - object inet extends InetAddressColumn(this) - - object int extends IntColumn(this) - - object date extends DateColumn(this) - - object uuid extends UUIDColumn(this) - - object bi extends BigIntColumn(this) - - override def fromRow(r: Row): Primitive = extract[Primitive](r) -} - -abstract class ConcretePrimitives extends Primitives with RootConnector { - - override val tableName = "Primitives" - - def store(row: Primitive): InsertQuery.Default[ConcretePrimitives, Primitive] = { - insert - .value(_.pkey, row.pkey) - .value(_.long, row.long) - .value(_.boolean, row.boolean) - .value(_.bDecimal, row.bDecimal) - .value(_.double, row.double) - .value(_.float, row.float) - .value(_.inet, row.inet) - .value(_.int, row.int) - .value(_.date, row.date) - .value(_.uuid, row.uuid) - .value(_.bi, row.bi) - } - -} diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/tables/PrimitivesCassandra22.scala b/phantom-dsl/src/test/scala/com/websudos/phantom/tables/PrimitivesCassandra22.scala deleted file mode 100644 index 4e4b5b569..000000000 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/tables/PrimitivesCassandra22.scala +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.tables - -import com.websudos.phantom.builder.query.InsertQuery -import com.websudos.phantom.dsl._ -import org.joda.time.LocalDate - -case class PrimitiveCassandra22( - pkey: String, - short: Short, - byte: Byte, - date: LocalDate -) - -sealed class PrimitivesCassandra22 extends CassandraTable[ConcretePrimitivesCassandra22, PrimitiveCassandra22] { - - object pkey extends StringColumn(this) with PartitionKey[String] - - object short extends SmallIntColumn(this) - - object byte extends TinyIntColumn(this) - - object date extends LocalDateColumn(this) - - override def fromRow(r: Row): PrimitiveCassandra22 = { - PrimitiveCassandra22( - pkey = pkey(r), - short = short(r), - byte = byte(r), - date = date(r) - ) - } -} - -abstract class ConcretePrimitivesCassandra22 extends PrimitivesCassandra22 with RootConnector { - - override val tableName = "PrimitivesCassandra22" - - def store(row: PrimitiveCassandra22): InsertQuery.Default[ConcretePrimitivesCassandra22, PrimitiveCassandra22] = { - insert - .value(_.pkey, row.pkey) - .value(_.short, row.short) - .value(_.byte, row.byte) - .value(_.date, row.date) - } -} diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/tables/PrimitivesJoda.scala b/phantom-dsl/src/test/scala/com/websudos/phantom/tables/PrimitivesJoda.scala deleted file mode 100644 index 46c3daf0a..000000000 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/tables/PrimitivesJoda.scala +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.tables - -import com.datastax.driver.core.PagingState -import com.outworkers.util.testing.sample -import com.websudos.phantom.builder.query.InsertQuery -import com.websudos.phantom.dsl._ -import org.joda.time.DateTime - -import scala.concurrent.Future - -case class JodaRow( - pkey: String, - intColumn: Int, - timestamp: DateTime -) - -sealed class PrimitivesJoda extends CassandraTable[ConcretePrimitivesJoda, JodaRow] { - object pkey extends StringColumn(this) with PartitionKey[String] - object intColumn extends IntColumn(this) - object timestamp extends DateTimeColumn(this) - - override def fromRow(r: Row): JodaRow = extract[JodaRow](r) -} - -abstract class ConcretePrimitivesJoda extends PrimitivesJoda with RootConnector { - - def store(primitive: JodaRow): InsertQuery.Default[ConcretePrimitivesJoda, JodaRow] = { - insert.value(_.pkey, primitive.pkey) - .value(_.intColumn, primitive.intColumn) - .value(_.timestamp, primitive.timestamp) - } - - def fetchPage(limit: Int, paging: Option[PagingState]): Future[ListResult[JodaRow]] = { - select.limit(limit).fetchRecord(paging) - } - - override val tableName = "PrimitivesJoda" - -} - diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/tables/Recipes.scala b/phantom-dsl/src/test/scala/com/websudos/phantom/tables/Recipes.scala deleted file mode 100644 index 1ed7575cc..000000000 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/tables/Recipes.scala +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.tables - -import com.websudos.phantom.builder.query.{CreateQuery, InsertQuery, SelectQuery} -import com.websudos.phantom.dsl._ -import org.joda.time.DateTime - -import scala.concurrent.Future - -case class Recipe( - url: String, - description: Option[String], - ingredients: List[String], - servings: Option[Int], - lastCheckedAt: DateTime, - props: Map[String, String], - uid: UUID -) - -class Recipes extends CassandraTable[ConcreteRecipes, Recipe] { - - object url extends StringColumn(this) with PartitionKey[String] - - object description extends OptionalStringColumn(this) - - object ingredients extends ListColumn[String](this) - - object servings extends OptionalIntColumn(this) - - object lastcheckedat extends DateTimeColumn(this) - - object props extends MapColumn[String, String](this) - - object uid extends UUIDColumn(this) - - - override def fromRow(r: Row): Recipe = { - Recipe( - url(r), - description(r), - ingredients(r), - servings(r), - lastcheckedat(r), - props(r), - uid(r) - ) - } -} - -abstract class ConcreteRecipes extends Recipes with RootConnector { - - def store(recipe: Recipe): InsertQuery.Default[ConcreteRecipes, Recipe] = { - insert - .value(_.url, recipe.url) - .value(_.description, recipe.description) - .value(_.ingredients, recipe.ingredients) - .value(_.lastcheckedat, recipe.lastCheckedAt) - .value(_.props, recipe.props) - .value(_.uid, recipe.uid) - .value(_.servings, recipe.servings) - } -} - - -case class SampleEvent(id: UUID, map: Map[Long, DateTime]) - -sealed class Events extends CassandraTable[ConcreteEvents, SampleEvent] { - - object id extends UUIDColumn(this) with PartitionKey[UUID] - - object map extends MapColumn[Long, DateTime](this) - - def fromRow(row: Row): SampleEvent = { - SampleEvent( - id = id(row), - map = map(row) - ) - } -} - -abstract class ConcreteEvents extends Events with RootConnector { - - def store(event: SampleEvent): InsertQuery.Default[ConcreteEvents, SampleEvent] = { - insert.value(_.id, event.id) - .value(_.map, event.map) - } - - def findById(id: UUID): Future[Option[SampleEvent]] = { - select.where(_.id eqs id).one() - } -} diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/tables/ScalaTypesMapTable.scala b/phantom-dsl/src/test/scala/com/websudos/phantom/tables/ScalaTypesMapTable.scala deleted file mode 100644 index e1ce51371..000000000 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/tables/ScalaTypesMapTable.scala +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright 2013-2016 Outworkers, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.tables - -import com.websudos.phantom.builder.query.InsertQuery -import com.websudos.phantom.dsl._ - -import scala.concurrent.Future - -case class ScalaPrimitiveMapRecord( - id: UUID, - map: Map[DateTime, BigDecimal] -) - -class ScalaTypesMapTable extends CassandraTable[ConcreteScalaTypesMapTable, ScalaPrimitiveMapRecord] { - - object id extends UUIDColumn(this) with PartitionKey[UUID] - object map extends MapColumn[DateTime, BigDecimal](this) - - override def fromRow(row: Row): ScalaPrimitiveMapRecord = { - ScalaPrimitiveMapRecord( - id(row), - map(row) - ) - } -} - -abstract class ConcreteScalaTypesMapTable extends ScalaTypesMapTable with RootConnector { - def store( - rec: ScalaPrimitiveMapRecord - ): InsertQuery.Default[ConcreteScalaTypesMapTable, ScalaPrimitiveMapRecord] = { - insert - .value(_.id, rec.id) - .value(_.map, rec.map) - } - - def findById(id: UUID): Future[Option[ScalaPrimitiveMapRecord]] = { - select.where(_.id eqs id).one() - } -} \ No newline at end of file diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/tables/SecondaryIndexTable.scala b/phantom-dsl/src/test/scala/com/websudos/phantom/tables/SecondaryIndexTable.scala deleted file mode 100644 index d5a59d4af..000000000 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/tables/SecondaryIndexTable.scala +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.tables - -import com.websudos.phantom.builder.query.InsertQuery -import com.websudos.phantom.dsl._ - - case class SecondaryIndexRecord( - primary: UUID, - secondary: UUID, - name: String -) - -sealed class SecondaryIndexTable extends CassandraTable[ConcreteSecondaryIndexTable, SecondaryIndexRecord] { - - object id extends UUIDColumn(this) with PartitionKey[UUID] - object secondary extends UUIDColumn(this) with Index[UUID] - object name extends StringColumn(this) - - def fromRow(r: Row): SecondaryIndexRecord = { - SecondaryIndexRecord( - primary = id(r), - secondary = secondary(r), - name = name(r) - ) - } -} - -abstract class ConcreteSecondaryIndexTable extends SecondaryIndexTable with RootConnector { - - def store(sample: SecondaryIndexRecord): InsertQuery.Default[ConcreteSecondaryIndexTable, SecondaryIndexRecord] = { - insert - .value(_.id, sample.primary) - .value(_.secondary, sample.secondary) - .value(_.name, sample.name) - } - -} \ No newline at end of file diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/tables/StaticTableTest.scala b/phantom-dsl/src/test/scala/com/websudos/phantom/tables/StaticTableTest.scala deleted file mode 100644 index 889c8efae..000000000 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/tables/StaticTableTest.scala +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.tables - -import com.websudos.phantom.builder.query.InsertQuery -import com.websudos.phantom.dsl._ - -case class StaticCollectionSingle(id: UUID, clusteringId: UUID, static: String) - -sealed class StaticTableTest extends CassandraTable[ConcreteStaticTableTest, StaticCollectionSingle] { - - object id extends UUIDColumn(this) with PartitionKey[UUID] - - object clusteringId extends UUIDColumn(this) with PrimaryKey[UUID] with ClusteringOrder[UUID] with Descending - object staticTest extends StringColumn(this) with StaticColumn[String] - - def fromRow(row: Row): StaticCollectionSingle = { - StaticCollectionSingle( - id(row), - clusteringId(row), - staticTest(row) - ) - } -} - -abstract class ConcreteStaticTableTest extends StaticTableTest with RootConnector - - -case class StaticCollectionRecord( - id: UUID, - clustering: UUID, - list: List[String] -) - -sealed class StaticCollectionTableTest extends CassandraTable[ConcreteStaticCollectionTableTest, StaticCollectionRecord] { - - object id extends UUIDColumn(this) with PartitionKey[UUID] - - object clusteringId extends UUIDColumn(this) with PrimaryKey[UUID] with ClusteringOrder[UUID] with Descending - object staticList extends ListColumn[String](this) with StaticColumn[List[String]] - - def fromRow(row: Row): StaticCollectionRecord = { - StaticCollectionRecord( - id = id(row), - clustering = clusteringId(row), - list = staticList(row) - ) - } -} - -abstract class ConcreteStaticCollectionTableTest extends StaticCollectionTableTest with RootConnector { - def store(record: StaticCollectionRecord): InsertQuery.Default[ConcreteStaticCollectionTableTest, StaticCollectionRecord] = { - insert.value(_.id, record.id) - .value(_.clusteringId, record.clustering) - .value(_.staticList, record.list) - } -} diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/tables/TableKeyTests.scala b/phantom-dsl/src/test/scala/com/websudos/phantom/tables/TableKeyTests.scala deleted file mode 100644 index 262e33408..000000000 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/tables/TableKeyTests.scala +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.tables - -import com.websudos.phantom.dsl._ - -case class StubRecord(name: String, id: UUID) -sealed class TableWithSingleKey extends CassandraTable[ConcreteTableWithSingleKey, StubRecord] { - - object id extends UUIDColumn(this) with PartitionKey[UUID] - object name extends StringColumn(this) - - def fromRow(r: Row): StubRecord = { - StubRecord(name(r), id(r)) - } -} - -abstract class ConcreteTableWithSingleKey extends TableWithSingleKey with RootConnector - -class TableWithCompoundKey extends CassandraTable[ConcreteTableWithCompoundKey, StubRecord] { - - object id extends UUIDColumn(this) with PartitionKey[UUID] - object second extends UUIDColumn(this) with PrimaryKey[UUID] - object name extends StringColumn(this) - - def fromRow(r: Row): StubRecord = { - StubRecord(name(r), id(r)) - } -} - -abstract class ConcreteTableWithCompoundKey extends TableWithCompoundKey with RootConnector - - -sealed class TableWithCompositeKey extends CassandraTable[ConcreteTableWithCompositeKey, StubRecord] { - - object id extends UUIDColumn(this) with PartitionKey[UUID] - object second_part extends UUIDColumn(this) with PartitionKey[UUID] - object second extends UUIDColumn(this) with PrimaryKey[UUID] - object name extends StringColumn(this) - - def fromRow(r: Row): StubRecord = { - StubRecord( - name = name(r), - id = id(r) - ) - } -} - -abstract class ConcreteTableWithCompositeKey extends TableWithCompositeKey with RootConnector - -sealed class TableWithNoKey extends CassandraTable[ConcreteTableWithNoKey, StubRecord] { - - object id extends UUIDColumn(this) - object name extends StringColumn(this) - - def fromRow(r: Row): StubRecord = { - StubRecord( - name = name(r), - id = id(r) - ) - } -} - -abstract class ConcreteTableWithNoKey extends TableWithNoKey with RootConnector diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/tables/TestTable.scala b/phantom-dsl/src/test/scala/com/websudos/phantom/tables/TestTable.scala deleted file mode 100644 index 93e159d08..000000000 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/tables/TestTable.scala +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.tables - -import com.websudos.phantom.builder.query.InsertQuery -import com.websudos.phantom.dsl._ - -case class TestRow( - key: String, - list: List[String], - setText: Set[String], - mapTextToText: Map[String, String], - setInt: Set[Int], - mapIntToText: Map[Int, String], - mapIntToInt: Map[Int, Int] -) - -sealed class TestTable extends CassandraTable[ConcreteTestTable, TestRow] { - - object key extends StringColumn(this) with PartitionKey[String] - - object list extends ListColumn[String](this) - - object setText extends SetColumn[String](this) - - object mapTextToText extends MapColumn[String, String](this) - - object setInt extends SetColumn[Int](this) - - object mapIntToText extends MapColumn[Int, String](this) - - def fromRow(r: Row): TestRow = { - TestRow( - key = key(r), - list = list(r), - setText = setText(r), - mapTextToText = mapTextToText(r), - setInt = setInt(r), - mapIntToText = mapIntToText(r), - mapIntToInt = Map.empty[Int, Int] - ) - } -} - -abstract class ConcreteTestTable extends TestTable with RootConnector { - override val tableName = "TestTable" - - def store(row: TestRow): InsertQuery.Default[ConcreteTestTable, TestRow] = { - insert - .value(_.key, row.key) - .value(_.list, row.list) - .value(_.setText, row.setText) - .value(_.mapTextToText, row.mapTextToText) - .value(_.setInt, row.setInt) - .value(_.mapIntToText, row.mapIntToText) - } - -} - diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/tables/TestTable2.scala b/phantom-dsl/src/test/scala/com/websudos/phantom/tables/TestTable2.scala deleted file mode 100644 index 66e205de4..000000000 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/tables/TestTable2.scala +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.tables - -case class SimpleStringClass(something: String) - -case class SimpleMapOfStringsClass(something: Map[String, Int]) - -case class TestList(key: String, l: List[String]) - -case class TestRow2( - key: String, - optionalInt: Option[Int], - simpleMapOfString: SimpleMapOfStringsClass, - optionalSimpleMapOfString: Option[SimpleMapOfStringsClass], - mapOfStringToCaseClass: Map[String, SimpleMapOfStringsClass] -) \ No newline at end of file diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/tables/TimeSeriesTable.scala b/phantom-dsl/src/test/scala/com/websudos/phantom/tables/TimeSeriesTable.scala deleted file mode 100644 index a17ab1c22..000000000 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/tables/TimeSeriesTable.scala +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.tables - -import com.datastax.driver.core.utils.UUIDs -import com.websudos.phantom.builder.query.InsertQuery -import com.websudos.phantom.dsl._ -import org.joda.time.{DateTime, DateTimeZone} - -import scala.concurrent.Future - -case class TimeSeriesRecord( - id: UUID, - name: String, - timestamp: DateTime -) - -case class TimeUUIDRecord( - user: UUID, - id: UUID, - name: String, - timestamp: DateTime -) - -sealed class TimeSeriesTable extends CassandraTable[ConcreteTimeSeriesTable, TimeSeriesRecord] { - object id extends UUIDColumn(this) with PartitionKey[UUID] - object name extends StringColumn(this) - object timestamp extends DateTimeColumn(this) with ClusteringOrder[DateTime] with Descending { - override val name = "unixTimestamp" - } - - def fromRow(row: Row): TimeSeriesRecord = { - TimeSeriesRecord( - id(row), - name(row), - timestamp(row) - ) - } -} - -abstract class ConcreteTimeSeriesTable extends TimeSeriesTable with RootConnector - -sealed class TimeUUIDTable extends CassandraTable[ConcreteTimeUUIDTable, TimeUUIDRecord] { - - object user extends UUIDColumn(this) with PartitionKey[UUID] - object id extends TimeUUIDColumn(this) with ClusteringOrder[UUID] with Descending - object name extends StringColumn(this) - - def fromRow(row: Row): TimeUUIDRecord = { - TimeUUIDRecord( - user(row), - id(row), - name(row), - id(row).datetime - ) - } -} - -abstract class ConcreteTimeUUIDTable extends TimeUUIDTable with RootConnector { - - def store(rec: TimeUUIDRecord): InsertQuery.Default[ConcreteTimeUUIDTable, TimeUUIDRecord] = { - insert - .value(_.user, rec.user) - .value(_.id, rec.id) - .value(_.name, rec.name) - } - - def retrieve(user: UUID): Future[List[TimeUUIDRecord]] = { - select.where(_.user eqs user).orderBy(_.id ascending).fetch() - } - - def retrieveDescending(user: UUID): Future[List[TimeUUIDRecord]] = { - select.where(_.user eqs user).orderBy(_.id descending).fetch() - } -} diff --git a/phantom-dsl/src/test/scala/com/websudos/phantom/tables/TimeSeriesTableWithTTL.scala b/phantom-dsl/src/test/scala/com/websudos/phantom/tables/TimeSeriesTableWithTTL.scala deleted file mode 100644 index 192912a62..000000000 --- a/phantom-dsl/src/test/scala/com/websudos/phantom/tables/TimeSeriesTableWithTTL.scala +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.tables - -import com.websudos.phantom.dsl._ -import com.outworkers.util.testing._ -import org.joda.time.DateTime - -sealed class TimeSeriesTableWithTTL extends CassandraTable[ConcreteTimeSeriesTableWithTTL, TimeSeriesRecord] { - object id extends UUIDColumn(this) with PartitionKey[UUID] - object name extends StringColumn(this) - object timestamp extends DateTimeColumn(this) with ClusteringOrder[DateTime] with Descending - - def fromRow(row: Row): TimeSeriesRecord = { - TimeSeriesRecord( - id(row), - name(row), - timestamp(row) - ) - } -} - -abstract class ConcreteTimeSeriesTableWithTTL extends TimeSeriesTableWithTTL with RootConnector { - val testUUID = gen[UUID] -} - -sealed class TimeSeriesTableWithTTL2 extends CassandraTable[ConcreteTimeSeriesTableWithTTL2, TimeSeriesRecord] { - object id extends UUIDColumn(this) with PartitionKey[UUID] - object name extends StringColumn(this) - object timestamp extends DateTimeColumn(this) - - def fromRow(row: Row): TimeSeriesRecord = { - TimeSeriesRecord( - id(row), - name(row), - timestamp(row) - ) - } -} - -abstract class ConcreteTimeSeriesTableWithTTL2 extends TimeSeriesTableWithTTL2 with RootConnector { - val testUUID = gen[UUID] -} - diff --git a/phantom-example/src/main/scala/com/outworkers/phantom/example/advanced/AdvancedRecipes.scala b/phantom-example/src/main/scala/com/outworkers/phantom/example/advanced/AdvancedRecipes.scala new file mode 100644 index 000000000..4a0e44b7c --- /dev/null +++ b/phantom-example/src/main/scala/com/outworkers/phantom/example/advanced/AdvancedRecipes.scala @@ -0,0 +1,78 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.example.advanced + +import java.util.UUID + +import com.datastax.driver.core.{ResultSet, Row} +import com.outworkers.phantom.connectors.RootConnector +import com.twitter.conversions.time._ +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.example.basics.Recipe +import com.outworkers.phantom.{CassandraTable => _, _} +import org.joda.time.DateTime + +import scala.concurrent.{Future => ScalaFuture} + +/** + * In this example we will create a table storing recipes. + * This time we will use a composite key formed by name and id. + */ +// You can seal the class and only allow importing the companion object. +// It's not directly meant for end user consumption anyway, the correct approach +// Keep reading for examples. +sealed class AdvancedRecipes extends CassandraTable[ConcreteAdvancedRecipes, Recipe] { + // First the partition key, which is also a Primary key in Cassandra. + object id extends UUIDColumn(this) with PartitionKey { + // You can override the name of your key to whatever you like. + // The default will be the name used for the object, in this case "id". + override lazy val name = "the_primary_key" + } + + object name extends StringColumn(this) + + object title extends StringColumn(this) + object author extends StringColumn(this) + object description extends StringColumn(this) + + // Custom data types can be stored easily. + // Cassandra collections target a small number of items, but usage is trivial. + object ingredients extends SetColumn[String](this) + object props extends MapColumn[String, String](this) + object timestamp extends DateTimeColumn(this) with ClusteringOrder +} + + +abstract class ConcreteAdvancedRecipes extends AdvancedRecipes with RootConnector { + + def insertRecipe(recipe: Recipe): ScalaFuture[ResultSet] = { + insert.value(_.id, recipe.id) + .value(_.author, recipe.author) + .value(_.title, recipe.title) + .value(_.description, recipe.description) + .value(_.ingredients, recipe.ingredients) + .value(_.name, recipe.name) + .value(_.props, recipe.props) + .value(_.timestamp, recipe.timestamp) + .future() + } + + // Like in the real world, you have now planned your queries ahead. + // You know what you can do and what you can't based on the schema limitations. + def findById(id: UUID): ScalaFuture[Option[Recipe]] = { + select.where(_.id eqs id).one() + } +} diff --git a/phantom-example/src/main/scala/com/outworkers/phantom/example/advanced/AdvancedRecipesByTitle.scala b/phantom-example/src/main/scala/com/outworkers/phantom/example/advanced/AdvancedRecipesByTitle.scala new file mode 100644 index 000000000..5590760ca --- /dev/null +++ b/phantom-example/src/main/scala/com/outworkers/phantom/example/advanced/AdvancedRecipesByTitle.scala @@ -0,0 +1,54 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.example.advanced + +import java.util.UUID + +import com.datastax.driver.core.{ResultSet, Row} +import com.outworkers.phantom.connectors.RootConnector +import com.outworkers.phantom.dsl._ + +import scala.concurrent.{Future => ScalaFuture} + + +// Now you want to enable querying Recipes by author. +// Because of the massive performance overhead of filtering, +// you can't really use a SecondaryKey for multi-billion record databases. + +// Instead, you create mapping tables and ensure consistency from the application level. +// This will illustrate just how easy it is to do that with com.outworkers.phantom. +sealed class AdvancedRecipesByTitle extends CassandraTable[ConcreteAdvancedRecipesByTitle, (String, UUID)] { + + // In this table, the author will be PrimaryKey and PartitionKey. + object title extends StringColumn(this) with PartitionKey + + // The id is just another normal field. + object id extends UUIDColumn(this) +} + +abstract class ConcreteAdvancedRecipesByTitle extends AdvancedRecipesByTitle with RootConnector { + override lazy val tableName = "recipes_by_title" + + def insertRecipe(recipe: (String, UUID)): ScalaFuture[ResultSet] = { + insert.value(_.title, recipe._1).value(_.id, recipe._2).future() + } + + // now you can have the tile in a where clause + // without the performance impact of a secondary index. + def findRecipeByTitle(title: String): ScalaFuture[Option[(String, UUID)]] = { + select.where(_.title eqs title).one() + } +} diff --git a/phantom-example/src/main/scala/com/websudos/phantom/example/advanced/RecipesDatabase.scala b/phantom-example/src/main/scala/com/outworkers/phantom/example/advanced/RecipesDatabase.scala similarity index 54% rename from phantom-example/src/main/scala/com/websudos/phantom/example/advanced/RecipesDatabase.scala rename to phantom-example/src/main/scala/com/outworkers/phantom/example/advanced/RecipesDatabase.scala index 5b05f3a9b..292e562c1 100644 --- a/phantom-example/src/main/scala/com/websudos/phantom/example/advanced/RecipesDatabase.scala +++ b/phantom-example/src/main/scala/com/outworkers/phantom/example/advanced/RecipesDatabase.scala @@ -1,41 +1,28 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.example.advanced +package com.outworkers.phantom.example.advanced -import com.websudos.phantom.connectors.{ContactPoint, KeySpaceDef} -import com.websudos.phantom.dsl._ -import com.websudos.phantom.example.basics._ +import com.outworkers.phantom.connectors +import com.outworkers.phantom.connectors.CassandraConnection +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.example.basics._ import scala.concurrent.{Future => ScalaFuture} -// In this section, we will show how you can create a real-world Cassandra service with com.websudos.phantom. +// In this section, we will show how you can create a real-world Cassandra service with com.outworkers.phantom. // First you have to think of what queries you need to perform. The usual. // Say you come up with id and author. @@ -44,7 +31,7 @@ import scala.concurrent.{Future => ScalaFuture} // We usually overlay a service on top of the mapping tables. // To keep all the complexity away from other parts of the application. -class RecipesDatabase(override val connector: KeySpaceDef) extends Database[RecipesDatabase](connector) { +class RecipesDatabase(override val connector: CassandraConnection) extends Database[RecipesDatabase](connector) { object Recipes extends ConcreteRecipes with connector.Connector object AdvancedRecipes extends ConcreteAdvancedRecipes with connector.Connector @@ -62,7 +49,7 @@ class RecipesDatabase(override val connector: KeySpaceDef) extends Database[Reci * Nonetheless, if you are using Scala you can almost replicate the below with a Future.sequence or Future.traverse over a List. * * This is a very neat and simple trick which will initialise all your tables in parallel at any time you want. The initialisation will automatically - * trigger the mecbanism that connects to Cassandra and gives you back a session. + * trigger the mechanism that connects to Cassandra and gives you back a session. */ // For instance, right now when you want to insert a new recipe. @@ -80,4 +67,4 @@ class RecipesDatabase(override val connector: KeySpaceDef) extends Database[Reci } } -object RecipesDatabase extends RecipesDatabase(ContactPoint.local.keySpace("recipes")) \ No newline at end of file +object RecipesDatabase extends RecipesDatabase(connectors.ContactPoint.local.keySpace("recipes")) diff --git a/phantom-example/src/main/scala/com/outworkers/phantom/example/basics/CompositeKeyRecipes.scala b/phantom-example/src/main/scala/com/outworkers/phantom/example/basics/CompositeKeyRecipes.scala new file mode 100644 index 000000000..a03f8b2e0 --- /dev/null +++ b/phantom-example/src/main/scala/com/outworkers/phantom/example/basics/CompositeKeyRecipes.scala @@ -0,0 +1,79 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.example.basics + +import java.util.UUID + +import scala.concurrent.{Future => ScalaFuture} +import com.datastax.driver.core.Row +import com.outworkers.phantom.connectors.RootConnector +import com.outworkers.phantom.dsl._ + +/** + * In this example we will create a table storing recipes. + * This time we will use a composite key formed by name and id. + */ + +// You can seal the class and only allow importing the companion object. +// The companion object is where you would implement your custom methods. +// Keep reading for examples. +sealed class CompositeKeyRecipes extends CassandraTable[ConcreteCompositeKeyRecipes, Recipe] { + // First the partition key, which is also a Primary key in Cassandra. + object id extends UUIDColumn(this) with PartitionKey { + // You can override the name of your key to whatever you like. + // The default will be the name used for the object, in this case "id". + override lazy val name = "the_primary_key" + } + + // Now we define a column for each field in our case class. + // If we want to add another key to our composite, simply mixin PrimaryKey[ValueType] + object name extends StringColumn(this) with PrimaryKey // and you're done + + + object title extends StringColumn(this) + object author extends StringColumn(this) + object description extends StringColumn(this) + + // Custom data types can be stored easily. + // Cassandra collections target a small number of items, but usage is trivial. + object ingredients extends SetColumn[String](this) + object props extends MapColumn[String, String](this) + object timestamp extends DateTimeColumn(this) +} + + +abstract class ConcreteCompositeKeyRecipes extends CompositeKeyRecipes with RootConnector { + + def store(recipe: Recipe): ScalaFuture[ResultSet] = { + insert.value(_.id, recipe.id) + .value(_.author, recipe.author) + .value(_.title, recipe.title) + .value(_.description, recipe.description) + .value(_.ingredients, recipe.ingredients) + .value(_.name, recipe.name) + .value(_.props, recipe.props) + .value(_.timestamp, recipe.timestamp) + .future() + } + + // now you can use composite keys in the normal way. + // If you would select only by id, + // Cassandra will tell you a part of the primary is missing from the where clause. + // Querying by composite keys is trivial using the "and" operator. + def findRecipeByIdAndName(id: UUID, name: String): ScalaFuture[Option[Recipe]] = { + select.where(_.id eqs id).and(_.name eqs name).one() + } +} diff --git a/phantom-example/src/main/scala/com/outworkers/phantom/example/basics/ExampleConnector.scala b/phantom-example/src/main/scala/com/outworkers/phantom/example/basics/ExampleConnector.scala new file mode 100644 index 000000000..2cd1aad99 --- /dev/null +++ b/phantom-example/src/main/scala/com/outworkers/phantom/example/basics/ExampleConnector.scala @@ -0,0 +1,50 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.example.basics + +import com.outworkers.phantom.connectors.{ContactPoint, ContactPoints} +import com.outworkers.phantom.connectors._ + +object Defaults { + + val connector = ContactPoint.local.noHeartbeat().keySpace("phantom_example") +} + +/** + * This is an example of how to connect to Cassandra in the easiest possible way. + * The SimpleCassandraConnector is designed to get you up and running immediately, with almost 0 effort. + * + * What you have to do now is to tell phantom what keyspace you will be using in Cassandra. This connector will automaticalyl try to connect to localhost:9042. + * If you want to tell the connector to use a different host:port combination, simply override the address inside it. + * + * Otherwise, simply mixing this connector in will magically inject a database session for all your queries and you can immediately run them. + */ +trait ExampleConnector extends Defaults.connector.Connector + +/** + * This is an example of how to connect to a custom set of hosts and ports. + * First, we need to obtain a connector and keep a singleton reference to it. + * It's really important to guarantee we are using a singleton here, otherwise + * we will end up spawning a cluster on every call. + */ +object RemoteConnector { + + // Simply specify the list of hosts followed by the keyspace. + // Now the connector object will automatically create the Database connection for us and initialise it. + val connector = ContactPoints(Seq("docker.local")).keySpace("phantom_example") +} + +trait DockerConnector extends RemoteConnector.connector.Connector \ No newline at end of file diff --git a/phantom-example/src/main/scala/com/outworkers/phantom/example/basics/SecondaryKeyRecipes.scala b/phantom-example/src/main/scala/com/outworkers/phantom/example/basics/SecondaryKeyRecipes.scala new file mode 100644 index 000000000..d50bf3b15 --- /dev/null +++ b/phantom-example/src/main/scala/com/outworkers/phantom/example/basics/SecondaryKeyRecipes.scala @@ -0,0 +1,68 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.example.basics + +import java.util.UUID + +import scala.concurrent.{Future => ScalaFuture} +import com.datastax.driver.core.Row +import com.outworkers.phantom.connectors.RootConnector +import com.outworkers.phantom.dsl._ + +/** + * In this example we will create a table storing recipes with a SecondaryKey. + * This time we will use a non-composite Primary key with a SecondaryKey on author. + */ + +// You can seal the class and only allow importing the companion object. +// The companion object is where you would implement your custom methods. +// Keep reading for examples. +sealed class SecondaryKeyRecipes extends CassandraTable[ConcreteSecondaryKeyRecipes, Recipe] { + // First the partition key, which is also a Primary key in Cassandra. + object id extends UUIDColumn(this) with PartitionKey { + // You can override the name of your key to whatever you like. + // The default will be the name used for the object, in this case "id". + override lazy val name = "the_primary_key" + } + + object name extends StringColumn(this) with PrimaryKey + + object title extends StringColumn(this) + + // If you want to query by a field, you need an index on it. + // One of the strategies for doing so is using a SecondaryKey + object author extends StringColumn(this) with Index // done + + object description extends StringColumn(this) + + object ingredients extends SetColumn[String](this) + object props extends MapColumn[String, String](this) + object timestamp extends DateTimeColumn(this) +} + + +abstract class ConcreteSecondaryKeyRecipes extends SecondaryKeyRecipes with RootConnector { + + // Now say you want to get a Recipe by author. + // author is a Index, you can now use it in a "where" clause. + // Performance is unpredictable for such queries, so you need to allow filtering. + // Note this is not the best practice. + // In a real world environment, you create a RecipesByTitle mapping table. + // Check out the example. + def findRecipeByAuthor(author: String): ScalaFuture[Option[Recipe]] = { + select.allowFiltering().where(_.author eqs author).one() + } +} diff --git a/phantom-example/src/main/scala/com/websudos/phantom/example/basics/SimpleRecipes.scala b/phantom-example/src/main/scala/com/outworkers/phantom/example/basics/SimpleRecipes.scala similarity index 69% rename from phantom-example/src/main/scala/com/websudos/phantom/example/basics/SimpleRecipes.scala rename to phantom-example/src/main/scala/com/outworkers/phantom/example/basics/SimpleRecipes.scala index 2bc0a2a8b..62b92eed2 100644 --- a/phantom-example/src/main/scala/com/websudos/phantom/example/basics/SimpleRecipes.scala +++ b/phantom-example/src/main/scala/com/outworkers/phantom/example/basics/SimpleRecipes.scala @@ -1,50 +1,33 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.example.basics +package com.outworkers.phantom.example.basics import java.util.UUID -import scala.concurrent.{ Future => ScalaFuture } - +import scala.concurrent.{Future => ScalaFuture} import org.joda.time.DateTime - -import com.datastax.driver.core.{ ResultSet, Row } - -import com.websudos.phantom.dsl._ -import com.websudos.phantom.reactivestreams._ - +import com.datastax.driver.core.{ResultSet, Row} +import com.outworkers.phantom.connectors.RootConnector +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.reactivestreams._ import com.twitter.conversions.time._ /** * In this example we will create a simple table storing recipes. - * Data modeling with com.websudos.phantom is trivial and covers some of the more advanced features of Cassandra. + * Data modeling with com.outworkers.phantom is trivial and covers some of the more advanced features of Cassandra. * * Phantom will auto-generate the CQL3 table definition from your Scala code. * And you can automatically insert the schema during tests or even live environments. @@ -66,7 +49,7 @@ case class Recipe( // The companion object is where you would implement your custom methods. // Keep reading for examples. sealed class Recipes extends CassandraTable[Recipes, Recipe] { - object id extends UUIDColumn(this) with PartitionKey[UUID] { + object id extends UUIDColumn(this) with PartitionKey { // You can override the name of your key to whatever you like. // The default will be the name used for the object, in this case "id". override lazy val name = "the_primary_key" @@ -85,21 +68,6 @@ sealed class Recipes extends CassandraTable[Recipes, Recipe] { object props extends MapColumn[String, String](this) object timestamp extends DateTimeColumn(this) - - // Now the mapping function, transforming a row into a custom type. - // This is a bit of boilerplate, but it's one time only and very short. - def fromRow(row: Row): Recipe = { - Recipe( - id(row), - name(row), - title(row), - author(row), - description(row), - ingredients(row), - props(row), - timestamp(row) - ) - } } @@ -113,12 +81,12 @@ abstract class ConcreteRecipes extends Recipes with RootConnector { def insertNewRecord(recipe: Recipe): ScalaFuture[ResultSet] = { insert.value(_.id, recipe.id) .value(_.author, recipe.author) + .value(_.title, recipe.title) .value(_.description, recipe.description) .value(_.ingredients, recipe.ingredients) .value(_.name, recipe.name) .value(_.props, recipe.props) .value(_.timestamp, recipe.timestamp) - .ttl(150.minutes.inSeconds) // you can use TTL if you want to. .future() } @@ -134,7 +102,7 @@ abstract class ConcreteRecipes extends Recipes with RootConnector { select.where(_.id eqs id).one() } - // com.websudos.phantom allows partial selects from any query. + // com.outworkers.phantom allows partial selects from any query. // this is currently limited to 22 fields. def findRecipeIngredients(id: UUID): ScalaFuture[Option[Set[String]]] = { select(_.ingredients).where(_.id eqs id).one() diff --git a/phantom-example/src/main/scala/com/outworkers/phantom/example/basics/ThriftModels.scala b/phantom-example/src/main/scala/com/outworkers/phantom/example/basics/ThriftModels.scala new file mode 100644 index 000000000..ae24f734b --- /dev/null +++ b/phantom-example/src/main/scala/com/outworkers/phantom/example/basics/ThriftModels.scala @@ -0,0 +1,55 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.example.basics + +import com.outworkers.phantom.connectors.RootConnector +import com.twitter.scrooge.CompactThriftSerializer +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.thrift._ +import com.outworkers.phantom.thrift.columns.ThriftColumn + +// Sample model here comes from the Thrift struct definition. +// The IDL is available in phantom-example/src/main/thrift. +case class SampleRecord( + stuff: String, + someList: List[String], + thriftModel: SampleModel +) + +sealed class ThriftTable extends CassandraTable[ConcreteThriftTable, SampleRecord] { + object id extends UUIDColumn(this) with PartitionKey + object stuff extends StringColumn(this) + object someList extends ListColumn[String](this) + + + // As you can see, com.outworkers.phantom will use a compact Thrift serializer. + // And store the records as strings in Cassandra. + object thriftModel extends ThriftColumn[ConcreteThriftTable, SampleRecord, SampleModel](this) { + def serializer = new CompactThriftSerializer[SampleModel] { + override def codec = SampleModel + } + } + + override def fromRow(r: Row): SampleRecord = { + SampleRecord( + stuff = stuff(r), + someList = someList(r), + thriftModel = thriftModel(r) + ) + } +} + +abstract class ConcreteThriftTable extends ThriftTable with RootConnector diff --git a/phantom-example/src/main/scala/com/websudos/phantom/example/advanced/AdvancedRecipes.scala b/phantom-example/src/main/scala/com/websudos/phantom/example/advanced/AdvancedRecipes.scala deleted file mode 100644 index f25c7c839..000000000 --- a/phantom-example/src/main/scala/com/websudos/phantom/example/advanced/AdvancedRecipes.scala +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.example.advanced - -import java.util.UUID - -import com.datastax.driver.core.{ResultSet, Row} -import com.twitter.conversions.time._ -import com.websudos.phantom.dsl._ -import com.websudos.phantom.example.basics.Recipe -import org.joda.time.DateTime - -import scala.concurrent.{Future => ScalaFuture} - -/** - * In this example we will create a table storing recipes. - * This time we will use a composite key formed by name and id. - */ - -// You can seal the class and only allow importing the companion object. -// The companion object is where you would implement your custom methods. -// Keep reading for examples. -sealed class AdvancedRecipes extends CassandraTable[ConcreteAdvancedRecipes, Recipe] { - // First the partition key, which is also a Primary key in Cassandra. - object id extends UUIDColumn(this) with PartitionKey[UUID] { - // You can override the name of your key to whatever you like. - // The default will be the name used for the object, in this case "id". - override lazy val name = "the_primary_key" - } - - object name extends StringColumn(this) - - object title extends StringColumn(this) - object author extends StringColumn(this) - object description extends StringColumn(this) - - // Custom data types can be stored easily. - // Cassandra collections target a small number of items, but usage is trivial. - object ingredients extends SetColumn[String](this) - object props extends MapColumn[String, String](this) - object timestamp extends DateTimeColumn(this) with ClusteringOrder[DateTime] - - // Now the mapping function, transforming a row into a custom type. - // This is a bit of boilerplate, but it's one time only and very short. - def fromRow(row: Row): Recipe = { - Recipe( - id(row), - name(row), - title(row), - author(row), - description(row), - ingredients(row), - props(row), - timestamp(row) - ) - } -} - - -abstract class ConcreteAdvancedRecipes extends AdvancedRecipes with RootConnector { - - def insertRecipe(recipe: Recipe): ScalaFuture[ResultSet] = { - insert.value(_.id, recipe.id) - .value(_.author, recipe.author) - .value(_.description, recipe.description) - .value(_.ingredients, recipe.ingredients) - .value(_.name, recipe.name) - .value(_.props, recipe.props) - .value(_.timestamp, recipe.timestamp) - .ttl(150.minutes.inSeconds) // you can use TTL if you want to. - .future() - } - - // Like in the real world, you have now planned your queries ahead. - // You know what you can do and what you can't based on the schema limitations. - def findById(id: UUID): ScalaFuture[Option[Recipe]] = { - select.where(_.id eqs id).one() - } -} diff --git a/phantom-example/src/main/scala/com/websudos/phantom/example/advanced/AdvancedRecipesByTitle.scala b/phantom-example/src/main/scala/com/websudos/phantom/example/advanced/AdvancedRecipesByTitle.scala deleted file mode 100644 index 5319f07a0..000000000 --- a/phantom-example/src/main/scala/com/websudos/phantom/example/advanced/AdvancedRecipesByTitle.scala +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.example.advanced - -import java.util.UUID - -import com.datastax.driver.core.{ResultSet, Row} -import com.websudos.phantom.dsl._ - -import scala.concurrent.{Future => ScalaFuture} - - -// Now you want to enable querying Recipes by author. -// Because of the massive performance overhead of filtering, -// you can't really use a SecondaryKey for multi-billion record databases. - -// Instead, you create mapping tables and ensure consistency from the application level. -// This will illustrate just how easy it is to do that with com.websudos.phantom. -sealed class AdvancedRecipesByTitle extends CassandraTable[ConcreteAdvancedRecipesByTitle, (String, UUID)] { - - // In this table, the author will be PrimaryKey and PartitionKey. - object title extends StringColumn(this) with PartitionKey[String] - - // The id is just another normal field. - object id extends UUIDColumn(this) - - def fromRow(row: Row): (String, UUID) = { - Tuple2(title(row), id(row)) - } -} - -abstract class ConcreteAdvancedRecipesByTitle extends AdvancedRecipesByTitle with RootConnector { - override lazy val tableName = "recipes_by_title" - - def insertRecipe(recipe: (String, UUID)): ScalaFuture[ResultSet] = { - insert.value(_.title, recipe._1).value(_.id, recipe._2).future() - } - - // now you can have the tile in a where clause - // without the performance impact of a secondary index. - def findRecipeByTitle(title: String): ScalaFuture[Option[(String, UUID)]] = { - select.where(_.title eqs title).one() - } -} diff --git a/phantom-example/src/main/scala/com/websudos/phantom/example/basics/CompositeKeyRecipes.scala b/phantom-example/src/main/scala/com/websudos/phantom/example/basics/CompositeKeyRecipes.scala deleted file mode 100644 index a60fbc8f9..000000000 --- a/phantom-example/src/main/scala/com/websudos/phantom/example/basics/CompositeKeyRecipes.scala +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.example.basics - -import java.util.UUID -import scala.concurrent.{ Future => ScalaFuture } -import com.datastax.driver.core.Row -import com.websudos.phantom.dsl._ - -/** - * In this example we will create a table storing recipes. - * This time we will use a composite key formed by name and id. - */ - -// You can seal the class and only allow importing the companion object. -// The companion object is where you would implement your custom methods. -// Keep reading for examples. -sealed class CompositeKeyRecipes extends CassandraTable[ConcreteCompositeKeyRecipes, Recipe] { - // First the partition key, which is also a Primary key in Cassandra. - object id extends UUIDColumn(this) with PartitionKey[UUID] { - // You can override the name of your key to whatever you like. - // The default will be the name used for the object, in this case "id". - override lazy val name = "the_primary_key" - } - - // Now we define a column for each field in our case class. - // If we want to add another key to our composite, simply mixin PrimaryKey[ValueType] - object name extends StringColumn(this) with PrimaryKey[String] // and you're done - - - object title extends StringColumn(this) - object author extends StringColumn(this) - object description extends StringColumn(this) - - // Custom data types can be stored easily. - // Cassandra collections target a small number of items, but usage is trivial. - object ingredients extends SetColumn[String](this) - object props extends MapColumn[String, String](this) - object timestamp extends DateTimeColumn(this) - - // Now the mapping function, transforming a row into a custom type. - // This is a bit of boilerplate, but it's one time only and very short. - def fromRow(row: Row): Recipe = { - Recipe( - id(row), - name(row), - title(row), - author(row), - description(row), - ingredients(row), - props(row), - timestamp(row) - ) - } -} - - -abstract class ConcreteCompositeKeyRecipes extends CompositeKeyRecipes with RootConnector { - - // now you can use composite keys in the normal way. - // If you would select only by id, - // Cassandra will tell you a part of the primary is missing from the where clause. - // Querying by composite keys is trivial using the "and" operator. - def findRecipeByIdAndName(id: UUID, name: String): ScalaFuture[Option[Recipe]] = { - select.where(_.id eqs id).and(_.name eqs name).one() - } - -} diff --git a/phantom-example/src/main/scala/com/websudos/phantom/example/basics/ExampleConnector.scala b/phantom-example/src/main/scala/com/websudos/phantom/example/basics/ExampleConnector.scala deleted file mode 100644 index 373021883..000000000 --- a/phantom-example/src/main/scala/com/websudos/phantom/example/basics/ExampleConnector.scala +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.example.basics - -import com.websudos.phantom.connectors._ - -object Defaults { - - val connector = ContactPoint.local.keySpace("phantom_example") -} - -/** - * This is an example of how to connect to Cassandra in the easiest possible way. - * The SimpleCassandraConnector is designed to get you up and running immediately, with almost 0 effort. - * - * What you have to do now is to tell phantom what keyspace you will be using in Cassandra. This connector will automaticalyl try to connect to localhost:9042. - * If you want to tell the connector to use a different host:port combination, simply override the address inside it. - * - * Otherwise, simply mixing this connector in will magically inject a database session for all your queries and you can immediately run them. - */ -trait ExampleConnector extends Defaults.connector.Connector - -/** - * This is an example of how to connect to a custom set of hosts and ports. - * First, we need to obtain a connector and keep a singleton reference to it. - * It's really important to guarantee we are using a singleton here, otherwise - * we will end up spawning a cluster on every call. - */ -object RemoteConnector { - - // Simply specify the list of hosts followed by the keyspace. - // Now the connector object will automatically create the Database connection for us and initialise it. - val connector = ContactPoints(Seq("docker.local")).keySpace("phantom_example") -} - -trait DockerConnector extends RemoteConnector.connector.Connector \ No newline at end of file diff --git a/phantom-example/src/main/scala/com/websudos/phantom/example/basics/SecondaryKeyRecipes.scala b/phantom-example/src/main/scala/com/websudos/phantom/example/basics/SecondaryKeyRecipes.scala deleted file mode 100644 index b22a39f31..000000000 --- a/phantom-example/src/main/scala/com/websudos/phantom/example/basics/SecondaryKeyRecipes.scala +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.example.basics - -import java.util.UUID -import scala.concurrent.{ Future => ScalaFuture } -import com.datastax.driver.core.Row -import com.websudos.phantom.dsl._ - -/** - * In this example we will create a table storing recipes with a SecondaryKey. - * This time we will use a non-composite Primary key with a SecondaryKey on author. - */ - -// You can seal the class and only allow importing the companion object. -// The companion object is where you would implement your custom methods. -// Keep reading for examples. -sealed class SecondaryKeyRecipes extends CassandraTable[ConcreteSecondaryKeyRecipes, Recipe] { - // First the partition key, which is also a Primary key in Cassandra. - object id extends UUIDColumn(this) with PartitionKey[UUID] { - // You can override the name of your key to whatever you like. - // The default will be the name used for the object, in this case "id". - override lazy val name = "the_primary_key" - } - - object name extends StringColumn(this) with PrimaryKey[String] - - object title extends StringColumn(this) - - // If you want to query by a field, you need an index on it. - // One of the strategies for doing so is using a SecondaryKey - object author extends StringColumn(this) with Index[String] // done - - object description extends StringColumn(this) - - object ingredients extends SetColumn[String](this) - object props extends MapColumn[String, String](this) - object timestamp extends DateTimeColumn(this) - - // Now the mapping function, transforming a row into a custom type. - // This is a bit of boilerplate, but it's one time only and very short. - def fromRow(row: Row): Recipe = { - Recipe( - id(row), - name(row), - title(row), - author(row), - description(row), - ingredients(row), - props(row), - timestamp(row) - ) - } -} - - -abstract class ConcreteSecondaryKeyRecipes extends SecondaryKeyRecipes with RootConnector { - - // Now say you want to get a Recipe by author. - // author is a Index, you can now use it in a "where" clause. - // Performance is unpredictable for such queries, so you need to allow filtering. - // Note this is not the best practice. - // In a real world environment, you create a RecipesByTitle mapping table. - // Check out the example. - def findRecipeByAuthor(author: String): ScalaFuture[Option[Recipe]] = { - select.allowFiltering().where(_.author eqs author).one() - } -} diff --git a/phantom-example/src/main/scala/com/websudos/phantom/example/basics/ThriftModels.scala b/phantom-example/src/main/scala/com/websudos/phantom/example/basics/ThriftModels.scala deleted file mode 100644 index ba90c2d8b..000000000 --- a/phantom-example/src/main/scala/com/websudos/phantom/example/basics/ThriftModels.scala +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.example.basics - -import com.twitter.scrooge.CompactThriftSerializer -import com.websudos.phantom.dsl._ -import com.websudos.phantom.thrift._ -import com.websudos.phantom.thrift.columns.ThriftColumn - -// Sample model here comes from the Thrift struct definition. -// The IDL is available in phantom-example/src/main/thrift. -case class SampleRecord( - stuff: String, - someList: List[String], - thriftModel: SampleModel -) - -sealed class ThriftTable extends CassandraTable[ConcreteThriftTable, SampleRecord] { - object id extends UUIDColumn(this) with PartitionKey[UUID] - object stuff extends StringColumn(this) - object someList extends ListColumn[String](this) - - - // As you can see, com.websudos.phantom will use a compact Thrift serializer. - // And store the records as strings in Cassandra. - object thriftModel extends ThriftColumn[ConcreteThriftTable, SampleRecord, SampleModel](this) { - def serializer = new CompactThriftSerializer[SampleModel] { - override def codec = SampleModel - } - } - - def fromRow(r: Row): SampleRecord = { - SampleRecord( - stuff = stuff(r), - someList = someList(r), - thriftModel = thriftModel(r) - ) - } -} - -abstract class ConcreteThriftTable extends ThriftTable with RootConnector diff --git a/phantom-example/src/main/thrift/Sample.thrift b/phantom-example/src/main/thrift/Sample.thrift index 01e3a7e41..8f98d8276 100644 --- a/phantom-example/src/main/thrift/Sample.thrift +++ b/phantom-example/src/main/thrift/Sample.thrift @@ -1,4 +1,4 @@ -namespace java com.websudos.phantom.example.basics +namespace java com.outworkers.phantom.example.basics struct SampleModel { 1: required string id, diff --git a/phantom-example/src/test/scala/com/outworkers/phantom/example/ExampleSuite.scala b/phantom-example/src/test/scala/com/outworkers/phantom/example/ExampleSuite.scala new file mode 100644 index 000000000..a4b0c7f6c --- /dev/null +++ b/phantom-example/src/test/scala/com/outworkers/phantom/example/ExampleSuite.scala @@ -0,0 +1,52 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.example + +import java.util.UUID + +import com.outworkers.phantom.PhantomBaseSuite +import com.outworkers.phantom.dsl.DatabaseProvider +import com.outworkers.phantom.example.advanced.RecipesDatabase +import com.outworkers.phantom.example.basics.Recipe +import com.outworkers.util.testing._ +import org.joda.time.DateTime +import org.scalatest.FlatSpec +import com.outworkers.phantom.dsl.context + +trait RecipesDbProvider extends DatabaseProvider[RecipesDatabase] { + override def database: RecipesDatabase = RecipesDatabase +} + +trait ExampleSuite extends FlatSpec with PhantomBaseSuite with RecipesDbProvider with RecipesDatabase.Connector { + + override def beforeAll(): Unit = { + super.beforeAll() + database.create() + } + + implicit object RecipeSampler extends Sample[Recipe] { + override def sample: Recipe = Recipe( + id = gen[UUID], + name = gen[ShortString].value, + title = gen[ShortString].value, + author = gen[ShortString].value, + description = gen[ShortString].value, + ingredients = genList[String]().toSet, + props = genMap[String](), + timestamp = gen[DateTime] + ) + } +} diff --git a/phantom-example/src/test/scala/com/outworkers/phantom/example/basics/AdvancedRecipesTest.scala b/phantom-example/src/test/scala/com/outworkers/phantom/example/basics/AdvancedRecipesTest.scala new file mode 100644 index 000000000..e7f1c3efc --- /dev/null +++ b/phantom-example/src/test/scala/com/outworkers/phantom/example/basics/AdvancedRecipesTest.scala @@ -0,0 +1,37 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.example.basics + +import com.outworkers.phantom.example.ExampleSuite +import com.outworkers.util.testing._ +import com.outworkers.phantom.dsl.context + +class AdvancedRecipesTest extends ExampleSuite { + + it should "insert a new record in the table" in { + val sample = gen[Recipe] + + val chain = for { + store <- database.AdvancedRecipes.insertRecipe(sample) + rec <- database.AdvancedRecipes.findById(sample.id) + } yield rec + + whenReady(chain) { res => + res shouldBe defined + res.value shouldEqual sample + } + } +} diff --git a/phantom-example/src/test/scala/com/outworkers/phantom/example/basics/CompositeKeyTests.scala b/phantom-example/src/test/scala/com/outworkers/phantom/example/basics/CompositeKeyTests.scala new file mode 100644 index 000000000..5b01f86a7 --- /dev/null +++ b/phantom-example/src/test/scala/com/outworkers/phantom/example/basics/CompositeKeyTests.scala @@ -0,0 +1,37 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.example.basics + +import com.outworkers.phantom.example.ExampleSuite +import com.outworkers.util.testing._ +import com.outworkers.phantom.dsl.context + +class CompositeKeyTests extends ExampleSuite { + + it should "insert a new record in the table and retrieve it using the full primary key" in { + val sample = gen[Recipe] + + val chain = for { + store <- database.CompositeKeyRecipes.store(sample) + rec <- database.CompositeKeyRecipes.findRecipeByIdAndName(sample.id, sample.name) + } yield rec + + whenReady(chain) { res => + res shouldBe defined + res.value shouldEqual sample + } + } +} diff --git a/phantom-example/src/test/scala/com/outworkers/phantom/example/basics/SimpleRecipesTest.scala b/phantom-example/src/test/scala/com/outworkers/phantom/example/basics/SimpleRecipesTest.scala new file mode 100644 index 000000000..87ff1691f --- /dev/null +++ b/phantom-example/src/test/scala/com/outworkers/phantom/example/basics/SimpleRecipesTest.scala @@ -0,0 +1,106 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.example.basics + +import com.outworkers.phantom.dsl.context +import com.outworkers.phantom.example.ExampleSuite +import com.outworkers.util.testing._ + +import scala.concurrent.Future + +class SimpleRecipesTest extends ExampleSuite { + + it should "insert a new record in the recipes table and retrieve it" in { + val sample = gen[Recipe] + + val chain = for { + store <- database.Recipes.insertNewRecord(sample).future + res <- database.Recipes.findRecipeById(sample.id) + } yield res + + whenReady(chain) { res => + res shouldBe defined + res.value shouldEqual sample + } + } + + it should "retrieve the ingredients of a recipe" in { + val sample = gen[Recipe] + + val chain = for { + store <- database.Recipes.insertNewRecord(sample).future + res <- database.Recipes.findRecipeIngredients(sample.id) + } yield res + + whenReady(chain) { res => + res shouldBe defined + res.value shouldEqual sample.ingredients + } + } + + it should "retrieve an entire table in a single fetch" in { + val sample = genList[Recipe]() + + val chain = for { + store <- database.Recipes.truncate().future() + store <- Future.sequence( + sample.map(s => database.Recipes.insertNewRecord(s).future) + ) + res <- database.Recipes.retrieveEntireTable + } yield res + + whenReady(chain) { res => + res should contain theSameElementsAs sample + } + } + + it should "update the author of a recipe" in { + val sample = gen[Recipe] + val newAuthor = gen[ShortString].value + + val chain = for { + store <- database.Recipes.insertNewRecord(sample).future + res <- database.Recipes.findRecipeById(sample.id) + updateAuthor <- database.Recipes.updateRecipeAuthor(sample.id, newAuthor) + res2 <- database.Recipes.findRecipeById(sample.id) + } yield (res, res2) + + whenReady(chain) { case (res, res2) => + res shouldBe defined + res.value shouldEqual sample + res2 shouldBe defined + res2.value shouldEqual sample.copy(author = newAuthor) + } + } + + it should "delete a recipe by its id" in { + val sample = gen[Recipe] + + val chain = for { + store <- database.Recipes.insertNewRecord(sample).future + res <- database.Recipes.findRecipeById(sample.id) + updateAuthor <- database.Recipes.deleteRecipeById(sample.id) + res2 <- database.Recipes.findRecipeById(sample.id) + } yield (res, res2) + + whenReady(chain) { case (res, res2) => + res shouldBe defined + res.value shouldEqual sample + res2 shouldBe empty + } + } + +} diff --git a/phantom-example/src/test/scala/com/websudos/phantom/example/ExampleSuite.scala b/phantom-example/src/test/scala/com/websudos/phantom/example/ExampleSuite.scala deleted file mode 100644 index 8f4bdac24..000000000 --- a/phantom-example/src/test/scala/com/websudos/phantom/example/ExampleSuite.scala +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright 2013-2016 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.example - -import com.websudos.phantom.Manager._ -import com.websudos.phantom.connectors.RootConnector -import com.websudos.phantom.example.advanced.RecipesDatabase -import com.outworkers.util.lift.{DateTimeSerializer, UUIDSerializer} -import org.scalatest.concurrent.{PatienceConfiguration, ScalaFutures} -import org.scalatest._ - -import scala.concurrent.Await -import scala.concurrent.duration._ - -trait BaseSuite extends Suite - with Matchers - with BeforeAndAfterAll - with RootConnector - with ScalaFutures - with OptionValues { - - implicit val defaultTimeout: PatienceConfiguration.Timeout = timeout(10 seconds) - - implicit val formats = net.liftweb.json.DefaultFormats + new UUIDSerializer + new DateTimeSerializer -} - - -trait ExampleSuite extends Suite with BaseSuite with RecipesDatabase.connector.Connector { - - override def beforeAll(): Unit = { - super.beforeAll() - Await.ready(RecipesDatabase.autocreate().future(), 20.seconds) - } - - override def afterAll(): Unit = { - super.afterAll() - Await.result(RecipesDatabase.autotruncate().future(), 20.seconds) - } -} - - diff --git a/phantom-example/src/test/scala/com/websudos/phantom/example/basics/SimpleRecipesTest.scala b/phantom-example/src/test/scala/com/websudos/phantom/example/basics/SimpleRecipesTest.scala deleted file mode 100644 index e59fc4ee1..000000000 --- a/phantom-example/src/test/scala/com/websudos/phantom/example/basics/SimpleRecipesTest.scala +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.example.basics - -import com.websudos.phantom.example.ExampleSuite -import org.scalatest.FlatSpec - -class SimpleRecipesTest extends FlatSpec with ExampleSuite { - it should "insert a new record in" in { - } -} diff --git a/phantom-finagle/src/main/scala/com/outworkers/phantom/finagle/ResultSpool.scala b/phantom-finagle/src/main/scala/com/outworkers/phantom/finagle/ResultSpool.scala new file mode 100644 index 000000000..d7aae672f --- /dev/null +++ b/phantom-finagle/src/main/scala/com/outworkers/phantom/finagle/ResultSpool.scala @@ -0,0 +1,70 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.finagle + +import com.datastax.driver.core.{ResultSet, Row} +import com.twitter.concurrent.Spool +import com.twitter.util.{FuturePool, Future => TFuture} + +import scala.collection.JavaConversions._ + +/** + * Wrapper for creating Spools of Rows + */ +private[phantom] object ResultSpool { + lazy val pool = FuturePool.unboundedPool + + def loop(head: Row, it: Iterator[Row], rs: ResultSet): Spool[Row] = { + lazy val tail = + if (rs.isExhausted) { + TFuture.value(Spool.empty) + } else { + val a = rs.getAvailableWithoutFetching + + // 100 is somewhat arbitrary. In practice it might not matter that much + // but it should be tested. + if (a < 100 && !rs.isFullyFetched) { + rs.fetchMoreResults + } + + if (a > 0) { + TFuture.value(loop(it.next(), it, rs)) + } else { + pool(it.next()).map(x => loop(x, it, rs)) + } + } + + head *:: tail + } + + /** + * Create a Spool of Rows. + * + * Things to make sure: + * 1) We don't block! + * 2) If we don't have anything else to do we submit to the thread pool and + * wait to get called back and chain onto that. + */ + def spool(rs: ResultSet): TFuture[Spool[Row]] = { + val it = rs.iterator + if (!rs.isExhausted) { + pool(it.next).map(x => loop(x, it, rs)) + } else { + TFuture.value(Spool.empty) + } + } +} + diff --git a/phantom-finagle/src/main/scala/com/websudos/phantom/finagle/package.scala b/phantom-finagle/src/main/scala/com/outworkers/phantom/finagle/package.scala similarity index 81% rename from phantom-finagle/src/main/scala/com/websudos/phantom/finagle/package.scala rename to phantom-finagle/src/main/scala/com/outworkers/phantom/finagle/package.scala index 117553a3b..bf87cc466 100644 --- a/phantom-finagle/src/main/scala/com/websudos/phantom/finagle/package.scala +++ b/phantom-finagle/src/main/scala/com/outworkers/phantom/finagle/package.scala @@ -1,33 +1,19 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom +package com.outworkers.phantom import java.util.concurrent.Executor import java.util.{List => JavaList} @@ -36,14 +22,14 @@ import com.datastax.driver.core._ import com.google.common.util.concurrent.{FutureCallback, Futures} import com.twitter.concurrent.Spool import com.twitter.util._ -import com.websudos.phantom.batch.BatchQuery -import com.websudos.phantom.builder._ -import com.websudos.phantom.builder.query._ -import com.websudos.phantom.builder.query.options.{CompressionStrategy, GcGraceSecondsBuilder, TablePropertyClause, TimeToLiveBuilder} -import com.websudos.phantom.builder.query.prepared.ExecutablePreparedSelectQuery -import com.websudos.phantom.builder.syntax.CQLSyntax -import com.websudos.phantom.connectors.KeySpace -import com.websudos.phantom.database.ExecutableCreateStatementsList +import com.outworkers.phantom.batch.BatchQuery +import com.outworkers.phantom.builder._ +import com.outworkers.phantom.builder.query._ +import com.outworkers.phantom.builder.query.options.{CompressionStrategy, GcGraceSecondsBuilder, TablePropertyClause, TimeToLiveBuilder} +import com.outworkers.phantom.builder.query.prepared.ExecutablePreparedSelectQuery +import com.outworkers.phantom.builder.syntax.CQLSyntax +import com.outworkers.phantom.connectors.KeySpace +import com.outworkers.phantom.database.ExecutableCreateStatementsList import org.joda.time.Seconds import shapeless.HList @@ -85,8 +71,8 @@ package object finagle { * Produces a Twitter Spool of [R]ows * This enumerator can be consumed afterwards with an Iteratee * - * @param session The implicit session provided by a [[com.websudos.phantom.connectors.Connector]]. - * @param keySpace The implicit keySpace definition provided by a [[com.websudos.phantom.connectors.Connector]]. + * @param session The implicit session provided by a [[com.outworkers.phantom.connectors.Connector]]. + * @param keySpace The implicit keySpace definition provided by a [[com.outworkers.phantom.connectors.Connector]]. * @param executor The implicit Java executor. * @return */ @@ -107,10 +93,10 @@ package object finagle { * Unlike Scala Futures, Twitter Futures and operations on them do not require an implicit context. * Instead, the context propagates from one future to another inside a flatMap chain which means * all operations(map, flatMap) that originate on a Twitter Future obtained as the result of a database - * call will execute inside [[com.websudos.phantom.Manager.executor]]. + * call will execute inside [[Manager.scalaExecutor]]. * - * @param session The implicit session provided by a [[com.websudos.phantom.connectors.Connector]]. - * @param keySpace The implicit keySpace definition provided by a [[com.websudos.phantom.connectors.Connector]]. + * @param session The implicit session provided by a [[com.outworkers.phantom.connectors.Connector]]. + * @param keySpace The implicit keySpace definition provided by a [[com.outworkers.phantom.connectors.Connector]]. * @param executor The implicit Java executor. * @return */ @@ -124,13 +110,13 @@ package object finagle { * database end. * * The execution context of the transformation is provided by phantom via - * [[com.websudos.phantom.Manager.scalaExecutor]] and it is recommended to - * use [[com.websudos.phantom.dsl.context]] for operations that chain + * [[Manager.scalaExecutor]] and it is recommended to + * use [[com.outworkers.phantom.dsl.context]] for operations that chain * database calls. * * @param modifyStatement The function allowing to modify underlying [[Statement]] - * @param session The implicit session provided by a [[com.websudos.phantom.connectors.Connector]]. - * @param keySpace The implicit keySpace definition provided by a [[com.websudos.phantom.connectors.Connector]]. + * @param session The implicit session provided by a [[com.outworkers.phantom.connectors.Connector]]. + * @param keySpace The implicit keySpace definition provided by a [[com.outworkers.phantom.connectors.Connector]]. * @param executor The implicit Java executor. * @return */ @@ -170,8 +156,8 @@ package object finagle { * A spool is both lazily constructed and consumed, suitable for large * collections when using twitter futures. * - * @param session The implicit session provided by a [[com.websudos.phantom.connectors.Connector]]. - * @param keySpace The implicit keySpace definition provided by a [[com.websudos.phantom.connectors.Connector]]. + * @param session The implicit session provided by a [[com.outworkers.phantom.connectors.Connector]]. + * @param keySpace The implicit keySpace definition provided by a [[com.outworkers.phantom.connectors.Connector]]. * @param executor The implicit Java executor. * @return A Spool of R. */ @@ -186,8 +172,8 @@ package object finagle { * Returns a parsed sequence of [R]ows * This is not suitable for big results set * - * @param session The implicit session provided by a [[com.websudos.phantom.connectors.Connector]]. - * @param keySpace The implicit keySpace definition provided by a [[com.websudos.phantom.connectors.Connector]]. + * @param session The implicit session provided by a [[com.outworkers.phantom.connectors.Connector]]. + * @param keySpace The implicit keySpace definition provided by a [[com.outworkers.phantom.connectors.Connector]]. * @param executor The implicit Java executor. * @return A Twitter future wrapping a list of mapped results. */ @@ -199,8 +185,8 @@ package object finagle { * Returns a parsed sequence of rows after the generated statement is modified by the modifier function. * This is not suitable for big results set * - * @param session The implicit session provided by a [[com.websudos.phantom.connectors.Connector]]. - * @param keySpace The implicit keySpace definition provided by a [[com.websudos.phantom.connectors.Connector]]. + * @param session The implicit session provided by a [[com.outworkers.phantom.connectors.Connector]]. + * @param keySpace The implicit keySpace definition provided by a [[com.outworkers.phantom.connectors.Connector]]. * @param executor The implicit Java executor. * @return A Twitter future wrapping a list of mapped results. */ @@ -216,8 +202,8 @@ package object finagle { * Returns a parsed sequence of [R]ows together with a result set. * This is not suitable for big results set * - * @param session The implicit session provided by a [[com.websudos.phantom.connectors.Connector]]. - * @param keySpace The implicit keySpace definition provided by a [[com.websudos.phantom.connectors.Connector]]. + * @param session The implicit session provided by a [[com.outworkers.phantom.connectors.Connector]]. + * @param keySpace The implicit keySpace definition provided by a [[com.outworkers.phantom.connectors.Connector]]. * @param executor The implicit Java executor. * @return A Twitter future wrapping a list of mapped results. */ @@ -233,8 +219,8 @@ package object finagle { * Returns a parsed sequence of [R]ows together with a result set. * This is not suitable for big results set * - * @param session The implicit session provided by a [[com.websudos.phantom.connectors.Connector]]. - * @param keySpace The implicit keySpace definition provided by a [[com.websudos.phantom.connectors.Connector]]. + * @param session The implicit session provided by a [[com.outworkers.phantom.connectors.Connector]]. + * @param keySpace The implicit keySpace definition provided by a [[com.outworkers.phantom.connectors.Connector]]. * @param executor The implicit Java executor. * @return A Twitter future wrapping a list of mapped results. */ @@ -246,8 +232,8 @@ package object finagle { * Returns a parsed sequence of [R]ows together with a result set. * This is not suitable for big results set * - * @param session The implicit session provided by a [[com.websudos.phantom.connectors.Connector]]. - * @param keySpace The implicit keySpace definition provided by a [[com.websudos.phantom.connectors.Connector]]. + * @param session The implicit session provided by a [[com.outworkers.phantom.connectors.Connector]]. + * @param keySpace The implicit keySpace definition provided by a [[com.outworkers.phantom.connectors.Connector]]. * @param executor The implicit Java executor. * @return A Twitter future wrapping a list of mapped results. */ @@ -263,8 +249,8 @@ package object finagle { * Returns a parsed sequence of [R]ows together with a result set. * This is not suitable for big results set * - * @param session The implicit session provided by a [[com.websudos.phantom.connectors.Connector]]. - * @param keySpace The implicit keySpace definition provided by a [[com.websudos.phantom.connectors.Connector]]. + * @param session The implicit session provided by a [[com.outworkers.phantom.connectors.Connector]]. + * @param keySpace The implicit keySpace definition provided by a [[com.outworkers.phantom.connectors.Connector]]. * @param executor The implicit Java executor. * @return A Twitter future wrapping a list of mapped results. */ @@ -284,8 +270,8 @@ package object finagle { * This is not suitable for big results set * * @param state An optional paging state that will be added only if the state is defined. - * @param session The implicit session provided by a [[com.websudos.phantom.connectors.Connector]]. - * @param keySpace The implicit keySpace definition provided by a [[com.websudos.phantom.connectors.Connector]]. + * @param session The implicit session provided by a [[com.outworkers.phantom.connectors.Connector]]. + * @param keySpace The implicit keySpace definition provided by a [[com.outworkers.phantom.connectors.Connector]]. * @param executor The implicit Java executor. * @return A Twitter future wrapping a list of mapped results. */ @@ -316,8 +302,6 @@ package object finagle { } } - - implicit class CreateQueryAugmenter[ Table <: CassandraTable[Table, _], Record, @@ -329,13 +313,11 @@ package object finagle { twitterQueryStringExecuteToFuture(new SimpleStatement(query.qb.terminate().queryString)) } else { query.execute() flatMap { - res => { - query.indexList(keySpace.name).execute() map { - _ => { - Manager.logger.debug(s"Creating secondary indexes on ${QueryBuilder.keyspace(keySpace.name, query.table.tableName).queryString}") - res - } - } + res => query.indexList(keySpace.name).execute() map { _ => + Manager.logger.debug( + s"Creating secondary indexes on ${QueryBuilder.keyspace(keySpace.name, query.table.tableName).queryString}" + ) + res } } } @@ -344,7 +326,7 @@ package object finagle { implicit class ExecutableCreateStatementsListAugmenter(val list: ExecutableCreateStatementsList) extends AnyVal { def execute()(implicit session: Session, keySpace: KeySpace, executor: Executor): Future[Seq[ResultSet]] = { - Future.collect(list.tables.toSeq.map(_.autocreate(keySpace).execute())) + Future.collect(list.queries(keySpace).map(_.execute())) } } @@ -370,8 +352,8 @@ package object finagle { /** * Returns the first row from the select ignoring everything else * This will always use a LIMIT 1 in the Cassandra query. - * @param session The implicit session provided by a [[com.websudos.phantom.connectors.Connector]]. - * @param keySpace The implicit keySpace definition provided by a [[com.websudos.phantom.connectors.Connector]]. + * @param session The implicit session provided by a [[com.outworkers.phantom.connectors.Connector]]. + * @param keySpace The implicit keySpace definition provided by a [[com.outworkers.phantom.connectors.Connector]]. * @param ev The implicit limit for the query. * @param executor The implicit Java executor. * @return @@ -470,8 +452,8 @@ package object finagle { /** * Get the result of an operation as a Twitter Future. * - * @param session The implicit session provided by a [[com.websudos.phantom.connectors.Connector]]. - * @param keySpace The implicit keySpace definition provided by a [[com.websudos.phantom.connectors.Connector]]. + * @param session The implicit session provided by a [[com.outworkers.phantom.connectors.Connector]]. + * @param keySpace The implicit keySpace definition provided by a [[com.outworkers.phantom.connectors.Connector]]. * @param ev The implicit limit for the query. * @param executor The implicit Java executor. * @return A Twitter future wrapping the result. diff --git a/phantom-finagle/src/main/scala/com/websudos/phantom/finagle/ResultSpool.scala b/phantom-finagle/src/main/scala/com/websudos/phantom/finagle/ResultSpool.scala deleted file mode 100644 index 5a27acada..000000000 --- a/phantom-finagle/src/main/scala/com/websudos/phantom/finagle/ResultSpool.scala +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.finagle - -import com.datastax.driver.core.{ResultSet, Row} -import com.twitter.concurrent.Spool -import com.twitter.util.{FuturePool, Future => TFuture} - -import scala.collection.JavaConversions._ - -/** - * Wrapper for creating Spools of Rows - */ -private[phantom] object ResultSpool { - lazy val pool = FuturePool.unboundedPool - - def loop(head: Row, it: Iterator[Row], rs: ResultSet): Spool[Row] = { - lazy val tail = - if (rs.isExhausted) { - TFuture.value(Spool.empty) - } else { - val a = rs.getAvailableWithoutFetching - - // 100 is somewhat arbitrary. In practice it might not matter that much - // but it should be tested. - if (a < 100 && !rs.isFullyFetched) { - rs.fetchMoreResults - } - - if (a > 0) { - TFuture.value(loop(it.next(), it, rs)) - } else { - pool(it.next()).map(x => loop(x, it, rs)) - } - } - - head *:: tail - } - - /** - * Create a Spool of Rows. - * - * Things to make sure: - * 1) We don't block! - * 2) If we don't have anything else to do we submit to the thread pool and - * wait to get called back and chain onto that. - */ - def spool(rs: ResultSet): TFuture[Spool[Row]] = { - val it = rs.iterator - if (!rs.isExhausted) { - pool(it.next).map(x => loop(x, it, rs)) - } else { - TFuture.value(Spool.empty) - } - } -} - diff --git a/phantom-finagle/src/test/scala/com/outworkers/phantom/finagle/SpoolBenchmarkPerformanceTest.scala b/phantom-finagle/src/test/scala/com/outworkers/phantom/finagle/SpoolBenchmarkPerformanceTest.scala new file mode 100644 index 000000000..1c5daef96 --- /dev/null +++ b/phantom-finagle/src/test/scala/com/outworkers/phantom/finagle/SpoolBenchmarkPerformanceTest.scala @@ -0,0 +1,62 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.finagle + +import com.twitter.util.{Await => TwitterAwait} +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.tables.{JodaRow, TestDatabase} +import com.outworkers.util.testing._ +import org.scalameter.api.{Gen => MeterGen, gen => _, _} +import org.scalatest.time.SpanSugar._ + +import scala.collection.immutable.IndexedSeq +import scala.concurrent.{Await, Future} + +class SpoolBenchmarkPerformanceTest extends Bench.LocalTime with TestDatabase.connector.Connector { + + TestDatabase.primitivesJoda.insertSchema() + + val fs: IndexedSeq[Future[Unit]] = for { + step <- 1 to 3 + rows = Iterator.fill(10000)(gen[JodaRow]) + + batch = rows.foldLeft(Batch.unlogged)((b, row) => { + val statement = TestDatabase.primitivesJoda.insert + .value(_.pkey, row.pkey) + .value(_.intColumn, row.intColumn) + .value(_.timestamp, row.timestamp) + b.add(statement) + }) + w = batch.future() + f = w map (_ =>println(s"step $step has succeed") ) + r = Await.result(f, 200 seconds) + } yield f map (_ => r) + + Await.ready(Future.sequence(fs), 20 seconds) + + val sizes: MeterGen[Int] = MeterGen.range("size")(10000, 30000, 10000) + + performance of "ResultSpool" in { + measure method "fetchSpool" in { + using(sizes) in { + size => TwitterAwait.ready { + TestDatabase.primitivesJoda.select.limit(size).fetchSpool().flatMap(_.toSeq) + } + } + } + } +} + diff --git a/phantom-finagle/src/test/scala/com/websudos/phantom/finagle/SpoolBenchmarkPerformanceTest.scala b/phantom-finagle/src/test/scala/com/websudos/phantom/finagle/SpoolBenchmarkPerformanceTest.scala deleted file mode 100644 index 1a471524f..000000000 --- a/phantom-finagle/src/test/scala/com/websudos/phantom/finagle/SpoolBenchmarkPerformanceTest.scala +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.finagle - -import com.twitter.util.{Await => TwitterAwait} -import com.websudos.phantom.dsl._ -import com.websudos.phantom.tables.{JodaRow, TestDatabase} -import com.outworkers.util.testing._ -import org.scalameter.api.{Gen => MeterGen, gen => _, _} -import org.scalatest.time.SpanSugar._ -import scala.concurrent.{Await, Future} - - -class SpoolBenchmarkPerformanceTest extends PerformanceTest.Quickbenchmark with TestDatabase.connector.Connector { - - TestDatabase.primitivesJoda.insertSchema() - - val fs = for { - step <- 1 to 3 - rows = Iterator.fill(10000)(gen[JodaRow]) - - batch = rows.foldLeft(Batch.unlogged)((b, row) => { - val statement = TestDatabase.primitivesJoda.insert - .value(_.pkey, row.pkey) - .value(_.intColumn, row.intColumn) - .value(_.timestamp, row.timestamp) - b.add(statement) - }) - w = batch.future() - f = w map (_ => println(s"step $step has succeed") ) - r = Await.result(f, 200 seconds) - } yield f map (_ => r) - - Await.ready(Future.sequence(fs), 20 seconds) - - val sizes: MeterGen[Int] = MeterGen.range("size")(10000, 30000, 10000) - - performance of "ResultSpool" in { - measure method "fetchSpool" in { - using(sizes) in { - size => TwitterAwait.ready { - TestDatabase.primitivesJoda.select.limit(size).fetchSpool().flatMap(s => s.toSeq) - } - } - } - } -} - diff --git a/phantom-jdk8/src/main/scala/com/outworkers/phantom/jdk8/DefaultJava8Primitives.scala b/phantom-jdk8/src/main/scala/com/outworkers/phantom/jdk8/DefaultJava8Primitives.scala new file mode 100644 index 000000000..957ff58e3 --- /dev/null +++ b/phantom-jdk8/src/main/scala/com/outworkers/phantom/jdk8/DefaultJava8Primitives.scala @@ -0,0 +1,127 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.jdk8 + +import java.time._ +import java.util.Date + +import com.datastax.driver.core.{GettableByIndexData, GettableByNameData, GettableData} +import com.outworkers.phantom.jdk8.dsl.JdkLocalDate +import com.outworkers.phantom.builder.primitives.Primitive +import com.outworkers.phantom.builder.query.CQLQuery +import com.outworkers.phantom.builder.syntax.CQLSyntax + +import scala.util.Try + +trait DefaultJava8Primitives { + + implicit object OffsetDateTimeIsPrimitive extends Primitive[OffsetDateTime] { + + override type PrimitiveType = java.util.Date + + val cassandraType = CQLSyntax.Types.Timestamp + + override def asCql(value: OffsetDateTime): String = { + value.toInstant.toEpochMilli.toString + } + + override def fromRow(column: String, row: GettableByNameData): Try[OffsetDateTime] = nullCheck(column, row) { + r => OffsetDateTime.ofInstant(r.getTimestamp(column).toInstant, ZoneOffset.UTC) + } + + override def fromRow(index: Int, row: GettableByIndexData): Try[OffsetDateTime] = nullCheck(index, row) { + r => OffsetDateTime.ofInstant(r.getTimestamp(index).toInstant, ZoneOffset.UTC) + } + + override def fromString(value: String): OffsetDateTime = OffsetDateTime.parse(value) + + override def clz: Class[Date] = classOf[Date] + } + + implicit object ZonedDateTimeIsPrimitive extends Primitive[ZonedDateTime] { + + override type PrimitiveType = java.util.Date + + val cassandraType = CQLSyntax.Types.Timestamp + + override def asCql(value: ZonedDateTime): String = { + value.toInstant.toEpochMilli.toString + } + + override def fromRow(column: String, row: GettableByNameData): Try[ZonedDateTime] = nullCheck(column, row) { + r => ZonedDateTime.ofInstant(r.getTimestamp(column).toInstant, ZoneOffset.UTC) + } + + override def fromRow(index: Int, row: GettableByIndexData): Try[ZonedDateTime] = nullCheck(index, row) { + r => ZonedDateTime.ofInstant(r.getTimestamp(index).toInstant, ZoneOffset.UTC) + } + + override def fromString(value: String): ZonedDateTime = ZonedDateTime.parse(value) + + override def clz: Class[Date] = classOf[Date] + } + + implicit object JdkLocalDateIsPrimitive extends Primitive[JdkLocalDate] { + + override type PrimitiveType = com.datastax.driver.core.LocalDate + + val cassandraType = CQLSyntax.Types.Date + + override def asCql(value: JdkLocalDate): String = { + CQLQuery.empty.singleQuote(value.toString) + } + + override def fromRow(column: String, row: GettableByNameData): Try[JdkLocalDate] = nullCheck(column, row) { + r => LocalDate.ofEpochDay(r.getDate(column).getDaysSinceEpoch) + } + + override def fromRow(index: Int, row: GettableByIndexData): Try[JdkLocalDate] = nullCheck(index, row) { + r => LocalDate.ofEpochDay(r.getDate(index).getDaysSinceEpoch) + } + + override def fromString(value: String): JdkLocalDate = { + Instant.ofEpochMilli(value.toLong).atOffset(ZoneOffset.UTC).toLocalDate + } + + override def clz: Class[com.datastax.driver.core.LocalDate] = classOf[com.datastax.driver.core.LocalDate] + } + + implicit object JdkLocalDateTimeIsPrimitive extends Primitive[LocalDateTime] { + + override type PrimitiveType = java.time.LocalDateTime + + val cassandraType = CQLSyntax.Types.Timestamp + + override def asCql(value: LocalDateTime): String = { + CQLQuery.empty.singleQuote(value.atZone(ZoneOffset.UTC).toString) + } + + override def fromRow(column: String, row: GettableByNameData): Try[LocalDateTime] = nullCheck(column, row) { + r => LocalDateTime.ofInstant(Instant.ofEpochMilli(r.getTimestamp(column).getTime), ZoneOffset.UTC) + } + + override def fromRow(index: Int, row: GettableByIndexData): Try[LocalDateTime] = nullCheck(index, row) { + r => LocalDateTime.ofInstant(Instant.ofEpochMilli(r.getTimestamp(index).getTime), ZoneOffset.UTC) + } + + override def fromString(value: String): LocalDateTime = { + Instant.ofEpochMilli(value.toLong).atZone(ZoneOffset.UTC).toLocalDateTime + } + + override def clz: Class[LocalDateTime] = classOf[LocalDateTime] + } + +} diff --git a/phantom-jdk8/src/main/scala/com/outworkers/phantom/jdk8/dsl/package.scala b/phantom-jdk8/src/main/scala/com/outworkers/phantom/jdk8/dsl/package.scala new file mode 100644 index 000000000..e70971221 --- /dev/null +++ b/phantom-jdk8/src/main/scala/com/outworkers/phantom/jdk8/dsl/package.scala @@ -0,0 +1,69 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.jdk8 + +import java.time.LocalDateTime + +import com.outworkers.phantom.dsl.CassandraTable + +package object dsl extends DefaultJava8Primitives { + + type OffsetDateTimeColumn[ + Owner <: CassandraTable[Owner, Record], + Record + ] = com.outworkers.phantom.column.PrimitiveColumn[Owner, Record, OffsetDateTime] + + type ZonedDateTimeColumn[ + Owner <: CassandraTable[Owner, Record], + Record + ] = com.outworkers.phantom.column.PrimitiveColumn[Owner, Record, ZonedDateTime] + + type JdkLocalDateColumn[ + Owner <: CassandraTable[Owner, Record], + Record + ] = com.outworkers.phantom.column.PrimitiveColumn[Owner, Record, JdkLocalDate] + + type JdkLocalDateTimeColumn[ + Owner <: CassandraTable[Owner, Record], + Record + ] = com.outworkers.phantom.column.PrimitiveColumn[Owner, Record, LocalDateTime] + + type OptionalOffsetDateTimeColumn[ + Owner <: CassandraTable[Owner, Record], + Record + ] = com.outworkers.phantom.column.OptionalPrimitiveColumn[Owner, Record, OffsetDateTime] + + type OptionalZonedDateTimeColumn[ + Owner <: CassandraTable[Owner, Record], + Record + ] = com.outworkers.phantom.column.OptionalPrimitiveColumn[Owner, Record, ZonedDateTime] + + type OptionalJdkLocalDateColumn[ + Owner <: CassandraTable[Owner, Record], + Record + ] = com.outworkers.phantom.column.OptionalPrimitiveColumn[Owner, Record, JdkLocalDate] + + type OptionalJdkLocalDateTimeColumn[ + Owner <: CassandraTable[Owner, Record], + Record + ] = com.outworkers.phantom.column.OptionalPrimitiveColumn[Owner, Record, LocalDateTime] + + type OffsetDateTime = java.time.OffsetDateTime + type ZonedDateTime = java.time.ZonedDateTime + type JdkLocalDate = java.time.LocalDate + type JdkLocalDateTime = java.time.LocalDateTime + +} diff --git a/phantom-jdk8/src/main/scala/com/websudos/phantom/jdk8/DefaultJava8Primitives.scala b/phantom-jdk8/src/main/scala/com/websudos/phantom/jdk8/DefaultJava8Primitives.scala deleted file mode 100644 index 1656b9c28..000000000 --- a/phantom-jdk8/src/main/scala/com/websudos/phantom/jdk8/DefaultJava8Primitives.scala +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.jdk8 - -import java.time._ -import java.util.Date - -import com.datastax.driver.core.GettableData -import com.websudos.phantom.builder.primitives.Primitive -import com.websudos.phantom.builder.query.CQLQuery -import com.websudos.phantom.builder.syntax.CQLSyntax -import com.websudos.phantom.jdk8.dsl.{JdkLocalDate, JdkLocalDateTime, OffsetDateTime, ZonedDateTime} - -import scala.util.Try - -trait DefaultJava8Primitives { - - implicit object OffsetDateTimeIsPrimitive extends Primitive[OffsetDateTime] { - - override type PrimitiveType = java.util.Date - - val cassandraType = CQLSyntax.Types.Timestamp - - override def asCql(value: OffsetDateTime): String = { - value.toInstant.toEpochMilli.toString - } - - override def fromRow(column: String, row: GettableData): Try[OffsetDateTime] = nullCheck(column, row) { - r => OffsetDateTime.ofInstant(r.getTimestamp(column).toInstant, ZoneOffset.UTC) - } - - override def fromString(value: String): OffsetDateTime = OffsetDateTime.parse(value) - - override def clz: Class[Date] = classOf[Date] - } - - implicit object ZonedDateTimeIsPrimitive extends Primitive[ZonedDateTime] { - - override type PrimitiveType = java.util.Date - - val cassandraType = CQLSyntax.Types.Timestamp - - override def asCql(value: ZonedDateTime): String = { - value.toInstant.toEpochMilli.toString - } - - override def fromRow(column: String, row: GettableData): Try[ZonedDateTime] = nullCheck(column, row) { - r => ZonedDateTime.ofInstant(r.getTimestamp(column).toInstant, ZoneOffset.UTC) - } - - override def fromString(value: String): ZonedDateTime = ZonedDateTime.parse(value) - - override def clz: Class[Date] = classOf[Date] - } - - implicit object JdkLocalDateIsPrimitive extends Primitive[JdkLocalDate] { - - override type PrimitiveType = com.datastax.driver.core.LocalDate - - val cassandraType = CQLSyntax.Types.Date - - override def asCql(value: JdkLocalDate): String = { - CQLQuery.empty.singleQuote(value.toString) - } - - override def fromRow(column: String, row: GettableData): Try[JdkLocalDate] = nullCheck(column, row) { - r => LocalDate.ofEpochDay(r.getDate(column).getDaysSinceEpoch) - } - - override def fromString(value: String): JdkLocalDate = { - Instant.ofEpochMilli(value.toLong).atOffset(ZoneOffset.UTC).toLocalDate - } - - override def clz: Class[com.datastax.driver.core.LocalDate] = classOf[com.datastax.driver.core.LocalDate] - } - - implicit object JdkLocalDateTimeIsPrimitive extends Primitive[JdkLocalDateTime] { - - override type PrimitiveType = java.time.LocalDateTime - - val cassandraType = CQLSyntax.Types.Timestamp - - override def asCql(value: JdkLocalDateTime): String = { - CQLQuery.empty.singleQuote(value.atZone(ZoneOffset.UTC).toString) - } - - override def fromRow(column: String, row: GettableData): Try[JdkLocalDateTime] = nullCheck(column, row) { - r => LocalDateTime.ofInstant(Instant.ofEpochMilli(r.getTimestamp(column).getTime), ZoneOffset.UTC) - } - - override def fromString(value: String): JdkLocalDateTime = { - Instant.ofEpochMilli(value.toLong).atZone(ZoneOffset.UTC).toLocalDateTime - } - - override def clz: Class[JdkLocalDateTime] = classOf[JdkLocalDateTime] - } - -} diff --git a/phantom-jdk8/src/main/scala/com/websudos/phantom/jdk8/dsl/package.scala b/phantom-jdk8/src/main/scala/com/websudos/phantom/jdk8/dsl/package.scala deleted file mode 100644 index f2afd08a4..000000000 --- a/phantom-jdk8/src/main/scala/com/websudos/phantom/jdk8/dsl/package.scala +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.jdk8 - -import com.websudos.phantom.dsl.CassandraTable - -package object dsl extends DefaultJava8Primitives { - - type OffsetDateTimeColumn[Owner <: CassandraTable[Owner, Record], Record] = com.websudos.phantom.column.PrimitiveColumn[Owner, Record, OffsetDateTime] - type ZonedDateTimeColumn[Owner <: CassandraTable[Owner, Record], Record] = com.websudos.phantom.column.PrimitiveColumn[Owner, Record, ZonedDateTime] - type JdkLocalDateColumn[Owner <: CassandraTable[Owner, Record], Record] = com.websudos.phantom.column.PrimitiveColumn[Owner, Record, JdkLocalDate] - type JdkLocalDateTimeColumn[Owner <: CassandraTable[Owner, Record], Record] = com.websudos.phantom.column.PrimitiveColumn[Owner, Record, JdkLocalDateTime] - - type OptionalOffsetDateTimeColumn[ - Owner <: CassandraTable[Owner, Record], - Record - ] = com.websudos.phantom.column.OptionalPrimitiveColumn[Owner, Record, OffsetDateTime] - - type OptionalZonedDateTimeColumn[ - Owner <: CassandraTable[Owner, Record], - Record - ] = com.websudos.phantom.column.OptionalPrimitiveColumn[Owner, Record, ZonedDateTime] - - type OptionalJdkLocalDateColumn[Owner <: CassandraTable[Owner, Record], Record] = com.websudos.phantom.column.OptionalPrimitiveColumn[Owner, Record, JdkLocalDate] - type OptionalJdkLocalDateTimeColumn[Owner <: CassandraTable[Owner, Record], Record] = com.websudos.phantom.column.OptionalPrimitiveColumn[Owner, Record, JdkLocalDateTime] - - type OffsetDateTime = java.time.OffsetDateTime - type ZonedDateTime = java.time.ZonedDateTime - type JdkLocalDate = java.time.LocalDate - type JdkLocalDateTime = java.time.LocalDateTime - -} diff --git a/phantom-jdk8/src/test/scala/com/outworkers/phantom/jdk8/Jdk8TimeColumnsTest.scala b/phantom-jdk8/src/test/scala/com/outworkers/phantom/jdk8/Jdk8TimeColumnsTest.scala new file mode 100644 index 000000000..5ca9eabec --- /dev/null +++ b/phantom-jdk8/src/test/scala/com/outworkers/phantom/jdk8/Jdk8TimeColumnsTest.scala @@ -0,0 +1,60 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.jdk8 + +import com.outworkers.phantom.PhantomSuite +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.jdk8.tables.{Jdk8Row, TestDatabase, _} +import com.outworkers.util.testing._ + +class Jdk8TimeColumnsTest extends PhantomSuite { + + override def beforeAll(): Unit = { + super.beforeAll() + if (session.v4orNewer) { + TestDatabase.primitivesJdk8.insertSchema() + TestDatabase.optionalPrimitivesJdk8.insertSchema() + } + } + + if (session.v4orNewer) { + it should "correctly insert and extract java.time columns" in { + val row = gen[Jdk8Row] + + val chain = for { + store <- TestDatabase.primitivesJdk8.store(row).future() + select <- TestDatabase.primitivesJdk8.select.where(_.pkey eqs row.pkey).one() + } yield select + + chain successful { + res => res.value shouldEqual row + } + } + + it should "correctly insert and extract optional java.time columns" in { + val row = gen[OptionalJdk8Row] + + val chain = for { + store <- TestDatabase.optionalPrimitivesJdk8.store(row).future() + select <- TestDatabase.optionalPrimitivesJdk8.select.where(_.pkey eqs row.pkey).one() + } yield select + + chain successful { + res => res.value shouldEqual row + } + } + } +} diff --git a/phantom-jdk8/src/test/scala/com/outworkers/phantom/jdk8/OptionalPrimitivesJdk8.scala b/phantom-jdk8/src/test/scala/com/outworkers/phantom/jdk8/OptionalPrimitivesJdk8.scala new file mode 100644 index 000000000..0ba891eac --- /dev/null +++ b/phantom-jdk8/src/test/scala/com/outworkers/phantom/jdk8/OptionalPrimitivesJdk8.scala @@ -0,0 +1,59 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.jdk8 + +import java.time.{LocalDate, LocalDateTime, OffsetDateTime} + +import com.outworkers.phantom.CassandraTable +import com.outworkers.phantom.connectors.RootConnector +import com.outworkers.phantom.jdk8.dsl._ +import com.outworkers.phantom.builder.query.InsertQuery +import com.outworkers.phantom.dsl._ + +case class OptionalJdk8Row( + pkey: String, + offsetDateTime: Option[OffsetDateTime], + zonedDateTime: Option[ZonedDateTime], + localDate: Option[LocalDate], + localDateTime: Option[LocalDateTime] +) + +sealed class OptionalPrimitivesJdk8 extends CassandraTable[ConcreteOptionalPrimitivesJdk8, OptionalJdk8Row] { + + object pkey extends StringColumn(this) with PartitionKey + + object offsetDateTime extends OptionalOffsetDateTimeColumn(this) + + object zonedDateTime extends OptionalZonedDateTimeColumn(this) + + object localDate extends OptionalJdkLocalDateColumn(this) + + object localDateTime extends OptionalJdkLocalDateTimeColumn(this) +} + +abstract class ConcreteOptionalPrimitivesJdk8 extends OptionalPrimitivesJdk8 with RootConnector { + + def store(primitive: OptionalJdk8Row): InsertQuery.Default[ConcreteOptionalPrimitivesJdk8, OptionalJdk8Row] = { + insert.value(_.pkey, primitive.pkey) + .value(_.offsetDateTime, primitive.offsetDateTime) + .value(_.zonedDateTime, primitive.zonedDateTime) + .value(_.localDate, primitive.localDate) + .value(_.localDateTime, primitive.localDateTime) + } + + override val tableName = "OptionalPrimitivesJdk8" + +} \ No newline at end of file diff --git a/phantom-jdk8/src/test/scala/com/outworkers/phantom/jdk8/tables/ConcretePrimitivesJdk8.scala b/phantom-jdk8/src/test/scala/com/outworkers/phantom/jdk8/tables/ConcretePrimitivesJdk8.scala new file mode 100644 index 000000000..baf5a317d --- /dev/null +++ b/phantom-jdk8/src/test/scala/com/outworkers/phantom/jdk8/tables/ConcretePrimitivesJdk8.scala @@ -0,0 +1,59 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.jdk8.tables + +import java.time.{LocalDate, LocalDateTime, OffsetDateTime} + +import com.outworkers.phantom.CassandraTable +import com.outworkers.phantom.connectors.RootConnector +import com.outworkers.phantom.builder.query.InsertQuery +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.jdk8.dsl._ + +case class Jdk8Row( + pkey: String, + offsetDateTime: OffsetDateTime, + zonedDateTime: ZonedDateTime, + localDate: LocalDate, + localDateTime: LocalDateTime +) + +sealed class PrimitivesJdk8 extends CassandraTable[ConcretePrimitivesJdk8, Jdk8Row] { + + object pkey extends StringColumn(this) with PartitionKey + + object offsetDateTime extends OffsetDateTimeColumn(this) + + object zonedDateTime extends ZonedDateTimeColumn(this) + + object localDate extends JdkLocalDateColumn(this) + + object localDateTime extends JdkLocalDateTimeColumn(this) +} + +abstract class ConcretePrimitivesJdk8 extends PrimitivesJdk8 with RootConnector { + + def store(primitive: Jdk8Row): InsertQuery.Default[ConcretePrimitivesJdk8, Jdk8Row] = { + insert.value(_.pkey, primitive.pkey) + .value(_.offsetDateTime, primitive.offsetDateTime) + .value(_.zonedDateTime, primitive.zonedDateTime) + .value(_.localDate, primitive.localDate) + .value(_.localDateTime, primitive.localDateTime) + } + + override val tableName = "PrimitivesJdk8" + +} \ No newline at end of file diff --git a/phantom-jdk8/src/test/scala/com/outworkers/phantom/jdk8/tables/TestDatabase.scala b/phantom-jdk8/src/test/scala/com/outworkers/phantom/jdk8/tables/TestDatabase.scala new file mode 100644 index 000000000..734855b45 --- /dev/null +++ b/phantom-jdk8/src/test/scala/com/outworkers/phantom/jdk8/tables/TestDatabase.scala @@ -0,0 +1,32 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.jdk8.tables + +import com.outworkers.phantom.connectors.ContactPoint +import com.outworkers.phantom.jdk8.ConcreteOptionalPrimitivesJdk8 +import com.outworkers.phantom.connectors.CassandraConnection +import com.outworkers.phantom.database.Database + + +class TestDatabase(override val connector: CassandraConnection) extends Database[TestDatabase](connector) { + + object primitivesJdk8 extends ConcretePrimitivesJdk8 with connector.Connector + + object optionalPrimitivesJdk8 extends ConcreteOptionalPrimitivesJdk8 with connector.Connector + +} + +object TestDatabase extends TestDatabase(ContactPoint.local.keySpace("phantom")) \ No newline at end of file diff --git a/phantom-jdk8/src/test/scala/com/outworkers/phantom/jdk8/tables/package.scala b/phantom-jdk8/src/test/scala/com/outworkers/phantom/jdk8/tables/package.scala new file mode 100644 index 000000000..58fa5ef85 --- /dev/null +++ b/phantom-jdk8/src/test/scala/com/outworkers/phantom/jdk8/tables/package.scala @@ -0,0 +1,48 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.jdk8 + +import java.time._ + +import com.outworkers.util.testing.{Sample, _} + +package object tables { + + implicit object Jdk8RowSampler extends Sample[Jdk8Row] { + def sample: Jdk8Row = { + Jdk8Row( + gen[String], + OffsetDateTime.now(ZoneOffset.UTC).plusSeconds(gen[Long]), + ZonedDateTime.now(ZoneOffset.UTC).plusSeconds(gen[Long]), + LocalDate.now().plusDays(gen[Long]), + LocalDateTime.now().plusSeconds(gen[Long]) + ) + } + } + + implicit object OptionalJdk8RowSampler extends Sample[OptionalJdk8Row] { + def sample: OptionalJdk8Row = { + OptionalJdk8Row( + gen[String], + Some(OffsetDateTime.now(ZoneOffset.UTC).plusSeconds(gen[Long])), + Some(ZonedDateTime.now(ZoneOffset.UTC).plusSeconds(gen[Long])), + Some(LocalDate.now().plusDays(gen[Long])), + Some(LocalDateTime.now().plusSeconds(gen[Long])) + ) + } + } + +} diff --git a/phantom-jdk8/src/test/scala/com/websudos/phantom/jdk8/Jdk8TimeColumnsTest.scala b/phantom-jdk8/src/test/scala/com/websudos/phantom/jdk8/Jdk8TimeColumnsTest.scala deleted file mode 100644 index 728f8baa8..000000000 --- a/phantom-jdk8/src/test/scala/com/websudos/phantom/jdk8/Jdk8TimeColumnsTest.scala +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.jdk8 - -import com.websudos.phantom.PhantomSuite -import com.websudos.phantom.dsl._ -import com.websudos.phantom.jdk8.tables.{Jdk8Row, TestDatabase, _} -import com.outworkers.util.testing._ - -class Jdk8TimeColumnsTest extends PhantomSuite { - - override def beforeAll(): Unit = { - super.beforeAll() - if (session.v4orNewer) { - TestDatabase.primitivesJdk8.insertSchema() - TestDatabase.optionalPrimitivesJdk8.insertSchema() - } - } - - if (session.v4orNewer) { - it should "correctly insert and extract java.time columns" in { - val row = gen[Jdk8Row] - - val chain = for { - store <- TestDatabase.primitivesJdk8.store(row).future() - select <- TestDatabase.primitivesJdk8.select.where(_.pkey eqs row.pkey).one() - } yield select - - chain successful { - res => res.value shouldEqual row - } - } - - it should "correctly insert and extract optional java.time columns" in { - val row = gen[OptionalJdk8Row] - - val chain = for { - store <- TestDatabase.optionalPrimitivesJdk8.store(row).future() - select <- TestDatabase.optionalPrimitivesJdk8.select.where(_.pkey eqs row.pkey).one() - } yield select - - chain successful { - res => res.value shouldEqual row - } - } - } -} diff --git a/phantom-jdk8/src/test/scala/com/websudos/phantom/jdk8/tables/ConcretePrimitivesJdk8.scala b/phantom-jdk8/src/test/scala/com/websudos/phantom/jdk8/tables/ConcretePrimitivesJdk8.scala deleted file mode 100644 index b2a582382..000000000 --- a/phantom-jdk8/src/test/scala/com/websudos/phantom/jdk8/tables/ConcretePrimitivesJdk8.scala +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.jdk8.tables - -import java.time.{LocalDate, LocalDateTime, OffsetDateTime} - -import com.websudos.phantom.CassandraTable -import com.websudos.phantom.builder.query.InsertQuery -import com.websudos.phantom.dsl._ -import com.websudos.phantom.jdk8.dsl._ - -case class Jdk8Row( - pkey: String, - offsetDateTime: OffsetDateTime, - zonedDateTime: ZonedDateTime, - localDate: LocalDate, - localDateTime: LocalDateTime -) - -sealed class PrimitivesJdk8 extends CassandraTable[ConcretePrimitivesJdk8, Jdk8Row] { - - object pkey extends StringColumn(this) with PartitionKey[String] - - object offsetDateTime extends OffsetDateTimeColumn(this) - - object zonedDateTime extends ZonedDateTimeColumn(this) - - object localDate extends JdkLocalDateColumn(this) - - object localDateTime extends JdkLocalDateTimeColumn(this) - - override def fromRow(r: Row): Jdk8Row = { - Jdk8Row( - pkey = pkey(r), - offsetDateTime = offsetDateTime(r), - zonedDateTime = zonedDateTime(r), - localDate = localDate(r), - localDateTime = localDateTime(r) - ) - } -} - -abstract class ConcretePrimitivesJdk8 extends PrimitivesJdk8 with RootConnector { - - def store(primitive: Jdk8Row): InsertQuery.Default[ConcretePrimitivesJdk8, Jdk8Row] = { - insert.value(_.pkey, primitive.pkey) - .value(_.offsetDateTime, primitive.offsetDateTime) - .value(_.zonedDateTime, primitive.zonedDateTime) - .value(_.localDate, primitive.localDate) - .value(_.localDateTime, primitive.localDateTime) - } - - override val tableName = "PrimitivesJdk8" - -} diff --git a/phantom-jdk8/src/test/scala/com/websudos/phantom/jdk8/tables/OptionalPrimitivesJdk8.scala b/phantom-jdk8/src/test/scala/com/websudos/phantom/jdk8/tables/OptionalPrimitivesJdk8.scala deleted file mode 100644 index e2cf8efef..000000000 --- a/phantom-jdk8/src/test/scala/com/websudos/phantom/jdk8/tables/OptionalPrimitivesJdk8.scala +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.jdk8.tables - -import java.time.{LocalDate, LocalDateTime, OffsetDateTime} - -import com.websudos.phantom.CassandraTable -import com.websudos.phantom.builder.query.InsertQuery -import com.websudos.phantom.dsl._ -import com.websudos.phantom.jdk8.dsl._ - -case class OptionalJdk8Row( - pkey: String, - offsetDateTime: Option[OffsetDateTime], - zonedDateTime: Option[ZonedDateTime], - localDate: Option[LocalDate], - localDateTime: Option[LocalDateTime] -) - -sealed class OptionalPrimitivesJdk8 extends CassandraTable[ConcreteOptionalPrimitivesJdk8, OptionalJdk8Row] { - - object pkey extends StringColumn(this) with PartitionKey[String] - - object offsetDateTime extends OptionalOffsetDateTimeColumn(this) - - object zonedDateTime extends OptionalZonedDateTimeColumn(this) - - object localDate extends OptionalJdkLocalDateColumn(this) - - object localDateTime extends OptionalJdkLocalDateTimeColumn(this) - - override def fromRow(r: Row): OptionalJdk8Row = { - OptionalJdk8Row( - pkey = pkey(r), - offsetDateTime = offsetDateTime(r), - zonedDateTime = zonedDateTime(r), - localDate = localDate(r), - localDateTime = localDateTime(r) - ) - } -} - -abstract class ConcreteOptionalPrimitivesJdk8 extends OptionalPrimitivesJdk8 with RootConnector { - - def store(primitive: OptionalJdk8Row): InsertQuery.Default[ConcreteOptionalPrimitivesJdk8, OptionalJdk8Row] = { - insert.value(_.pkey, primitive.pkey) - .value(_.offsetDateTime, primitive.offsetDateTime) - .value(_.zonedDateTime, primitive.zonedDateTime) - .value(_.localDate, primitive.localDate) - .value(_.localDateTime, primitive.localDateTime) - } - - override val tableName = "OptionalPrimitivesJdk8" - -} diff --git a/phantom-jdk8/src/test/scala/com/websudos/phantom/jdk8/tables/TestDatabase.scala b/phantom-jdk8/src/test/scala/com/websudos/phantom/jdk8/tables/TestDatabase.scala deleted file mode 100644 index 8121527a3..000000000 --- a/phantom-jdk8/src/test/scala/com/websudos/phantom/jdk8/tables/TestDatabase.scala +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.jdk8.tables - -import com.websudos.phantom.connectors.{ContactPoint, KeySpaceDef} -import com.websudos.phantom.database.Database - - -class TestDatabase(override val connector: KeySpaceDef) extends Database[TestDatabase](connector) { - - object primitivesJdk8 extends ConcretePrimitivesJdk8 with connector.Connector - - object optionalPrimitivesJdk8 extends ConcreteOptionalPrimitivesJdk8 with connector.Connector - -} - -object TestDatabase extends TestDatabase(ContactPoint.local.keySpace("phantom")) \ No newline at end of file diff --git a/phantom-jdk8/src/test/scala/com/websudos/phantom/jdk8/tables/package.scala b/phantom-jdk8/src/test/scala/com/websudos/phantom/jdk8/tables/package.scala deleted file mode 100644 index 85b0c11ab..000000000 --- a/phantom-jdk8/src/test/scala/com/websudos/phantom/jdk8/tables/package.scala +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.jdk8 - -import java.time._ - -import com.outworkers.util.testing.{Sample, _} - -package object tables { - - implicit object Jdk8RowSampler extends Sample[Jdk8Row] { - def sample: Jdk8Row = { - Jdk8Row( - gen[String], - OffsetDateTime.now(ZoneOffset.UTC).plusSeconds(gen[Long]), - ZonedDateTime.now(ZoneOffset.UTC).plusSeconds(gen[Long]), - LocalDate.now().plusDays(gen[Long]), - LocalDateTime.now().plusSeconds(gen[Long]) - ) - } - } - - implicit object OptionalJdk8RowSampler extends Sample[OptionalJdk8Row] { - def sample: OptionalJdk8Row = { - OptionalJdk8Row( - gen[String], - Some(OffsetDateTime.now(ZoneOffset.UTC).plusSeconds(gen[Long])), - Some(ZonedDateTime.now(ZoneOffset.UTC).plusSeconds(gen[Long])), - Some(LocalDate.now().plusDays(gen[Long])), - Some(LocalDateTime.now().plusSeconds(gen[Long])) - ) - } - } - -} diff --git a/phantom-reactivestreams/src/test/scala/com/websudos/phantom/reactivestreams/suites/BatchSubscriberIntegrationTest.scala b/phantom-reactivestreams/src/test/scala/com/websudos/phantom/reactivestreams/suites/BatchSubscriberIntegrationTest.scala deleted file mode 100644 index 999a1529e..000000000 --- a/phantom-reactivestreams/src/test/scala/com/websudos/phantom/reactivestreams/suites/BatchSubscriberIntegrationTest.scala +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.reactivestreams.suites - -import java.util.concurrent.{CountDownLatch, TimeUnit} - -import com.websudos.phantom.batch.BatchType -import com.websudos.phantom.dsl._ -import com.websudos.phantom.reactivestreams._ -import com.websudos.phantom.reactivestreams.suites.iteratee.OperaPublisher -import org.scalatest.{FlatSpec, Retries} -import org.scalatest.concurrent.ScalaFutures -import org.scalatest.tagobjects.Retryable - -import scala.concurrent.Await -import scala.concurrent.duration._ - -class BatchSubscriberIntegrationTest extends FlatSpec with StreamTest with ScalaFutures with Retries { - - implicit val defaultPatience = PatienceConfig(timeout = 10.seconds, interval = 50.millis) - - override def beforeAll(): Unit = { - super.beforeAll() - Await.result(StreamDatabase.autotruncate().future(), 5.seconds) - } - - it should "persist all data" taggedAs Retryable in { - val completionLatch = new CountDownLatch(1) - - val subscriber = StreamDatabase.operaTable.subscriber( - batchSize = 2, - concurrentRequests = 2, - batchType = BatchType.Unlogged, - flushInterval = None, - completionFn = () => completionLatch.countDown() - ) - - OperaPublisher.subscribe(subscriber) - - completionLatch.await(5, TimeUnit.SECONDS) - - val chain = for { - count <- StreamDatabase.operaTable.select.count().one() - } yield count - - whenReady(chain) { - res => res.value shouldEqual OperaData.operas.length - } - - } - -} - diff --git a/phantom-reactivestreams/src/test/scala/com/websudos/phantom/reactivestreams/suites/BatchSubscriberWhiteboxTest.scala b/phantom-reactivestreams/src/test/scala/com/websudos/phantom/reactivestreams/suites/BatchSubscriberWhiteboxTest.scala deleted file mode 100644 index 3625a78d2..000000000 --- a/phantom-reactivestreams/src/test/scala/com/websudos/phantom/reactivestreams/suites/BatchSubscriberWhiteboxTest.scala +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.reactivestreams.suites - -import com.websudos.phantom.batch.BatchType -import com.websudos.phantom.reactivestreams._ -import org.reactivestreams.tck.SubscriberWhiteboxVerification.{SubscriberPuppet, WhiteboxSubscriberProbe} -import org.reactivestreams.tck.{SubscriberWhiteboxVerification, TestEnvironment} -import org.reactivestreams.{Subscriber, Subscription} -import com.outworkers.util.testing._ - -class BatchSubscriberWhiteboxTest extends SubscriberWhiteboxVerification[Opera](new TestEnvironment()) - with StreamDatabase.connector.Connector with TestImplicits { - - override def createSubscriber(probe: WhiteboxSubscriberProbe[Opera]): Subscriber[Opera] = { - new BatchSubscriber[ConcreteOperaTable, Opera]( - StreamDatabase.operaTable, - builder = OperaRequestBuilder, - batchSize = 5, - concurrentRequests = 2, - batchType = BatchType.Unlogged, - flushInterval = None, - completionFn = () => (), - errorFn = _ => () - ) { - - override def onSubscribe(s: Subscription): Unit = { - super.onSubscribe(s) - - probe.registerOnSubscribe(new SubscriberPuppet { - - override def triggerRequest(elements: Long): Unit = { - s.request(elements) - } - - override def signalCancel(): Unit = { - s.cancel() - } - }) - } - - override def onComplete(): Unit = { - super.onComplete() - probe.registerOnComplete() - } - - override def onError(t: Throwable): Unit = { - probe.registerOnError(t) - } - - override def onNext(t: Opera): Unit = { - super.onNext(t) - probe.registerOnNext(t) - } - - } - } - - override def createElement(element: Int): Opera = Opera(gen[String]) -} \ No newline at end of file diff --git a/phantom-reactivestreams/src/test/scala/com/websudos/phantom/reactivestreams/suites/CassandraTest.scala b/phantom-reactivestreams/src/test/scala/com/websudos/phantom/reactivestreams/suites/CassandraTest.scala deleted file mode 100644 index c4c3426fa..000000000 --- a/phantom-reactivestreams/src/test/scala/com/websudos/phantom/reactivestreams/suites/CassandraTest.scala +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.reactivestreams.suites - -import akka.actor.ActorSystem -import com.websudos.phantom.builder.query.{Batchable, ExecutableStatement, InsertQuery} -import com.websudos.phantom.database.Database -import com.websudos.phantom.dsl._ -import com.websudos.phantom.reactivestreams.RequestBuilder -import com.outworkers.util.testing._ -import org.scalatest._ - -import scala.concurrent.Await -import scala.concurrent.duration._ - -trait TestImplicits { - implicit val system = ActorSystem() - - implicit object OperaRequestBuilder extends RequestBuilder[ConcreteOperaTable, Opera] { - - override def request(ct: ConcreteOperaTable, t: Opera)( - implicit session: Session, - keySpace: KeySpace - ): ExecutableStatement with Batchable = { - ct.insert.value(_.name, t.name) - } - } - -} - -trait StreamTest extends FlatSpec with BeforeAndAfterAll - with OptionValues - with Matchers - with TestImplicits - with Retries - with StreamDatabase.connector.Connector { - self: Suite => - - override def withFixture(test: NoArgTest): Outcome = { - if (isRetryable(test)) { - withRetry(super.withFixture(test)) - } else { - super.withFixture(test) - } - } - - override def beforeAll(): Unit = { - super.beforeAll() - Await.result(StreamDatabase.autocreate().future(), 5.seconds) - } - - override def afterAll(): Unit = { - super.afterAll() - system.shutdown() - } - -} - -case class Opera(name: String) - -abstract class OperaTable extends CassandraTable[ConcreteOperaTable, Opera] { - object name extends StringColumn(this) with PartitionKey[String] - - def fromRow(row: Row): Opera = { - Opera(name(row)) - } -} - -abstract class ConcreteOperaTable extends OperaTable with RootConnector { - def store(item: Opera): InsertQuery.Default[ConcreteOperaTable, Opera] = { - insert.value(_.name, item.name) - } -} - - -object StreamConnector { - val connector = ContactPoint.local.keySpace("phantom") -} - -class StreamDatabase extends Database[StreamDatabase](StreamConnector.connector) { - object operaTable extends ConcreteOperaTable with connector.Connector -} - -object StreamDatabase extends StreamDatabase - -object OperaData { - val operas = genList[String]().map(Opera) -} \ No newline at end of file diff --git a/phantom-reactivestreams/src/test/scala/com/websudos/phantom/reactivestreams/suites/iteratee/BigTest.scala b/phantom-reactivestreams/src/test/scala/com/websudos/phantom/reactivestreams/suites/iteratee/BigTest.scala deleted file mode 100644 index 2275027ff..000000000 --- a/phantom-reactivestreams/src/test/scala/com/websudos/phantom/reactivestreams/suites/iteratee/BigTest.scala +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.reactivestreams.suites.iteratee - -import com.datastax.driver.core.{PoolingOptions, Session, SocketOptions} -import com.websudos.phantom.PhantomSuite -import com.websudos.phantom.connectors.ContactPoint - -trait BigTest extends PhantomSuite { - - val connectionTimeoutMillis = 1000 - - override implicit lazy val session: Session = { - ContactPoint.local.withClusterBuilder( - _.withSocketOptions(new SocketOptions() - .setReadTimeoutMillis(connectionTimeoutMillis) - .setConnectTimeoutMillis(connectionTimeoutMillis) - ) - ).noHeartbeat().keySpace(keySpace).session - } -} diff --git a/phantom-reactivestreams/src/test/scala/com/websudos/phantom/reactivestreams/suites/iteratee/IterateeBenchmarkPerformanceTest.scala b/phantom-reactivestreams/src/test/scala/com/websudos/phantom/reactivestreams/suites/iteratee/IterateeBenchmarkPerformanceTest.scala deleted file mode 100644 index 0d4fd412a..000000000 --- a/phantom-reactivestreams/src/test/scala/com/websudos/phantom/reactivestreams/suites/iteratee/IterateeBenchmarkPerformanceTest.scala +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.reactivestreams.suites.iteratee - -import com.websudos.phantom.dsl._ -import com.websudos.phantom.reactivestreams._ -import com.websudos.phantom.tables.{JodaRow, TestDatabase} -import com.outworkers.util.testing._ -import org.scalameter.api.{Gen => MeterGen, gen => _, _} -import org.scalatest.time.SpanSugar._ - -import scala.concurrent.{Await, Future} - -class IterateeBenchmarkPerformanceTest extends PerformanceTest.Quickbenchmark with TestDatabase.connector.Connector { - - TestDatabase.primitivesJoda.insertSchema() - - val limit = 10000 - val sampleGenLimit = 30000 - - val fs = for { - step <- 1 to 3 - rows = Iterator.fill(limit)(gen[JodaRow]) - - batch = rows.foldLeft(Batch.unlogged)((b, row) => { - val statement = TestDatabase.primitivesJoda.insert - .value(_.pkey, row.pkey) - .value(_.intColumn, row.intColumn) - .value(_.timestamp, row.timestamp) - b.add(statement) - }) - w = batch.future() - f = w map (_ => println(s"step $step was completed successfully")) - r = Await.result(f, 200 seconds) - } yield f map (_ => r) - - Await.ready(Future.sequence(fs), 20 seconds) - - val sizes: MeterGen[Int] = MeterGen.range("size")(limit, sampleGenLimit, limit) - - performance of "Enumerator" in { - measure method "enumerator" in { - using(sizes) in { - size => Await.ready(TestDatabase.primitivesJoda.select.limit(size).fetchEnumerator run Iteratee.forEach { r => }, 10 seconds) - } - } - } -} diff --git a/phantom-reactivestreams/src/test/scala/com/websudos/phantom/reactivestreams/suites/iteratee/IterateeBigReadPerformanceTest.scala b/phantom-reactivestreams/src/test/scala/com/websudos/phantom/reactivestreams/suites/iteratee/IterateeBigReadPerformanceTest.scala deleted file mode 100644 index d13639c95..000000000 --- a/phantom-reactivestreams/src/test/scala/com/websudos/phantom/reactivestreams/suites/iteratee/IterateeBigReadPerformanceTest.scala +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.reactivestreams.suites.iteratee - -import java.util.concurrent.atomic.AtomicLong - -import com.websudos.phantom.dsl._ -import com.websudos.phantom.reactivestreams._ -import com.outworkers.util.testing._ -import org.scalatest.concurrent.ScalaFutures - -class IterateeBigReadPerformanceTest extends BigTest with ScalaFutures { - - it should "read the correct number of records found in the table" in { - val counter = new AtomicLong(0) - - val result = database.primitivesJoda.select.fetchEnumerator run Iteratee.forEach { - r => counter.incrementAndGet() - } - - result.successful { - query => { - val count = counter.getAndIncrement() - info(s"Done, reading: $count elements from the table.") - count shouldEqual 2000000 - } - } - } -} diff --git a/phantom-reactivestreams/src/test/scala/com/websudos/phantom/reactivestreams/suites/iteratee/IterateeInsertPerformanceTest.scala b/phantom-reactivestreams/src/test/scala/com/websudos/phantom/reactivestreams/suites/iteratee/IterateeInsertPerformanceTest.scala deleted file mode 100644 index a6180e59e..000000000 --- a/phantom-reactivestreams/src/test/scala/com/websudos/phantom/reactivestreams/suites/iteratee/IterateeInsertPerformanceTest.scala +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.reactivestreams.suites.iteratee - -import java.util.concurrent.atomic.AtomicLong -import com.websudos.phantom.reactivestreams._ - -import scala.concurrent.{ Await, Future } - -import org.scalatest.Matchers -import org.scalatest.concurrent.PatienceConfiguration -import org.scalatest.time.SpanSugar._ - -import com.websudos.phantom.dsl._ -import com.websudos.phantom.tables.{ TestDatabase, JodaRow } -import com.outworkers.util.testing._ - -class IterateeInsertPerformanceTest extends BigTest with Matchers { - - implicit val s: PatienceConfiguration.Timeout = timeout(12 minutes) - private[this] final val iteratorLimit = 10000 - - it should "retrieve the right amount of results" in { - TestDatabase.primitivesJoda.insertSchema() - val fs = for { - step <- 1 to 100 - rows = Iterator.fill(iteratorLimit)(gen[JodaRow]) - - batch = rows.foldLeft(Batch.unlogged)((b, row) => { - val statement = TestDatabase.primitivesJoda.insert - .value(_.pkey, row.pkey) - .value(_.intColumn, row.intColumn) - .value(_.timestamp, row.timestamp) - b.add(statement) - }) - w = batch.future() - f = w map (_ => info(s"step $step has succeed")) - r = Await.result(f, 200 seconds) - } yield f map (_ => r) - - - val combinedFuture = Future.sequence(fs) map { - r => TestDatabase.primitivesJoda.select.count.one() - } - - val counter: AtomicLong = new AtomicLong(0) - val result = combinedFuture flatMap { - rs => { - info(s"done, inserted: $rs rows - start parsing") - TestDatabase.primitivesJoda.select.fetchEnumerator run Iteratee.forEach { r => counter.incrementAndGet() } - } - } - - (result flatMap (_ => combinedFuture)) successful { - r => { - info(s"done, reading: ${counter.addAndGet(0)}") - counter.get() shouldEqual r - } - } - } -} diff --git a/phantom-reactivestreams/src/test/scala/com/websudos/phantom/reactivestreams/suites/iteratee/IteratorTest.scala b/phantom-reactivestreams/src/test/scala/com/websudos/phantom/reactivestreams/suites/iteratee/IteratorTest.scala deleted file mode 100644 index 3f00887a6..000000000 --- a/phantom-reactivestreams/src/test/scala/com/websudos/phantom/reactivestreams/suites/iteratee/IteratorTest.scala +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.reactivestreams.suites.iteratee - -import com.outworkers.util.testing._ -import com.websudos.phantom.dsl._ -import com.websudos.phantom.tables.{TestDatabase, TimeUUIDRecord} -import org.scalatest.concurrent.ScalaFutures - -import scala.concurrent.Future - -class IteratorTest extends BigTest with ScalaFutures { - - override def beforeAll(): Unit = { - super.beforeAll() - database.timeuuidTable.insertSchema() - } - - it should "correctly retrieve the right number of records using scala iterator" in { - val generationSize = 100 - val user = gen[UUID] - val rows = genList[TimeUUIDRecord](generationSize).map(_.copy(user = user)) - - val chain = for { - store <- Future.sequence(rows.map(row => database.timeuuidTable.store(row).future())) - iterator <- TestDatabase.timeuuidTable.select.where(_.user eqs user).iterator() - } yield iterator - - whenReady(chain) { - res => { - res.size shouldEqual generationSize - res.foreach(x => rows should contain (x)) - } - } - } -} diff --git a/phantom-reactivestreams/src/test/scala/com/websudos/phantom/reactivestreams/suites/iteratee/OperaPublisher.scala b/phantom-reactivestreams/src/test/scala/com/websudos/phantom/reactivestreams/suites/iteratee/OperaPublisher.scala deleted file mode 100644 index f9782ae59..000000000 --- a/phantom-reactivestreams/src/test/scala/com/websudos/phantom/reactivestreams/suites/iteratee/OperaPublisher.scala +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.reactivestreams.suites.iteratee - -import java.util.concurrent.atomic.AtomicInteger - -import com.websudos.phantom.reactivestreams.suites.{Opera, OperaData} -import org.reactivestreams.{Publisher, Subscriber, Subscription} - -object OperaPublisher extends Publisher[Opera] { - - val counter = new AtomicInteger(0) - - override def subscribe(s: Subscriber[_ >: Opera]): Unit = { - s.onSubscribe(new Subscription { - override def cancel(): Unit = () - - override def request(l: Long): Unit = { - val start = counter.getAndIncrement() * l.toInt - val end = start + l.toInt - - if (start < OperaData.operas.size) { - OperaData.operas.slice(start, end).foreach(s.onNext) - } else { - s.onComplete() - } - } - }) - } - -} diff --git a/phantom-sbt/src/main/scala-2.10/com/websudos/phantom/sbt/SbtPlugin.scala b/phantom-sbt/src/main/scala/com/outworkers/phantom/sbt/SbtPlugin.scala similarity index 76% rename from phantom-sbt/src/main/scala-2.10/com/websudos/phantom/sbt/SbtPlugin.scala rename to phantom-sbt/src/main/scala/com/outworkers/phantom/sbt/SbtPlugin.scala index def2c0d12..7df94f961 100644 --- a/phantom-sbt/src/main/scala-2.10/com/websudos/phantom/sbt/SbtPlugin.scala +++ b/phantom-sbt/src/main/scala/com/outworkers/phantom/sbt/SbtPlugin.scala @@ -1,33 +1,19 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.sbt +package com.outworkers.phantom.sbt import java.util.concurrent.atomic.AtomicBoolean @@ -36,8 +22,8 @@ import sbt.Keys._ import sbt._ import scala.concurrent.blocking -import scala.util.{Failure, Success, Try} import scala.util.control.NonFatal +import scala.util.{Failure, Success, Try} /** * sbt plugin for starting Cassandra in embedded mode before running @@ -46,7 +32,7 @@ import scala.util.control.NonFatal * First the plugin must be included in your `plugins.sbt`: * * {{{ - * addSbtPlugin("com.websudos" %% "phantom-sbt" % phantomVersion) + * addSbtPlugin("com.outworkers" %% "phantom-sbt" % phantomVersion) * }}} * The plugin does the following * things: diff --git a/phantom-reactivestreams/src/main/scala/com/websudos/phantom/reactivestreams/ReactiveCassandra.scala b/phantom-streams/src/main/scala/com/outworkers/phantom/reactivestreams/ReactiveCassandra.scala similarity index 72% rename from phantom-reactivestreams/src/main/scala/com/websudos/phantom/reactivestreams/ReactiveCassandra.scala rename to phantom-streams/src/main/scala/com/outworkers/phantom/reactivestreams/ReactiveCassandra.scala index de67b9f5b..f21b31660 100644 --- a/phantom-reactivestreams/src/main/scala/com/websudos/phantom/reactivestreams/ReactiveCassandra.scala +++ b/phantom-streams/src/main/scala/com/outworkers/phantom/reactivestreams/ReactiveCassandra.scala @@ -1,40 +1,26 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.reactivestreams +package com.outworkers.phantom.reactivestreams import akka.actor.{Actor, ActorRef, ActorSystem, Props} import com.datastax.driver.core.ResultSet -import com.websudos.phantom.CassandraTable -import com.websudos.phantom.batch.{BatchQuery, BatchType} -import com.websudos.phantom.builder.query.{QueryOptions, Batchable, ExecutableStatement, UsingPart} -import com.websudos.phantom.dsl._ +import com.outworkers.phantom.CassandraTable +import com.outworkers.phantom.batch.{BatchQuery, BatchType} +import com.outworkers.phantom.builder.query.{Batchable, ExecutableStatement, QueryOptions, UsingPart} +import com.outworkers.phantom.dsl._ import org.reactivestreams.{Subscriber, Subscription} import scala.collection.mutable.ArrayBuffer @@ -44,7 +30,7 @@ import scala.util.{Failure, Success} /** * The [[Subscriber]] internal implementation based on Akka actors. * - * @see [[com.websudos.phantom.reactivestreams.StreamedCassandraTable.subscriber()]] + * @see [[com.outworkers.phantom.reactivestreams.StreamedCassandraTable.subscriber()]] */ class BatchSubscriber[CT <: CassandraTable[CT, T], T] private[reactivestreams] ( table: CT, diff --git a/phantom-reactivestreams/src/main/scala/com/websudos/phantom/reactivestreams/iteratee/Enumerator.scala b/phantom-streams/src/main/scala/com/outworkers/phantom/reactivestreams/iteratee/Enumerator.scala similarity index 50% rename from phantom-reactivestreams/src/main/scala/com/websudos/phantom/reactivestreams/iteratee/Enumerator.scala rename to phantom-streams/src/main/scala/com/outworkers/phantom/reactivestreams/iteratee/Enumerator.scala index 5359fe76f..94c96ab37 100644 --- a/phantom-reactivestreams/src/main/scala/com/websudos/phantom/reactivestreams/iteratee/Enumerator.scala +++ b/phantom-streams/src/main/scala/com/outworkers/phantom/reactivestreams/iteratee/Enumerator.scala @@ -1,37 +1,23 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.reactivestreams.iteratee +package com.outworkers.phantom.reactivestreams.iteratee import com.datastax.driver.core.{ResultSet, Row} import play.api.libs.iteratee.Execution.{defaultExecutionContext => dec} -import play.api.libs.iteratee.{Cont, Done, Enumerator => PlayEnum, Error, Input, Iteratee => PlayIter, Step} +import play.api.libs.iteratee.{Cont, Done, Error, Input, Step, Enumerator => PlayEnum, Iteratee => PlayIter} import scala.concurrent.Future diff --git a/phantom-reactivestreams/src/main/scala/com/websudos/phantom/reactivestreams/iteratee/Iteratee.scala b/phantom-streams/src/main/scala/com/outworkers/phantom/reactivestreams/iteratee/Iteratee.scala similarity index 70% rename from phantom-reactivestreams/src/main/scala/com/websudos/phantom/reactivestreams/iteratee/Iteratee.scala rename to phantom-streams/src/main/scala/com/outworkers/phantom/reactivestreams/iteratee/Iteratee.scala index cb24cb177..dbc663264 100644 --- a/phantom-reactivestreams/src/main/scala/com/websudos/phantom/reactivestreams/iteratee/Iteratee.scala +++ b/phantom-streams/src/main/scala/com/outworkers/phantom/reactivestreams/iteratee/Iteratee.scala @@ -1,35 +1,21 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.reactivestreams.iteratee +package com.outworkers.phantom.reactivestreams.iteratee -import play.api.libs.iteratee.{ Iteratee => PlayIteratee } +import play.api.libs.iteratee.{Iteratee => PlayIteratee} import scala.concurrent.{ExecutionContext, Future} @@ -78,7 +64,7 @@ object Iteratee { } /** - * A drop method called directly on the iteratee, will asynchronously processs the drop using the Play Iteratee API. + * A drop method called directly on the iteratee, will asynchronously process the drop using the Play Iteratee API. * @param num The number of records to drop from the "left hand side" of the iteratee. * @param ex The execution context in which to execute the operation. * @tparam R The type of the Record being selected from the Cassandra table. diff --git a/phantom-reactivestreams/src/main/scala/com/websudos/phantom/reactivestreams/package.scala b/phantom-streams/src/main/scala/com/outworkers/phantom/reactivestreams/package.scala similarity index 63% rename from phantom-reactivestreams/src/main/scala/com/websudos/phantom/reactivestreams/package.scala rename to phantom-streams/src/main/scala/com/outworkers/phantom/reactivestreams/package.scala index 27bf20460..48db94703 100644 --- a/phantom-reactivestreams/src/main/scala/com/websudos/phantom/reactivestreams/package.scala +++ b/phantom-streams/src/main/scala/com/outworkers/phantom/reactivestreams/package.scala @@ -1,42 +1,28 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom +package com.outworkers.phantom import akka.actor.ActorSystem -import com.datastax.driver.core.Session -import com.websudos.phantom.batch.BatchType -import com.websudos.phantom.builder.LimitBound -import com.websudos.phantom.builder.query.{ExecutableQuery, RootSelectBlock} -import com.websudos.phantom.connectors.KeySpace -import com.websudos.phantom.dsl.{context => _, _} -import com.websudos.phantom.reactivestreams.iteratee.{Enumerator, Iteratee => PhantomIteratee} +import com.datastax.driver.core.{Session, Statement} +import com.outworkers.phantom.batch.BatchType +import com.outworkers.phantom.builder.LimitBound +import com.outworkers.phantom.builder.query.{ExecutableQuery, RootSelectBlock} +import com.outworkers.phantom.connectors.KeySpace +import com.outworkers.phantom.dsl.{context => _} +import com.outworkers.phantom.reactivestreams.iteratee.{Enumerator, Iteratee => PhantomIteratee} import org.reactivestreams.Publisher import play.api.libs.iteratee.{Enumeratee, Enumerator => PlayEnumerator} import play.api.libs.streams.Streams @@ -85,15 +71,15 @@ package object reactivestreams { * explanation. * @param flushInterval used to schedule periodic batch execution even though the number of statements hasn't * been reached yet. Useful in never-ending streams that will never been completed. - * @param completionFn a function that will be invoked when the stream is completed - * @param errorFn a function that will be invoked when an error occurs - * @param builder an implicitly resolved [[RequestBuilder]] that wraps a phantom [[com.websudos.phantom.builder.query.ExecutableStatement]]. - * Every T element that gets into the stream from the upstream is turned into a ExecutableStatement - * by means of this builder. - * @param system the underlying [[ActorSystem]]. This [[org.reactivestreams.Subscriber]] implementation uses Akka - * actors, but is not restricted to be used in the context of Akka Streams. - * @param session the Cassandra [[com.datastax.driver.core.Session]] - * @param space the Cassandra [[KeySpace]] + * @param completionFn a function that will be invoked when the stream is completed + * @param errorFn a function that will be invoked when an error occurs + * @param builder an implicitly resolved [[RequestBuilder]] that wraps a phantom [[com.outworkers.phantom.builder.query.ExecutableStatement]]. + * Every T element that gets into the stream from the upstream is turned into a ExecutableStatement + * by means of this builder. + * @param system the underlying [[ActorSystem]]. This [[org.reactivestreams.Subscriber]] implementation uses Akka + * actors, but is not restricted to be used in the context of Akka Streams. + * @param session the Cassandra [[com.datastax.driver.core.Session]] + * @param space the Cassandra [[KeySpace]] * @param ev an evidence to get the T type removed by erasure * @return the [[org.reactivestreams.Subscriber]] to be connected to a reactive stream typically initiated by * a [[org.reactivestreams.Publisher]] @@ -105,8 +91,7 @@ package object reactivestreams { flushInterval: Option[FiniteDuration] = None, completionFn: () => Unit = () => (), errorFn: Throwable => Unit = _ => () - )(implicit - builder: RequestBuilder[CT, T], + )(implicit builder: RequestBuilder[CT, T], system: ActorSystem, session: Session, space: KeySpace, @@ -143,9 +128,7 @@ package object reactivestreams { implicit class PublisherConverter[T](val enumerator: PlayEnumerator[T]) extends AnyVal { - def publisher: Publisher[T] = { - Streams.enumeratorToPublisher(enumerator) - } + def publisher: Publisher[T] = Streams.enumeratorToPublisher(enumerator) } /** @@ -190,10 +173,11 @@ package object reactivestreams { keySpace: KeySpace, ctx: ExecutionContextExecutor ): PlayEnumerator[R] = { - val eventualEnum = block.all().future() map { - resultSet => Enumerator.enumerator(resultSet) through Enumeratee.map(block.fromRow) + PlayEnumerator.flatten { + block.all().future() map { res => + Enumerator.enumerator(res) through Enumeratee.map(block.rowFunc) + } } - PlayEnumerator.flatten(eventualEnum) } } @@ -211,17 +195,39 @@ package object reactivestreams { * @param session The Cassandra session in use. * @param keySpace The keyspace object in use. * @param ctx The Execution Context. - * @return + * @return A play enumerator containing the results of the query. */ def fetchEnumerator()( implicit session: Session, keySpace: KeySpace, ctx: ExecutionContextExecutor ): PlayEnumerator[R] = { - val eventualEnum = query.future() map { - resultSet => Enumerator.enumerator(resultSet) through Enumeratee.map(query.fromRow) + PlayEnumerator.flatten { + query.future() map { res => + Enumerator.enumerator(res) through Enumeratee.map(query.fromRow) + } + } + } + + /** + * Produces an Enumerator for [R]ows + * This enumerator can be consumed afterwards with an Iteratee + * @param mod A modifier to apply to a statement. + * @param session The Cassandra session in use. + * @param keySpace The keyspace object in use. + * @param ctx The Execution Context. + * @return A play enumerator containing the results of the query. + */ + def fetchEnumerator(mod: Statement => Statement)( + implicit session: Session, + keySpace: KeySpace, + ctx: ExecutionContextExecutor + ): PlayEnumerator[R] = { + PlayEnumerator.flatten { + query.future(mod) map { res => + Enumerator.enumerator(res) through Enumeratee.map(query.fromRow) + } } - PlayEnumerator.flatten(eventualEnum) } } diff --git a/phantom-streams/src/test/logback-test.xml b/phantom-streams/src/test/logback-test.xml new file mode 100644 index 000000000..2e7418b67 --- /dev/null +++ b/phantom-streams/src/test/logback-test.xml @@ -0,0 +1,19 @@ + + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + + + \ No newline at end of file diff --git a/phantom-streams/src/test/scala/com/outworkers/phantom/reactivestreams/suites/BatchSubscriberIntegrationTest.scala b/phantom-streams/src/test/scala/com/outworkers/phantom/reactivestreams/suites/BatchSubscriberIntegrationTest.scala new file mode 100644 index 000000000..27cf341f7 --- /dev/null +++ b/phantom-streams/src/test/scala/com/outworkers/phantom/reactivestreams/suites/BatchSubscriberIntegrationTest.scala @@ -0,0 +1,66 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.reactivestreams.suites + +import java.util.concurrent.{CountDownLatch, TimeUnit} + +import com.outworkers.phantom.batch.BatchType +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.reactivestreams._ +import com.outworkers.phantom.reactivestreams.suites.iteratee.OperaPublisher +import org.scalatest.concurrent.ScalaFutures +import org.scalatest.tagobjects.Retryable +import org.scalatest.{FlatSpec, Retries} + +import scala.concurrent.Await +import scala.concurrent.duration._ + +class BatchSubscriberIntegrationTest extends FlatSpec with StreamTest with ScalaFutures with Retries { + + implicit val defaultPatience = PatienceConfig(timeout = 10.seconds, interval = 50.millis) + + override def beforeAll(): Unit = { + super.beforeAll() + Await.result(StreamDatabase.autotruncate().future(), 5.seconds) + } + + it should "persist all data" taggedAs Retryable in { + val completionLatch = new CountDownLatch(1) + + val subscriber = StreamDatabase.operaTable.subscriber( + batchSize = 2, + concurrentRequests = 2, + batchType = BatchType.Unlogged, + flushInterval = None, + completionFn = () => completionLatch.countDown() + ) + + OperaPublisher.subscribe(subscriber) + + completionLatch.await(5, TimeUnit.SECONDS) + + val chain = for { + count <- StreamDatabase.operaTable.select.count().one() + } yield count + + whenReady(chain) { + res => res.value shouldEqual OperaData.operas.length + } + + } + +} + diff --git a/phantom-streams/src/test/scala/com/outworkers/phantom/reactivestreams/suites/BatchSubscriberWhiteboxTest.scala b/phantom-streams/src/test/scala/com/outworkers/phantom/reactivestreams/suites/BatchSubscriberWhiteboxTest.scala new file mode 100644 index 000000000..906f450a0 --- /dev/null +++ b/phantom-streams/src/test/scala/com/outworkers/phantom/reactivestreams/suites/BatchSubscriberWhiteboxTest.scala @@ -0,0 +1,73 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.reactivestreams.suites + +import com.outworkers.phantom.batch.BatchType +import com.outworkers.phantom.reactivestreams.BatchSubscriber +import com.outworkers.util.testing._ +import org.reactivestreams.tck.SubscriberWhiteboxVerification.{SubscriberPuppet, WhiteboxSubscriberProbe} +import org.reactivestreams.tck.{SubscriberWhiteboxVerification, TestEnvironment} +import org.reactivestreams.{Subscriber, Subscription} + +class BatchSubscriberWhiteboxTest extends SubscriberWhiteboxVerification[Opera](new TestEnvironment()) + with StreamDatabase.connector.Connector with TestImplicits { + + override def createSubscriber(probe: WhiteboxSubscriberProbe[Opera]): Subscriber[Opera] = { + new BatchSubscriber[ConcreteOperaTable, Opera]( + StreamDatabase.operaTable, + builder = OperaRequestBuilder, + batchSize = 5, + concurrentRequests = 2, + batchType = BatchType.Unlogged, + flushInterval = None, + completionFn = () => (), + errorFn = _ => () + ) { + + override def onSubscribe(s: Subscription): Unit = { + super.onSubscribe(s) + + probe.registerOnSubscribe(new SubscriberPuppet { + + override def triggerRequest(elements: Long): Unit = { + s.request(elements) + } + + override def signalCancel(): Unit = { + s.cancel() + } + }) + } + + override def onComplete(): Unit = { + super.onComplete() + probe.registerOnComplete() + } + + override def onError(t: Throwable): Unit = { + probe.registerOnError(t) + } + + override def onNext(t: Opera): Unit = { + super.onNext(t) + probe.registerOnNext(t) + } + + } + } + + override def createElement(element: Int): Opera = Opera(gen[String]) +} \ No newline at end of file diff --git a/phantom-streams/src/test/scala/com/outworkers/phantom/reactivestreams/suites/CassandraTest.scala b/phantom-streams/src/test/scala/com/outworkers/phantom/reactivestreams/suites/CassandraTest.scala new file mode 100644 index 000000000..556b21cdc --- /dev/null +++ b/phantom-streams/src/test/scala/com/outworkers/phantom/reactivestreams/suites/CassandraTest.scala @@ -0,0 +1,98 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.reactivestreams.suites + +import akka.actor.ActorSystem +import com.outworkers.phantom.builder.query.{Batchable, ExecutableStatement, InsertQuery} +import com.outworkers.phantom.connectors.RootConnector +import com.outworkers.phantom.database.Database +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.reactivestreams.RequestBuilder +import com.outworkers.util.testing._ +import org.scalatest._ + +import scala.concurrent.Await +import scala.concurrent.duration._ + +trait TestImplicits { + implicit val system = ActorSystem() + + implicit object OperaRequestBuilder extends RequestBuilder[ConcreteOperaTable, Opera] { + + override def request(ct: ConcreteOperaTable, t: Opera)( + implicit session: Session, + keySpace: KeySpace + ): ExecutableStatement with Batchable = { + ct.insert.value(_.name, t.name) + } + } + +} + +trait StreamTest extends FlatSpec with BeforeAndAfterAll + with OptionValues + with Matchers + with TestImplicits + with Retries + with StreamDatabase.connector.Connector { + self: Suite => + + override def withFixture(test: NoArgTest): Outcome = { + if (isRetryable(test)) { + withRetry(super.withFixture(test)) + } else { + super.withFixture(test) + } + } + + override def beforeAll(): Unit = { + super.beforeAll() + Await.result(StreamDatabase.autocreate().future(), 5.seconds) + } + + override def afterAll(): Unit = { + super.afterAll() + system.shutdown() + } + +} + +case class Opera(name: String) + +class OperaTable extends CassandraTable[ConcreteOperaTable, Opera] { + object name extends StringColumn(this) with PartitionKey +} + +abstract class ConcreteOperaTable extends OperaTable with RootConnector { + def store(item: Opera): InsertQuery.Default[ConcreteOperaTable, Opera] = { + insert.value(_.name, item.name) + } +} + + +object StreamConnector { + val connector = ContactPoint.local.keySpace("phantom") +} + +class StreamDatabase extends Database[StreamDatabase](StreamConnector.connector) { + object operaTable extends ConcreteOperaTable with connector.Connector +} + +object StreamDatabase extends StreamDatabase + +object OperaData { + val operas = genList[String]().map(Opera) +} \ No newline at end of file diff --git a/phantom-reactivestreams/src/test/scala/com/websudos/phantom/reactivestreams/suites/PublisherIntegrationTest.scala b/phantom-streams/src/test/scala/com/outworkers/phantom/reactivestreams/suites/PublisherIntegrationTest.scala similarity index 51% rename from phantom-reactivestreams/src/test/scala/com/websudos/phantom/reactivestreams/suites/PublisherIntegrationTest.scala rename to phantom-streams/src/test/scala/com/outworkers/phantom/reactivestreams/suites/PublisherIntegrationTest.scala index d94dbab91..b5e0eed23 100644 --- a/phantom-reactivestreams/src/test/scala/com/websudos/phantom/reactivestreams/suites/PublisherIntegrationTest.scala +++ b/phantom-streams/src/test/scala/com/outworkers/phantom/reactivestreams/suites/PublisherIntegrationTest.scala @@ -1,38 +1,24 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.reactivestreams.suites +package com.outworkers.phantom.reactivestreams.suites import java.util.concurrent.atomic.AtomicInteger -import com.websudos.phantom.dsl._ -import com.websudos.phantom.reactivestreams._ +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.reactivestreams._ import com.outworkers.util.testing._ import org.reactivestreams.{Subscriber, Subscription} import org.scalatest.FlatSpec diff --git a/phantom-streams/src/test/scala/com/outworkers/phantom/reactivestreams/suites/iteratee/BigTest.scala b/phantom-streams/src/test/scala/com/outworkers/phantom/reactivestreams/suites/iteratee/BigTest.scala new file mode 100644 index 000000000..41e115d17 --- /dev/null +++ b/phantom-streams/src/test/scala/com/outworkers/phantom/reactivestreams/suites/iteratee/BigTest.scala @@ -0,0 +1,34 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.reactivestreams.suites.iteratee + +import com.datastax.driver.core.{Session, SocketOptions} +import com.outworkers.phantom.PhantomSuite +import com.outworkers.phantom.connectors.ContactPoint + +trait BigTest extends PhantomSuite { + + val connectionTimeoutMillis = 1000 + + override implicit lazy val session: Session = { + ContactPoint.local.withClusterBuilder( + _.withSocketOptions(new SocketOptions() + .setReadTimeoutMillis(connectionTimeoutMillis) + .setConnectTimeoutMillis(connectionTimeoutMillis) + ) + ).noHeartbeat().keySpace(keySpace).session + } +} diff --git a/phantom-streams/src/test/scala/com/outworkers/phantom/reactivestreams/suites/iteratee/IterateeBenchmarkPerformanceTest.scala b/phantom-streams/src/test/scala/com/outworkers/phantom/reactivestreams/suites/iteratee/IterateeBenchmarkPerformanceTest.scala new file mode 100644 index 000000000..7ebed75f0 --- /dev/null +++ b/phantom-streams/src/test/scala/com/outworkers/phantom/reactivestreams/suites/iteratee/IterateeBenchmarkPerformanceTest.scala @@ -0,0 +1,61 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.reactivestreams.suites.iteratee + +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.reactivestreams._ +import com.outworkers.phantom.tables.{JodaRow, TestDatabase} +import com.outworkers.util.testing._ +import org.scalameter.api.{Gen => MeterGen, gen => _, _} +import org.scalatest.time.SpanSugar._ + +import scala.concurrent.{Await, Future} + +class IterateeBenchmarkPerformanceTest extends Bench.LocalTime with TestDatabase.connector.Connector { + + TestDatabase.primitivesJoda.insertSchema() + + val limit = 10000 + val sampleGenLimit = 30000 + + val fs = for { + step <- 1 to 3 + rows = Iterator.fill(limit)(gen[JodaRow]) + + batch = rows.foldLeft(Batch.unlogged)((b, row) => { + val statement = TestDatabase.primitivesJoda.insert + .value(_.pkey, row.pkey) + .value(_.intColumn, row.intColumn) + .value(_.timestamp, row.timestamp) + b.add(statement) + }) + w = batch.future() + f = w map (_ => println(s"step $step was completed successfully")) + r = Await.result(f, 200 seconds) + } yield f map (_ => r) + + Await.ready(Future.sequence(fs), 20 seconds) + + val sizes: MeterGen[Int] = MeterGen.range("size")(limit, sampleGenLimit, limit) + + performance of "Enumerator" in { + measure method "enumerator" in { + using(sizes) in { + size => Await.ready(TestDatabase.primitivesJoda.select.limit(size).fetchEnumerator run Iteratee.forEach { r => }, 10 seconds) + } + } + } +} diff --git a/phantom-streams/src/test/scala/com/outworkers/phantom/reactivestreams/suites/iteratee/IterateeBigReadPerformanceTest.scala b/phantom-streams/src/test/scala/com/outworkers/phantom/reactivestreams/suites/iteratee/IterateeBigReadPerformanceTest.scala new file mode 100644 index 000000000..af39cf966 --- /dev/null +++ b/phantom-streams/src/test/scala/com/outworkers/phantom/reactivestreams/suites/iteratee/IterateeBigReadPerformanceTest.scala @@ -0,0 +1,42 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.reactivestreams.suites.iteratee + +import java.util.concurrent.atomic.AtomicLong + +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.reactivestreams._ +import com.outworkers.util.testing._ +import org.scalatest.concurrent.ScalaFutures + +class IterateeBigReadPerformanceTest extends BigTest with ScalaFutures { + + it should "read the correct number of records found in the table" in { + val counter = new AtomicLong(0) + + val result = database.primitivesJoda.select.fetchEnumerator run Iteratee.forEach { + r => counter.incrementAndGet() + } + + result.successful { + query => { + val count = counter.getAndIncrement() + info(s"Done, reading: $count elements from the table.") + count shouldEqual 2000000 + } + } + } +} diff --git a/phantom-streams/src/test/scala/com/outworkers/phantom/reactivestreams/suites/iteratee/IterateeInsertPerformanceTest.scala b/phantom-streams/src/test/scala/com/outworkers/phantom/reactivestreams/suites/iteratee/IterateeInsertPerformanceTest.scala new file mode 100644 index 000000000..b094a9983 --- /dev/null +++ b/phantom-streams/src/test/scala/com/outworkers/phantom/reactivestreams/suites/iteratee/IterateeInsertPerformanceTest.scala @@ -0,0 +1,73 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.reactivestreams.suites.iteratee + +import java.util.concurrent.atomic.AtomicLong + +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.reactivestreams._ +import com.outworkers.phantom.tables.{JodaRow, TestDatabase} +import com.outworkers.util.testing._ +import org.scalatest.Matchers +import org.scalatest.concurrent.PatienceConfiguration +import org.scalatest.time.SpanSugar._ + +import scala.concurrent.{Await, Future} + +class IterateeInsertPerformanceTest extends BigTest with Matchers { + + implicit val s: PatienceConfiguration.Timeout = timeout(12 minutes) + private[this] final val iteratorLimit = 10000 + + it should "retrieve the right amount of results" in { + TestDatabase.primitivesJoda.insertSchema() + val fs = for { + step <- 1 to 100 + rows = Iterator.fill(iteratorLimit)(gen[JodaRow]) + + batch = rows.foldLeft(Batch.unlogged)((b, row) => { + val statement = TestDatabase.primitivesJoda.insert + .value(_.pkey, row.pkey) + .value(_.intColumn, row.intColumn) + .value(_.timestamp, row.timestamp) + b.add(statement) + }) + w = batch.future() + f = w map (_ => info(s"step $step has succeed")) + r = Await.result(f, 200 seconds) + } yield f map (_ => r) + + + val combinedFuture = Future.sequence(fs) map { + r => TestDatabase.primitivesJoda.select.count.one() + } + + val counter: AtomicLong = new AtomicLong(0) + val result = combinedFuture flatMap { + rs => { + info(s"done, inserted: $rs rows - start parsing") + TestDatabase.primitivesJoda.select.fetchEnumerator run Iteratee.forEach { r => counter.incrementAndGet() } + } + } + + (result flatMap (_ => combinedFuture)) successful { + r => { + info(s"done, reading: ${counter.addAndGet(0)}") + counter.get() shouldEqual r + } + } + } +} diff --git a/phantom-reactivestreams/src/test/scala/com/websudos/phantom/reactivestreams/suites/iteratee/IterateePerformanceTest.scala b/phantom-streams/src/test/scala/com/outworkers/phantom/reactivestreams/suites/iteratee/IterateePerformanceTest.scala similarity index 53% rename from phantom-reactivestreams/src/test/scala/com/websudos/phantom/reactivestreams/suites/iteratee/IterateePerformanceTest.scala rename to phantom-streams/src/test/scala/com/outworkers/phantom/reactivestreams/suites/iteratee/IterateePerformanceTest.scala index 72b0feaa2..32a794989 100644 --- a/phantom-reactivestreams/src/test/scala/com/websudos/phantom/reactivestreams/suites/iteratee/IterateePerformanceTest.scala +++ b/phantom-streams/src/test/scala/com/outworkers/phantom/reactivestreams/suites/iteratee/IterateePerformanceTest.scala @@ -1,42 +1,29 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.reactivestreams.suites.iteratee +package com.outworkers.phantom.reactivestreams.suites.iteratee import java.util.concurrent.atomic.AtomicInteger -import com.websudos.phantom.PhantomSuite -import com.websudos.phantom.reactivestreams._ + +import com.outworkers.phantom.PhantomSuite +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.reactivestreams._ +import com.outworkers.phantom.tables._ +import com.outworkers.util.testing._ import org.scalatest.concurrent.PatienceConfiguration import org.scalatest.time.SpanSugar._ -import com.websudos.phantom.dsl._ -import com.websudos.phantom.tables._ -import com.outworkers.util.testing._ class IterateePerformanceTest extends PhantomSuite { diff --git a/phantom-streams/src/test/scala/com/outworkers/phantom/reactivestreams/suites/iteratee/IteratorTest.scala b/phantom-streams/src/test/scala/com/outworkers/phantom/reactivestreams/suites/iteratee/IteratorTest.scala new file mode 100644 index 000000000..3b1b633b9 --- /dev/null +++ b/phantom-streams/src/test/scala/com/outworkers/phantom/reactivestreams/suites/iteratee/IteratorTest.scala @@ -0,0 +1,72 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.reactivestreams.suites.iteratee + +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.tables.{TestDatabase, TimeUUIDRecord} +import com.outworkers.util.testing._ +import org.scalatest.concurrent.ScalaFutures + +import scala.concurrent.Future + +class IteratorTest extends BigTest with ScalaFutures { + + override def beforeAll(): Unit = { + super.beforeAll() + database.timeuuidTable.insertSchema() + } + + it should "correctly retrieve the right number of records using scala iterator" in { + val generationSize = 100 + val user = gen[UUID] + val rows = genList[TimeUUIDRecord](generationSize).map(_.copy(user = user)) + + val chain = for { + store <- Future.sequence(rows.map(row => database.timeuuidTable.store(row).future())) + iterator <- database.timeuuidTable.select.where(_.user eqs user).iterator() + } yield iterator + + whenReady(chain) { + res => { + res.records.size shouldEqual generationSize + res.records.forall(rows contains _) + } + } + } + + ignore should "correctly paginate a query using an iterator" in { + val generationSize = 100 + val fetchSize = generationSize / 2 + val user = gen[UUID] + val rows = genList[TimeUUIDRecord](generationSize).map(_.copy(user = user)) + + val chain = for { + store <- Future.sequence(rows.map(row => database.timeuuidTable.store(row).future())) + firstHalf <- database.timeuuidTable.select.where(_.user eqs user).iterator(_.setFetchSize(fetchSize)) + secondHalf <- database.timeuuidTable.select.where(_.user eqs user).iterator(firstHalf.pagingState) + } yield (firstHalf, secondHalf) + + whenReady(chain) { + case (firstBatch, secondBatch) => { + firstBatch.records.size shouldEqual fetchSize + firstBatch.records.forall(rows contains _) + + secondBatch.records.size shouldEqual fetchSize + secondBatch.records.forall(rows contains _) + } + } + } +} diff --git a/phantom-streams/src/test/scala/com/outworkers/phantom/reactivestreams/suites/iteratee/OperaPublisher.scala b/phantom-streams/src/test/scala/com/outworkers/phantom/reactivestreams/suites/iteratee/OperaPublisher.scala new file mode 100644 index 000000000..e14760be9 --- /dev/null +++ b/phantom-streams/src/test/scala/com/outworkers/phantom/reactivestreams/suites/iteratee/OperaPublisher.scala @@ -0,0 +1,44 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.reactivestreams.suites.iteratee + +import java.util.concurrent.atomic.AtomicInteger + +import com.outworkers.phantom.reactivestreams.suites.{Opera, OperaData} +import org.reactivestreams.{Publisher, Subscriber, Subscription} + +object OperaPublisher extends Publisher[Opera] { + + val counter = new AtomicInteger(0) + + override def subscribe(s: Subscriber[_ >: Opera]): Unit = { + s.onSubscribe(new Subscription { + override def cancel(): Unit = () + + override def request(l: Long): Unit = { + val start = counter.getAndIncrement() * l.toInt + val end = start + l.toInt + + if (start < OperaData.operas.size) { + OperaData.operas.slice(start, end).foreach(s.onNext) + } else { + s.onComplete() + } + } + }) + } + +} diff --git a/phantom-thrift/src/main/scala/com/websudos/phantom/thrift/columns/ThriftColumn.scala b/phantom-thrift/src/main/scala/com/outworkers/phantom/thrift/columns/ThriftColumn.scala similarity index 68% rename from phantom-thrift/src/main/scala/com/websudos/phantom/thrift/columns/ThriftColumn.scala rename to phantom-thrift/src/main/scala/com/outworkers/phantom/thrift/columns/ThriftColumn.scala index ac87aab2f..90a4a49c6 100644 --- a/phantom-thrift/src/main/scala/com/websudos/phantom/thrift/columns/ThriftColumn.scala +++ b/phantom-thrift/src/main/scala/com/outworkers/phantom/thrift/columns/ThriftColumn.scala @@ -1,46 +1,32 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.thrift.columns +package com.outworkers.phantom.thrift.columns import scala.annotation.implicitNotFound import scala.collection.JavaConverters._ import scala.util.{Success, Try} -import com.websudos.phantom.builder.QueryBuilder -import com.websudos.phantom.builder.QueryBuilder.Utils -import com.websudos.phantom.builder.query.CQLQuery -import com.websudos.phantom.builder.syntax.CQLSyntax -import com.datastax.driver.core.{GettableData, Row} +import com.outworkers.phantom.builder.QueryBuilder +import com.outworkers.phantom.builder.QueryBuilder.Utils +import com.outworkers.phantom.builder.query.CQLQuery +import com.outworkers.phantom.builder.syntax.CQLSyntax +import com.datastax.driver.core.{GettableByIndexData, GettableByNameData, GettableData, Row} +import com.outworkers.phantom.CassandraTable import com.twitter.scrooge.{CompactThriftSerializer, ThriftStruct, ThriftStructSerializer} -import com.websudos.phantom.builder.primitives.Primitive -import com.websudos.phantom.column.{AbstractListColumn, AbstractMapColumn, AbstractSetColumn, CollectionValueDefinition, Column, OptionalColumn} -import com.websudos.phantom.CassandraTable +import com.outworkers.phantom.builder.primitives.Primitive +import com.outworkers.phantom.column.{AbstractListColumn, AbstractMapColumn, AbstractSetColumn, CollectionValueDefinition, Column, OptionalColumn} trait ThriftColumnDefinition[ValueType <: ThriftStruct] { @@ -121,9 +107,6 @@ abstract class ThriftListColumn[T <: CassandraTable[T, R], R, ValueType <: Thrif override val cassandraType = QueryBuilder.Collections.listType(CQLSyntax.Types.Text).queryString - override def asCql(v: List[ValueType]): String = Utils.collection(v.map(valueAsCql)).queryString - - override def parse(r: Row): Try[List[ValueType]] = { if (r.isNull(name)) { Success(Nil) @@ -166,10 +149,14 @@ abstract class RootThriftPrimitive[T <: ThriftStruct] extends Primitive[T] { override type PrimitiveType = java.lang.String - override def fromRow(column: String, row: GettableData): Try[T] = nullCheck(column, row) { + override def fromRow(column: String, row: GettableByNameData): Try[T] = nullCheck(column, row) { existing => serializer.fromString(row.getString(column)) } + override def fromRow(index: Int, row: GettableByIndexData): Try[T] = nullCheck(index, row) { + existing => serializer.fromString(row.getString(index)) + } + override def cassandraType: String = CQLSyntax.Types.Text override def fromString(value: String): T = serializer.fromString(value) diff --git a/phantom-thrift/src/main/scala/com/outworkers/phantom/thrift/package.scala b/phantom-thrift/src/main/scala/com/outworkers/phantom/thrift/package.scala new file mode 100644 index 000000000..2c054102d --- /dev/null +++ b/phantom-thrift/src/main/scala/com/outworkers/phantom/thrift/package.scala @@ -0,0 +1,57 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom + +import com.outworkers.phantom.thrift.columns.RootThriftPrimitive + +package object thrift { + type ThriftStruct = com.twitter.scrooge.ThriftStruct + + type ThriftColumn[ + T <: CassandraTable[T, R], + R, Model <: ThriftStruct + ] = com.outworkers.phantom.thrift.columns.ThriftColumn[T, R, Model] + + type ThriftSetColumn[ + T <: CassandraTable[T, R], + R, + Model <: ThriftStruct + ] = com.outworkers.phantom.thrift.columns.ThriftSetColumn[T, R, Model] + + type ThriftListColumn[ + T <: CassandraTable[T, R], + R, + Model <: ThriftStruct + ] = com.outworkers.phantom.thrift.columns.ThriftListColumn[T, R, Model] + + type ThriftMapColumn[ + T <: CassandraTable[T, R], + R, + KeyType, + Model <: ThriftStruct + ] = com.outworkers.phantom.thrift.columns.ThriftMapColumn[T, R, KeyType, Model] + + type OptionalThriftColumn[ + T <: CassandraTable[T, R], + R, + Model <: ThriftStruct + ] = com.outworkers.phantom.thrift.columns.OptionalThriftColumn[T, R, Model] + + type ThriftPrimitive[T <: ThriftStruct] = RootThriftPrimitive[T] +} + + + diff --git a/phantom-thrift/src/main/scala/com/websudos/phantom/thrift/package.scala b/phantom-thrift/src/main/scala/com/websudos/phantom/thrift/package.scala deleted file mode 100644 index 73086bddc..000000000 --- a/phantom-thrift/src/main/scala/com/websudos/phantom/thrift/package.scala +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -package com.websudos.phantom - -import com.websudos.phantom.thrift.columns.RootThriftPrimitive - -package object thrift { - type ThriftStruct = com.twitter.scrooge.ThriftStruct - type ThriftColumn[T <: CassandraTable[T, R], R, Model <: ThriftStruct] = com.websudos.phantom.thrift.columns.ThriftColumn[T, R, Model] - type ThriftSetColumn[T <: CassandraTable[T, R], R, Model <: ThriftStruct] = com.websudos.phantom.thrift.columns.ThriftSetColumn[T, R, Model] - type ThriftListColumn[T <: CassandraTable[T, R], R, Model <: ThriftStruct] = com.websudos.phantom.thrift.columns.ThriftListColumn[T, R, Model] - type ThriftMapColumn[T <: CassandraTable[T, R], R, KeyType, Model <: ThriftStruct] = com.websudos.phantom.thrift.columns.ThriftMapColumn[T, R, KeyType, Model] - - type OptionalThriftColumn[T <: CassandraTable[T, R], R, Model <: ThriftStruct] = com.websudos.phantom.thrift.columns.OptionalThriftColumn[T, R, Model] - - type ThriftPrimitive[T <: ThriftStruct] = RootThriftPrimitive[T] -} - - - diff --git a/phantom-thrift/src/main/thrift/test.thrift b/phantom-thrift/src/main/thrift/test.thrift index 7c7ac66c4..7e2e0c3a8 100644 --- a/phantom-thrift/src/main/thrift/test.thrift +++ b/phantom-thrift/src/main/thrift/test.thrift @@ -1,4 +1,4 @@ -namespace java com.websudos.phantom.thrift +namespace java com.outworkers.phantom.thrift struct ThriftTest { 1: required i32 id, diff --git a/phantom-thrift/src/test/resources/log4j.xml b/phantom-thrift/src/test/resources/log4j.xml index 6455241f0..0beee5bf3 100644 --- a/phantom-thrift/src/test/resources/log4j.xml +++ b/phantom-thrift/src/test/resources/log4j.xml @@ -15,7 +15,7 @@ - + @@ -27,7 +27,7 @@ - + diff --git a/phantom-thrift/src/test/scala/com/outworkers/phantom/suites/OptionalThriftColumnTest.scala b/phantom-thrift/src/test/scala/com/outworkers/phantom/suites/OptionalThriftColumnTest.scala new file mode 100644 index 000000000..bdd09b84b --- /dev/null +++ b/phantom-thrift/src/test/scala/com/outworkers/phantom/suites/OptionalThriftColumnTest.scala @@ -0,0 +1,83 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.suites + +import com.datastax.driver.core.utils.UUIDs +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.tables.ThriftDatabase +import com.outworkers.util.testing._ +import org.scalatest.FlatSpec +import org.scalatest.time.SpanSugar._ + +class OptionalThriftColumnTest extends FlatSpec with ThriftTestSuite { + + override def beforeAll(): Unit = { + ThriftDatabase.thriftColumnTable.create.ifNotExists().future().block(5.seconds) + } + + it should "find an item if it was defined" in { + + val id = UUIDs.timeBased() + + val sample = gen[ThriftTest] + + val insert = ThriftDatabase.thriftColumnTable.insert + .value(_.id, id) + .value(_.name, sample.name) + .value(_.ref, sample) + .value(_.thriftSet, Set(sample)) + .value(_.thriftList, List(sample)) + .value(_.optionalThrift, Some(sample)) + .future() + + val operation = for { + insertDone <- insert + select <- ThriftDatabase.thriftColumnTable.select(_.optionalThrift).where(_.id eqs id).one + } yield select + + operation.successful { + res => { + res.value shouldBe Some(sample) + } + } + } + + it should "not find an item if was not defined" in { + val id = UUIDs.timeBased() + + val sample = gen[ThriftTest] + + val insert = ThriftDatabase.thriftColumnTable.insert + .value(_.id, id) + .value(_.name, sample.name) + .value(_.ref, sample) + .value(_.thriftSet, Set(sample)) + .value(_.thriftList, List(sample)) + .value(_.optionalThrift, None) + .future() + + val operation = for { + insertDone <- insert + select <- ThriftDatabase.thriftColumnTable.select(_.optionalThrift).where(_.id eqs id).one + } yield select + + operation.successful { + res => { + res.value.isDefined shouldBe false + } + } + } +} diff --git a/phantom-thrift/src/test/scala/com/outworkers/phantom/suites/ThriftColumnTest.scala b/phantom-thrift/src/test/scala/com/outworkers/phantom/suites/ThriftColumnTest.scala new file mode 100644 index 000000000..d3c03f4f7 --- /dev/null +++ b/phantom-thrift/src/test/scala/com/outworkers/phantom/suites/ThriftColumnTest.scala @@ -0,0 +1,72 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.suites + +import com.datastax.driver.core.utils.UUIDs +import com.outworkers.phantom.tables.ThriftDatabase +import com.outworkers.phantom.dsl._ +import com.outworkers.util.testing._ +import org.scalatest.FlatSpec +import org.scalatest.time.SpanSugar._ + +class ThriftColumnTest extends FlatSpec with ThriftTestSuite { + + override def beforeAll(): Unit = { + ThriftDatabase.thriftColumnTable.create.ifNotExists().future().block(5.seconds) + } + + it should "allow storing thrift columns" in { + val id = UUIDs.timeBased() + val sample = gen[ThriftTest] + + val insert = ThriftDatabase.thriftColumnTable.insert + .value(_.id, id) + .value(_.name, sample.name) + .value(_.ref, sample) + .future() flatMap { + _ => ThriftDatabase.thriftColumnTable.select.where(_.id eqs id).one() + } + + insert.successful { + result => { + result.value.struct shouldEqual sample + } + } + } + + it should "allow storing lists of thrift objects" in { + val id = UUIDs.timeBased() + val sample = gen[ThriftTest] + val sample2 = gen[ThriftTest] + val sampleList = Set(sample, sample2) + + val insert = ThriftDatabase.thriftColumnTable.insert + .value(_.id, id) + .value(_.name, sample.name) + .value(_.ref, sample) + .value(_.thriftSet, sampleList) + .future() flatMap { + _ => ThriftDatabase.thriftColumnTable.select.where(_.id eqs id).one() + } + + insert.successful { + result => { + result.value.struct shouldEqual sample + result.value.thriftSet shouldEqual sampleList + } + } + } +} diff --git a/phantom-thrift/src/test/scala/com/websudos/phantom/thrift/suites/ThriftIndexTableTest.scala b/phantom-thrift/src/test/scala/com/outworkers/phantom/suites/ThriftIndexTableTest.scala similarity index 54% rename from phantom-thrift/src/test/scala/com/websudos/phantom/thrift/suites/ThriftIndexTableTest.scala rename to phantom-thrift/src/test/scala/com/outworkers/phantom/suites/ThriftIndexTableTest.scala index 94e53f635..bb7edccb7 100644 --- a/phantom-thrift/src/test/scala/com/websudos/phantom/thrift/suites/ThriftIndexTableTest.scala +++ b/phantom-thrift/src/test/scala/com/outworkers/phantom/suites/ThriftIndexTableTest.scala @@ -1,40 +1,26 @@ /* - * Copyright 2013-2016 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.thrift.suites +package com.outworkers.phantom.suites -import com.twitter.scrooge.CompactThriftSerializer -import com.websudos.phantom.dsl._ -import com.websudos.phantom.finagle._ -import com.websudos.phantom.tables.{Output, ThriftDatabase} -import com.websudos.phantom.thrift._ +import com.outworkers.phantom.tables.{Output, ThriftDatabase} import com.outworkers.util.testing._ +import com.twitter.scrooge.CompactThriftSerializer +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.finagle._ +import com.outworkers.phantom.thrift.ThriftPrimitive import org.scalatest.FlatSpec class ThriftIndexTableTest extends FlatSpec with ThriftTestSuite { diff --git a/phantom-thrift/src/test/scala/com/websudos/phantom/thrift/suites/ThriftListOperations.scala b/phantom-thrift/src/test/scala/com/outworkers/phantom/suites/ThriftListOperations.scala similarity index 88% rename from phantom-thrift/src/test/scala/com/websudos/phantom/thrift/suites/ThriftListOperations.scala rename to phantom-thrift/src/test/scala/com/outworkers/phantom/suites/ThriftListOperations.scala index d06a90442..9efc9d9ae 100644 --- a/phantom-thrift/src/test/scala/com/websudos/phantom/thrift/suites/ThriftListOperations.scala +++ b/phantom-thrift/src/test/scala/com/outworkers/phantom/suites/ThriftListOperations.scala @@ -1,37 +1,24 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.thrift.suites +package com.outworkers.phantom.suites -import com.websudos.phantom.dsl._ -import com.websudos.phantom.finagle._ -import com.websudos.phantom.tables.{Output, ThriftDatabase} +import com.outworkers.phantom.tables.{Output, ThriftDatabase} +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.finagle._ +import com.outworkers.phantom.tables.ThriftDatabase import com.outworkers.util.testing._ import org.scalatest.FlatSpec import org.scalatest.concurrent.PatienceConfiguration @@ -59,8 +46,12 @@ class ThriftListOperations extends FlatSpec with ThriftTestSuite { val operation = for { insertDone <- insert - update <- ThriftDatabase.thriftColumnTable.update.where(_.id eqs id).modify(_.thriftList prepend sample2).future() - select <- ThriftDatabase.thriftColumnTable.select(_.thriftList).where(_.id eqs id).one + update <- ThriftDatabase.thriftColumnTable + .update.where(_.id eqs id) + .modify(_.thriftList prepend sample2) + .future() + select <- ThriftDatabase.thriftColumnTable + .select(_.thriftList).where(_.id eqs id).one } yield { select } diff --git a/phantom-thrift/src/test/scala/com/websudos/phantom/thrift/suites/ThriftMapColumnTest.scala b/phantom-thrift/src/test/scala/com/outworkers/phantom/suites/ThriftMapColumnTest.scala similarity index 70% rename from phantom-thrift/src/test/scala/com/websudos/phantom/thrift/suites/ThriftMapColumnTest.scala rename to phantom-thrift/src/test/scala/com/outworkers/phantom/suites/ThriftMapColumnTest.scala index 3d29245eb..cda829a76 100644 --- a/phantom-thrift/src/test/scala/com/websudos/phantom/thrift/suites/ThriftMapColumnTest.scala +++ b/phantom-thrift/src/test/scala/com/outworkers/phantom/suites/ThriftMapColumnTest.scala @@ -1,37 +1,23 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.thrift.suites +package com.outworkers.phantom.suites -import com.websudos.phantom.dsl._ -import com.websudos.phantom.finagle._ -import com.websudos.phantom.tables.ThriftDatabase +import com.outworkers.phantom.tables.ThriftDatabase +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.finagle._ import com.outworkers.util.testing._ import org.scalatest.FlatSpec import org.scalatest.time.SpanSugar._ @@ -68,7 +54,8 @@ class ThriftMapColumnTest extends FlatSpec with ThriftTestSuite { val operation = for { insertDone <- insert - update <- ThriftDatabase.thriftColumnTable.update.where(_.id eqs id).modify(_.thriftMap put toAdd).future() + update <- ThriftDatabase.thriftColumnTable.update + .where(_.id eqs id).modify(_.thriftMap put toAdd).future() select <- ThriftDatabase.thriftColumnTable.select(_.thriftMap).where(_.id eqs id).one } yield { select diff --git a/phantom-thrift/src/test/scala/com/websudos/phantom/thrift/suites/ThriftSetOperationsTest.scala b/phantom-thrift/src/test/scala/com/outworkers/phantom/suites/ThriftSetOperationsTest.scala similarity index 67% rename from phantom-thrift/src/test/scala/com/websudos/phantom/thrift/suites/ThriftSetOperationsTest.scala rename to phantom-thrift/src/test/scala/com/outworkers/phantom/suites/ThriftSetOperationsTest.scala index 406e63715..26c5bdfef 100644 --- a/phantom-thrift/src/test/scala/com/websudos/phantom/thrift/suites/ThriftSetOperationsTest.scala +++ b/phantom-thrift/src/test/scala/com/outworkers/phantom/suites/ThriftSetOperationsTest.scala @@ -1,36 +1,22 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.thrift.suites +package com.outworkers.phantom.suites -import com.websudos.phantom.dsl._ -import com.websudos.phantom.tables.{ThriftDatabase} +import com.outworkers.phantom.tables.ThriftDatabase +import com.outworkers.phantom.dsl._ import com.outworkers.util.testing._ import org.scalatest.FlatSpec import org.scalatest.concurrent.PatienceConfiguration @@ -147,7 +133,10 @@ class ThriftSetOperationsTest extends FlatSpec with ThriftTestSuite { val operation = for { insertDone <- insert - update <- ThriftDatabase.thriftColumnTable.update.where(_.id eqs id).modify(_.thriftSet removeAll Set(sample2, sample3)).future() + update <- ThriftDatabase + .thriftColumnTable.update.where(_.id eqs id) + .modify(_.thriftSet removeAll Set(sample2, sample3)) + .future() select <- ThriftDatabase.thriftColumnTable.select(_.thriftSet).where(_.id eqs id).one } yield { select diff --git a/phantom-thrift/src/test/scala/com/outworkers/phantom/suites/ThriftTestSuite.scala b/phantom-thrift/src/test/scala/com/outworkers/phantom/suites/ThriftTestSuite.scala new file mode 100644 index 000000000..330c7ddb6 --- /dev/null +++ b/phantom-thrift/src/test/scala/com/outworkers/phantom/suites/ThriftTestSuite.scala @@ -0,0 +1,60 @@ +/* + * Copyright 2013 - 2017 Outworkers Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.outworkers.phantom.suites + +import java.util.UUID + +import com.outworkers.phantom.tables.{Output, ThriftDatabase} +import com.outworkers.util.testing._ +import org.scalatest.concurrent.PatienceConfiguration + +import scala.concurrent.duration._ +import org.scalatest.{BeforeAndAfterAll, Matchers, OptionValues, Suite} + +trait ThriftTestSuite extends Suite + with BeforeAndAfterAll + with Matchers + with OptionValues + with ThriftDatabase.connector.Connector { + implicit val s: PatienceConfiguration.Timeout = timeout(10 seconds) + + type ThriftTest = com.outworkers.phantom.thrift.ThriftTest + val ThriftTest = com.outworkers.phantom.thrift.ThriftTest + + implicit object OutputSample extends Sample[Output] { + def sample: Output = { + Output( + id = gen[UUID], + name = gen[String], + struct = gen[ThriftTest], + thriftSet = genList[ThriftTest]().toSet[ThriftTest], + thriftList = genList[ThriftTest](), + thriftMap = genList[ThriftTest]().map { + item => (item.toString, item) + }.toMap, + optThrift = genOpt[ThriftTest] + ) + } + } + + implicit object ThriftTestSample extends Sample[ThriftTest] { + def sample: ThriftTest = ThriftTest( + gen[Int], + gen[String], + test = false + ) + } +} diff --git a/phantom-thrift/src/test/scala/com/websudos/phantom/tables/ThriftColumnTable.scala b/phantom-thrift/src/test/scala/com/outworkers/phantom/tables/ThriftColumnTable.scala similarity index 60% rename from phantom-thrift/src/test/scala/com/websudos/phantom/tables/ThriftColumnTable.scala rename to phantom-thrift/src/test/scala/com/outworkers/phantom/tables/ThriftColumnTable.scala index 1f89592f6..d3b7d64ea 100644 --- a/phantom-thrift/src/test/scala/com/websudos/phantom/tables/ThriftColumnTable.scala +++ b/phantom-thrift/src/test/scala/com/outworkers/phantom/tables/ThriftColumnTable.scala @@ -1,43 +1,31 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ -package com.websudos.phantom.tables +package com.outworkers.phantom.tables import java.util.UUID import com.datastax.driver.core.Row +import com.outworkers.phantom.connectors +import com.outworkers.phantom.connectors.RootConnector import com.twitter.scrooge.CompactThriftSerializer -import com.websudos.phantom.builder.query.InsertQuery -import com.websudos.phantom.connectors.{ContactPoint, KeySpaceDef} -import com.websudos.phantom.database.Database -import com.websudos.phantom.dsl._ -import com.websudos.phantom.thrift._ +import com.outworkers.phantom.builder.query.InsertQuery +import com.outworkers.phantom.connectors.CassandraConnection +import com.outworkers.phantom.database.Database +import com.outworkers.phantom.dsl._ +import com.outworkers.phantom.thrift._ case class Output( id: UUID, @@ -51,7 +39,7 @@ case class Output( sealed class ThriftColumnTable extends CassandraTable[ConcreteThriftColumnTable, Output] { - object id extends UUIDColumn(this) with PartitionKey[UUID] + object id extends UUIDColumn(this) with PartitionKey object name extends StringColumn(this) object ref extends ThriftColumn[ConcreteThriftColumnTable, Output, ThriftTest](this) { val serializer = new CompactThriftSerializer[ThriftTest] { @@ -82,18 +70,6 @@ sealed class ThriftColumnTable extends CassandraTable[ConcreteThriftColumnTable, val codec = ThriftTest } } - - def fromRow(row: Row): Output = { - Output( - id = id(row), - name = name(row), - struct = ref(row), - thriftSet = thriftSet(row), - thriftList = thriftList(row), - thriftMap = thriftMap(row), - optThrift = optionalThrift(row) - ) - } } abstract class ConcreteThriftColumnTable extends ThriftColumnTable with RootConnector { @@ -115,7 +91,7 @@ sealed class ThriftIndexedTable extends CassandraTable[ConcreteThriftIndexedTabl object id extends UUIDColumn(this) object name extends StringColumn(this) - object ref extends ThriftColumn[ConcreteThriftIndexedTable, Output, ThriftTest](this) with PartitionKey[ThriftTest] { + object ref extends ThriftColumn[ConcreteThriftIndexedTable, Output, ThriftTest](this) with PartitionKey { val serializer = new CompactThriftSerializer[ThriftTest] { val codec = ThriftTest } @@ -144,18 +120,6 @@ sealed class ThriftIndexedTable extends CassandraTable[ConcreteThriftIndexedTabl val codec = ThriftTest } } - - def fromRow(row: Row): Output = { - Output( - id(row), - name(row), - ref(row), - thriftSet(row), - thriftList(row), - thriftMap(row), - optionalThrift(row) - ) - } } abstract class ConcreteThriftIndexedTable extends ThriftIndexedTable with RootConnector { @@ -173,9 +137,9 @@ abstract class ConcreteThriftIndexedTable extends ThriftIndexedTable with RootCo } } -class ThriftDatabase(override val connector: KeySpaceDef) extends Database[ThriftDatabase](connector) { +class ThriftDatabase(override val connector: CassandraConnection) extends Database[ThriftDatabase](connector) { object thriftColumnTable extends ConcreteThriftColumnTable with connector.Connector object thriftIndexedTable extends ConcreteThriftIndexedTable with connector.Connector } -object ThriftDatabase extends ThriftDatabase(ContactPoint.local.keySpace("phantom")) \ No newline at end of file +object ThriftDatabase extends ThriftDatabase(connectors.ContactPoint.local.keySpace("phantom")) \ No newline at end of file diff --git a/phantom-thrift/src/test/scala/com/websudos/phantom/thrift/suites/OptionalThriftColumnTest.scala b/phantom-thrift/src/test/scala/com/websudos/phantom/thrift/suites/OptionalThriftColumnTest.scala deleted file mode 100644 index 1fde7d42e..000000000 --- a/phantom-thrift/src/test/scala/com/websudos/phantom/thrift/suites/OptionalThriftColumnTest.scala +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.thrift.suites - -import com.datastax.driver.core.utils.UUIDs -import com.websudos.phantom.dsl._ -import com.websudos.phantom.tables.ThriftDatabase -import com.outworkers.util.testing._ -import org.scalatest.{Matchers, OptionValues, BeforeAndAfterAll, FlatSpec} -import org.scalatest.concurrent.PatienceConfiguration -import org.scalatest.time.SpanSugar._ - -class OptionalThriftColumnTest extends FlatSpec with OptionValues with Matchers with BeforeAndAfterAll with ThriftDatabase.connector.Connector { - - override def beforeAll(): Unit = { - ThriftDatabase.thriftColumnTable.create.ifNotExists().future().block(5.seconds) - } - - implicit val s: PatienceConfiguration.Timeout = timeout(10 seconds) - - it should "find an item if it was defined" in { - - val id = UUIDs.timeBased() - - val sample = gen[ThriftTest] - - val insert = ThriftDatabase.thriftColumnTable.insert - .value(_.id, id) - .value(_.name, sample.name) - .value(_.ref, sample) - .value(_.thriftSet, Set(sample)) - .value(_.thriftList, List(sample)) - .value(_.optionalThrift, Some(sample)) - .future() - - val operation = for { - insertDone <- insert - select <- ThriftDatabase.thriftColumnTable.select(_.optionalThrift).where(_.id eqs id).one - } yield select - - operation.successful { - res => { - res.value shouldBe Some(sample) - } - } - } - - it should "not find an item if was not defined" in { - val id = UUIDs.timeBased() - - val sample = gen[ThriftTest] - - val insert = ThriftDatabase.thriftColumnTable.insert - .value(_.id, id) - .value(_.name, sample.name) - .value(_.ref, sample) - .value(_.thriftSet, Set(sample)) - .value(_.thriftList, List(sample)) - .value(_.optionalThrift, None) - .future() - - val operation = for { - insertDone <- insert - select <- ThriftDatabase.thriftColumnTable.select(_.optionalThrift).where(_.id eqs id).one - } yield select - - operation.successful { - res => { - res.value.isDefined shouldBe false - } - } - } -} diff --git a/phantom-thrift/src/test/scala/com/websudos/phantom/thrift/suites/ThriftColumnTest.scala b/phantom-thrift/src/test/scala/com/websudos/phantom/thrift/suites/ThriftColumnTest.scala deleted file mode 100644 index 5e0afb254..000000000 --- a/phantom-thrift/src/test/scala/com/websudos/phantom/thrift/suites/ThriftColumnTest.scala +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.thrift.suites - -import com.datastax.driver.core.utils.UUIDs -import com.websudos.phantom.dsl._ -import com.websudos.phantom.tables.ThriftDatabase -import com.outworkers.util.testing._ -import org.scalatest.FlatSpec -import org.scalatest.time.SpanSugar._ - -class ThriftColumnTest extends FlatSpec with ThriftTestSuite { - - override def beforeAll(): Unit = { - ThriftDatabase.thriftColumnTable.create.ifNotExists().future().block(5.seconds) - } - - it should "allow storing thrift columns" in { - val id = UUIDs.timeBased() - val sample = gen[ThriftTest] - - val insert = ThriftDatabase.thriftColumnTable.insert - .value(_.id, id) - .value(_.name, sample.name) - .value(_.ref, sample) - .future() flatMap { - _ => ThriftDatabase.thriftColumnTable.select.where(_.id eqs id).one() - } - - insert.successful { - result => { - result.value.struct shouldEqual sample - } - } - } - - it should "allow storing lists of thrift objects" in { - val id = UUIDs.timeBased() - val sample = gen[ThriftTest] - val sample2 = gen[ThriftTest] - val sampleList = Set(sample, sample2) - - val insert = ThriftDatabase.thriftColumnTable.insert - .value(_.id, id) - .value(_.name, sample.name) - .value(_.ref, sample) - .value(_.thriftSet, sampleList) - .future() flatMap { - _ => ThriftDatabase.thriftColumnTable.select.where(_.id eqs id).one() - } - - insert.successful { - result => { - result.value.struct shouldEqual sample - result.value.thriftSet shouldEqual sampleList - } - } - } -} diff --git a/phantom-thrift/src/test/scala/com/websudos/phantom/thrift/suites/ThriftTestSuite.scala b/phantom-thrift/src/test/scala/com/websudos/phantom/thrift/suites/ThriftTestSuite.scala deleted file mode 100644 index e5f0c3f23..000000000 --- a/phantom-thrift/src/test/scala/com/websudos/phantom/thrift/suites/ThriftTestSuite.scala +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright 2013-2016 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.thrift.suites - -import com.websudos.phantom.tables.ThriftDatabase -import com.outworkers.util.testing._ -import org.scalatest.concurrent.PatienceConfiguration -import scala.concurrent.duration._ -import org.scalatest.{OptionValues, Matchers, BeforeAndAfterAll, Suite} - -trait ThriftTestSuite extends Suite - with BeforeAndAfterAll - with Matchers - with OptionValues - with ThriftDatabase.connector.Connector { - implicit val s: PatienceConfiguration.Timeout = timeout(10 seconds) -} diff --git a/phantom-thrift/src/test/scala/com/websudos/phantom/thrift/suites/package.scala b/phantom-thrift/src/test/scala/com/websudos/phantom/thrift/suites/package.scala deleted file mode 100644 index 54d392fe4..000000000 --- a/phantom-thrift/src/test/scala/com/websudos/phantom/thrift/suites/package.scala +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright 2013-2015 Websudos, Limited. - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -package com.websudos.phantom.thrift - -import java.util.UUID - -import com.websudos.phantom.tables.Output -import com.outworkers.util.testing._ - -package object suites { - - type ThriftTest = com.websudos.phantom.thrift.ThriftTest - - implicit object OutputSample extends Sample[Output] { - def sample: Output = { - Output( - id = gen[UUID], - name = gen[String], - struct = gen[ThriftTest], - thriftSet = genList[ThriftTest]().toSet[ThriftTest], - thriftList = genList[ThriftTest](), - thriftMap = genList[ThriftTest]().map { - item => (item.toString, item) - }.toMap, - optThrift = genOpt[ThriftTest] - ) - } - } - - implicit object ThriftTestSample extends Sample[ThriftTest] { - def sample: ThriftTest = ThriftTest( - gen[Int], - gen[String], - test = false - ) - } - -} diff --git a/project/Publishing.scala b/project/Publishing.scala index 664c3015b..563e079a3 100644 --- a/project/Publishing.scala +++ b/project/Publishing.scala @@ -1,31 +1,17 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ import bintray.BintrayKeys._ import sbt.Keys._ @@ -37,7 +23,7 @@ import scala.util.Properties object Publishing { val defaultPublishingSettings = Seq( - version := "1.29.6" + version := "2.0.13" ) lazy val noPublishSettings = Seq( @@ -80,7 +66,7 @@ object Publishing { lazy val bintraySettings: Seq[Def.Setting[_]] = Seq( publishMavenStyle := true, - bintrayOrganization := Some("websudos"), + bintrayOrganization := Some("outworkers"), bintrayRepository <<= scalaVersion.apply { v => if (v.trim.endsWith("SNAPSHOT")) "oss-snapshots" else "oss-releases" }, diff --git a/project/plugins.sbt b/project/plugins.sbt index ea4ffee95..d41a1d538 100644 --- a/project/plugins.sbt +++ b/project/plugins.sbt @@ -1,31 +1,17 @@ /* - * Copyright 2013-2015 Websudos, Limited. + * Copyright 2013 - 2017 Outworkers Ltd. * - * All rights reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * http://www.apache.org/licenses/LICENSE-2.0 * - * - Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Explicit consent must be obtained from the copyright owner, Outworkers Limited before any redistribution is made. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ def outworkersPattern: Patterns = { val pList = List( @@ -40,17 +26,16 @@ def outworkersPattern: Patterns = { } resolvers ++= Seq( - "Sonatype snapshots" at "http://oss.sonatype.org/content/repositories/snapshots/", - "sonatype-releases" at "https://oss.sonatype.org/content/repositories/releases/", "jgit-repo" at "http://download.eclipse.org/jgit/maven", "Twitter Repo" at "http://maven.twttr.com/", + Resolver.sonatypeRepo("releases"), Resolver.bintrayRepo("websudos", "oss-releases"), Resolver.url("scoverage-bintray", url("https://dl.bintray.com/sksamuel/sbt-plugins/"))(Resolver.ivyStylePatterns), Resolver.url("bintray-csl-sbt-plugins", url("https://dl.bintray.com/twittercsl/sbt-plugins"))(Resolver.mavenStylePatterns), Resolver.url("twitter-csl-sbt-plugins", url("https://dl.bintray.com/twittercsl/sbt-plugins"))(Resolver.ivyStylePatterns) ) -addSbtPlugin("org.scoverage" %% "sbt-scoverage" % "1.3.5") +addSbtPlugin("org.scoverage" %% "sbt-scoverage" % "1.5.0") addSbtPlugin("org.scoverage" %% "sbt-coveralls" % "1.1.0") @@ -72,4 +57,6 @@ addSbtPlugin("com.websudos" % "sbt-package-dist" % "1.2.0") addSbtPlugin("com.earldouglas" % "xsbt-web-plugin" % "2.0.4") -addSbtPlugin("com.twitter" % "scrooge-sbt-plugin" % "4.7.0") \ No newline at end of file +addSbtPlugin("com.twitter" % "scrooge-sbt-plugin" % "4.7.0") + +addSbtPlugin("com.eed3si9n" % "sbt-doge" % "0.1.5") \ No newline at end of file diff --git a/scalastyle-config.xml b/scalastyle-config.xml index e67e01f12..f8d80da32 100644 --- a/scalastyle-config.xml +++ b/scalastyle-config.xml @@ -9,33 +9,19 @@