Browse files

Source import.

  • Loading branch information...
1 parent 6ca5d53 commit 457509ba6bb8f7f1d013b71b4ed38b53685ba50d Nick Kallen committed Feb 5, 2010
Showing with 2,421 additions and 0 deletions.
  1. +2 −0 .gitignore
  2. +201 −0 LICENSE
  3. +174 −0 README.markdown
  4. +71 −0 ant/bootstrap.xml
  5. +20 −0 ant/clean.xml
  6. +225 −0 ant/compile.xml
  7. +35 −0 ant/docs.xml
  8. +127 −0 ant/package.xml
  9. +55 −0 ant/prepare.xml
  10. +56 −0 ant/test.xml
  11. +10 −0 build.xml
  12. +4 −0 config/test.conf
  13. +42 −0 ivy/ivy.xml
  14. +32 −0 ivy/ivysettings.xml
  15. +6 −0 src/main/scala/com/twitter/querulous/StatsCollector.scala
  16. +35 −0 src/main/scala/com/twitter/querulous/Timeout.scala
  17. +85 −0 src/main/scala/com/twitter/querulous/connectionpool/ApacheConnectionPool.scala
  18. +20 −0 src/main/scala/com/twitter/querulous/connectionpool/ConnectionPool.scala
  19. +18 −0 src/main/scala/com/twitter/querulous/connectionpool/MemoizingConnectionPoolFactory.scala
  20. +32 −0 src/main/scala/com/twitter/querulous/connectionpool/StatsCollectingConnectionPool.scala
  21. +71 −0 src/main/scala/com/twitter/querulous/evaluator/AutoDisablingQueryEvaluator.scala
  22. +32 −0 src/main/scala/com/twitter/querulous/evaluator/QueryEvaluator.scala
  23. +39 −0 src/main/scala/com/twitter/querulous/evaluator/QueryEvaluatorProxy.scala
  24. +67 −0 src/main/scala/com/twitter/querulous/evaluator/StandardQueryEvaluator.scala
  25. +55 −0 src/main/scala/com/twitter/querulous/evaluator/Transaction.scala
  26. +43 −0 src/main/scala/com/twitter/querulous/query/DebuggingQuery.scala
  27. +13 −0 src/main/scala/com/twitter/querulous/query/Query.scala
  28. +13 −0 src/main/scala/com/twitter/querulous/query/QueryProxy.scala
  29. +26 −0 src/main/scala/com/twitter/querulous/query/RetryingQuery.scala
  30. +120 −0 src/main/scala/com/twitter/querulous/query/SqlQuery.scala
  31. +27 −0 src/main/scala/com/twitter/querulous/query/StatsCollectingQuery.scala
  32. +35 −0 src/main/scala/com/twitter/querulous/query/TimingOutQuery.scala
  33. +12 −0 src/test/scala/com/twitter/querulous/TestRunner.scala
  34. +19 −0 src/test/scala/com/twitter/querulous/fake/FakeConnectionPool.scala
  35. +15 −0 src/test/scala/com/twitter/querulous/fake/FakeQuery.scala
  36. +15 −0 src/test/scala/com/twitter/querulous/fake/FakeQueryEvaluator.scala
  37. +22 −0 src/test/scala/com/twitter/querulous/fake/FakeStatsCollector.scala
  38. +32 −0 src/test/scala/com/twitter/querulous/integration/QuerySpec.scala
  39. +55 −0 src/test/scala/com/twitter/querulous/integration/TimeoutSpec.scala
  40. +82 −0 src/test/scala/com/twitter/querulous/unit/AutoDisablingQueryEvaluatorSpec.scala
  41. +40 −0 src/test/scala/com/twitter/querulous/unit/DebuggingQuerySpec.scala
  42. +29 −0 src/test/scala/com/twitter/querulous/unit/MemoizingConnectionPoolFactorySpec.scala
  43. +112 −0 src/test/scala/com/twitter/querulous/unit/QueryEvaluatorSpec.scala
  44. +46 −0 src/test/scala/com/twitter/querulous/unit/RetryingQuerySpec.scala
  45. +42 −0 src/test/scala/com/twitter/querulous/unit/SqlQuerySpec.scala
  46. +32 −0 src/test/scala/com/twitter/querulous/unit/StatsCollectingConnectionPoolSpec.scala
  47. +33 −0 src/test/scala/com/twitter/querulous/unit/StatsCollectingQuerySpec.scala
  48. +44 −0 src/test/scala/com/twitter/querulous/unit/TimingOutQuerySpec.scala
@@ -0,0 +1,2 @@
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+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,
+ implied, including, without limitation, any warranties or conditions
+ 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.
+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 2010 Twitter, Inc.
+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
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+See the License for the specific language governing permissions and
+limitations under the License.
@@ -0,0 +1,174 @@
+# Querulous
+The friendly way to talk to your database.
+## License
+Copyright 2010 Twitter, Inc. See included LICENSE file.
+## Features
+* Handles all the JDBC bullshit so you don't have to: type casting for primitives and collections, exception handling and transactions, and so forth;
+* Feels like idiomatic Scala;
+* Fault tolerant: configurable strategies such as timeouts, mark-dead thresholds, and retries;
+* Designed for operability: rich statistics about your database usage and extensive debug logging;
+* Advanced connection pooling;
+* Minimalist: minimal code, minimal assumptions, minimal dependencies. You write highly-tuned SQL and we get out of the way;
+* Highly modular, highly configurable.
+The Github source repository is {here}[]. Patches and contributions are
+## Understanding the Implementation
+`Querulous` is made out of three components: QueryEvaluators, Queries, and ConnectionPools.
+* QueryEvaluators are a convenient procedural interface for executing queries.
+* Queries are objects representing a SELECT/UPDATE/INSERT/DELETE SQL Query. They are responsible for most type-casting, timeouts, and so forth. You will rarely interact with Queries directly.
+* ConnectionPools reserve and release connections to the database.
+Each of these three kinds of objects implement an interface. Enhanced functionality is meant to be "layered-on" by wrapping decorators around these objects that implement the enhanced functionality and delegate the primitive functionality.
+Each of the three components are meant to be instantiated with their corresponding factories (e.g., QueryEvaluatorFactory, ConnectionPoolFactory, etc.). The system is made configurable by constructing factories that manufacture the Decorators you're interested in. For example,
+ val queryFactory = new DebuggingQueryFactory(new TimingOutQueryFactory(new SqlQueryFactory))
+ val query = queryFactory(...) // this query will have debugging information and timeouts!
+## Usage
+### Basic Usage
+Create a QueryEvaluator by connecting to a database host with a username and password:
+ import com.twitter.querulous.evaluator.QueryEvaluator
+ val queryEvaluator = QueryEvaluator("host", "username", "password")
+Run a query or two:
+ val users ="SELECT * FROM users WHERE id IN (?) OR name = ?", List(1,2,3), "Jacques") { row =>
+ new User(row.getInt("id"), row.getString("name"))
+ }
+ queryEvaluator.execute("INSERT INTO users VALUES (?, ?)", 1, "Jacques")
+Note that sequences are handled automatically (i.e., you only need one question-mark (?)).
+Run a query in a transaction for enhanced pleasure:
+ queryEvaluator.transaction { transaction =>
+"SELECT ... FOR UPDATE", ...)
+ transaction.execute("INSERT INTO users VALUES (?, ?)", 1, "Jacques")
+ transaction.execute("INSERT INTO users VALUES (?, ?)", 2, "Luc")
+ }
+The yielded transaction object implements the same interface as QueryEvaluator. Note that the transaction will be rolled back if you raise an exception.
+### Advanced Usage
+For production-quality use of `Querulous` you'll want to set configuration options and layer-on more functionality. Here is the maximally configurable, if somewhat elaborate, way to instantiate a QueryEvaluator
+ import com.twitter.querulous.evaluator._
+ import com.twitter.querulous.query._
+ import com.twitter.querulous.connectionpool._
+ val queryFactory = new SqlQueryFactory
+ val apacheConnectionPoolConfig = new ApacheConnectionPoolConfig()
+ val connectionPoolFactory = new ApacheConnectionPoolFactory(
+ minOpenConnections: Int, // minimum number of open/active connections at all times
+ maxOpenConnections: Int, // minimum number of open/active connections at all times
+ checkConnectionHealthWhenIdleFor: Duration, // asynchronously check the health of open connections every `checkConnectionHealthWhenIdleFor` amount of time
+ maxWaitForConnectionReservation: Duration, // maximum amount of time you're willing to wait to reserve a connection from the pool; throw an exception otherwise
+ checkConnectionHealthOnReservation: Boolean, // check connection health when reserving the connection from the pool
+ evictConnectionIfIdleFor: Duration // destroy connections if they are idle for longer than `evictConnectionIfIdleFor` amount of time
+ )
+ val queryEvaluatorFactory = new StandardQueryEvaluatorFactory(connectionPoolFactory, queryFactory)
+ val queryEvaluator = queryEvaluatorFactory(List("primaryhost", "fallbackhost1", "fallbackhost2", ...), "username", "password")
+Now comes the fun part.
+#### Query Decorators
+Suppose you want timeouts around queries:
+ val queryFactory = new TimingOutQueryFactory(new SqlQueryFactory, 3.seconds)
+Suppose you ALSO want to retry queries up to 5 times:
+ val queryFactory = new RetryingQueryFactory(new TimingOutQueryFactory(new SqlQueryFactory, 3000.millis), 5)
+Suppose you have no idea what's going on and need some debug info:
+ val queryFactory = new DebuggingQueryFactory(new RetryingQueryFactory(new TimingOutQueryFactory(new SqlQueryFactory, 3.seconds), 5), println)
+You'll notice, at this point, that all of these advanced features can be layered-on by composing QueryFactories. In what follows, I'll omit some layering to keep the examples terse.
+Suppose you want to measure average and standard deviation of latency, and query counts:
+ val stats = new StatsCollector
+ val queryFactory = new StatsCollectingQueryFactory(new SqlQueryFactory, stats)
+See the section [Statistics Collection] for more information.
+#### ConnectionPool Decorators
+Suppose you want to measure latency around the reserve/release operations of the ConnectionPool:
+ val stats = new StatsCollector
+ val connectionPoolFactory = new StatsCollectingConnectionPoolFactory(new ApacheConnectionPoolFactory(...), stats)
+Suppose you are actually dynamically connecting to dozens of hosts (because of a sharding strategy or something similar) and you want to maintain proper connection limits. You can memoize your connection pools like this:
+ val connectionPoolFactory = new MemoizingConnectionPoolFactory(new ApacheConnectionPoolFactory(...))
+#### QueryEvaluator Decorators
+Suppose you want to automatically disable all connections to a particular host after a certain number of SQL Exceptions (timeouts, etc.):
+ val queryEvaluatorFactory = new AutoDisablingQueryEvaluatorFactory(new StandardQueryEvaluatorFactory(connectionPoolFactory, queryFactory))
+### Recommended Configuration Options
+* Set minActive equal to maxActive. This ensures that the system is fully utilizing the connection resource even when the system is idle. This is good because you will not be surprised by connection usage (and e.g., unexpectedly hit server-side connection limits) during peak load.
+* Set minActive equal to maxActive equal to the MySql connection limit divided by the number of instances of your client process
+* Set testIdle to 1.second or so. It should be substantially less than the server-side connection timeout.
+* Set maxWait to 10.millis--to start. In general, it should be set to the average experienced latency plus twice the standard deviation. Gather statistics!
+* Set minEvictableIdle to 5.minutes or more. It has no effect when minActive equals maxActive, but in case these differ you don't want excessive connection churning. It should certainly be less than or equal to the server-side connection timeout.
+## Statistics Collection
+StatsCollector is actually just a trait that you'll need to implement using your favorite statistics collecting library. My favorite is [Ostrich]( and you can write an adapter in a few lines of code. Here is one such adapter:
+ val stats = new StatsCollector {
+ def incr(name: String, count: Int) = Stats.incr(name, count)
+ def time[A](name: String)(f: => A): A = Stats.time(name)(f)
+ }
+## Installation
+### Maven
+ <dependency>
+ <groupId>commons-dbcp</groupId>
+ <artifactId>commons-dbcp</artifactId>
+ <version>1.2.2</version>
+ </dependency>
+### Ivy
+ <dependency org="commons-dbcp" name="commons-dbcp" rev="1.2.2"/>
+## Running Tests
+Most of the tests are unit tests and are heavily mocked. However, some tests run database queries. You should change the `username` and `password` in `config/test.conf` to something that actually works for your system. Then, from the command line, simply run:
+ % ant test
+## Reporting problems
+The Github issue tracker is {here}[].
+## Contributors
+* Nick Kallen
+* Robey Pointer
+* Ed Ceaser
+* Utkarsh Srivastava
Oops, something went wrong.

0 comments on commit 457509b

Please sign in to comment.