Compare commits

...
Author SHA1 Message Date
rob bygrave 08d241d946 #1966 Remove sequence batching - postgres opps 2020-03-05 00:34:05 +13:00
rob bygrave 1c24ebf6dc Remove Sequence batching in favour of JPA increment 50
Also remove h2sqldb in favour of always using H2
2020-03-05 00:22:20 +13:00
rob bygrave 0ce39c73f1 Test only update postgres DDL review 2020-03-05 00:21:36 +13:00
rob bygrave 82d6294dcb Test only update h2 DDL review 2020-03-05 00:13:41 +13:00
rob bygrave ba01103f48 #1965 @Identity with sequence ddl generation 2020-03-05 00:13:08 +13:00
Rob BygraveandGitHub 3e14ec6a5a Merge pull request #1965 from ebean-orm/feature/identityMode2
Support for @Identity - with cache, generated by (ALWAYS/BY DEFAULT), start, increment options
2020-03-04 22:56:44 +13:00
rob bygrave b9d5d35850 Set testing default back to H2 2020-03-04 22:55:51 +13:00
rob bygrave 04adc35ccd Support for @Identity - Fix sequence name propagation 2020-03-04 22:49:08 +13:00
rob bygrave bfc2b57df5 Support for @Identity - use identity options with sequence 2020-03-04 21:29:56 +13:00
rob bygrave a5880fca97 Support for @Identity - update sql server ddl review 2020-03-04 21:23:50 +13:00
rob bygrave 8685f2056a Support for @Identity - update ddl review 2020-03-04 17:18:01 +13:00
rob bygrave 2ac19bea1a Support for @Identity - with start, increment, cache 2020-03-04 16:59:42 +13:00
rob bygrave 9410f82f5a Support for @Identity - update default sequence increment 2020-03-03 22:36:59 +13:00
rob bygrave 21382a52ed Support for @Identity - split IdentityMode and DeployIdentityMode 2020-03-03 22:36:27 +13:00
rob bygrave f871259f20 Support for @Identity - split IdentityMode and DeployIdentityMode 2020-03-03 22:36:27 +13:00
rob bygrave eb765056fd Support for @Identity - initial refactor to add IdentityMode 2020-03-03 22:36:27 +13:00
rob bygrave ddf3c753d6 Ability to use order(<orderByClause>) on filterMany() (related to #1943) #1964 2020-03-03 22:31:01 +13:00
rob bygrave 4767aff046 Test only update sql server DDL review 2020-03-03 22:03:24 +13:00
rob bygrave 75846edd97 Test only update H2 DDL review 2020-03-03 21:20:19 +13:00
rob bygrave f7c6745de1 Ci Testing - remove test/resources/dbmigration/migrationtest/postgres9 2020-03-01 13:09:37 +13:00
rob bygrave f080f16e63 #1962 - Refactor simplify Postgres platforms to POSTGRES and POSTGRES9 2020-03-01 12:53:34 +13:00
rob bygrave 9135f87253 CI Testing - ParentQueryTest cascade on parent.data 2020-03-01 12:42:03 +13:00
rob bygrave 90ccf2d8b4 CI Testing - ParentQueryTest cascade on parent.data 2020-03-01 12:29:54 +13:00
rob bygrave 11409f8c09 CI Testing - ParentQueryTest cascade on parent.data 2020-03-01 12:23:16 +13:00
rob bygrave fb472a0304 CI Testing - ParentQueryTest truncate 2020-03-01 12:12:01 +13:00
rob bygrave 04c9007d22 CI Testing - Update travis to not both with oraclejdk8 which is no longer available 2020-03-01 11:55:31 +13:00
rob bygrave 8f75a04ad0 CI Testing - Update travis to xenial & postgresql: 10 2020-03-01 11:45:56 +13:00
Rob BygraveandGitHub 2236e4bfd7 Refactor PlatformDdl separate call to asIdentityColumn() (#1961) 2020-03-01 10:42:41 +13:00
rob bygrave 6d1c3738de #1960 - CVEs - Update postgresql and h2 jdbc drivers (provided scope only) 2020-02-28 16:22:48 +13:00
rob bygrave 20160144f5 No effective change - remove unused snakeyaml.version from pom 2020-02-22 14:42:00 +13:00
rob bygrave 891166507d Test only - restore postgres9 and postgres10 migration resources for CI postgres 2020-02-22 13:36:33 +13:00
rob bygrave bce97b1063 Test only - add dummy files for pg9 and pg10 DbMigrationTest for running on CI (with old postgres) 2020-02-22 12:54:16 +13:00
Rob BygraveandGitHub c5b960c588 Merge pull request #1959 from ebean-orm/feature/1955
#1953 - Do we need SqlServer2005Platform and SqlServer2005SqlLimiter?
2020-02-22 12:47:13 +13:00
rob bygrave 009b400ed3 Test only - delete test/resources/dbmigration/migrationtest/postgres10 and postgres9 2020-02-22 12:45:07 +13:00
rob bygrave b6ee6ade8c Test only - update ddl review for postgres 2020-02-22 12:44:00 +13:00
rob bygrave 0891c067d5 #1953 - Do we need SqlServer2005Platform and SqlServer2005SqlLimiter? 2020-02-22 11:48:16 +13:00
Rob BygraveandGitHub 7b3b32f0ff Merge pull request #1957 from ebean-orm/feature/1955
#1955 #1956  SqlQuery.mapToScalar() and SqlQuery.mapTo(RowMapper)
2020-02-22 11:25:48 +13:00
rob bygrave 3878b02cff #1956 - Add SqlQuery - mapTo( RowMapper) ... to deprecate findOne(RowMapper) 2020-02-22 10:50:23 +13:00
rob bygrave 92995b807e #1955 - mapToScalar - Add SqlQuery.mapToScalar( <class> ).findOne() / findList() ... to deprecate findSingleAttribute() 2020-02-22 10:09:44 +13:00
Rob BygraveandGitHub 907d36123d OraclePlatform update (ANSI row limiting with OFFSET), Oracle11Platform for old behaviour (#1951)
* #1947 - Oracle change to use concat operator rather than function

* #1947 - setMaxRows(1).findIds() under Oracle returns wrong result

* #1950 - Change OraclePlatform to use ANSI row limiting - OFFSET and NEXT ROWS, old platform as Oracle11Platform

* Revert test default to H2

* #1947 - Oracle & Oracle11 platform
2020-02-22 09:28:34 +13:00
Rob BygraveandGitHub 2db95f909d Merge pull request #1944 from ebean-orm/feature/1943
#1943 - Use limit & offset via setFirstRow() and setMaxRows() on filterMany()
2020-02-22 09:26:03 +13:00
rob bygrave 5213e8b653 Fix test merge for StartPostgres9 - using int for port 2020-02-22 09:24:58 +13:00
Rob BygraveandGitHub 2314fd267f Split Postgres platform into Postgres10 & Postgres9 (DDL - generated by default as identity) (#1921)
* Split Postgres platform into Postgres10 & Postgres9

- Use "generated by default as identity" for Postgres10 identity columns

* Add postgres9 migrationtest resources

* Set default back to h2

* Add postgres10 migration test resources
2020-02-22 09:18:05 +13:00
Rob BygraveandGitHub b24f093bbb Remove io.ebean.meta.MetricType as it is unnecessary (#1923) 2020-02-22 09:17:14 +13:00
Rob BygraveandGitHub 444c868124 Refactor to use avaje config (#1894)
* Move to use Avaje Config for properties loading
2020-02-22 09:11:37 +13:00
rob bygrave 81b16b8f73 [maven-release-plugin] prepare for next development iteration 2020-02-22 08:59:33 +13:00
rob bygrave 850db70be3 [maven-release-plugin] prepare release ebean-12.1.13 2020-02-22 08:59:20 +13:00
rob bygrave ee81ee4d7c test only update of ddl review for mysql-create-all.sql 2020-02-22 08:50:32 +13:00
Rob BygraveandGitHub 4cbeb282eb Merge pull request #1954 from boeckers/added_MySqlDbExpression.json
Add JSON expression handing for MySql - MySqlDbExpression.json
2020-02-22 08:40:09 +13:00
Michael Böckers 5278c010ba added MySqlDbExpression.json 2020-02-21 12:58:18 +01:00
rob bygrave ea490a5ac3 Collect the DB schemas in the model via MTable 2020-02-21 17:16:28 +13:00
rob bygrave e4390ed8a2 #1952 - Entity bean with @Id and ONLY @WhenCreated treated as reference bean - not inserted 2020-02-21 00:14:23 +13:00
Rob BygraveandGitHub a23d9f7db8 Merge pull request #1949 from sebastianmrozek/master
Test usingDatabase with a non default db
2020-02-20 22:43:53 +13:00
Sebastian Mrozek b1704ff5dc Test usingDatabase with a non default db
Move the test to separate class with better name.
2020-02-20 22:13:38 +13:00
rob bygrave c0d752b445 #1941 - @History it seems does not work well when it got generated with ebean.allQuotedIdentifiers enabled 2020-02-20 16:51:07 +13:00
Rob BygraveandGitHub ef5ea59559 Merge pull request #1948 from ebean-orm/feature/queryUsingDatabase
ENH: Add query.usingDatabase(database)
2020-02-20 16:42:25 +13:00
rob bygrave de42655bbd Refactor tests using assertSql() helper method
This helper method trims column alias from the sql (for Oracle)
2020-02-20 15:08:43 +13:00
rob bygrave 661230909c ENH: Add query.usingDatabase(database) - add better test 2020-02-19 11:48:47 +13:00
rob bygrave e9325a81f7 ENH: Add query.usingDatabase(database) 2020-02-19 11:41:06 +13:00
Rob BygraveandGitHub 78b9066345 Merge pull request #1946 from ebean-orm/feature/orderByDeprecate
Deprecate orderBy() migrate to order()
2020-02-19 10:00:15 +13:00
rob bygrave 1959e01844 Javadoc update only - change server to database in examples 2020-02-18 23:43:39 +13:00
rob bygrave cf6179c86b Deprecate orderBy() migrate to order() - update javadoc 2020-02-18 23:36:48 +13:00
rob bygrave 168dacffa7 Deprecate orderBy() migrate to order() 2020-02-18 23:27:43 +13:00
rob bygrave e0d322d80a #1943 - Return ExpressionList<T> from setMaxRows() setFirstRow() to allow fluid style
This is to allow fluid style use of setMaxRows() setFirstRow() with filterMany query
2020-02-17 17:19:27 +13:00
rob bygrave 1dd0f3cbf8 #1943 - Use limit & offset via setFirstRow() and setMaxRows() on filterMany() 2020-02-17 17:05:01 +13:00
rob bygrave 6961bf5787 #1945 - ENH: Add query.orderById(boolean) to ExpressionList ... improve fluid style 2020-02-17 16:47:37 +13:00
rob bygrave a14288b06d Refactor tidy DefaultExpressionList, no functional change 2020-02-17 16:40:03 +13:00
rob bygrave 171d1a19f4 #1937 - When add a new col with @DbComment in Entity,the DbMigration does not generate comment ddl 2020-02-17 14:19:19 +13:00
rob bygrave cbaaad89ab #1942 - Bump datasource to 4.7.3, includes - datasource.offline() closes busy connections ... should let them close on return 2020-02-17 11:51:40 +13:00
Rob BygraveandGitHub 413290a040 Merge pull request #1939 from ebean-orm/feature/1938
#1938 - API consistency add setParameters(varargs) & setParameter() - migrate from setNextParameter() and setParams()
2020-02-17 11:37:34 +13:00
rob bygrave 8feb100ac6 #1938 - API consistency add setParameters(varargs) & setParameter() - migrate from setNextParameter() and setParams() 2020-02-15 02:01:02 +13:00
rob bygrave d236988035 [maven-release-plugin] prepare for next development iteration 2020-02-09 22:23:59 +13:00
rob bygrave df0d84424c [maven-release-plugin] prepare release ebean-12.1.12 2020-02-09 22:23:48 +13:00
rob bygrave fb30a15a5b Update to ebean-maven-plugin 12.1.12 2020-02-09 22:21:14 +13:00
rob bygrave 3707d611b1 No effective change - EBasicVer extend Model 2020-02-07 22:07:38 +13:00
rob bygrave 60aa720777 No effective change - javadoc format SpiTransaction 2020-02-07 20:53:08 +13:00
rob bygrave 427152a894 Add test for IllegalStateException("Transaction is Inactive") 2020-02-07 20:15:59 +13:00
rob bygrave 3e43d544fb #1936 - ENH: Add saveAll(Object... beans) ... using varargs for DB and Database 2020-02-07 16:10:11 +13:00
rob bygrave 62b1da1be2 #1935 - ENH: Add DB.createTransaction() 2020-02-07 15:52:26 +13:00
rob bygrave 8b4eae2f91 #1934 - ENH: Add methods to Model that take explicit transaction - save(transaction), delete(transaction) ... 2020-02-07 13:00:59 +13:00
rob bygrave 4ed3a18b9d #1933 - ENH: Add DtoQuery.usingTransaction(Transaction) ... dto query with supplied transaction 2020-02-07 12:42:10 +13:00
Rob BygraveandGitHub 3c9d7e3127 Merge pull request #1925 from ebean-orm/feature/refatorTxnProfile
#1924 - Refactor for Transaction profiling - base on ProfileLocation / remove profileId
2020-02-04 22:38:44 +13:00
rob bygrave a89744a7bd No functional change - fix error message in DataSourceConfigurationException throw by Ebean 2020-02-03 22:34:10 +13:00
Rob BygraveandGitHub 5962f14874 Merge pull request #1928 from ebean-orm/feature/1755
FIX: Regression of #1775 - set date for other platforms (non MySQL) broken, when ebean.dataTimeZone is set to GMT
2020-02-01 16:03:33 +13:00
Roland Pramlandrob bygrave f161a38334 FIX: Regression of #1775 - set date for other platfroms broken, when ebean.dataTimeZone is set to GMT 2020-02-01 15:59:18 +13:00
Roland Pramlandrob bygrave 13f8da6b2e FIX: Add cause to exception 2020-02-01 14:07:09 +13:00
rob bygrave 9ad14c5306 #1926 - Postgres (Multi value bind) fix related to empty idIn() expression 2020-02-01 14:05:12 +13:00
rob bygrave 61ed4a5a74 Merge branch 'master' of github.com:ebean-orm/ebean 2020-02-01 13:51:48 +13:00
Rob BygraveandGitHub 275f2dbc98 Merge pull request #1927 from ebean-orm/foconis-cache-emptylist
Fix cache emptylist and Fix / improvement for UUIDv1Generator mac address detection
2020-02-01 13:51:25 +13:00
Roland Pramlandrob bygrave 521b6a36ef changed ip.ebeaninternal.api.SpiQuery to io.ebean.Query in Server.exists 2020-02-01 13:46:28 +13:00
Roland Pramlandrob bygrave 0a6c26e5d3 FIX: Virtual Prüfung 2020-02-01 13:38:56 +13:00
Roland Pramlandrob bygrave 33416bffd0 FIX: Detecting MAC address improved 2020-02-01 13:38:44 +13:00
Roland Pramlandrob bygrave 4ce484f3f2 FIX: Cache also empty lists 2020-02-01 13:38:21 +13:00
rob bygrave cacf033647 Merge branch 'foc-imports' 2020-02-01 13:18:55 +13:00
rob bygrave e3dba6bfe1 Failing test for idIn() empty 2020-02-01 13:18:42 +13:00
Roland Pramlandrob bygrave c0b6f291a1 FIX: handle empty collection in "in (...)" queries 2020-02-01 13:06:37 +13:00
rob bygrave 9eab67d82e #1924 - Refactor for Transaction profiling - base on ProfileLocation / remove profileId 2020-02-01 11:31:43 +13:00
rob bygrave 840cb2ee7b [maven-release-plugin] prepare for next development iteration 2020-01-30 18:53:46 +13:00
479 changed files with 7636 additions and 6853 deletions
+2 -3
View File
@@ -1,15 +1,14 @@
dist: trusty
dist: xenial
sudo: required
language: java
jdk:
- oraclejdk8
- openjdk11
git:
depth: 3
addons:
postgresql: "9.6"
postgresql: 10
# apt:
# packages:
# - mysql-server-5.7
+17 -48
View File
@@ -9,7 +9,7 @@
<groupId>io.ebean</groupId>
<artifactId>ebean</artifactId>
<version>12.1.11</version>
<version>12.1.14-SNAPSHOT</version>
<packaging>jar</packaging>
<name>ebean</name>
@@ -18,42 +18,14 @@
<properties>
<jackson-core.version>2.10.0</jackson-core.version>
<jackson-databind.version>2.10.0</jackson-databind.version>
<snakeyaml.version>1.21</snakeyaml.version>
</properties>
<scm>
<developerConnection>scm:git:git@github.com:ebean-orm/ebean.git</developerConnection>
<tag>ebean-12.1.11</tag>
<tag>HEAD</tag>
</scm>
<profiles>
<profile>
<!-- Note: to use this profile, you need credentials for the oracle repository in your
settings.xml as described here:
http://docs.oracle.com/middleware/1213/core/MAVEN/config_maven_repo.htm#MAVEN9010 -->
<id>oracle</id>
<dependencies>
<dependency>
<groupId>com.oracle.jdbc</groupId>
<artifactId>ojdbc8</artifactId>
<version>12.2.0.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<repositories>
<repository>
<id>maven.oracle.com</id>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
<url>https://maven.oracle.com</url>
<layout>default</layout>
</repository>
</repositories>
</profile>
<profile>
<!-- Note: to use this profile, you need to download manually the db2jcc4 driver.
After that, install it into your local maven repository:
@@ -89,13 +61,10 @@
<scope>provided</scope>
</dependency>
<!--
Exclude snakeyaml if you desire - it is not strictly required.
-->
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>${snakeyaml.version}</version>
<groupId>io.avaje</groupId>
<artifactId>config</artifactId>
<version>1.0</version>
</dependency>
<!--
@@ -118,7 +87,7 @@
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-annotation</artifactId>
<version>6.4</version>
<version>6.9</version>
</dependency>
<dependency>
@@ -130,7 +99,7 @@
<dependency>
<groupId>io.ebean</groupId>
<artifactId>ebean-datasource</artifactId>
<version>4.7.1</version>
<version>4.7.3</version>
</dependency>
<dependency>
@@ -208,7 +177,7 @@
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.2</version>
<version>42.2.10</version>
<scope>provided</scope>
</dependency>
@@ -221,17 +190,17 @@
<scope>test</scope>
</dependency>
<!--<dependency>-->
<!--<groupId>oracle</groupId>-->
<!--<artifactId>oracle-jdbc</artifactId>-->
<!--<version>7.0</version>-->
<!--<scope>test</scope>-->
<!--</dependency>-->
<dependency>
<groupId>com.oracle.ojdbc</groupId>
<artifactId>ojdbc10</artifactId>
<version>19.3.0.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.ebean.test</groupId>
<artifactId>ebean-test-docker</artifactId>
<version>2.10.3</version>
<version>3.1.3</version>
<scope>test</scope>
</dependency>
@@ -247,7 +216,7 @@
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.197</version>
<version>1.4.199</version>
<scope>provided</scope>
</dependency>
@@ -323,7 +292,7 @@
<plugin>
<groupId>io.ebean</groupId>
<artifactId>ebean-maven-plugin</artifactId>
<version>12.1.6</version>
<version>12.1.12</version>
<executions>
<execution>
<id>test</id>
+22 -3
View File
@@ -86,14 +86,14 @@ public class DB {
// /**
// * Register the server with this Ebean singleton. Specify if the registered
// * server is the primary/default server.
// * server is the primary/default database.
// */
// public static void register(EbeanServer server, boolean defaultServer) {
// serverMgr.register(server, defaultServer);
// }
//
// /**
// * Backdoor for registering a mock implementation of EbeanServer as the default server.
// * Backdoor for registering a mock implementation of EbeanServer as the default database.
// */
// protected static EbeanServer mock(String name, EbeanServer server, boolean defaultServer) {
// EbeanServer originalPrimaryServer = serverMgr.defaultServer;
@@ -176,6 +176,18 @@ public class DB {
return getDefault().beginTransaction();
}
/**
* Create a new transaction that is not held in TransactionThreadLocal.
* <p>
* You will want to do this if you want multiple Transactions in a single
* thread or generally use transactions outside of the TransactionThreadLocal
* management.
* </p>
*/
public static Transaction createTransaction() {
return getDefault().createTransaction();
}
/**
* Start a transaction additionally specifying the isolation level.
*
@@ -442,6 +454,13 @@ public class DB {
return getDefault().saveAll(beans);
}
/**
* Save all the beans from a Collection.
*/
public static int saveAll(Object... beans) throws OptimisticLockException {
return getDefault().saveAll(beans);
}
/**
* This method checks the uniqueness of a bean. I.e. if the save will work. It will return the
* properties that violates an unique / primary key. This may be done in an UI save action to
@@ -650,7 +669,7 @@ public class DB {
* // find orders and their customers
* List<Order> list = DB.find(Order.class)
* .fetch("customer")
* .orderBy("id")
* .order("id")
* .findList();
*
* // sort by customer name ascending, then by order shipDate
+7 -2
View File
@@ -122,7 +122,7 @@ public interface Database {
String getName();
/**
* Return the ExpressionFactory for this server.
* Return the ExpressionFactory for this database.
*/
ExpressionFactory getExpressionFactory();
@@ -375,7 +375,7 @@ public interface Database {
* // find orders and their customers
* List<Order> list = database.find(Order.class)
* .fetch("customer")
* .orderBy("id")
* .order("id")
* .findList();
*
* // sort by customer name ascending, then by order shipDate
@@ -881,6 +881,11 @@ public interface Database {
*/
int saveAll(Collection<?> beans) throws OptimisticLockException;
/**
* Save all the beans.
*/
int saveAll(Object... beans) throws OptimisticLockException;
/**
* Delete the bean.
* <p>
+2 -2
View File
@@ -34,14 +34,14 @@ public class DatabaseFactory {
}
/**
* Create using ebean.properties to configure the server.
* Create using ebean.properties to configure the database.
*/
public static synchronized Database create(String name) {
return EbeanServerFactory.create(name);
}
/**
* Create using the ServerConfig object to configure the server.
* Create using the ServerConfig object to configure the database.
*/
public static synchronized Database create(DatabaseConfig config) {
return EbeanServerFactory.create(config);
+8 -8
View File
@@ -61,7 +61,7 @@ public interface DocumentStore {
* <pre>{@code
*
* Customer customer =
* server.find(Customer.class)
* database.find(Customer.class)
* .setUseDocStore(true)
* .setId(42)
* .findOne();
@@ -79,7 +79,7 @@ public interface DocumentStore {
* <pre>{@code
*
* List<Customer> newCustomers =
* server.find(Customer.class)
* database.find(Customer.class)
* .setUseDocStore(true)
* .where().eq("status, Customer.Status.NEW)
* .findList();
@@ -99,7 +99,7 @@ public interface DocumentStore {
* <pre>{@code
*
* PagedList<Customer> newCustomers =
* server.find(Customer.class)
* database.find(Customer.class)
* .setUseDocStore(true)
* .where().eq("status, Customer.Status.NEW)
* .setMaxRows(50)
@@ -120,7 +120,7 @@ public interface DocumentStore {
* </p>
* <pre>{@code
*
* server.find(Order.class)
* database.find(Order.class)
* .setUseDocStore(true)
* .where()... // perhaps add predicates
* .findEach((Order order) -> {
@@ -145,7 +145,7 @@ public interface DocumentStore {
* </p>
* <pre>{@code
*
* server.find(Order.class)
* database.find(Order.class)
* .setUseDocStore(true)
* .where()... // perhaps add predicates
* .findEachWhile(new Predicate<Order>() {
@@ -190,7 +190,7 @@ public interface DocumentStore {
* Drop the index from the document store (similar to DDL drop table).
* <pre>{@code
*
* DocumentStore documentStore = server.docStore();
* DocumentStore documentStore = database.docStore();
*
* documentStore.dropIndex("product_copy");
*
@@ -202,7 +202,7 @@ public interface DocumentStore {
* Create an index given a mapping file as a resource in the classPath (similar to DDL create table).
* <pre>{@code
*
* DocumentStore documentStore = server.docStore();
* DocumentStore documentStore = database.docStore();
*
* // uses product_copy.mapping.json resource
* // ... to define mappings for the index
@@ -289,7 +289,7 @@ public interface DocumentStore {
* <pre>{@code
*
* // predicates to select the source documents to copy
* Query<Product> query = server.find(Product.class)
* Query<Product> query = database.find(Product.class)
* .where()
* .ge("whenModified", new Timestamp(since))
* .ge("name", "A")
+23 -2
View File
@@ -77,12 +77,29 @@ public interface DtoQuery<T> {
Optional<T> findOneOrEmpty();
/**
* The same as bind for named parameters.
* Bind all the parameters using index positions.
* <p>
* Binds each parameter moving the index position each time.
* <p>
* A convenience for multiple calls to {@link #setParameter(Object)}
*/
DtoQuery<T> setParameters(Object... value);
/**
* Bind the next parameter using index position.
* <p>
* Bind the parameter using index position starting at 1 and incrementing.
* <p>
*/
DtoQuery<T> setParameter(Object value);
/**
* Bind the named parameter.
*/
DtoQuery<T> setParameter(String name, Object value);
/**
* The same as bind for positioned parameters.
* Bind the parameter by its index position (1 based like JDBC).
*/
DtoQuery<T> setParameter(int position, Object value);
@@ -136,4 +153,8 @@ public interface DtoQuery<T> {
*/
DtoQuery<T> setBufferFetchSizeHint(int bufferFetchSizeHint);
/**
* Use the explicit transaction to execute the query.
*/
DtoQuery<T> usingTransaction(Transaction transaction);
}
+5 -5
View File
@@ -82,7 +82,7 @@ public final class Ebean {
} catch (DataSourceConfigurationException e) {
String msg = "Configuration error creating DataSource for the default Database." +
" This typically means a missing application-test.yaml or missing ebean-test-config dependency." +
" This typically means a missing application-test.yaml or missing ebean-test dependency." +
" See https://ebean.io/docs/trouble-shooting#datasource";
throw new DataSourceConfigurationException(msg, e);
@@ -187,7 +187,7 @@ public final class Ebean {
}
/**
* Return the ExpressionFactory from the default server.
* Return the ExpressionFactory from the default database.
* <p>
* The ExpressionFactory is used internally by the query and ExpressionList to
* build the WHERE and HAVING clauses. Alternatively you can use the
@@ -209,14 +209,14 @@ public final class Ebean {
/**
* Register the server with this Ebean singleton. Specify if the registered
* server is the primary/default server.
* server is the primary/default database.
*/
public static void register(EbeanServer server, boolean defaultServer) {
serverMgr.register(server, defaultServer);
}
/**
* Backdoor for registering a mock implementation of EbeanServer as the default server.
* Backdoor for registering a mock implementation of EbeanServer as the default database.
*/
protected static EbeanServer mock(String name, EbeanServer server, boolean defaultServer) {
EbeanServer originalPrimaryServer = serverMgr.defaultServer;
@@ -796,7 +796,7 @@ public final class Ebean {
* // find orders and their customers
* List<Order> list = Ebean.find(Order.class)
* .fetch("customer")
* .orderBy("id")
* .order("id")
* .findList();
*
* // sort by customer name ascending, then by order shipDate
@@ -48,7 +48,7 @@ public class EbeanServerFactory {
}
/**
* Create using ebean.properties to configure the server.
* Create using ebean.properties to configure the database.
*/
public static synchronized EbeanServer create(String name) {
@@ -59,7 +59,7 @@ public class EbeanServerFactory {
}
/**
* Create using the ServerConfig object to configure the server.
* Create using the ServerConfig object to configure the database.
*/
public static synchronized EbeanServer create(ServerConfig config) {
+25 -27
View File
@@ -30,7 +30,7 @@ import java.util.function.Predicate;
* </p>
* <p>
* The ExpressionList also duplicates methods that are found on the Query such
* as findList() and orderBy(). The purpose of these methods is provide a fluid
* as findList() and order(). The purpose of these methods is provide a fluid
* API. The upside of this approach is that you can build and execute a query
* via chained methods. The down side is that this ExpressionList object has
* more methods than you would initially expect (the ones duplicated from
@@ -52,6 +52,14 @@ public interface ExpressionList<T> {
*/
Query<T> query();
/**
* Controls, if paginated queries should always append an 'order by id' statement at the end to
* guarantee a deterministic sort result. This may affect performance.
* If this is not enabled, and an orderBy is set on the query, it's up to the programmer that
* this query provides a deterministic result.
*/
Query<T> orderById(boolean orderById);
/**
* Set the order by clause replacing the existing order by clause if there is
* one.
@@ -59,12 +67,8 @@ public interface ExpressionList<T> {
* This follows SQL syntax using commas between each property with the
* optional asc and desc keywords representing ascending and descending order
* respectively.
* </p>
* <p>
* This is EXACTLY the same as {@link #orderBy(String)}.
* </p>
*/
Query<T> order(String orderByClause);
ExpressionList<T> order(String orderByClause);
/**
* Return the OrderBy so that you can append an ascending or descending
@@ -77,27 +81,21 @@ public interface ExpressionList<T> {
OrderBy<T> order();
/**
* Return the OrderBy so that you can append an ascending or descending
* property to the order by clause.
* <p>
* This will never return a null. If no order by clause exists then an 'empty'
* OrderBy object is returned.
* </p>
* Deprecated migrate to order().
*/
@Deprecated
OrderBy<T> orderBy();
/**
* Add an orderBy clause to the query.
*
* @see Query#orderBy(String)
* Deprecated migrate to {@link #order(String)}
*/
@Deprecated
Query<T> orderBy(String orderBy);
/**
* Add an orderBy clause to the query.
*
* @see Query#orderBy(String)
* Deprecated migrate to {@link #order(String)}
*/
@Deprecated
Query<T> setOrderBy(String orderBy);
/**
@@ -334,7 +332,7 @@ public interface ExpressionList<T> {
* List<String> names =
* DB.find(Customer.class)
* .select("name")
* .orderBy().asc("name")
* .order().asc("name")
* .findSingleAttributeList();
*
* }</pre>
@@ -347,7 +345,7 @@ public interface ExpressionList<T> {
* .setDistinct(true)
* .select("name")
* .where().eq("status", Customer.Status.NEW)
* .orderBy().asc("name")
* .order().asc("name")
* .setMaxRows(100)
* .findSingleAttributeList();
*
@@ -508,7 +506,7 @@ public interface ExpressionList<T> {
* @param expressions Filter expressions with and, or and ? or ?1 type bind parameters
* @param params Bind parameters used in the expressions
*/
Query<T> filterMany(String manyProperty, String expressions, Object... params);
ExpressionList<T> filterMany(String manyProperty, String expressions, Object... params);
/**
* Specify specific properties to fetch on the main/root bean (aka partial
@@ -559,14 +557,14 @@ public interface ExpressionList<T> {
*
* @see Query#setFirstRow(int)
*/
Query<T> setFirstRow(int firstRow);
ExpressionList<T> setFirstRow(int firstRow);
/**
* Set the maximum number of rows to fetch.
*
* @see Query#setMaxRows(int)
*/
Query<T> setMaxRows(int maxRows);
ExpressionList<T> setMaxRows(int maxRows);
/**
* Set the name of the property which values become the key of a map.
@@ -1451,7 +1449,7 @@ public interface ExpressionList<T> {
* .eq("status", Customer.Status.ACTIVE)
* .gt("id", 0)
* .endAnd()
* .orderBy().asc("name")
* .order().asc("name")
* .findList();
* }</pre>
*/
@@ -1472,7 +1470,7 @@ public interface ExpressionList<T> {
* .or()
* .eq("status", Customer.Status.ACTIVE)
* .isNull("anniversary")
* .orderBy().asc("name")
* .order().asc("name")
* .findList();
*
* }</pre>
@@ -1492,7 +1490,7 @@ public interface ExpressionList<T> {
* .eq("status", Customer.Status.ACTIVE)
* .gt("id", 0)
* .endAnd()
* .orderBy().asc("name")
* .order().asc("name")
* .findList();
*
* }</pre>
@@ -1526,7 +1524,7 @@ public interface ExpressionList<T> {
* .gt("id", 1)
* .eq("anniversary", onAfter)
* .endNot()
* .orderBy()
* .order()
* .asc("name")
* .findList();
*
+3 -6
View File
@@ -1,8 +1,5 @@
package io.ebean;
import io.ebeaninternal.api.SpiQuery;
import io.ebeaninternal.api.SpiTransaction;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.persistence.NonUniqueResultException;
@@ -70,7 +67,7 @@ public interface ExtendedServer {
*
* @return True if the query finds a matching row in the database
*/
<T> boolean exists(SpiQuery<?> ormQuery, SpiTransaction transaction);
<T> boolean exists(Query<?> ormQuery, Transaction transaction);
/**
* Return the number of 'top level' or 'root' entities this query should return.
@@ -360,7 +357,7 @@ public interface ExtendedServer {
* List<String> names =
* DB.find(Customer.class)
* .select("name")
* .orderBy().asc("name")
* .order().asc("name")
* .findSingleAttributeList();
*
* }</pre>
@@ -372,7 +369,7 @@ public interface ExtendedServer {
* .setDistinct(true)
* .select("name")
* .where().eq("status", Customer.Status.NEW)
* .orderBy().asc("name")
* .order().asc("name")
* .setMaxRows(100)
* .findSingleAttributeList();
*
+1 -1
View File
@@ -32,7 +32,7 @@ import java.util.List;
* public List<Customer> findNew() {
* return query().where()
* .eq("status", Customer.Status.NEW)
* .orderBy("name")
* .order("name")
* .findList()
* }
* }
+35
View File
@@ -192,6 +192,13 @@ public abstract class Model {
db().save(this);
}
/**
* Save this entity with an explicit transaction.
*/
public void save(Transaction transaction) {
db().save(this, transaction);
}
/**
* Flush any batched changes to the database.
* <p>
@@ -212,6 +219,13 @@ public abstract class Model {
db().update(this);
}
/**
* Update this entity with an explicit transaction.
*/
public void update(Transaction transaction) {
db().update(this, transaction);
}
/**
* Insert this entity.
*
@@ -221,6 +235,13 @@ public abstract class Model {
db().insert(this);
}
/**
* Insert with an explicit transaction.
*/
public void insert(Transaction transaction) {
db().insert(this, transaction);
}
/**
* Delete this bean.
* <p>
@@ -242,6 +263,13 @@ public abstract class Model {
return db().delete(this);
}
/**
* Delete this entity with an explicit transaction.
*/
public boolean delete(Transaction transaction) {
return db().delete(this, transaction);
}
/**
* Delete a bean permanently without soft delete.
* <p>
@@ -255,6 +283,13 @@ public abstract class Model {
return db().deletePermanent(this);
}
/**
* Delete a bean permanently without soft delete using an explicit transaction.
*/
public boolean deletePermanent(Transaction transaction) {
return db().deletePermanent(this, transaction);
}
/**
* Refreshes this entity from the database.
*
+1 -1
View File
@@ -30,7 +30,7 @@ import java.util.List;
* .where()
* .eq("store", "def")
* .inPairs(pairs) // IN clause with 'pairs' of values
* .orderBy("sku desc")
* .order("sku desc")
*
* // query expressions cover the natural key properties
* // so we can choose to hit the L2 bean cache if we want
+9 -21
View File
@@ -1,38 +1,36 @@
package io.ebean;
import io.ebean.config.properties.PropertiesLoader;
import io.avaje.config.Config;
import java.util.Properties;
/**
* Provides singleton state for the default server.
* Provides singleton state for the default database.
* <p/>
* Intended for internal use as part of bootup, construction, registration of the default server.
* Intended for internal use as part of bootup, construction, registration of the default database.
*/
class PrimaryServer {
private static Properties globalProperties;
private static String defaultServerName;
private static boolean skip;
/**
* Set whether to skip automatically creating the primary server.
* Set whether to skip automatically creating the primary database.
*/
static synchronized void setSkip(boolean skip) {
PrimaryServer.skip = skip;
}
/**
* Return true to skip automatically creating the primary server.
* Return true to skip automatically creating the primary database.
*/
static synchronized boolean isSkip() {
return skip;
}
/**
* Return the default server name.
* Return the default database name.
*/
static synchronized String getDefaultServerName() {
getProperties();
@@ -43,14 +41,10 @@ class PrimaryServer {
* Return the default configuration Properties.
*/
static synchronized Properties getProperties() {
if (globalProperties == null) {
globalProperties = PropertiesLoader.load();
}
if (defaultServerName == null) {
defaultServerName = determineDefaultServerName();
}
return globalProperties;
return Config.asProperties();
}
/**
@@ -62,15 +56,9 @@ class PrimaryServer {
defaultServerName = System.getProperty("db", defaultServerName);
defaultServerName = System.getProperty("ebean_db", defaultServerName);
if (isEmpty(defaultServerName)) {
defaultServerName = System.getProperty("datasource.default");
defaultServerName = Config.get("datasource.default", null);
if (isEmpty(defaultServerName)) {
defaultServerName = System.getProperty("ebean.default.datasource");
if (isEmpty(defaultServerName)) {
defaultServerName = globalProperties.getProperty("datasource.default");
if (isEmpty(defaultServerName)) {
defaultServerName = globalProperties.getProperty("ebean.default.datasource");
}
}
defaultServerName = Config.get("ebean.default.datasource", null);
}
}
if (defaultServerName == null) {
+17 -2
View File
@@ -31,9 +31,9 @@ public interface ProfileLocation {
}
/**
* Obtain the location description.
* Obtain the description returning true if this is the initial call.
*/
String obtain();
boolean obtain();
/**
* Return a short version of the location description.
@@ -45,8 +45,23 @@ public interface ProfileLocation {
*/
String label();
/**
* Return the full location.
*/
String fullLocation();
/**
* Add execution time.
*/
void add(long executionTime);
/**
* Return true if this request should be traced.
*/
boolean trace();
/**
* Set the number of times to trace the transactions for this profile location.
*/
void setTraceCount(int traceCount);
}
+38 -48
View File
@@ -25,7 +25,7 @@ import java.util.stream.Stream;
* .where()
* .like("customer.name","rob%")
* .gt("orderDate",lastWeek)
* .orderBy("customer.id, id desc")
* .order("customer.id, id desc")
* .setMaxRows(50)
* .findList();
*
@@ -656,6 +656,11 @@ public interface Query<T> {
*/
Query<T> usingConnection(Connection connection);
/**
* Execute the query using the given database.
*/
Query<T> usingDatabase(Database database);
/**
* Execute the query returning the list of Id's.
* <p>
@@ -885,7 +890,7 @@ public interface Query<T> {
* List<String> names =
* DB.find(Customer.class)
* .select("name")
* .orderBy().asc("name")
* .order().asc("name")
* .findSingleAttributeList();
*
* }</pre>
@@ -898,7 +903,7 @@ public interface Query<T> {
* .setDistinct(true)
* .select("name")
* .where().eq("status", Customer.Status.NEW)
* .orderBy().asc("name")
* .order().asc("name")
* .setMaxRows(100)
* .findSingleAttributeList();
*
@@ -1183,6 +1188,30 @@ public interface Query<T> {
*/
Query<T> setParameter(int position, Object value);
/**
* Bind the next positioned parameter.
*
* <pre>{@code
*
* // a query with a positioned parameters
* String oql = "where status = ? and name = ?";
*
* List<Order> list = DB.createQuery(Order.class, oql)
* .setParameter(OrderStatus.NEW)
* .setParameter("Rob")
* .findList();
*
* }</pre>
*/
Query<T> setParameter(Object value);
/**
* Bind all the positioned parameters.
* <p>
* A convenience for multiple calls to {@link #setParameter(Object)}
*/
Query<T> setParameters(Object... values);
/**
* Set the Id value to query. This is used with findOne().
* <p>
@@ -1323,17 +1352,9 @@ public interface Query<T> {
Query<T> having(Expression addExpressionToHaving);
/**
* Set the order by clause replacing the existing order by clause if there is
* one.
* <p>
* This follows SQL syntax using commas between each property with the
* optional asc and desc keywords representing ascending and descending order
* respectively.
* </p>
* <p>
* This is EXACTLY the same as {@link #order(String)}.
* </p>
* Deprecated migrate to {@link #order(String)}
*/
@Deprecated
Query<T> orderBy(String orderByClause);
/**
@@ -1343,10 +1364,6 @@ public interface Query<T> {
* This follows SQL syntax using commas between each property with the
* optional asc and desc keywords representing ascending and descending order
* respectively.
* </p>
* <p>
* This is EXACTLY the same as {@link #orderBy(String)}.
* </p>
*/
Query<T> order(String orderByClause);
@@ -1356,40 +1373,24 @@ public interface Query<T> {
* <p>
* This will never return a null. If no order by clause exists then an 'empty'
* OrderBy object is returned.
* </p>
* <p>
* This is EXACTLY the same as {@link #orderBy()}.
* </p>
*/
OrderBy<T> order();
/**
* Return the OrderBy so that you can append an ascending or descending
* property to the order by clause.
* <p>
* This will never return a null. If no order by clause exists then an 'empty'
* OrderBy object is returned.
* </p>
* <p>
* This is EXACTLY the same as {@link #order()}.
* </p>
* Deprecated migrate to order().
*/
@Deprecated
OrderBy<T> orderBy();
/**
* Set an OrderBy object to replace any existing OrderBy clause.
* <p>
* This is EXACTLY the same as {@link #setOrderBy(OrderBy)}.
* </p>
*/
Query<T> setOrder(OrderBy<T> orderBy);
/**
* Set an OrderBy object to replace any existing OrderBy clause.
* <p>
* This is EXACTLY the same as {@link #setOrder(OrderBy)}.
* </p>
* Deprecated migrate to {@link #setOrder(OrderBy)}
*/
@Deprecated
Query<T> setOrderBy(OrderBy<T> orderBy);
/**
@@ -1524,17 +1525,6 @@ public interface Query<T> {
return setUseQueryCache(enabled ? CacheMode.ON : CacheMode.OFF);
}
/**
* Set an id to identify this query for profiling purposes.
* <p>
* The profileId is expected to be unique for a given bean type.
* </p>
* <p>
* Note that the profileId is treated as a short internally and has a MAX value of 32,767.
* </p>
*/
Query<T> setProfileId(int profileId);
/**
* Set the profile location of this query. This is used to relate query execution metrics
* back to a location like a specific line of code.
+2 -2
View File
@@ -23,9 +23,9 @@ import java.util.Iterator;
* <h3>Try finally style</h3>
* <pre>{@code
*
* Query<Customer> query = server.find(Customer.class)
* Query<Customer> query = database.find(Customer.class)
* .where().gt("id", 0)
* .orderBy("id")
* .order("id")
* .setMaxRows(2);
*
* QueryIterator<Customer> it = query.findIterate();
+3 -2
View File
@@ -18,7 +18,7 @@ import java.sql.SQLException;
* <pre>{@code
*
* //
* // A mapper from ResultSet into our CustomerDto bean
* // Map from ResultSet to CustomerDto bean
* //
* class CustomerMapper implements RowMapper<CustomerDto> {
*
@@ -42,7 +42,8 @@ import java.sql.SQLException;
*
* CustomerDto rob = DB.sqlQuery(sql)
* .setParameter(1, "Rob")
* .findOne(CUSTOMER_MAPPER);
* .mapTo(CUSTOMER_MAPPER)
* .findOne();
*
*
* }</pre>
+131 -62
View File
@@ -75,17 +75,15 @@ public interface SqlQuery extends Serializable {
SqlRow findOne();
/**
* Execute the query returning a single result using the mapper.
*
* @param mapper Used to map each ResultSet row into the result object.
* Deprecated migrate to use {@link #mapTo(RowMapper)}
*/
@Deprecated
<T> T findOne(RowMapper<T> mapper);
/**
* Execute the query returning a list using the mapper.
*
* @param mapper Used to map each ResultSet row into the result object.
* Deprecated migrate to use {@link #mapTo(RowMapper)}
*/
@Deprecated
<T> List<T> findList(RowMapper<T> mapper);
/**
@@ -125,77 +123,53 @@ public interface SqlQuery extends Serializable {
Optional<SqlRow> findOneOrEmpty();
/**
* Execute the query returning a single scalar attribute.
* <pre>@{code
* Deprecated - migrate to <code>.mapToScalar(attributeType).findOne()</code>.
* <pre>{@code
*
* String sql = "select max(unit_price) from o_order_detail where order_qty > ?";
*
* BigDecimal maxPrice = DB.sqlQuery(sql)
* .setParameter(1, 2)
* .findSingleAttribute(BigDecimal.class);
*
* }</pre>
*
* <p>
* The attributeType can be any scalar type that Ebean supports (includes javax time types, Joda types etc).
* </p>
*
* @param attributeType The type of the returned value
* .mapToScalar(BigDecimal.class)
* .findOne();
* }
*/
@Deprecated
<T> T findSingleAttribute(Class<T> attributeType);
/**
* Execute the query returning a single BigDecimal value.
* <p>
* This is an alias for <code>findSingleAttribute(BigDecimal.class)</code>
* </p>
* Deprecated - migrate to <code>.mapToScalar(BigDecimal.class).findOne()</code>.
* <pre>{@code
*
* .mapToScalar(BigDecimal.class)
* .findOne();
* }
*/
@Deprecated
BigDecimal findSingleDecimal();
/**
* Execute the query returning a single Long value.
* <p>
* This is an alias for <code>findSingleAttribute(Long.class)</code>
* </p>
* Deprecated - migrate to <code>.mapToScalar(Long.class).findOne()</code>.
* <pre>{@code
*
* .mapToScalar(Long.class)
* .findOne();
* }
*/
@Deprecated
Long findSingleLong();
/**
* Execute the query returning a list of scalar attribute values.
*
* Deprecated - migrate to <code>.mapToScalar(Long.class).findList()</code>.
* <pre>{@code
*
* String sql =
* " select (unit_price * order_qty) " +
* " from o_order_detail " +
* " where unit_price > ? " +
* " order by (unit_price * order_qty) desc";
*
* //
* List<BigDecimal> lineAmounts =
* DB.sqlQuery(sql)
* .setParameter(1, 3)
* .findSingleAttributeList(BigDecimal.class);
*
* }</pre>
*
* <p>
* The attributeType can be any scalar type that Ebean supports (includes javax time types, Joda types etc).
* </p>
*
* @param attributeType The type of the returned value
* .mapToScalar(Long.class)
* .findList();
* }
*/
@Deprecated
<T> List<T> findSingleAttributeList(Class<T> attributeType);
/**
* The same as bind for named parameters.
*/
SqlQuery setParameter(String name, Object value);
/**
* Set one of more positioned parameters.
* <p>
* This is a convenient alternative to multiple calls setParameter().
* This is a convenient alternative to multiple calls to {@link #setParameter(Object)}.
*
* <pre>{@code
*
@@ -203,27 +177,67 @@ public interface SqlQuery extends Serializable {
*
* List<SqlRow> list =
* DB.sqlQuery(sql)
* .setParams("Rob", Status.NEW)
* .setParameters("Rob", Status.NEW)
* .findList();
*
*
* // is the same as ...
* // effectively the same as ...
*
* .setParameter("Rob")
* .setParameter("Status.NEW)
*
* // and ...
*
* List<SqlRow> list =
* DB.sqlQuery(sql)
* .setParameter(1, "Rob")
* .setParameter(2, "Status.NEW)
* .findList();
*
* }</pre>
*/
SqlQuery setParameters(Object... values);
/**
* Deprecated migrate to setParameters(Object... values)
*/
@Deprecated
SqlQuery setParams(Object... values);
/**
* The same as bind for positioned parameters.
* Set the next bind parameter by position.
* <pre>{@code
*
* String sql = "select id, name from customer where name like ? and status = ?";
*
* List<SqlRow> list =
* DB.sqlQuery(sql)
* .setParameter("Rob")
* .setParameter("Status.NEW)
* .findList();
*
* // the same as ...
*
* .setParameters("Rob", Status.NEW)
*
* // and ...
*
* .setParameter(1, "Rob")
* .setParameter(2, "Status.NEW)
*
* }</pre>
*
* @param value The value to bind
*/
SqlQuery setParameter(Object value);
/**
* Bind the parameter by its index position (1 based like JDBC).
*/
SqlQuery setParameter(int position, Object value);
/**
* Bind the named parameter value.
*/
SqlQuery setParameter(String name, Object value);
/**
* Set the index of the first row of the results to return.
*/
@@ -260,4 +274,59 @@ public interface SqlQuery extends Serializable {
*/
SqlQuery setBufferFetchSizeHint(int bufferFetchSizeHint);
/**
* The query result maps to a single scalar value like Long, BigDecimal,
* String, UUID, OffsetDateTime etc.
* <p>
* Any scalar type Ebean is aware of can be used including java time
* types like Instant, LocalDate, OffsetDateTime, UUID, Inet, Cdir etc.
*
* <pre>{@code
*
* String sql = " select min(updtime) from o_order_detail " +
* " where unit_price > ? and updtime is not null ";
*
* OffsetDateTime minCreated = DB.sqlQuery(sql)
* .setParameter(42)
* .mapToScalar(OffsetDateTime.class)
* .findOne();
*
* }</pre>
*
* @param attributeType The type the result is returned as
* @return The query to execute via findOne() findList() etc
*/
<T> TypeQuery<T> mapToScalar(Class<T> attributeType);
/**
* Use a RowMapper to map the result to beans.
*
* @param mapper Maps rows to beans
* @param <T> The type of beans mapped to
* @return The query to execute by findOne() findList() etc
*/
<T> TypeQuery<T> mapTo(RowMapper<T> mapper);
/**
* Query mapping to single scalar values.
*
* @param <T> The type of the scalar values
*/
interface TypeQuery<T> {
/**
* Return the single value.
*/
T findOne();
/**
* Return the single value that is optional.
*/
Optional<T> findOneOrEmpty();
/**
* Return the list of values.
*/
List<T> findList();
}
}
+22 -3
View File
@@ -239,28 +239,47 @@ public interface SqlUpdate {
* String sql = "insert into audit_log (id, name, version) values (?,?,?)";
*
* DB.sqlUpdate(sql)
* .setParams(UUID.randomUUID(), "Hello", 1)
* .setParameters(UUID.randomUUID(), "Hello", 1)
* .executeNow();
*
*
* // is the same as ...
*
* DB.sqlUpdate(sql)
* .setParameter(UUID.randomUUID())
* .setParameter("Hello")
* .setParameter(1)
* .executeNow();
*
* // which is the same as ...
*
* DB.sqlUpdate(sql)
* .setParameter(1, UUID.randomUUID())
* .setParameter(2, "Hello")
* .setParameter(3, 1)
* .executeNow();
*
* }</pre>
*
*/
SqlUpdate setParameters(Object... values);
/**
* Deprecated migrate to setParameters(Object... values).
*/
@Deprecated
SqlUpdate setParams(Object... values);
/**
* Set the next positioned parameter.
* Set the next bind parameter by position.
*
* @param value The value to bind
*/
SqlUpdate setParameter(Object value);
/**
* Deprecated migrate to setParameter(value).
*/
@Deprecated
SqlUpdate setNextParameter(Object value);
/**
+2 -2
View File
@@ -295,7 +295,7 @@ public interface Transaction extends AutoCloseable {
*
* <pre>{@code
*
* try (Transaction transaction = server.beginTransaction()) {
* try (Transaction transaction = database.beginTransaction()) {
*
* // turn on JDBC batch
* transaction.setBatchMode(true);
@@ -318,7 +318,7 @@ public interface Transaction extends AutoCloseable {
* </p>
* <pre>{@code
*
* try (Transaction transaction = server.beginTransaction()) {
* try (Transaction transaction = database.beginTransaction()) {
*
* transaction.setBatchMode(true);
* transaction.setBatchSize(100);
@@ -29,7 +29,7 @@ public class DocStoreConfig {
protected boolean create;
/**
* The URL of the Document store server. For example: http://localhost:9200.
* The URL of the Document store. For example: http://localhost:9200.
*/
protected String url;
@@ -131,7 +131,7 @@ public class DocStoreConfig {
}
/**
* Set the URL to the Document store server.
* Set the URL to the Document store.
* <p>
* For a local ElasticSearch server this would be: http://localhost:9200
*/
@@ -34,11 +34,6 @@ public class PlatformConfig {
*/
private String databaseBooleanFalse;
/**
* For DB's using sequences this is the number of sequence values prefetched.
*/
private int databaseSequenceBatchSize = 20;
/**
* Set for DB's that support both Sequence and Identity (and the default choice is not desired).
*/
@@ -79,7 +74,6 @@ public class PlatformConfig {
public PlatformConfig(PlatformConfig platformConfig) {
this.databaseBooleanFalse = platformConfig.databaseBooleanFalse;
this.databaseBooleanTrue = platformConfig.databaseBooleanTrue;
this.databaseSequenceBatchSize = platformConfig.databaseSequenceBatchSize;
this.idType = platformConfig.idType;
this.geometrySRID = platformConfig.geometrySRID;
this.dbUuid = platformConfig.dbUuid;
@@ -173,20 +167,6 @@ public class PlatformConfig {
this.databaseBooleanFalse = databaseBooleanFalse;
}
/**
* Return the number of DB sequence values that should be preallocated.
*/
public int getDatabaseSequenceBatchSize() {
return databaseSequenceBatchSize;
}
/**
* Set the number of DB sequence values that should be preallocated.
*/
public void setDatabaseSequenceBatchSize(int databaseSequenceBatchSize) {
this.databaseSequenceBatchSize = databaseSequenceBatchSize;
}
/**
* Return the Geometry SRID.
*/
@@ -294,7 +274,6 @@ public class PlatformConfig {
public void loadSettings(PropertiesWrapper p) {
idType = p.getEnum(IdType.class, "idType", idType);
databaseSequenceBatchSize = p.getInt("databaseSequenceBatchSize", databaseSequenceBatchSize);
databaseBooleanTrue = p.get("databaseBooleanTrue", databaseBooleanTrue);
databaseBooleanFalse = p.get("databaseBooleanFalse", databaseBooleanFalse);
databaseInetAddressVarchar = p.getBoolean("databaseInetAddressVarchar", databaseInetAddressVarchar);
@@ -1,6 +1,7 @@
package io.ebean.config;
import com.fasterxml.jackson.core.JsonFactory;
import io.avaje.config.Config;
import io.ebean.DatabaseFactory;
import io.ebean.PersistenceContextScope;
import io.ebean.Query;
@@ -13,7 +14,6 @@ import io.ebean.config.dbplatform.DatabasePlatform;
import io.ebean.config.dbplatform.DbEncrypt;
import io.ebean.config.dbplatform.DbType;
import io.ebean.config.dbplatform.IdType;
import io.ebean.config.properties.PropertiesLoader;
import io.ebean.datasource.DataSourceConfig;
import io.ebean.event.BeanFindController;
import io.ebean.event.BeanPersistController;
@@ -1050,18 +1050,6 @@ public class ServerConfig {
this.lazyLoadBatchSize = lazyLoadBatchSize;
}
/**
* Set the number of sequences to fetch/preallocate when using DB sequences.
* <p>
* This is a performance optimisation to reduce the number times Ebean
* requests a sequence to be used as an Id for a bean (aka reduce network
* chatter).
* </p>
*/
public void setDatabaseSequenceBatchSize(int databaseSequenceBatchSize) {
platformConfig.setDatabaseSequenceBatchSize(databaseSequenceBatchSize);
}
/**
* Return the default JDBC fetchSize hint for findList queries.
*/
@@ -1828,32 +1816,6 @@ public class ServerConfig {
this.platformConfig.setDatabaseBooleanFalse(databaseFalse);
}
/**
* Return the number of DB sequence values that should be preallocated.
*/
public int getDatabaseSequenceBatchSize() {
return platformConfig.getDatabaseSequenceBatchSize();
}
/**
* Set the number of DB sequence values that should be preallocated and cached
* by Ebean.
* <p>
* This is only used for DB's that use sequences and is a performance
* optimisation. This reduces the number of times Ebean needs to get a
* sequence value from the Database reducing network chatter.
* </p>
* <p>
* By default this value is 10 so when we need another Id (and don't have one
* in our cache) Ebean will fetch 10 id's from the database. Note that when
* the cache drops to have full (which is 5 by default) Ebean will fetch
* another batch of Id's in a background thread.
* </p>
*/
public void setDatabaseSequenceBatch(int databaseSequenceBatchSize) {
this.platformConfig.setDatabaseSequenceBatchSize(databaseSequenceBatchSize);
}
/**
* Return the database platform name (can be null).
* <p>
@@ -1886,7 +1848,7 @@ public class ServerConfig {
}
/**
* Return the database platform to use for this server.
* Return the database platform to use for this database.
*/
public DatabasePlatform getDatabasePlatform() {
return databasePlatform;
@@ -2282,7 +2244,7 @@ public class ServerConfig {
* </p>
*
* @param cls the entity type (or other type) that should be registered by this
* server.
* database.
*/
public void addClass(Class<?> cls) {
classes.add(cls);
@@ -2329,7 +2291,7 @@ public class ServerConfig {
/**
* Set the list of classes (entities, listeners, scalarTypes etc) that should
* be used for this server.
* be used for this database.
* <p>
* If no classes are specified then the classes are found automatically via
* searching the class path.
@@ -2343,7 +2305,7 @@ public class ServerConfig {
}
/**
* Return the classes registered for this server. Typically this includes
* Return the classes registered for this database. Typically this includes
* entities and perhaps listeners.
*/
public List<Class<?>> getClasses() {
@@ -2746,7 +2708,7 @@ public class ServerConfig {
* Load settings from ebean.properties.
*/
public void loadFromProperties() {
this.properties = PropertiesLoader.load();
this.properties = Config.asProperties();
configureFromProperties();
}
@@ -2755,7 +2717,7 @@ public class ServerConfig {
*/
public void loadFromProperties(Properties properties) {
// keep the properties used for configuration so that these are available for plugins
this.properties = PropertiesLoader.eval(properties);
this.properties = Config.asConfiguration().eval(properties);
configureFromProperties();
}
@@ -110,10 +110,6 @@ public class DatabasePlatform {
*/
protected DbIdentity dbIdentity = new DbIdentity();
protected boolean sequenceBatchMode = true;
protected int sequenceBatchSize = 20;
/**
* The history support for this database platform.
*/
@@ -235,7 +231,6 @@ public class DatabasePlatform {
* Configure the platform given the server configuration.
*/
public void configure(PlatformConfig config) {
this.sequenceBatchSize = config.getDatabaseSequenceBatchSize();
this.caseSensitiveCollation = config.isCaseSensitiveCollation();
configureIdType(config.getIdType());
configure(config, config.isAllQuotedIdentifiers());
@@ -278,7 +273,7 @@ public class DatabasePlatform {
* Return true if this matches the given platform.
*/
public boolean isPlatform(Platform platform) {
return this.platform == platform;
return this.platform.base() == platform;
}
/**
@@ -298,20 +293,6 @@ public class DatabasePlatform {
return platform.name().toLowerCase();
}
/**
* Return true if we are using Sequence batch mode rather than STEP.
*/
public boolean isSequenceBatchMode() {
return sequenceBatchMode;
}
/**
* Set to false to not use sequence batch mode but instead STEP mode.
*/
public void setSequenceBatchMode(boolean sequenceBatchMode) {
this.sequenceBatchMode = sequenceBatchMode;
}
/**
* Return true if this database platform supports native ILIKE expression.
*/
@@ -381,13 +362,13 @@ public class DatabasePlatform {
/**
* Return a DB Sequence based IdGenerator.
*
* @param be the BackgroundExecutor that can be used to load the sequence if
* desired
* @param ds the DataSource
* @param stepSize the sequence allocation size as defined by mapping (defaults to 50)
* @param seqName the name of the sequence
* @param be the BackgroundExecutor that can be used to load the sequence if
* desired
* @param ds the DataSource
* @param increment the sequence allocation size as defined by mapping (defaults to 50)
* @param seqName the name of the sequence
*/
public PlatformIdGenerator createSequenceIdGenerator(BackgroundExecutor be, DataSource ds, int stepSize, String seqName) {
public PlatformIdGenerator createSequenceIdGenerator(BackgroundExecutor be, DataSource ds, int increment, String seqName) {
return null;
}
@@ -35,6 +35,11 @@ public enum IdType {
* Used when the key is a compound key or lookup table code.
* </p>
*/
EXTERNAL
EXTERNAL,
/**
* Auto mapping to platform preferred identity strategy.
*/
AUTO
}
@@ -40,8 +40,7 @@ public class LimitOffsetSqlLimiter implements SqlLimiter {
}
String sql = request.getDbPlatform().completeSql(sb.toString(), request.getOrmQuery());
return new SqlLimitResponse(sql, false);
return new SqlLimitResponse(sql);
}
}
@@ -1,75 +0,0 @@
package io.ebean.config.dbplatform;
/**
* Adds the ROW_NUMBER() OVER function to a query.
*/
public class RowNumberSqlLimiter implements SqlLimiter {
/**
* ROW_NUMBER() OVER (ORDER BY
*/
private static final String ROW_NUMBER_OVER = "row_number() over (order by ";
/**
* ) as rn,
*/
private static final String ROW_NUMBER_AS = ") as rn, ";
private final String rowNumberWindowAlias;
/**
* Specify the name of the rowNumberWindowAlias.
*/
public RowNumberSqlLimiter(String rowNumberWindowAlias) {
this.rowNumberWindowAlias = rowNumberWindowAlias;
}
public RowNumberSqlLimiter() {
this("as limitresult");
}
@Override
public SqlLimitResponse limit(SqlLimitRequest request) {
String dbSql = request.getDbSql();
StringBuilder sb = new StringBuilder(60 + dbSql.length());
int firstRow = request.getFirstRow();
int lastRow = request.getMaxRows();
if (lastRow > 0) {
lastRow += firstRow;
}
sb.append("select * from ( ");
sb.append("select ");
if (request.isDistinct()) {
sb.append("distinct ");
}
sb.append(ROW_NUMBER_OVER);
sb.append(request.getDbOrderBy());
sb.append(ROW_NUMBER_AS);
sb.append(dbSql);
sb.append(" ) ");
sb.append(rowNumberWindowAlias);
sb.append(" where ");
if (firstRow > 0) {
sb.append(" rn > ").append(firstRow);
if (lastRow > 0) {
sb.append(" and ");
}
}
if (lastRow > 0) {
sb.append(" rn <= ").append(lastRow);
}
String sql = request.getDbPlatform().completeSql(sb.toString(), request.getOrmQuery());
return new SqlLimitResponse(sql, true);
}
}
@@ -1,81 +0,0 @@
package io.ebean.config.dbplatform;
/**
* Add ROWNUM column etc around SQL query to limit results.
*/
public class RownumSqlLimiter implements SqlLimiter {
private final String rnum;
private final boolean useFirstRowsHint;
/**
* Create with default inner rownum column alias and used FIRST_ROWS hint.
*/
public RownumSqlLimiter() {
this("rn_", true);
}
/**
* Specify the inner rownum column alias and whether to include the FIRST_ROWS
* hint.
*/
public RownumSqlLimiter(String rnum, boolean useFirstRowsHint) {
this.rnum = rnum;
this.useFirstRowsHint = useFirstRowsHint;
}
@Override
public SqlLimitResponse limit(SqlLimitRequest request) {
// select *
// from ( select /*+ FIRST_ROWS(n) */ ROWNUM rnum, a.*
// from ( your_query_goes_here,
// with order by ) a
// where ROWNUM <=
// :MAX_ROW_TO_FETCH )
// where rnum >= :MIN_ROW_TO_FETCH;
String dbSql = request.getDbSql();
StringBuilder sb = new StringBuilder(60 + dbSql.length());
int firstRow = request.getFirstRow();
int lastRow = request.getMaxRows();
if (lastRow > 0) {
lastRow += firstRow;
}
sb.append("select * from ( ");
sb.append("select ");
if (useFirstRowsHint && request.getMaxRows() > 0) {
sb.append("/*+ FIRST_ROWS(").append(request.getMaxRows()).append(") */ ");
}
sb.append("rownum ").append(rnum).append(", a.* ");
sb.append(" from (");
sb.append(" select ");
if (request.isDistinct()) {
sb.append("distinct ");
}
sb.append(dbSql);
sb.append(NEW_LINE).append(" ) a ");
if (lastRow > 0) {
sb.append(" where rownum <= ").append(lastRow);
}
sb.append(" ) ");
if (firstRow > 0) {
sb.append(" where ");
sb.append(rnum).append(" > ").append(firstRow);
}
String sql = request.getDbPlatform().completeSql(sb.toString(), request.getOrmQuery());
return new SqlLimitResponse(sql, true);
}
}
@@ -1,57 +0,0 @@
package io.ebean.config.dbplatform;
import io.ebean.BackgroundExecutor;
import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* Database sequence based IdGenerator using Sequence Step 1 but batch fetch many sequence values.
*/
public abstract class SequenceBatchIdGenerator extends SequenceIdGenerator {
/**
* Construct where batchSize is the sequence step size.
*
*/
public SequenceBatchIdGenerator(BackgroundExecutor be, DataSource ds, String seqName, int batchSize) {
super(be, ds, seqName, batchSize);
}
/**
* If allocateSize is large load some sequences in a background thread.
* <p>
* For example, when inserting a bean with a cascade on a OneToMany with many
* beans Ebean can call this to ensure .
* </p>
*/
@Override
public void preAllocateIds(int requestSize) {
if (allocationSize > 1 && requestSize > allocationSize) {
// only bother if allocateSize is bigger than
// the normal loading batchSize
if (requestSize > 100) {
// max out at 100 for now
requestSize = 100;
}
loadInBackground(requestSize);
}
}
/**
* Add the next set of Ids as the next value plus all the following numbers up to the step size.
*/
@Override
protected List<Long> readIds(ResultSet resultSet, int loadSize) throws SQLException {
List<Long> newIds = new ArrayList<>(loadSize);
while (resultSet.next()) {
newIds.add(resultSet.getLong(1));
}
return newIds;
}
}
@@ -59,7 +59,7 @@ public abstract class SequenceIdGenerator implements PlatformIdGenerator {
this.allocationSize = allocationSize;
}
public abstract String getSql(int batchSize);
public abstract String getSql();
/**
* Returns the sequence name.
@@ -102,7 +102,7 @@ public abstract class SequenceIdGenerator implements PlatformIdGenerator {
if (size > 0) {
maybeLoadMoreInBackground(size);
} else {
loadMore(allocationSize);
loadMore();
}
return idList.pollFirst();
}
@@ -116,8 +116,8 @@ public abstract class SequenceIdGenerator implements PlatformIdGenerator {
}
}
private void loadMore(int requestSize) {
List<Long> newIds = getMoreIds(requestSize);
private void loadMore() {
List<Long> newIds = getMoreIds();
synchronized (monitor) {
idList.addAll(newIds);
}
@@ -139,7 +139,7 @@ public abstract class SequenceIdGenerator implements PlatformIdGenerator {
currentlyBackgroundLoading = true;
backgroundExecutor.execute(() -> {
loadMore(requestSize);
loadMore();
synchronized (backgroundLoadMonitor) {
currentlyBackgroundLoading = false;
}
@@ -150,14 +150,14 @@ public abstract class SequenceIdGenerator implements PlatformIdGenerator {
/**
* Read the resultSet returning the list of Id values.
*/
protected abstract List<Long> readIds(ResultSet resultSet, int loadSize) throws SQLException;
protected abstract List<Long> readIds(ResultSet resultSet) throws SQLException;
/**
* Get more Id's by executing a query and reading the Id's returned.
*/
protected List<Long> getMoreIds(int requestSize) {
protected List<Long> getMoreIds() {
String sql = getSql(requestSize);
String sql = getSql();
Connection connection = null;
PreparedStatement statement = null;
@@ -168,7 +168,7 @@ public abstract class SequenceIdGenerator implements PlatformIdGenerator {
statement = connection.prepareStatement(sql);
resultSet = statement.executeQuery();
List<Long> newIds = readIds(resultSet, requestSize);
List<Long> newIds = readIds(resultSet);
if (logger.isTraceEnabled()) {
logger.trace("seq:{} loaded:{} sql:{}", seqName, newIds.size(), sql);
}
@@ -13,19 +13,25 @@ import java.util.List;
*/
public abstract class SequenceStepIdGenerator extends SequenceIdGenerator {
private final String nextSql;
/**
* Construct with stepSize (typically 50).
*/
protected SequenceStepIdGenerator(BackgroundExecutor be, DataSource ds, String seqName, int stepSize) {
protected SequenceStepIdGenerator(BackgroundExecutor be, DataSource ds, String seqName, int stepSize, String nextSql) {
super(be, ds, seqName, stepSize);
this.nextSql = nextSql;
}
@Override
public String getSql() {
return nextSql;
}
/**
* Add the next set of Ids as the next value plus all the following numbers up to the step size.
*/
@Override
protected List<Long> readIds(ResultSet resultSet, int ignoreRequestSize) throws SQLException {
protected List<Long> readIds(ResultSet resultSet) throws SQLException {
List<Long> newIds = new ArrayList<>(allocationSize);
if (resultSet.next()) {
long start = resultSet.getLong(1);
@@ -7,14 +7,11 @@ public class SqlLimitResponse {
final String sql;
final boolean includesRowNumberColumn;
/**
* Create the response.
*/
public SqlLimitResponse(String sql, boolean includesRowNumberColumn) {
public SqlLimitResponse(String sql) {
this.sql = sql;
this.includesRowNumberColumn = includesRowNumberColumn;
}
/**
@@ -24,11 +21,4 @@ public class SqlLimitResponse {
return sql;
}
/**
* Returns true if a ROW_NUMBER column is used in the query.
*/
public boolean isIncludesRowNumberColumn() {
return includesRowNumberColumn;
}
}
@@ -52,9 +52,8 @@ public class DB2Platform extends DatabasePlatform {
* sequence values.
*/
@Override
public PlatformIdGenerator createSequenceIdGenerator(BackgroundExecutor be, DataSource ds, int stepSize, String seqName) {
return new DB2SequenceIdGenerator(be, ds, seqName, sequenceBatchSize);
public PlatformIdGenerator createSequenceIdGenerator(BackgroundExecutor be, DataSource ds, int increment, String seqName) {
return new DB2Sequence(be, ds, seqName, increment);
}
}
@@ -0,0 +1,17 @@
package io.ebean.config.dbplatform.db2;
import io.ebean.BackgroundExecutor;
import io.ebean.config.dbplatform.SequenceStepIdGenerator;
import javax.sql.DataSource;
/**
* DB2 specific sequence Id Generator.
*/
class DB2Sequence extends SequenceStepIdGenerator {
DB2Sequence(BackgroundExecutor be, DataSource ds, String seqName, int stepSize) {
super(be, ds, seqName, stepSize, "values nextval for " + seqName);
}
}
@@ -1,35 +0,0 @@
package io.ebean.config.dbplatform.db2;
import io.ebean.BackgroundExecutor;
import io.ebean.config.dbplatform.SequenceBatchIdGenerator;
import javax.sql.DataSource;
/**
* DB2 specific sequence Id Generator.
*/
public class DB2SequenceIdGenerator extends SequenceBatchIdGenerator {
private final String baseSql;
private final String unionBaseSql;
/**
* Construct given a dataSource and sql to return the next sequence value.
*/
public DB2SequenceIdGenerator(BackgroundExecutor be, DataSource ds, String seqName, int batchSize) {
super(be, ds, seqName, batchSize);
this.baseSql = "values nextval for " + seqName;
this.unionBaseSql = " union " + baseSql;
}
@Override
public String getSql(int batchSize) {
StringBuilder sb = new StringBuilder();
sb.append(baseSql);
for (int i = 1; i < batchSize; i++) {
sb.append(unionBaseSql);
}
return sb.toString();
}
}
@@ -22,6 +22,6 @@ public class Db2SqlLimiter implements SqlLimiter {
}
String sql = request.getDbPlatform().completeSql(sb.toString(), request.getOrmQuery());
return new SqlLimitResponse(sql, false);
return new SqlLimitResponse(sql);
}
}
@@ -0,0 +1,14 @@
package io.ebean.config.dbplatform.h2;
import io.ebean.BackgroundExecutor;
import io.ebean.config.dbplatform.SequenceStepIdGenerator;
import javax.sql.DataSource;
class H2DbSequence extends SequenceStepIdGenerator {
H2DbSequence(BackgroundExecutor be, DataSource ds, String seqName, int stepSize) {
super(be, ds, seqName, stepSize, "select " + seqName + ".nextval");
}
}
@@ -42,13 +42,9 @@ public class H2Platform extends DatabasePlatform {
dbTypeMap.put(DbType.UUID, new DbPlatformType("uuid", false));
}
/**
* Return a H2 specific sequence IdGenerator that supports batch fetching
* sequence values.
*/
@Override
public PlatformIdGenerator createSequenceIdGenerator(BackgroundExecutor be, DataSource ds, int stepSize, String seqName) {
return new H2SequenceIdGenerator(be, ds, seqName, sequenceBatchSize);
public PlatformIdGenerator createSequenceIdGenerator(BackgroundExecutor be, DataSource ds, int increment, String seqName) {
return new H2DbSequence(be, ds, seqName, increment);
}
@Override
@@ -1,35 +0,0 @@
package io.ebean.config.dbplatform.h2;
import io.ebean.BackgroundExecutor;
import io.ebean.config.dbplatform.SequenceBatchIdGenerator;
import javax.sql.DataSource;
/**
* H2 specific sequence Id Generator.
*/
public class H2SequenceIdGenerator extends SequenceBatchIdGenerator {
private final String baseSql;
private final String unionBaseSql;
/**
* Construct given a dataSource and sql to return the next sequence value.
*/
public H2SequenceIdGenerator(BackgroundExecutor be, DataSource ds, String seqName, int batchSize) {
super(be, ds, seqName, batchSize);
this.baseSql = "select " + seqName + ".nextval";
this.unionBaseSql = " union " + baseSql;
}
@Override
public String getSql(int batchSize) {
StringBuilder sb = new StringBuilder();
sb.append(baseSql);
for (int i = 1; i < batchSize; i++) {
sb.append(unionBaseSql);
}
return sb.toString();
}
}
@@ -29,7 +29,6 @@ public class HanaSqlLimiter implements SqlLimiter {
}
String sql = request.getDbPlatform().completeSql(sb.toString(), request.getOrmQuery());
return new SqlLimitResponse(sql, false);
return new SqlLimitResponse(sql);
}
}
}
@@ -1,38 +0,0 @@
package io.ebean.config.dbplatform.hsqldb;
import io.ebean.BackgroundExecutor;
import io.ebean.annotation.Platform;
import io.ebean.config.dbplatform.DatabasePlatform;
import io.ebean.config.dbplatform.DbPlatformType;
import io.ebean.config.dbplatform.DbType;
import io.ebean.config.dbplatform.IdType;
import io.ebean.config.dbplatform.PlatformIdGenerator;
import io.ebean.config.dbplatform.h2.H2DbEncrypt;
import io.ebean.config.dbplatform.h2.H2SequenceIdGenerator;
import javax.sql.DataSource;
/**
* H2 specific platform.
*/
public class HsqldbPlatform extends DatabasePlatform {
public HsqldbPlatform() {
super();
this.platform = Platform.HSQLDB;
this.dbEncrypt = new H2DbEncrypt();
this.truncateTable = "delete from %s";
this.dbIdentity.setIdType(IdType.IDENTITY);
this.dbIdentity.setSupportsGetGeneratedKeys(true);
this.dbIdentity.setSupportsSequence(true);
this.dbIdentity.setSupportsIdentity(true);
dbTypeMap.put(DbType.INTEGER, new DbPlatformType("integer", false));
}
@Override
public PlatformIdGenerator createSequenceIdGenerator(BackgroundExecutor be, DataSource ds, int stepSize, String seqName) {
return new H2SequenceIdGenerator(be, ds, seqName, sequenceBatchSize);
}
}
@@ -1,4 +0,0 @@
/**
* Hsqldb specific support.
*/
package io.ebean.config.dbplatform.hsqldb;
@@ -44,8 +44,8 @@ public class NuoDbPlatform extends DatabasePlatform {
}
@Override
public PlatformIdGenerator createSequenceIdGenerator(BackgroundExecutor be, DataSource ds, int stepSize, String seqName) {
return new NuoDbSequence(be, ds, seqName, stepSize);
public PlatformIdGenerator createSequenceIdGenerator(BackgroundExecutor be, DataSource ds, int increment, String seqName) {
return new NuoDbSequence(be, ds, seqName, increment);
}
@Override
@@ -5,20 +5,10 @@ import io.ebean.config.dbplatform.SequenceStepIdGenerator;
import javax.sql.DataSource;
public class NuoDbSequence extends SequenceStepIdGenerator {
class NuoDbSequence extends SequenceStepIdGenerator {
private final String nextSql;
/**
* Construct where batchSize is the sequence step size.
*/
public NuoDbSequence(BackgroundExecutor be, DataSource ds, String seqName, int stepSize) {
super(be, ds, seqName, stepSize);
this.nextSql = "select next value for " + seqName + " from dual";
NuoDbSequence(BackgroundExecutor be, DataSource ds, String seqName, int stepSize) {
super(be, ds, seqName, stepSize, "select next value for " + seqName + " from dual");
}
@Override
public String getSql(int batchSize) {
return nextSql;
}
}
@@ -0,0 +1,16 @@
package io.ebean.config.dbplatform.oracle;
import io.ebean.annotation.Platform;
/**
* Oracle 11 platform using rownum sql limiting.
*/
public class Oracle11Platform extends OraclePlatform {
public Oracle11Platform() {
super();
this.platform = Platform.ORACLE11;
this.columnAliasPrefix = "c";
this.sqlLimiter = new OracleRownumSqlLimiter();
}
}
@@ -0,0 +1,34 @@
package io.ebean.config.dbplatform.oracle;
import io.ebean.config.dbplatform.SqlLimitRequest;
import io.ebean.config.dbplatform.SqlLimitResponse;
import io.ebean.config.dbplatform.SqlLimiter;
/**
* Use ANSI offset rows syntax.
*/
class OracleAnsiSqlRowsLimiter implements SqlLimiter {
@Override
public SqlLimitResponse limit(SqlLimitRequest request) {
String dbSql = request.getDbSql();
StringBuilder sb = new StringBuilder(50 + dbSql.length());
int firstRow = request.getFirstRow();
int maxRows = request.getMaxRows();
sb.append("select ");
if (request.isDistinct()) {
sb.append("distinct ");
}
sb.append(dbSql);
if (firstRow > 0) {
sb.append(" offset ").append(firstRow).append(" rows");
}
if (maxRows > 0) {
sb.append(" fetch next ").append(maxRows).append(" rows only");
}
return new SqlLimitResponse(sb.toString());
}
}
@@ -0,0 +1,14 @@
package io.ebean.config.dbplatform.oracle;
import io.ebean.BackgroundExecutor;
import io.ebean.config.dbplatform.SequenceStepIdGenerator;
import javax.sql.DataSource;
class OracleDbSequence extends SequenceStepIdGenerator {
OracleDbSequence(BackgroundExecutor be, DataSource ds, String seqName, int stepSize) {
super(be, ds, seqName, stepSize, "select " + seqName + ".nextval from dual");
}
}
@@ -9,7 +9,6 @@ import io.ebean.config.dbplatform.DbPlatformType;
import io.ebean.config.dbplatform.DbType;
import io.ebean.config.dbplatform.IdType;
import io.ebean.config.dbplatform.PlatformIdGenerator;
import io.ebean.config.dbplatform.RownumSqlLimiter;
import io.ebean.config.dbplatform.SqlErrorCodes;
import javax.sql.DataSource;
@@ -23,11 +22,12 @@ public class OraclePlatform extends DatabasePlatform {
public OraclePlatform() {
super();
this.platform = Platform.ORACLE;
this.columnAliasPrefix = null;
this.supportsDeleteTableAlias = true;
this.maxTableNameLength = 30;
this.maxConstraintNameLength = 30;
this.dbEncrypt = new OracleDbEncrypt();
this.sqlLimiter = new RownumSqlLimiter();
this.sqlLimiter = new OracleAnsiSqlRowsLimiter();
this.basicSqlLimiter = new BasicSqlAnsiLimiter();
this.historySupport = new OracleDbHistorySupport();
this.truncateTable = "truncate table %s cascade";
@@ -76,8 +76,8 @@ public class OraclePlatform extends DatabasePlatform {
}
@Override
public PlatformIdGenerator createSequenceIdGenerator(BackgroundExecutor be, DataSource ds, int stepSize, String seqName) {
return new OracleSequenceIdGenerator(be, ds, seqName, sequenceBatchSize);
public PlatformIdGenerator createSequenceIdGenerator(BackgroundExecutor be, DataSource ds, int increment, String seqName) {
return new OracleDbSequence(be, ds, seqName, increment);
}
@Override
@@ -0,0 +1,54 @@
package io.ebean.config.dbplatform.oracle;
import io.ebean.config.dbplatform.SqlLimitRequest;
import io.ebean.config.dbplatform.SqlLimitResponse;
import io.ebean.config.dbplatform.SqlLimiter;
/**
* Add ROWNUM column etc around SQL query to limit results.
*/
class OracleRownumSqlLimiter implements SqlLimiter {
@Override
public SqlLimitResponse limit(SqlLimitRequest request) {
// select *
// from ( select /*+ FIRST_ROWS(n) */ a.*, ROWNUM rnum
// from ( your_query_goes_here,
// with order by ) a
// where ROWNUM <=
// :MAX_ROW_TO_FETCH )
// where rnum >= :MIN_ROW_TO_FETCH;
String dbSql = request.getDbSql();
StringBuilder sb = new StringBuilder(60 + dbSql.length());
int firstRow = request.getFirstRow();
int lastRow = request.getMaxRows();
if (lastRow > 0) {
lastRow += firstRow;
}
sb.append("select * from (select ");
if (request.getMaxRows() > 0) {
sb.append("/*+ FIRST_ROWS(").append(request.getMaxRows()).append(") */ ");
}
sb.append("a.*, rownum rn_ from (select ");
if (request.isDistinct()) {
sb.append("distinct ");
}
sb.append(dbSql).append(") a ");
if (lastRow > 0) {
sb.append(" where rownum <= ").append(lastRow);
}
sb.append(") ");
if (firstRow > 0) {
sb.append(" where rn_ > ").append(firstRow);
}
String sql = request.getDbPlatform().completeSql(sb.toString(), request.getOrmQuery());
return new SqlLimitResponse(sql);
}
}
@@ -1,27 +0,0 @@
package io.ebean.config.dbplatform.oracle;
import io.ebean.BackgroundExecutor;
import io.ebean.config.dbplatform.SequenceBatchIdGenerator;
import javax.sql.DataSource;
/**
* Oracle specific sequence Id Generator.
*/
public class OracleSequenceIdGenerator extends SequenceBatchIdGenerator {
private final String baseSql;
/**
* Construct given a dataSource and sql to return the next sequence value.
*/
public OracleSequenceIdGenerator(BackgroundExecutor be, DataSource ds, String seqName, int batchSize) {
super(be, ds, seqName, batchSize);
this.baseSql = "select " + seqName + ".nextval, a from (select level as a FROM dual CONNECT BY level <= ";
}
@Override
public String getSql(int batchSize) {
return baseSql + batchSize + ")";
}
}
@@ -1,20 +0,0 @@
package io.ebean.config.dbplatform.postgres;
import io.ebean.config.dbplatform.IdType;
/**
* Postgres v8.3 specific platform.
* <p>
* No support for getGeneratedKeys.
* </p>
*/
public class Postgres8Platform extends PostgresPlatform {
public Postgres8Platform() {
super();
this.dbIdentity.setSupportsGetGeneratedKeys(false);
this.dbIdentity.setIdType(IdType.SEQUENCE);
this.columnAliasPrefix = "as c";
}
}
@@ -0,0 +1,14 @@
package io.ebean.config.dbplatform.postgres;
import io.ebean.annotation.Platform;
/**
* Postgres9 platform - uses serial type for identity columns.
*/
public class Postgres9Platform extends PostgresPlatform {
public Postgres9Platform() {
super();
this.platform = Platform.POSTGRES9;
}
}
@@ -0,0 +1,14 @@
package io.ebean.config.dbplatform.postgres;
import io.ebean.BackgroundExecutor;
import io.ebean.config.dbplatform.SequenceStepIdGenerator;
import javax.sql.DataSource;
class PostgresDbSequence extends SequenceStepIdGenerator {
PostgresDbSequence(BackgroundExecutor be, DataSource ds, String seqName, int stepSize) {
super(be, ds, seqName, stepSize, "select nextval('" + seqName + "')");
}
}
@@ -19,10 +19,9 @@ import java.sql.SQLException;
import java.sql.Types;
/**
* Postgres v9 specific platform.
* Postgres 10+ platform.
* <p>
* Uses serial types and getGeneratedKeys.
* </p>
* Defaults to use "generated by default as identity".
*/
public class PostgresPlatform extends DatabasePlatform {
@@ -110,9 +109,8 @@ public class PostgresPlatform extends DatabasePlatform {
* Create a Postgres specific sequence IdGenerator.
*/
@Override
public PlatformIdGenerator createSequenceIdGenerator(BackgroundExecutor be, DataSource ds, int stepSize, String seqName) {
return new PostgresSequenceIdGenerator(be, ds, seqName, sequenceBatchSize);
public PlatformIdGenerator createSequenceIdGenerator(BackgroundExecutor be, DataSource ds, int increment, String seqName) {
return new PostgresDbSequence(be, ds, seqName, increment);
}
@Override
@@ -1,27 +0,0 @@
package io.ebean.config.dbplatform.postgres;
import io.ebean.BackgroundExecutor;
import io.ebean.config.dbplatform.SequenceBatchIdGenerator;
import javax.sql.DataSource;
/**
* Postgres specific sequence Id Generator.
*/
public class PostgresSequenceIdGenerator extends SequenceBatchIdGenerator {
private final String baseSql;
/**
* Construct given a dataSource and sql to return the next sequence value.
*/
public PostgresSequenceIdGenerator(BackgroundExecutor be, DataSource ds, String seqName, int batchSize) {
super(be, ds, seqName, batchSize);
this.baseSql = "select nextval('" + seqName + "'), s.generate_series from (select generate_series from generate_series(1,";
}
@Override
public String getSql(int batchSize) {
return baseSql + batchSize + ") ) as s";
}
}
@@ -35,8 +35,7 @@ public class SqlAnywhereLimiter implements SqlLimiter {
sb.append(dbSql);
String sql = request.getDbPlatform().completeSql(sb.toString(), request.getOrmQuery());
return new SqlLimitResponse(sql, false);
return new SqlLimitResponse(sql);
}
}
@@ -1,11 +0,0 @@
package io.ebean.config.dbplatform.sqlserver;
/**
* SQL Server platform using the older ROW_NUMBER() mechanism.
*/
public class SqlServer2005Platform extends SqlServer16Platform {
public SqlServer2005Platform() {
this.sqlLimiter = new SqlServer2005SqlLimiter();
}
}
@@ -1,79 +0,0 @@
package io.ebean.config.dbplatform.sqlserver;
import io.ebean.config.dbplatform.SqlLimitRequest;
import io.ebean.config.dbplatform.SqlLimitResponse;
import io.ebean.config.dbplatform.SqlLimiter;
/**
* Use top and row_number() function to limit sql results.
*/
public class SqlServer2005SqlLimiter implements SqlLimiter {
final String rowNumberWindowAlias;
/**
* Specify the name of the rowNumberWindowAlias.
*/
public SqlServer2005SqlLimiter(String rowNumberWindowAlias) {
this.rowNumberWindowAlias = rowNumberWindowAlias;
}
public SqlServer2005SqlLimiter() {
this("as limitresult");
}
@Override
public SqlLimitResponse limit(SqlLimitRequest request) {
StringBuilder sb = new StringBuilder(500);
int firstRow = request.getFirstRow();
int lastRow = request.getMaxRows();
if (lastRow > 0) {
lastRow += firstRow;
}
if (firstRow < 1) {
// just use top n
sb.append("select ");
if (request.isDistinct()) {
sb.append("distinct ");
}
sb.append("top ").append(lastRow).append(" ");
sb.append(request.getDbSql());
return new SqlLimitResponse(sb.toString(), false);
}
/*
* SELECT * FROM (SELECT TOP 20 ROW_NUMBER() OVER (ORDER BY ...) AS rn, ...)
* AS limitresult WHERE rn >= 11 AND rn <= 20
*/
sb.append("select * ").append(NEW_LINE).append("from ( ");
sb.append("select ");
if (request.isDistinct()) {
sb.append("distinct ");
}
sb.append("top ").append(lastRow);
sb.append(" row_number() over (order by ");
sb.append(request.getDbOrderBy());
sb.append(") as rn, ");
sb.append(request.getDbSql());
sb.append(NEW_LINE).append(") ");
sb.append(rowNumberWindowAlias);
sb.append(" where ");
sb.append(" rn > ").append(firstRow);
if (lastRow > 0) {
sb.append(" and ");
sb.append(" rn <= ").append(lastRow);
}
String sql = request.getDbPlatform().completeSql(sb.toString(), request.getOrmQuery());
return new SqlLimitResponse(sql, true);
}
}
@@ -36,7 +36,6 @@ abstract class SqlServerBasePlatform extends DatabasePlatform {
this.dbIdentity.setSupportsGetGeneratedKeys(true);
this.dbIdentity.setSupportsIdentity(true);
this.dbIdentity.setSupportsSequence(true);
this.sequenceBatchMode = false;
this.exceptionTranslator =
new SqlErrorCodes()
@@ -95,12 +94,9 @@ abstract class SqlServerBasePlatform extends DatabasePlatform {
sb.append('[').append(ch).append(']');
}
/**
* Create a Postgres specific sequence IdGenerator.
*/
@Override
public PlatformIdGenerator createSequenceIdGenerator(BackgroundExecutor be, DataSource ds, int stepSize, String seqName) {
return new SqlServerStepSequence(be, ds, seqName, stepSize);
public PlatformIdGenerator createSequenceIdGenerator(BackgroundExecutor be, DataSource ds, int increment, String seqName) {
return new SqlServerDbSequence(be, ds, seqName, increment);
}
/**
@@ -0,0 +1,13 @@
package io.ebean.config.dbplatform.sqlserver;
import io.ebean.BackgroundExecutor;
import io.ebean.config.dbplatform.SequenceStepIdGenerator;
import javax.sql.DataSource;
class SqlServerDbSequence extends SequenceStepIdGenerator {
SqlServerDbSequence(BackgroundExecutor be, DataSource ds, String seqName, int stepSize) {
super(be, ds, seqName, stepSize, "select next value for " + seqName);
}
}
@@ -29,7 +29,7 @@ public class SqlServerSqlLimiter implements SqlLimiter {
}
sb.append("top ").append(maxRows).append(" ");
sb.append(dbSql);
return new SqlLimitResponse(sb.toString(), false);
return new SqlLimitResponse(sb.toString());
}
sb.append("select ");
@@ -43,8 +43,7 @@ public class SqlServerSqlLimiter implements SqlLimiter {
if (maxRows > 0) {
sb.append(" fetch next ").append(maxRows).append(" rows only");
}
String sql = sb.toString();
return new SqlLimitResponse(sql, false);
return new SqlLimitResponse(sb.toString());
}
}
@@ -1,24 +0,0 @@
package io.ebean.config.dbplatform.sqlserver;
import io.ebean.BackgroundExecutor;
import io.ebean.config.dbplatform.SequenceStepIdGenerator;
import javax.sql.DataSource;
public class SqlServerStepSequence extends SequenceStepIdGenerator {
private final String nextSql;
/**
* Construct where batchSize is the sequence step size.
*/
public SqlServerStepSequence(BackgroundExecutor be, DataSource ds, String seqName, int stepSize) {
super(be, ds, seqName, stepSize);
this.nextSql = "select next value for "+seqName;
}
@Override
public String getSql(int batchSize) {
return nextSql;
}
}
@@ -1,106 +0,0 @@
package io.ebean.config.properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
/**
* Manages the underlying map of properties we are gathering.
*/
class LoadContext {
private static final Logger log = LoggerFactory.getLogger(LoadContext.class);
/**
* Map we are loading the properties into.
*/
private final Map<String, String> map = new LinkedHashMap<>();
/**
* Names of resources/files that were loaded.
*/
private final Set<String> loadedResources = new LinkedHashSet<>();
/**
* Return the input stream (maybe null) for the given source.
*/
InputStream resource(String resourcePath, Loader.Source source) {
InputStream is = null;
if (source == Loader.Source.RESOURCE) {
is = resourceStream(resourcePath);
if (is != null) {
loadedResources.add(resourcePath);
}
} else {
File file = new File(resourcePath);
if (file.exists()) {
try {
is = new FileInputStream(file);
loadedResources.add("file:" + resourcePath);
} catch (FileNotFoundException e) {
throw new IllegalStateException(e);
}
}
}
return is;
}
private InputStream resourceStream(String resourcePath) {
InputStream is = getClass().getResourceAsStream("/" + resourcePath);
if (is == null) {
// search the module path for top level resource
is = ClassLoader.getSystemResourceAsStream(resourcePath);
}
return is;
}
/**
* Add a property entry.
*/
void put(String key, String val) {
if (val != null) {
val = val.trim();
}
map.put(key, val);
}
/**
* Evaluate all the expressions and return as a Properties object.
*/
Properties eval() {
log.info("loaded properties from {}", loadedResources);
Properties properties = new Properties();
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
String value = PropertyEval.eval(entry.getValue());
properties.setProperty(key, value);
}
return properties;
}
/**
* Read the special properties that can point to an external properties source.
*/
String indirectLocation() {
String indirectLocation = map.get("load.properties");
if (indirectLocation == null) {
indirectLocation = map.get("load.properties.override");
}
return indirectLocation;
}
}
@@ -1,181 +0,0 @@
package io.ebean.config.properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Properties;
/**
* Loads the configuration from known/expected locations.
* <p>
* Defines the loading order of resources and files.
* </p>
*/
class Loader {
private static final Logger log = LoggerFactory.getLogger(Loader.class);
enum Source {
RESOURCE,
FILE
}
private final LoadContext loadContext = new LoadContext();
private YamlLoader yamlLoader;
Loader() {
String skipYaml = System.getProperty("ebeanSkipYaml");
if (!"true".equals(skipYaml)) {
try {
Class<?> exists = Class.forName("org.yaml.snakeyaml.Yaml");
if (exists != null) {
yamlLoader = new YamlLoader(loadContext);
}
} catch (Exception e) {
// ignored
}
}
}
/**
* Load the configuration with the expected ordering.
*/
void load() {
loadMain(Source.RESOURCE);
// external file configuration overrides the resources configuration
loadMain(Source.FILE);
loadViaSystemProperty();
loadViaIndirection();
// test configuration (if found) overrides main configuration
// we should only find these resources when running tests
loadTest();
}
/**
* Load test configuration.
*/
private void loadTest() {
loadProperties("application-test.properties", Source.RESOURCE);
loadYaml("application-test.yaml", Source.RESOURCE);
loadYaml("application-test.yml", Source.RESOURCE);
loadProperties("test-ebean.properties", Source.RESOURCE);
}
/**
* Load configuration defined by a <em>load.properties</em> entry in properties file.
*/
private void loadViaIndirection() {
String location = loadContext.indirectLocation();
if (location != null) {
location = PropertyEval.eval(location);
loadWithExtensionCheck(location);
}
}
/**
* Load the main configuration for the given source.
*/
private void loadMain(Source source) {
loadYaml("application.yaml", source);
loadYaml("application.yml", source);
loadProperties("application.properties", source);
loadProperties("ebean.properties", source);
}
private void loadViaSystemProperty() {
String fileName = System.getenv("EBEAN_PROPS_FILE");
if (fileName == null) {
fileName = System.getProperty("ebean.props.file");
if (fileName != null) {
loadWithExtensionCheck(fileName);
}
} else {
loadWithExtensionCheck(fileName);
}
}
void loadWithExtensionCheck(String fileName) {
if (fileName.endsWith("yaml") || fileName.endsWith("yml")) {
loadYaml(fileName, Source.FILE);
} else if (fileName.endsWith("properties")) {
loadProperties(fileName, Source.FILE);
} else {
throw new IllegalArgumentException("Expecting only yml or properties file but got [" + fileName + "]");
}
}
/**
* Evaluate all the configuration entries and return as properties.
*/
Properties eval() {
return loadContext.eval();
}
void loadYaml(String resourcePath, Source source) {
if (yamlLoader != null) {
try {
try (InputStream is = resource(resourcePath, source)) {
yamlLoader.load(is);
}
} catch (Exception e) {
log.warn("Failed to read yml from:" + resourcePath, e);
}
}
}
void loadProperties(String resourcePath, Source source) {
try {
try (InputStream is = resource(resourcePath, source)) {
if (is != null) {
loadProperties(is);
}
}
} catch (Exception e) {
log.warn("Failed to read properties from:" + resourcePath, e);
}
}
private InputStream resource(String resourcePath, Source source) {
return loadContext.resource(resourcePath, source);
}
private void loadProperties(InputStream is) {
if (is != null) {
try {
Properties properties = new Properties();
properties.load(is);
put(properties);
} catch (IOException e) {
throw new RuntimeException("Failed to load properties?", e);
} finally {
close(is);
}
}
}
private void put(Properties properties) {
Enumeration<?> enumeration = properties.propertyNames();
while (enumeration.hasMoreElements()) {
String key = (String) enumeration.nextElement();
String property = properties.getProperty(key);
loadContext.put(key, property);
}
}
private void close(InputStream is) {
try {
is.close();
} catch (IOException e) {
log.warn("Error closing input stream for properties", e);
}
}
}
@@ -1,74 +0,0 @@
package io.ebean.config.properties;
import java.util.Enumeration;
import java.util.Properties;
/**
* Loads and evaluates properties and yml configuration.
*/
public class PropertiesLoader {
private static Properties properties;
/**
* Provides properties by reading known locations.
* <p>
* <h3>Main configuration</h3>
* <p>
* <p>Firstly loads from main resources</p>
* <pre>
* - application.properties
* - application.yaml
* - ebean.properties
* </pre>
* <p>
* <p>Then loads from local files</p>
* <pre>
* - application.properties
* - application.yaml
* - ebean.properties
* </pre>
* <p>
* <p>Then loads from environment variable <em>EBEAN_PROPS_FILE</em></p>
* <p>Then loads from system property <em>ebean.props.file</em></p>
* <p>Then loads from <em>load.properties</em></p>
* <p>
* <h3>Test configuration</h3>
* <p>
* Once the main configuration is read it will try to read common test configuration.
* This will only be successful if the test resources are available (i.e. running tests).
* </p>
* <p>Loads from test resources</p>
* <pre>
* - application-test.properties
* - application-test.yaml
* - test-ebean.properties
* </pre>
*/
public static synchronized Properties load() {
if (properties == null) {
Loader loader = new Loader();
loader.load();
properties = loader.eval();
}
return properties;
}
/**
* Return a copy of the properties with 'eval' run on all the values.
* This resolves expressions like ${HOME} etc.
*/
public static Properties eval(Properties properties) {
Properties evalCopy = new Properties();
Enumeration<?> names = properties.propertyNames();
while (names.hasMoreElements()) {
String name = (String)names.nextElement();
String value = PropertyEval.eval(properties.getProperty(name));
evalCopy.setProperty(name, value);
}
return evalCopy;
}
}
@@ -1,205 +0,0 @@
package io.ebean.config.properties;
import javax.naming.InitialContext;
import javax.naming.NamingException;
/**
* Helper used to evaluate expressions such as ${CATALINA_HOME}.
* <p>
* The expressions can contain environment variables, system properties or JNDI
* properties. JNDI expressions take the form ${jndi:propertyName} where you
* substitute propertyName with the name of the jndi property you wish to
* evaluate.
* </p>
*/
final class PropertyEval {
/**
* Prefix for looking up JNDI Environment variable.
*/
private static final String JAVA_COMP_ENV = "java:comp/env/";
/**
* Used to detect the start of an expression.
*/
private static final String START = "${";
/**
* Used to detect the end of an expression.
*/
private static final String END = "}";
/**
* Specify the PropertyHolder.
*/
private PropertyEval() {
}
/**
* Return the property value evaluating and replacing any expressions such as
* ${CATALINA_HOME}.
*/
static String eval(String val) {
if (val == null) {
return null;
}
int sp = val.indexOf(START);
if (sp > -1) {
int ep = val.indexOf(END, sp + 1);
if (ep > -1) {
return eval(val, sp, ep);
}
}
return val;
}
/**
* Convert the expression using JNDI, Environment variables, System Properties
* or existing an property in SystemProperties itself.
*/
private static String evaluateExpression(String exp) {
if (exp.isEmpty()) {
return null;
}
if (isJndiExpression(exp)) {
// JNDI property lookup...
String val = getJndiProperty(exp);
if (val != null) {
return val;
}
}
String val = System.getProperty(exp);
if (val == null) {
val = System.getenv(exp);
}
return val;
}
private static String eval(String val, int sp, int ep) {
return new EvalBuffer(val, sp, ep).process();
}
private static boolean isJndiExpression(String exp) {
return exp.startsWith("JNDI:") || exp.startsWith("jndi:");
}
/**
* Returns null if JNDI is not setup or if the property is not found.
*
* @param key the key of the JNDI Environment property including a JNDI: prefix.
*/
private static String getJndiProperty(String key) {
try {
// remove the JNDI: prefix
key = key.substring(5);
return (String) getJndiObject(key);
} catch (NamingException ex) {
return null;
}
}
/**
* Similar to getProperty but throws NamingException if JNDI is not setup or
* if the property is not found.
*/
private static Object getJndiObject(String key) throws NamingException {
InitialContext ctx = new InitialContext();
return ctx.lookup(JAVA_COMP_ENV + key);
}
private static class EvalBuffer {
private final StringBuilder buf = new StringBuilder();
private final String original;
private int position;
private int start;
private int end;
private String expression;
private String defaultValue;
EvalBuffer(String val, int start, int ep) {
this.original = val;
this.start = start;
this.end = ep;
this.position = 0;
moveToStart();
}
void moveToStart() {
if (start > position) {
buf.append(original.substring(position, start));
position = start;
}
}
void parseForDefault() {
int colonPos = original.lastIndexOf(':', end);
if (colonPos > start) {
expression = original.substring(start + START.length(), colonPos);
defaultValue = original.substring(colonPos + 1, end);
} else {
expression = original.substring(start + START.length(), end);
}
}
void evaluate() {
String eval = evaluateExpression(expression);
if (eval != null) {
buf.append(eval);
} else {
if (defaultValue != null) {
buf.append(defaultValue);
} else {
buf.append(START).append(expression).append(END);
}
}
}
String end() {
if (end < original.length() - 1) {
buf.append(original.substring(end + 1));
}
return buf.toString();
}
boolean next() {
if (end < original.length()) {
int startPos = original.indexOf(START, end + 1);
if (startPos > -1) {
int endPos = original.indexOf(END, startPos + 1);
if (endPos > -1) {
if (startPos > end + 1) {
buf.append(original.substring(end + 1, startPos));
}
this.start = startPos;
this.end = endPos;
return true;
}
}
}
return false;
}
private void evalNext() {
parseForDefault();
evaluate();
}
String process() {
evalNext();
while (next()) {
evalNext();
}
return end();
}
}
}
@@ -1,58 +0,0 @@
package io.ebean.config.properties;
import org.yaml.snakeyaml.Yaml;
import java.io.InputStream;
import java.util.Map;
/**
* Loads configuration from Yml into the load context.
* <p>
* Note that this ignores 'lists' so just reads 'maps' and scalar values.
* </p>
*/
class YamlLoader {
private final Yaml yaml = new Yaml();
private final LoadContext loadContext;
YamlLoader(LoadContext loadContext) {
this.loadContext = loadContext;
}
@SuppressWarnings("unchecked")
void load(InputStream is) {
if (is != null) {
for (Object map : yaml.loadAll(is)) {
loadMap((Map<String, Object>)map, null);
}
}
}
@SuppressWarnings("unchecked")
void loadMap(Map<String, Object> map, String path) {
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
if (path != null) {
key = path + "." + key;
}
Object val = entry.getValue();
if (val instanceof Map) {
loadMap((Map<String, Object>) val, key);
} else {
addScalar(key, val);
}
}
}
private void addScalar(String key, Object val) {
if (val instanceof String) {
loadContext.put(key, (String) val);
} else if (val instanceof Number || val instanceof Boolean) {
loadContext.put(key, val.toString());
}
}
}
@@ -93,7 +93,7 @@ public interface DbMigration {
/**
* Set the specific platform to generate DDL for.
* <p>
* If not set this defaults to the platform of the default server.
* If not set this defaults to the platform of the default database.
* </p>
*/
void setPlatform(Platform platform);
@@ -101,7 +101,7 @@ public interface DbMigration {
/**
* Set the specific platform to generate DDL for.
* <p>
* If not set this defaults to the platform of the default server.
* If not set this defaults to the platform of the default database.
* </p>
*/
void setPlatform(DatabasePlatform databasePlatform);
@@ -15,8 +15,8 @@ package io.ebean.event;
*
* Object extaBeanToSave = ...;
* Transaction t = request.getTransaction();
* EbeanServer server = request.getEbeanServer();
* server.save(extraBeanToSave, t);
* Database server = request.getEbeanServer();
* database.save(extraBeanToSave, t);
*
* }</pre>
* <p>
@@ -5,11 +5,6 @@ package io.ebean.meta;
*/
public interface MetaMetric {
/**
* Return the metric type.
*/
MetricType getMetricType();
/**
* Return the metric name.
*/
+1 -11
View File
@@ -6,7 +6,6 @@ package io.ebean.meta;
public class MetricData {
private String name;
private String type;
private String hash;
private String loc;
private String sql;
@@ -16,9 +15,8 @@ public class MetricData {
private Long max;
private Long total;
public MetricData(String name, String type) {
public MetricData(String name) {
this.name = name;
this.type = type;
}
public MetricData() {
@@ -32,14 +30,6 @@ public class MetricData {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getHash() {
return hash;
}
@@ -1,40 +0,0 @@
package io.ebean.meta;
/**
* The type of Metric.
*/
public enum MetricType {
/**
* Transactions.
*/
TXN,
/**
* ORM Insert Update or Delete.
*/
IUD,
/**
* ORM queries.
*/
ORM,
/**
* DTO queries.
*/
DTO,
/**
* SQL queries with a label will have metrics collected.
* <p>
* SqlQuery and SqlUpdate without a label have no metrics collected.
*/
SQL,
/**
* L2 cache metrics.
*/
L2
}
@@ -1,7 +1,6 @@
package io.ebean.metric;
import io.ebean.ProfileLocation;
import io.ebean.meta.MetricType;
/**
* Factory to create timed metric counters.
@@ -18,21 +17,21 @@ public interface MetricFactory {
/**
* Create a timed metric group.
*/
TimedMetricMap createTimedMetricMap(MetricType metricType, String name);
TimedMetricMap createTimedMetricMap(String name);
/**
* Create a Timed metric.
*/
TimedMetric createTimedMetric(MetricType metricType, String name);
TimedMetric createTimedMetric(String name);
/**
* Create a counter metric.
*/
CountMetric createCountMetric(MetricType metricType, String name);
CountMetric createCountMetric(String name);
/**
* Create a Timed metric.
*/
QueryPlanMetric createQueryPlanMetric(MetricType metricType, Class<?> type, String label, ProfileLocation profileLocation, String sql);
QueryPlanMetric createQueryPlanMetric(Class<?> type, String label, ProfileLocation profileLocation, String sql);
}
+1 -12
View File
@@ -8,12 +8,11 @@ import io.ebean.event.BeanPersistListener;
import io.ebean.event.BeanQueryAdapter;
import io.ebeanservice.docstore.api.mapping.DocumentMapping;
import javax.annotation.Nonnull;
import java.util.Collection;
import java.util.List;
import java.util.function.Consumer;
import javax.annotation.Nonnull;
/**
* Information and methods on BeanDescriptors made available to plugins.
*/
@@ -25,11 +24,6 @@ public interface BeanType<T> {
@Nonnull
String getName();
/**
* Return the profileId of the bean type.
*/
short getProfileId();
/**
* Return the full name of the bean type.
*/
@@ -161,11 +155,6 @@ public interface BeanType<T> {
*/
IdType getIdType();
/**
* Return the sequence name associated to this entity bean type (if there is one).
*/
String getSequenceName();
/**
* Return true if this bean type has doc store backing.
*/
+1 -1
View File
@@ -20,7 +20,7 @@ public interface SpiServer extends EbeanServer, BeanLoader {
ServerConfig getServerConfig();
/**
* Return the DatabasePlatform for this server.
* Return the DatabasePlatform for this database.
*/
DatabasePlatform getDatabasePlatform();
@@ -13,7 +13,7 @@ package io.ebean.search;
* .lowFreqOperatorAnd(true)
* .highFreqOperatorAnd(true);
*
* List<Customer> customers = server.find(Customer.class)
* List<Customer> customers = database.find(Customer.class)
* .text()
* .textCommonTerms("the brown", options)
* .findList();
@@ -13,7 +13,7 @@ package io.ebean.search;
* .lenient(true)
* .opAnd();
*
* List<Customer> customers = server.find(Customer.class)
* List<Customer> customers = database.find(Customer.class)
* .text()
* .textSimple("quick brown", options)
* .findList();
@@ -24,7 +24,7 @@ package io.ebean.search;
* // just use default options
* TextQueryString options = new TextQueryString();
*
* List<Customer> customers = server.find(Customer.class)
* List<Customer> customers = database.find(Customer.class)
* .text()
* .textSimple("quick brown", options)
* .findList();
@@ -13,7 +13,7 @@ package io.ebean.search;
* .lenient(true)
* .opAnd();
*
* List<Customer> customers = server.find(Customer.class)
* List<Customer> customers = database.find(Customer.class)
* .text()
* .textSimple("quick brown", options)
* .findList();
@@ -12,7 +12,7 @@ public interface SpiContainer {
/**
* Create the EbeanServer for a given configuration.
*
* @param configuration The configuration information for this server.
* @param configuration The configuration information for this database.
*/
EbeanServer createServer(ServerConfig configuration);
@@ -38,6 +38,11 @@ public class BindParams implements Serializable {
*/
private String bindHash;
/**
* Helper to add positioned parameters in order.
*/
private int addPos;
public BindParams() {
}
@@ -156,6 +161,19 @@ public class BindParams implements Serializable {
p.setOutType(outType);
}
public void setNextParameters(Object... values) {
for (Object value : values) {
setNextParameter(value);
}
}
/**
* Bind the next positioned parameter.
*/
public void setNextParameter(Object value) {
setParameter(++addPos, value);
}
/**
* Using position set the In value of a parameter. Note that for nulls you
* must use setNullParameter.
@@ -1,6 +1,5 @@
package io.ebeaninternal.api;
import io.ebean.meta.MetricType;
import io.ebean.meta.MetricVisitor;
import io.ebean.metric.CountMetric;
import io.ebean.metric.MetricFactory;
@@ -22,11 +21,11 @@ public class ExtraMetrics {
*/
public ExtraMetrics() {
final MetricFactory factory = MetricFactory.get();
this.bindCapture = factory.createTimedMetric(MetricType.ORM, "ebean.queryplan.bindcapture");
this.planCollect = factory.createTimedMetric(MetricType.ORM, "ebean.queryplan.collect");
this.loadOneL2 = factory.createCountMetric(MetricType.ORM, "loadone.l2");
this.loadOneRef = factory.createCountMetric(MetricType.ORM, "loadone.ref");
this.loadOneNoLoader = factory.createCountMetric(MetricType.ORM, "loadone.noloader");
this.bindCapture = factory.createTimedMetric("ebean.queryplan.bindcapture");
this.planCollect = factory.createTimedMetric("ebean.queryplan.collect");
this.loadOneL2 = factory.createCountMetric("loadone.l2");
this.loadOneRef = factory.createCountMetric("loadone.ref");
this.loadOneNoLoader = factory.createCountMetric("loadone.noloader");
}
/**
@@ -118,7 +118,7 @@ public class LoadManyRequest extends LoadRequest {
SpiQuery<?> query = many.newQuery(server);
String orderBy = many.getLazyFetchOrderBy();
if (orderBy != null) {
query.orderBy(orderBy);
query.order(orderBy);
}
String extraWhere = many.getExtraWhere();
@@ -0,0 +1,27 @@
package io.ebeaninternal.api;
import io.ebean.annotation.Platform;
import io.ebean.util.StringHelper;
public class PlatformMatch {
/**
* Return true if the script platforms is a match/supported for the given platform.
*
* @param platform The database platform we are generating/running DDL for
* @param platforms The platforms (comma delimited) this script should run for
*/
public static boolean matchPlatform(Platform platform, String platforms) {
if (platforms == null || platforms.trim().isEmpty()) {
return true;
}
// match on base platform name and platform name
for (String name : StringHelper.splitNames(platforms)) {
if (name.equalsIgnoreCase(platform.base().name()) || name.equalsIgnoreCase(platform.name())) {
return true;
}
}
return false;
}
}
@@ -2,6 +2,7 @@ package io.ebeaninternal.api;
import io.ebean.DtoQuery;
import io.ebean.ProfileLocation;
import io.ebean.Transaction;
import io.ebeaninternal.server.dto.DtoMappingRequest;
import io.ebeaninternal.server.dto.DtoQueryPlan;
@@ -65,4 +66,9 @@ public interface SpiDtoQuery<T> extends DtoQuery<T>, SpiSqlBinding {
*/
SpiQuery<?> getOrmQuery();
/**
* Return the explicit transaction used to execute the query.
*/
Transaction getTransaction();
}
@@ -13,6 +13,9 @@ import java.io.IOException;
*/
public interface SpiExpression extends Expression {
static final String SQL_TRUE = "1=1";
static final String SQL_FALSE = "1=0";
/**
* Simplify nested expressions if possible.
*/
@@ -36,4 +36,11 @@ public interface SpiExpressionList<T> extends ExpressionList<T>, SpiExpression {
* Write the top level where expressions taking into account possible extra idEquals expression.
*/
void writeDocQuery(DocQueryContext context, SpiExpression idEquals) throws IOException;
/**
* Apply firstRow maxRows limits on the filterMany query.
*/
default void applyRowLimits(SpiQuery<?> query) {
// do nothing by default
}
}
@@ -1,5 +1,6 @@
package io.ebeaninternal.api;
import io.ebean.ProfileLocation;
import io.ebeaninternal.server.transaction.ProfileStream;
import io.ebeaninternal.server.transaction.TransactionProfile;
@@ -24,7 +25,7 @@ public interface SpiProfileHandler {
* Create a profiling stream if we are profiling this transaction.
* Return null if we are not profiling this transaction.
*
* @param profileId The transaction profileId
* @param location The profile location
*/
ProfileStream createProfileStream(int profileId);
ProfileStream createProfileStream(ProfileLocation location);
}
@@ -191,7 +191,7 @@ public interface SpiQuery<T> extends Query<T>, TxnProfileEventCodes {
/**
* Return the id used to identify a particular query for the given bean type.
*/
short getProfileId();
String getProfileId();
/**
* Return the profile location for this query.
@@ -20,7 +20,6 @@ import java.sql.SQLException;
* Extends Transaction with additional API required on server.
* <p>
* Provides support for batching and TransactionContext.
* </p>
*/
public interface SpiTransaction extends Transaction {
@@ -65,7 +64,6 @@ public interface SpiTransaction extends Transaction {
* Add a deleting bean to the registered list.
* <p>
* This is to handle bi-directional relationships where both sides Cascade.
* </p>
*/
void registerDeleteBean(Integer hash);
@@ -86,7 +84,6 @@ public interface SpiTransaction extends Transaction {
* the bean when cascade persist is on both sides of a relationship).
* <p>
* This will register the bean if it is not already.
* </p>
*/
boolean isRegisteredBean(Object bean);
@@ -111,7 +108,6 @@ public interface SpiTransaction extends Transaction {
* Return the batchSize specifically set for this transaction or 0.
* <p>
* Returning 0 implies to use the system wide default batch size.
* </p>
*/
DocStoreMode getDocStoreMode();
@@ -125,7 +121,6 @@ public interface SpiTransaction extends Transaction {
* Return the batchSize specifically set for this transaction or 0.
* <p>
* Returning 0 implies to use the system wide default batch size.
* </p>
*/
@Override
int getBatchSize();
@@ -141,11 +136,9 @@ public interface SpiTransaction extends Transaction {
* As we cascade save or delete we traverse the object graph tree. Going up
* to Assoc Ones the depth decreases and going down to Assoc Manys the depth
* increases.
* </p>
* <p>
* The depth is used for ordering batching statements. The lowest depth get
* executed first during save.
* </p>
*/
void depth(int diff);
@@ -166,7 +159,6 @@ public interface SpiTransaction extends Transaction {
* This information is used maintain the table state, cache and text
* indexes. On commit the Table modifications this generates is broadcast
* around the cluster (if you have a cluster).
* </p>
*/
TransactionEvent getEvent();
@@ -198,7 +190,6 @@ public interface SpiTransaction extends Transaction {
* You may wish to hold onto this and set it against another transaction
* later. This is along the lines of 'extended persistence context'
* behaviour.
* </p>
*/
PersistenceContext getPersistenceContext();
@@ -211,7 +202,6 @@ public interface SpiTransaction extends Transaction {
* is one PersistenceContext per Transaction. The getPersistenceContext()
* and setPersistenceContext() enable a developer to reuse a single
* PersistenceContext with multiple transactions.
* </p>
*/
void setPersistenceContext(PersistenceContext context);
@@ -221,7 +211,6 @@ public interface SpiTransaction extends Transaction {
* If the connection is made from Transaction and the user code calls
* that method we can no longer trust the query only status of a
* Transaction.
* </p>
*/
Connection getInternalConnection();
@@ -1,9 +1,9 @@
package io.ebeaninternal.dbmigration;
import io.ebean.annotation.Platform;
import io.ebean.config.DbMigrationConfig;
import io.ebean.config.ServerConfig;
import io.ebean.config.dbplatform.DatabasePlatform;
import io.ebean.migration.ddl.DdlAutoCommit;
import io.ebean.migration.ddl.DdlRunner;
import io.ebean.migration.runner.ScriptTransform;
import io.ebean.util.JdbcClose;
@@ -48,6 +48,7 @@ public class DdlGenerator {
private final boolean ddlAutoCommit;
private final String dbSchema;
private final ScriptTransform scriptTransform;
private final Platform platform;
private final String platformName;
private CurrentModel currentModel;
@@ -63,7 +64,8 @@ public class DdlGenerator {
this.createOnly = serverConfig.isDdlCreateOnly();
this.dbSchema = serverConfig.getDbSchema();
final DatabasePlatform databasePlatform = server.getDatabasePlatform();
this.platformName = databasePlatform.getPlatform().base().name();
this.platform = databasePlatform.getPlatform();
this.platformName = platform.base().name();
if (!serverConfig.getTenantMode().isDdlEnabled() && serverConfig.isDdlRun()) {
log.warn("DDL can't be run on startup with TenantMode " + serverConfig.getTenantMode());
this.runDdl = false;
@@ -188,7 +190,7 @@ public class DdlGenerator {
protected void runDropSql(Connection connection) throws IOException {
if (!createOnly) {
if (extraDdl && jaxbPresent) {
String extraApply = ExtraDdlXmlReader.buildExtra(server.getDatabasePlatform().getName(), true);
String extraApply = ExtraDdlXmlReader.buildExtra(platform, true);
if (extraApply != null) {
runScript(connection, false, extraApply, "extra-ddl");
}
@@ -209,13 +211,13 @@ public class DdlGenerator {
if (extraDdl && jaxbPresent) {
if (currentModel().isTablePartitioning()) {
String extraPartitioning = ExtraDdlXmlReader.buildPartitioning(server.getDatabasePlatform().getName());
String extraPartitioning = ExtraDdlXmlReader.buildPartitioning(platform);
if (extraPartitioning != null && !extraPartitioning.isEmpty()) {
runScript(connection, false, extraPartitioning, "builtin-partitioning-ddl");
}
}
String extraApply = ExtraDdlXmlReader.buildExtra(server.getDatabasePlatform().getName(), false);
String extraApply = ExtraDdlXmlReader.buildExtra(platform, false);
if (extraApply != null) {
runScript(connection, false, extraApply, "extra-ddl");
}
@@ -14,11 +14,12 @@ import io.ebean.config.dbplatform.cockroach.CockroachPlatform;
import io.ebean.config.dbplatform.db2.DB2Platform;
import io.ebean.config.dbplatform.h2.H2Platform;
import io.ebean.config.dbplatform.hana.HanaPlatform;
import io.ebean.config.dbplatform.hsqldb.HsqldbPlatform;
import io.ebean.config.dbplatform.mysql.MySql55Platform;
import io.ebean.config.dbplatform.mysql.MySqlPlatform;
import io.ebean.config.dbplatform.nuodb.NuoDbPlatform;
import io.ebean.config.dbplatform.oracle.Oracle11Platform;
import io.ebean.config.dbplatform.oracle.OraclePlatform;
import io.ebean.config.dbplatform.postgres.Postgres9Platform;
import io.ebean.config.dbplatform.postgres.PostgresPlatform;
import io.ebean.config.dbplatform.sqlanywhere.SqlAnywherePlatform;
import io.ebean.config.dbplatform.sqlite.SQLitePlatform;
@@ -49,6 +50,8 @@ import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import static io.ebeaninternal.api.PlatformMatch.matchPlatform;
/**
* Generates DB Migration xml and sql scripts.
* <p>
@@ -406,7 +409,7 @@ public class DefaultDbMigration implements DbMigration {
if (extraDdl != null) {
List<DdlScript> ddlScript = extraDdl.getDdlScript();
for (DdlScript script : ddlScript) {
if (!script.isDrop() && ExtraDdlXmlReader.matchPlatform(dbPlatform.getName(), script.getPlatforms())) {
if (!script.isDrop() && matchPlatform(dbPlatform.getPlatform(), script.getPlatforms())) {
writeExtraDdl(migrationDir, script);
}
}
@@ -810,8 +813,8 @@ public class DefaultDbMigration implements DbMigration {
switch (platform) {
case H2:
return new H2Platform();
case HSQLDB:
return new HsqldbPlatform();
case POSTGRES9:
return new Postgres9Platform();
case POSTGRES:
return new PostgresPlatform();
case MYSQL55:
@@ -820,6 +823,8 @@ public class DefaultDbMigration implements DbMigration {
return new MySqlPlatform();
case ORACLE:
return new OraclePlatform();
case ORACLE11:
return new Oracle11Platform();
case SQLANYWHERE:
return new SqlAnywherePlatform();
case SQLSERVER16:
@@ -44,8 +44,8 @@ public abstract class AbstractHanaDdl extends PlatformDdl {
String columnName = alter.getColumnName();
String currentType = alter.getCurrentType();
String type = alter.getType() != null ? alter.getType() : currentType;
type = convert(type, false);
currentType = convert(currentType, false);
type = convert(type);
currentType = convert(currentType);
boolean notnull = (alter.isNotnull() != null) ? alter.isNotnull() : Boolean.TRUE.equals(alter.isCurrentNotnull());
String notnullClause = notnull ? " not null" : "";
String defaultValue = DdlHelp.isDropDefault(alter.getDefaultValue()) ? "null"
@@ -103,7 +103,7 @@ public abstract class AbstractHanaDdl extends PlatformDdl {
protected String convertArrayType(String logicalArrayType) {
Matcher matcher = ARRAY_PATTERN.matcher(logicalArrayType);
if (matcher.matches()) {
return convert(matcher.group(1), false) + " array" + (matcher.group(2) == null ? "" : matcher.group(2));
return convert(matcher.group(1)) + " array" + (matcher.group(2) == null ? "" : matcher.group(2));
} else {
return fallbackArrayType;
}
@@ -1,5 +1,6 @@
package io.ebeaninternal.dbmigration.ddlgeneration.platform;
import io.ebean.annotation.Platform;
import io.ebean.config.DbConstraintNaming;
import io.ebean.config.NamingConvention;
import io.ebean.config.ServerConfig;
@@ -28,6 +29,8 @@ import io.ebeaninternal.dbmigration.migration.DropTable;
import io.ebeaninternal.dbmigration.migration.ForeignKey;
import io.ebeaninternal.dbmigration.migration.UniqueConstraint;
import io.ebeaninternal.dbmigration.model.MTable;
import io.ebeaninternal.dbmigration.model.MTableIdentity;
import io.ebeaninternal.server.deploy.IdentityMode;
import java.io.IOException;
import java.math.BigInteger;
@@ -37,6 +40,7 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static io.ebeaninternal.api.PlatformMatch.matchPlatform;
import static io.ebeaninternal.dbmigration.ddlgeneration.platform.SplitColumns.split;
/**
@@ -168,18 +172,14 @@ public class BaseTableDdl implements TableDdl {
}
private List<String> getScriptsForPlatform(List<DdlScript> scripts) {
String searchPlatform = platformDdl.getPlatform().getName();
List<String> ret = Collections.emptyList();
Platform searchPlatform = platformDdl.getPlatform().getPlatform();
for (DdlScript script : scripts) {
if (script.getPlatforms() == null || script.getPlatforms().isEmpty()) {
ret = script.getDdl();
} else for (String platform : StringHelper.splitNames(script.getPlatforms())) {
if (platform.equals(searchPlatform)) {
return script.getDdl();
}
if (matchPlatform(searchPlatform, script.getPlatforms())) {
// just returns the first match (rather than appends them)
return script.getDdl();
}
}
return ret;
return Collections.emptyList();
}
/**
@@ -248,21 +248,22 @@ public class BaseTableDdl implements TableDdl {
List<Column> columns = createTable.getColumn();
List<Column> pk = determinePrimaryKeyColumns(columns);
boolean singleColumnPrimaryKey = (pk.size() == 1);
boolean useIdentity = false;
boolean useSequence = false;
if (singleColumnPrimaryKey) {
IdType useDbIdentityType = platformDdl.useIdentityType(createTable.getIdentityType());
useIdentity = (IdType.IDENTITY == useDbIdentityType);
useSequence = (IdType.SEQUENCE == useDbIdentityType);
DdlIdentity identity = DdlIdentity.NONE;
if ((pk.size() == 1)) {
final IdentityMode identityMode = MTableIdentity.fromCreateTable(createTable);
IdType idType = platformDdl.useIdentityType(identityMode.getIdType());
String sequenceName = identityMode.getSequenceName();
if (IdType.SEQUENCE == idType && (sequenceName == null || sequenceName.isEmpty())) {
sequenceName = sequenceName(createTable, pk);
}
identity = new DdlIdentity(idType, identityMode, sequenceName);
}
String partitionMode = createTable.getPartitionMode();
DdlBuffer apply = writer.apply();
apply.append(platformDdl.getCreateTableCommandPrefix()).append(" ").append(tableName).append(" (");
writeTableColumns(apply, columns, useIdentity);
writeTableColumns(apply, columns, identity);
writeUniqueConstraints(apply, createTable);
writeCompoundUniqueConstraints(apply, createTable);
if (!pk.isEmpty()) {
@@ -297,9 +298,8 @@ public class BaseTableDdl implements TableDdl {
// we drop the related sequence (if sequences are used)
dropTable(writer.dropAll(), tableName);
if (useSequence) {
String pkCol = pk.get(0).getName();
writeSequence(writer, createTable, pkCol);
if (identity.useSequence()) {
writeSequence(writer, identity);
}
// add blank line for a bit of whitespace between tables
@@ -311,6 +311,10 @@ public class BaseTableDdl implements TableDdl {
}
}
private String sequenceName(CreateTable createTable, List<Column> pk) {
return namingConvention.getSequenceName(createTable.getName(), pk.get(0).getName());
}
/**
* Add table and column comments (separate from the create table statement).
*/
@@ -350,8 +354,8 @@ public class BaseTableDdl implements TableDdl {
}
}
private void writeTableColumns(DdlBuffer apply, List<Column> columns, boolean useIdentity) throws IOException {
platformDdl.writeTableColumns(apply, columns, useIdentity);
private void writeTableColumns(DdlBuffer apply, List<Column> columns, DdlIdentity identity) throws IOException {
platformDdl.writeTableColumns(apply, columns, identity);
}
/**
@@ -380,18 +384,9 @@ public class BaseTableDdl implements TableDdl {
}
}
protected void writeSequence(DdlWrite writer, CreateTable createTable, String pk) throws IOException {
// explicit sequence use or platform decides
String explicitSequenceName = createTable.getSequenceName();
int initial = toInt(createTable.getSequenceInitial());
int allocate = toInt(createTable.getSequenceAllocate());
String seqName = explicitSequenceName;
if (seqName == null) {
seqName = namingConvention.getSequenceName(createTable.getName(), pk);
}
String createSeq = platformDdl.createSequence(seqName, initial, allocate);
protected void writeSequence(DdlWrite writer, DdlIdentity identity) throws IOException {
String seqName = identity.getSequenceName();
String createSeq = platformDdl.createSequence(seqName, identity);
if (hasValue(createSeq)) {
writer.apply().append(createSeq).newLine();
writer.dropAll().appendStatement(platformDdl.dropSequence(seqName));
@@ -511,16 +506,7 @@ public class BaseTableDdl implements TableDdl {
}
private boolean platformInclude(String platforms) {
if (platforms == null || platforms.isEmpty()) {
return true;
}
String currentPlatform = platformDdl.getPlatform().getPlatform().name();
for (String name : StringHelper.splitNames(platforms)) {
if (currentPlatform.equalsIgnoreCase(name)) {
return true;
}
}
return false;
return matchPlatform(platformDdl.getPlatform().getPlatform(), platforms);
}
/**
@@ -951,6 +937,10 @@ public class BaseTableDdl implements TableDdl {
}
platformDdl.alterTableAddColumn(buffer, tableName, column, onHistoryTable, help.getDefaultValue());
final String comment = column.getComment();
if (comment != null && !comment.isEmpty()) {
platformDdl.addColumnComment(buffer, tableName, column.getName(), comment);
}
if (!onHistoryTable) {
help.writeAfter(buffer);
@@ -25,8 +25,7 @@ public class CockroachDdl extends PlatformDdl {
* Map bigint, integer and smallint all into serial.
*/
@Override
public String asIdentityColumn(String columnDefn) {
public String asIdentityColumn(String columnDefn, DdlIdentity identity) {
if ("bigint".equalsIgnoreCase(columnDefn)) {
return "serial";
}
@@ -195,7 +195,7 @@ public abstract class DbTriggerBasedHistoryDdl implements PlatformHistoryDdl {
*/
protected void writeColumnDefinition(DdlBuffer buffer, String columnName, String type) throws IOException {
String platformType = platformDdl.convert(type, false);
String platformType = platformDdl.convert(type);
buffer.append(" ");
buffer.append(platformDdl.lowerColumnName(columnName), 29);
buffer.append(platformType);
@@ -0,0 +1,98 @@
package io.ebeaninternal.dbmigration.ddlgeneration.platform;
import io.ebean.annotation.IdentityGenerated;
import io.ebean.config.dbplatform.IdType;
import io.ebeaninternal.server.deploy.IdentityMode;
public class DdlIdentity {
public static final DdlIdentity NONE = new DdlIdentity();
private final IdType idType;
private final IdentityMode identityMode;
private final String sequenceName;
public DdlIdentity(IdType idType, IdentityMode identityMode, String sequenceName) {
this.idType = idType;
this.identityMode = identityMode;
this.sequenceName = sequenceName;
}
private DdlIdentity() {
this.idType = null;
this.identityMode = null;
this.sequenceName = null;
}
public boolean useSequence() {
return idType == IdType.SEQUENCE;
}
public boolean useIdentity() {
return idType == IdType.IDENTITY;
}
public String getSequenceName() {
return sequenceName;
}
private String generatedBy() {
return isAlways() ? "always" : "by default";
}
private boolean isAlways() {
return IdentityGenerated.ALWAYS == identityMode.getGenerated();
}
public String optionGenerated() {
return " generated " + generatedBy() +" as identity";
}
public String identityOptions(String startWith, String incrementBy, String cache) {
return options(true, startWith, incrementBy, cache);
}
public String sequenceOptions(String startWith, String incrementBy, String cache) {
return options(false, startWith, incrementBy, cache);
}
private String options(boolean brackets, String startWith, String incrementBy, String cache) {
if (!identityMode.hasOptions()) {
return "";
}
StringBuilder sb = new StringBuilder(40);
if (brackets) {
sb.append(" (");
} else {
sb.append(" ");
}
optionFor(sb, startWith, identityMode.getStart());
optionFor(sb, incrementBy, identityMode.getIncrement());
optionFor(sb, cache, identityMode.getCache());
if (brackets) {
sb.append(")");
}
return sb.toString();
}
private void optionFor(StringBuilder sb, String prefix, int val) {
if (val > 0 && prefix != null) {
if (sb.length() > 2) {
sb.append(" ");
}
sb.append(prefix).append(" ").append(val);
}
}
public int getStart() {
return identityMode.getStart();
}
public int getIncrement() {
return identityMode.getIncrement();
}
public int getCache() {
return identityMode.getCache();
}
}
@@ -12,6 +12,14 @@ public class H2Ddl extends PlatformDdl {
this.historyDdl = new H2HistoryDdl();
}
/**
* Modify and return the column definition for autoincrement or identity definition.
*/
@Override
public String asIdentityColumn(String columnDefn, DdlIdentity identity) {
return asIdentityStandardOptions(columnDefn, identity);
}
@Override
protected String convertArrayType(String logicalArrayType) {
return "array";
@@ -109,7 +109,7 @@ public class HanaHistoryDdl implements PlatformHistoryDdl {
protected void writeColumnDefinition(DdlBuffer buffer, String columnName, String type, String defaultValue,
boolean isNotNull, String generated) throws IOException {
String platformType = platformDdl.convert(type, false);
String platformType = platformDdl.convert(type);
buffer.append(" ").append(platformDdl.lowerColumnName(columnName));
buffer.append(" ").append(platformType);
if (defaultValue != null) {

Some files were not shown because too many files have changed in this diff Show More