mirror of
https://github.com/ebean-orm/ebean.git
synced 2024-04-21 10:51:47 +00:00
Compare commits
48
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3ef77ea410 | ||
|
|
0d456b2ad6 | ||
|
|
39e913cbe2 | ||
|
|
ae38672e02 | ||
|
|
8a8b36ec1e | ||
|
|
62aca1e77b | ||
|
|
f0b80068b6 | ||
|
|
5721fe3807 | ||
|
|
afffb88a29 | ||
|
|
4c3a125192 | ||
|
|
f8804f8d18 | ||
|
|
4848c24a0a | ||
|
|
4c3d1d9edd | ||
|
|
42b112c3d7 | ||
|
|
59996da07a | ||
|
|
32d4b83a86 | ||
|
|
ca824c5e0d | ||
|
|
b2f7664316 | ||
|
|
062f7a281f | ||
|
|
019ce4e614 | ||
|
|
6b490ed8b1 | ||
|
|
1bee6fcae5 | ||
|
|
097552b8d3 | ||
|
|
9fbfca5f73 | ||
|
|
9e70ba915f | ||
|
|
a1a5dcd035 | ||
|
|
d2b048b0b4 | ||
|
|
4272c17689 | ||
|
|
11723e3a32 | ||
|
|
237cdcdd3d | ||
|
|
e96bee74ae | ||
|
|
c8b57c3302 | ||
|
|
f65ea96b89 | ||
|
|
a1bd0b469a | ||
|
|
fd5563e3da | ||
|
|
f9156ede55 | ||
|
|
10d2d591db | ||
|
|
998d8ed6f2 | ||
|
|
a8da472872 | ||
|
|
a9cdf9736a | ||
|
|
c930a1dd6b | ||
|
|
67ce6ef58e | ||
|
|
c4f28efc45 | ||
|
|
afa4bc06d9 | ||
|
|
828c9ce128 | ||
|
|
6f37a0bd72 | ||
|
|
036086af02 | ||
|
|
f34b5e52e0 |
+2
-1
@@ -1,5 +1,6 @@
|
||||
*.autofetch
|
||||
*.sql
|
||||
*create-all.sql
|
||||
*drop-all.sql
|
||||
*.orig
|
||||
.classpath
|
||||
.project
|
||||
|
||||
+13
-4
@@ -1,7 +1,11 @@
|
||||
sudo: required
|
||||
language: java
|
||||
jdk:
|
||||
- oraclejdk8
|
||||
|
||||
git:
|
||||
depth: 3
|
||||
|
||||
addons:
|
||||
postgresql: "9.4"
|
||||
|
||||
@@ -9,15 +13,20 @@ services:
|
||||
- postgresql
|
||||
|
||||
before_script:
|
||||
- psql -c 'create extension pgcrypto;' -U postgres
|
||||
- psql -c 'create extension hstore;' -U postgres
|
||||
- psql -c 'create extension postgis;' -U postgres
|
||||
- psql -c 'create database unit;' -U postgres
|
||||
- ./.travis/setup_database
|
||||
|
||||
env:
|
||||
- EBEAN_DB=h2
|
||||
- EBEAN_DB=pg
|
||||
|
||||
install: true
|
||||
|
||||
script:
|
||||
- mvn clean test
|
||||
|
||||
after_failure:
|
||||
- ./.travis/print_surefire_reports
|
||||
|
||||
cache:
|
||||
directories:
|
||||
- $HOME/.m2
|
||||
|
||||
Executable
+10
@@ -0,0 +1,10 @@
|
||||
#!/bin/sh
|
||||
|
||||
echo "\n=== SUREFIRE REPORTS ===\n"
|
||||
|
||||
for file in target/surefire-reports/*.txt
|
||||
do
|
||||
echo ${file}
|
||||
cat ${file}
|
||||
echo
|
||||
done
|
||||
Executable
+14
@@ -0,0 +1,14 @@
|
||||
#!/bin/sh
|
||||
|
||||
echo "\n=== SETUP DATABASE ===\n"
|
||||
|
||||
#set -e
|
||||
#set -x
|
||||
|
||||
# Setup postgres' users and databases
|
||||
sudo -u postgres psql -c "CREATE USER unit WITH PASSWORD 'unit';"
|
||||
sudo -u postgres psql -c 'CREATE DATABASE unit WITH OWNER unit;'
|
||||
sudo -u postgres psql unit -c 'CREATE EXTENSION hstore;'
|
||||
sudo -u postgres psql unit -c 'CREATE EXTENSION pgcrypto;'
|
||||
#sudo -u postgres psql test2 -c 'CREATE EXTENSION postgis;'
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
|
||||
<groupId>org.avaje.ebeanorm</groupId>
|
||||
<artifactId>avaje-ebeanorm</artifactId>
|
||||
<version>6.16.2</version>
|
||||
<version>6.17.3</version>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<name>avaje-ebeanorm</name>
|
||||
@@ -219,7 +219,7 @@
|
||||
<plugin>
|
||||
<groupId>org.avaje.ebeanorm</groupId>
|
||||
<artifactId>avaje-ebeanorm-mavenenhancer</artifactId>
|
||||
<version>4.8.1</version>
|
||||
<version>4.9.1</version>
|
||||
<executions>
|
||||
<!-- Not going to enhance Model bean -->
|
||||
<execution>
|
||||
|
||||
@@ -585,6 +585,9 @@ public final class RawSql implements Serializable {
|
||||
* <p>
|
||||
* For example modify all mappings with table alias "c" to have the path prefix "customer".
|
||||
* </p>
|
||||
* <p>
|
||||
* For the "Root type" you don't need to specify a tableAliasMapping.
|
||||
* </p>
|
||||
*/
|
||||
public void tableAliasMapping(String tableAlias, String path) {
|
||||
|
||||
|
||||
@@ -106,6 +106,9 @@ public class RawSqlBuilder {
|
||||
* <p>
|
||||
* For example modify all mappings with table alias "c" to have the path prefix "customer".
|
||||
* </p>
|
||||
* <p>
|
||||
* For the "Root type" you don't need to specify a tableAliasMapping.
|
||||
* </p>
|
||||
*/
|
||||
public RawSqlBuilder tableAliasMapping(String tableAlias, String path) {
|
||||
columnMapping.tableAliasMapping(tableAlias, path);
|
||||
|
||||
@@ -125,6 +125,11 @@ public interface BeanCollection<E> extends Serializable {
|
||||
*/
|
||||
void internalAdd(Object bean);
|
||||
|
||||
/**
|
||||
* Add the bean with a check to see if it is already contained.
|
||||
*/
|
||||
void internalAddWithCheck(Object bean);
|
||||
|
||||
/**
|
||||
* Return the number of elements in the List Set or Map.
|
||||
*/
|
||||
|
||||
@@ -343,28 +343,10 @@ public final class EntityBeanIntercept implements Serializable {
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the lazy load succeeded. If not then mark this bean as having
|
||||
* failed lazy loading due to the underlying row being deleted.
|
||||
* <p>
|
||||
* We mark the bean this way rather than immediately fail as we might be batch
|
||||
* lazy loading and this bean might not be used by the client code at all.
|
||||
* Instead we will fail as soon as the client code tries to use this bean.
|
||||
* </p>
|
||||
* @param lazyLoadPropertyIndex the property that is expected to be loaded
|
||||
* Set lazy load failure flag.
|
||||
*/
|
||||
public boolean isLazyLoadFailure(int lazyLoadPropertyIndex) {
|
||||
if (lazyLoadProperty != -1 || !isLoadedProperty(lazyLoadPropertyIndex)) {
|
||||
lazyLoadFailure = true;
|
||||
return true;
|
||||
}
|
||||
lazyLoadFailure = false;
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the Id of the owner bean.
|
||||
*/
|
||||
public void setOwnerId(Object ownerId) {
|
||||
public void setLazyLoadFailure(Object ownerId) {
|
||||
this.lazyLoadFailure = true;
|
||||
this.ownerId = ownerId;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
package com.avaje.ebean.common;
|
||||
|
||||
import com.avaje.ebean.bean.BeanCollectionAdd;
|
||||
import com.avaje.ebean.bean.BeanCollectionLoader;
|
||||
import com.avaje.ebean.bean.EntityBean;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
@@ -8,17 +12,13 @@ import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.ListIterator;
|
||||
|
||||
import com.avaje.ebean.bean.BeanCollectionAdd;
|
||||
import com.avaje.ebean.bean.BeanCollectionLoader;
|
||||
import com.avaje.ebean.bean.EntityBean;
|
||||
|
||||
/**
|
||||
* List capable of lazy loading.
|
||||
*/
|
||||
public final class BeanList<E> extends AbstractBeanCollection<E> implements List<E>, BeanCollectionAdd {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
|
||||
/**
|
||||
* The underlying List implementation.
|
||||
*/
|
||||
@@ -74,6 +74,13 @@ public final class BeanList<E> extends AbstractBeanCollection<E> implements List
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void internalAddWithCheck(Object bean) {
|
||||
if (list == null || !list.contains(bean)) {
|
||||
internalAdd(bean);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean checkEmptyLazyLoad() {
|
||||
if (list == null) {
|
||||
list = new ArrayList<E>();
|
||||
@@ -99,11 +106,11 @@ public final class BeanList<E> extends AbstractBeanCollection<E> implements List
|
||||
private void initAsUntouched() {
|
||||
init(false);
|
||||
}
|
||||
|
||||
|
||||
private void init() {
|
||||
init(true);
|
||||
}
|
||||
|
||||
|
||||
private void init(boolean setTouched) {
|
||||
synchronized (this) {
|
||||
if (list == null) {
|
||||
@@ -134,7 +141,7 @@ public final class BeanList<E> extends AbstractBeanCollection<E> implements List
|
||||
public Collection<E> getActualDetails() {
|
||||
return list;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public Collection<?> getActualEntries() {
|
||||
return list;
|
||||
|
||||
@@ -66,7 +66,18 @@ public final class BeanMap<K, E> extends AbstractBeanCollection<E> implements Ma
|
||||
map.put((K) key, (E) bean);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public void internalPutWithCheck(Object key, Object bean) {
|
||||
if (map == null || !map.containsKey(key)) {
|
||||
internalPut(key, bean);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void internalAddWithCheck(Object bean) {
|
||||
throw new RuntimeException("Not allowed for map");
|
||||
}
|
||||
|
||||
public void internalAdd(Object bean) {
|
||||
throw new RuntimeException("Not allowed for map");
|
||||
}
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
package com.avaje.ebean.common;
|
||||
|
||||
import com.avaje.ebean.bean.BeanCollectionAdd;
|
||||
import com.avaje.ebean.bean.BeanCollectionLoader;
|
||||
import com.avaje.ebean.bean.EntityBean;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Collection;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Set;
|
||||
|
||||
import com.avaje.ebean.bean.BeanCollectionAdd;
|
||||
import com.avaje.ebean.bean.BeanCollectionLoader;
|
||||
import com.avaje.ebean.bean.EntityBean;
|
||||
|
||||
/**
|
||||
* Set capable of lazy loading.
|
||||
*/
|
||||
@@ -57,6 +57,13 @@ public final class BeanSet<E> extends AbstractBeanCollection<E> implements Set<E
|
||||
set.add((E) bean);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void internalAddWithCheck(Object bean) {
|
||||
if (set == null || !set.contains(bean)) {
|
||||
internalAdd(bean);
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public void internalAdd(Object bean) {
|
||||
if (set == null) {
|
||||
@@ -107,11 +114,11 @@ public final class BeanSet<E> extends AbstractBeanCollection<E> implements Set<E
|
||||
private void initAsUntouched() {
|
||||
init(false);
|
||||
}
|
||||
|
||||
|
||||
private void init() {
|
||||
init(true);
|
||||
}
|
||||
|
||||
|
||||
private void init(boolean setTouched) {
|
||||
synchronized (this) {
|
||||
if (set == null) {
|
||||
|
||||
@@ -23,11 +23,6 @@ public class DbMigrationConfig {
|
||||
*/
|
||||
protected boolean generate;
|
||||
|
||||
/**
|
||||
* Set to true to suppress the output of the rollback script.
|
||||
*/
|
||||
protected boolean suppressRollback;
|
||||
|
||||
/**
|
||||
* The migration version name (typically FlywayDb compatible).
|
||||
* <p>
|
||||
@@ -61,33 +56,17 @@ public class DbMigrationConfig {
|
||||
*/
|
||||
protected String modelPath = "model";
|
||||
|
||||
/**
|
||||
* Subdirectory the drop ddl scripts go into.
|
||||
*/
|
||||
protected String dropPath = "drop";
|
||||
|
||||
/**
|
||||
* Subdirectory the rollback ddl scripts go into.
|
||||
*/
|
||||
protected String rollbackPath = "rollback";
|
||||
|
||||
/**
|
||||
* Apply script suffix.
|
||||
*/
|
||||
protected String applySuffix = ".sql";
|
||||
|
||||
/**
|
||||
* Default drop script suffix to ddl so that it isn't picked up by FlywayDb.
|
||||
*/
|
||||
protected String dropSuffix = ".drop.ddl";
|
||||
|
||||
/**
|
||||
* Default rollback script suffix to ddl so that it isn't picked up by FlywayDb.
|
||||
*/
|
||||
protected String rollbackSuffix = ".rollback.ddl";
|
||||
|
||||
protected String modelSuffix = ".model.xml";
|
||||
|
||||
protected boolean includeGeneratedFileComment;
|
||||
|
||||
/**
|
||||
* The version of a pending drop that should be generated as the next migration.
|
||||
*/
|
||||
protected String generatePendingDrop;
|
||||
|
||||
/**
|
||||
* Return the DB platform to generate migration DDL for.
|
||||
*
|
||||
@@ -138,34 +117,6 @@ public class DbMigrationConfig {
|
||||
this.modelPath = modelPath;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the relative path for the drop ddl scripts (defaults to drop).
|
||||
*/
|
||||
public String getDropPath() {
|
||||
return dropPath;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the relative path for the drop ddl scripts (defaults to drop).
|
||||
*/
|
||||
public void setDropPath(String dropPath) {
|
||||
this.dropPath = dropPath;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the relative path for the rollback ddl scripts (defaults to rollback).
|
||||
*/
|
||||
public String getRollbackPath() {
|
||||
return rollbackPath;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the relative path for the rollback ddl scripts (defaults to rollback).
|
||||
*/
|
||||
public void setRollbackPath(String rollbackPath) {
|
||||
this.rollbackPath = rollbackPath;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the model suffix (defaults to model.xml)
|
||||
*/
|
||||
@@ -180,20 +131,6 @@ public class DbMigrationConfig {
|
||||
this.modelSuffix = modelSuffix;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true if the rollback script should not be output.
|
||||
*/
|
||||
public boolean isSuppressRollback() {
|
||||
return suppressRollback;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set to true to suppress the output of the rollback script.
|
||||
*/
|
||||
public void setSuppressRollback(boolean suppressRollback) {
|
||||
this.suppressRollback = suppressRollback;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the apply script suffix (defaults to sql).
|
||||
*/
|
||||
@@ -209,31 +146,31 @@ public class DbMigrationConfig {
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the drop script suffix (defaults to ddl so that it isn't picked up by FlywayDb).
|
||||
* Return true if the generated file comment should be included.
|
||||
*/
|
||||
public String getDropSuffix() {
|
||||
return dropSuffix;
|
||||
public boolean isIncludeGeneratedFileComment() {
|
||||
return includeGeneratedFileComment;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the drop script suffix (defaults to ddl so that it isn't picked up by FlywayDb).
|
||||
* Set to true if the generated file comment should be included.
|
||||
*/
|
||||
public void setDropSuffix(String dropSuffix) {
|
||||
this.dropSuffix = dropSuffix;
|
||||
public void setIncludeGeneratedFileComment(boolean includeGeneratedFileComment) {
|
||||
this.includeGeneratedFileComment = includeGeneratedFileComment;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the rollback script suffix (defaults to ddl so that it isn't picked up by FlywayDb).
|
||||
* Return the migration version (or "next") to generate pending drops for.
|
||||
*/
|
||||
public String getRollbackSuffix() {
|
||||
return rollbackSuffix;
|
||||
public String getGeneratePendingDrop() {
|
||||
return generatePendingDrop;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the rollback script suffix (defaults to ddl so that it isn't picked up by FlywayDb).
|
||||
* Set the migration version (or "next") to generate pending drops for.
|
||||
*/
|
||||
public void setRollbackSuffix(String rollbackSuffix) {
|
||||
this.rollbackSuffix = rollbackSuffix;
|
||||
public void setGeneratePendingDrop(String generatePendingDrop) {
|
||||
this.generatePendingDrop = generatePendingDrop;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -259,8 +196,6 @@ public class DbMigrationConfig {
|
||||
* into a single directory.
|
||||
*/
|
||||
public void singleDirectory() {
|
||||
this.dropPath = "";
|
||||
this.rollbackPath = "";
|
||||
this.modelPath = "";
|
||||
}
|
||||
|
||||
@@ -274,16 +209,13 @@ public class DbMigrationConfig {
|
||||
singleDirectory();
|
||||
} else {
|
||||
modelPath = properties.get("migration.modelPath", modelPath);
|
||||
rollbackPath = properties.get("migration.rollbackPath", rollbackPath);
|
||||
dropPath = properties.get("migration.dropPath", dropPath);
|
||||
}
|
||||
applySuffix = properties.get("migration.applySuffix", applySuffix);
|
||||
dropSuffix = properties.get("migration.dropSuffix", dropSuffix);
|
||||
rollbackSuffix = properties.get("migration.rollbackSuffix", rollbackSuffix);
|
||||
modelSuffix = properties.get("migration.modelSuffix", modelSuffix);
|
||||
includeGeneratedFileComment = properties.getBoolean("migration.includeGeneratedFileComment", includeGeneratedFileComment);
|
||||
generatePendingDrop = properties.get("migration.generatePendingDrop", generatePendingDrop);
|
||||
|
||||
platform = properties.getEnum(DbPlatformName.class, "migration.platform", platform);
|
||||
suppressRollback = properties.getBoolean("migration.suppressRollback", suppressRollback);
|
||||
|
||||
generate = properties.getBoolean("migration.generate", generate);
|
||||
version = properties.get("migration.version", version);
|
||||
@@ -307,7 +239,6 @@ public class DbMigrationConfig {
|
||||
return generate;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Called by EbeanServer on start.
|
||||
*
|
||||
|
||||
@@ -20,6 +20,7 @@ import com.avaje.ebean.dbmigration.migrationreader.MigrationXmlWriter;
|
||||
import com.avaje.ebean.dbmigration.model.CurrentModel;
|
||||
import com.avaje.ebean.dbmigration.model.MConfiguration;
|
||||
import com.avaje.ebean.dbmigration.model.MigrationModel;
|
||||
import com.avaje.ebean.dbmigration.model.MigrationVersion;
|
||||
import com.avaje.ebean.dbmigration.model.ModelContainer;
|
||||
import com.avaje.ebean.dbmigration.model.ModelDiff;
|
||||
import com.avaje.ebean.dbmigration.model.PlatformDdlWriter;
|
||||
@@ -59,6 +60,8 @@ public class DbMigration {
|
||||
|
||||
private static final String initialVersion = "1.0";
|
||||
|
||||
private static final String GENERATED_COMMENT = "THIS IS A GENERATED FILE - DO NOT MODIFY";
|
||||
|
||||
/**
|
||||
* Set to true if DbMigration run with online EbeanServer instance.
|
||||
*/
|
||||
@@ -199,46 +202,15 @@ public class DbMigration {
|
||||
if (!online) {
|
||||
DbOffline.setRunningMigration();
|
||||
}
|
||||
|
||||
setDefaults();
|
||||
|
||||
try {
|
||||
Request request = createRequest();
|
||||
|
||||
File migrationDir = getMigrationDirectory();
|
||||
File modelDir = getModelDirectory(migrationDir);
|
||||
|
||||
MigrationModel migrationModel = new MigrationModel(modelDir, migrationConfig.getModelSuffix());
|
||||
ModelContainer migrated = migrationModel.read();
|
||||
|
||||
CurrentModel currentModel = new CurrentModel(server, constraintNaming);
|
||||
ModelContainer current = currentModel.read();
|
||||
|
||||
ModelDiff diff = new ModelDiff(migrated);
|
||||
diff.compareTo(current);
|
||||
|
||||
if (diff.isEmpty()) {
|
||||
logger.info("no changes detected - no migration written");
|
||||
return;
|
||||
}
|
||||
|
||||
// there were actually changes to write
|
||||
Migration dbMigration = diff.getMigration();
|
||||
|
||||
String fullVersion = getFullVersion(migrationModel);
|
||||
|
||||
logger.info("generating migration:{}", fullVersion);
|
||||
if (!writeMigrationXml(dbMigration, modelDir, fullVersion)) {
|
||||
logger.warn("migration already exists, not generating DDL");
|
||||
|
||||
String pendingVersion = generatePendingDrop();
|
||||
if (pendingVersion != null) {
|
||||
generatePendingDrop(request, pendingVersion);
|
||||
} else {
|
||||
if (databasePlatform != null) {
|
||||
// writer needs the current model to provide table/column details for
|
||||
// history ddl generation (triggers, history tables etc)
|
||||
DdlWrite write = new DdlWrite(new MConfiguration(), currentModel.read());
|
||||
PlatformDdlWriter writer = createDdlWriter(databasePlatform, "");
|
||||
writer.processMigration(dbMigration, write, migrationDir , fullVersion);
|
||||
}
|
||||
writeExtraPlatformDdl(fullVersion, currentModel, dbMigration, migrationDir);
|
||||
generateDiff(request);
|
||||
}
|
||||
|
||||
} finally {
|
||||
@@ -249,9 +221,128 @@ public class DbMigration {
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the full version for the migration being generated.
|
||||
* Generate the diff migration.
|
||||
*/
|
||||
private String getFullVersion(MigrationModel migrationModel) {
|
||||
private void generateDiff(Request request) throws IOException {
|
||||
|
||||
List<String> pendingDrops = request.getPendingDrops();
|
||||
if (!pendingDrops.isEmpty()) {
|
||||
logger.info("Pending un-applied drops in versions {}", pendingDrops);
|
||||
}
|
||||
|
||||
Migration migration = request.createDiffMigration();
|
||||
if (migration == null) {
|
||||
logger.info("no changes detected - no migration written");
|
||||
} else {
|
||||
// there were actually changes to write
|
||||
generateMigration(request, migration, null);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate the migration based on the pendingDrops from a prior version.
|
||||
*/
|
||||
private void generatePendingDrop(Request request, String pendingVersion) throws IOException {
|
||||
|
||||
Migration migration = request.migrationForPendingDrop(pendingVersion);
|
||||
|
||||
generateMigration(request, migration, pendingVersion);
|
||||
|
||||
List<String> pendingDrops = request.getPendingDrops();
|
||||
if (!pendingDrops.isEmpty()) {
|
||||
logger.info("... remaining pending un-applied drops in versions {}", pendingDrops);
|
||||
}
|
||||
}
|
||||
|
||||
private Request createRequest() {
|
||||
return new Request();
|
||||
}
|
||||
|
||||
private class Request {
|
||||
|
||||
final File migrationDir;
|
||||
final File modelDir;
|
||||
final MigrationModel migrationModel;
|
||||
final CurrentModel currentModel;
|
||||
final ModelContainer migrated;
|
||||
final ModelContainer current;
|
||||
|
||||
private Request() {
|
||||
this.migrationDir = getMigrationDirectory();
|
||||
this.modelDir = getModelDirectory(migrationDir);
|
||||
this.migrationModel = new MigrationModel(modelDir, migrationConfig.getModelSuffix());
|
||||
this.migrated = migrationModel.read();
|
||||
this.currentModel = new CurrentModel(server, constraintNaming);
|
||||
this.current = currentModel.read();
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the migration for the pending drops for a given version.
|
||||
*/
|
||||
public Migration migrationForPendingDrop(String pendingVersion) {
|
||||
|
||||
Migration migration = migrated.migrationForPendingDrop(pendingVersion);
|
||||
|
||||
// register any remaining pending drops
|
||||
migrated.registerPendingHistoryDropColumns(current);
|
||||
return migration;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the list of versions that have pending un-applied drops.
|
||||
*/
|
||||
public List<String> getPendingDrops() {
|
||||
return migrated.getPendingDrops();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create and return the diff of the current model to the migration model.
|
||||
*/
|
||||
public Migration createDiffMigration() {
|
||||
ModelDiff diff = new ModelDiff(migrated);
|
||||
diff.compareTo(current);
|
||||
return diff.isEmpty() ? null : diff.getMigration();
|
||||
}
|
||||
}
|
||||
|
||||
private void generateMigration(Request request, Migration dbMigration, String dropsFor) throws IOException {
|
||||
|
||||
String fullVersion = getFullVersion(request.migrationModel, dropsFor);
|
||||
|
||||
logger.info("generating migration:{}", fullVersion);
|
||||
if (!writeMigrationXml(dbMigration, request.modelDir, fullVersion)) {
|
||||
logger.warn("migration already exists, not generating DDL");
|
||||
|
||||
} else {
|
||||
if (databasePlatform != null) {
|
||||
// writer needs the current model to provide table/column details for
|
||||
// history ddl generation (triggers, history tables etc)
|
||||
DdlWrite write = new DdlWrite(new MConfiguration(), request.current);
|
||||
PlatformDdlWriter writer = createDdlWriter(databasePlatform, "");
|
||||
writer.processMigration(dbMigration, write, request.migrationDir , fullVersion);
|
||||
}
|
||||
writeExtraPlatformDdl(fullVersion, request.currentModel, dbMigration, request.migrationDir);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true if the next pending drop changeSet should be generated as the next migration.
|
||||
*/
|
||||
private String generatePendingDrop() {
|
||||
|
||||
String nextDrop = System.getProperty("ddl.migration.pendingDropsFor");
|
||||
if (nextDrop != null) {
|
||||
return nextDrop;
|
||||
}
|
||||
return migrationConfig.getGeneratePendingDrop();
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the full version for the migration being generated.
|
||||
*
|
||||
* The full version can contain a comment suffix after a "__" double underscore.
|
||||
*/
|
||||
private String getFullVersion(MigrationModel migrationModel, String dropsFor) {
|
||||
|
||||
String version = migrationConfig.getVersion();
|
||||
if (version == null) {
|
||||
@@ -259,10 +350,14 @@ public class DbMigration {
|
||||
}
|
||||
|
||||
String fullVersion = version;
|
||||
if (migrationConfig.getName() != null) {
|
||||
fullVersion += "__" + toUnderScore(migrationConfig.getName());
|
||||
|
||||
String name = migrationConfig.getName();
|
||||
if (name != null) {
|
||||
fullVersion += "__" + toUnderScore(name);
|
||||
} else if (dropsFor != null) {
|
||||
fullVersion += "__" + toUnderScore("dropsFor_" + MigrationVersion.trim(dropsFor));
|
||||
|
||||
} else if (version.equals(initialVersion)) {
|
||||
fullVersion += "__initial";
|
||||
}
|
||||
return fullVersion;
|
||||
}
|
||||
@@ -304,7 +399,8 @@ public class DbMigration {
|
||||
if (file.exists()) {
|
||||
return false;
|
||||
}
|
||||
MigrationXmlWriter xmlWriter = new MigrationXmlWriter();
|
||||
String comment = migrationConfig.isIncludeGeneratedFileComment() ? GENERATED_COMMENT : null;
|
||||
MigrationXmlWriter xmlWriter = new MigrationXmlWriter(comment);
|
||||
xmlWriter.write(dbMigration, file);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@ package com.avaje.ebean.dbmigration;
|
||||
|
||||
import com.avaje.ebean.config.ServerConfig;
|
||||
import com.avaje.ebean.dbmigration.model.CurrentModel;
|
||||
import com.avaje.ebeaninternal.api.SpiEbeanPlugin;
|
||||
import com.avaje.ebeaninternal.api.SpiEbeanServer;
|
||||
|
||||
import javax.persistence.PersistenceException;
|
||||
@@ -30,8 +29,8 @@ public class DdlGenerator {
|
||||
private final boolean createOnly;
|
||||
|
||||
private CurrentModel currentModel;
|
||||
private String dropContent;
|
||||
private String createContent;
|
||||
private String dropAllContent;
|
||||
private String createAllContent;
|
||||
|
||||
public DdlGenerator(SpiEbeanServer server, ServerConfig serverConfig) {
|
||||
this.server = server;
|
||||
@@ -84,18 +83,18 @@ public class DdlGenerator {
|
||||
|
||||
protected void runDropSql() throws IOException {
|
||||
if (!createOnly) {
|
||||
if (dropContent == null) {
|
||||
dropContent = readFile(getDropFileName());
|
||||
if (dropAllContent == null) {
|
||||
dropAllContent = readFile(getDropFileName());
|
||||
}
|
||||
runScript(true, dropContent, getDropFileName());
|
||||
runScript(true, dropAllContent, getDropFileName());
|
||||
}
|
||||
}
|
||||
|
||||
protected void runCreateSql() throws IOException {
|
||||
if (createContent == null) {
|
||||
createContent = readFile(getCreateFileName());
|
||||
if (createAllContent == null) {
|
||||
createAllContent = readFile(getCreateFileName());
|
||||
}
|
||||
runScript(false, createContent, getCreateFileName());
|
||||
runScript(false, createAllContent, getCreateFileName());
|
||||
}
|
||||
|
||||
protected void runInitSql() throws IOException {
|
||||
@@ -132,8 +131,7 @@ public class DdlGenerator {
|
||||
protected void writeDrop(String dropFile) {
|
||||
|
||||
try {
|
||||
String c = generateDropDdl();
|
||||
writeFile(dropFile, c);
|
||||
writeFile(dropFile, generateDropAllDdl());
|
||||
} catch (IOException e) {
|
||||
throw new PersistenceException("Error generating Drop DDL", e);
|
||||
}
|
||||
@@ -142,28 +140,27 @@ public class DdlGenerator {
|
||||
protected void writeCreate(String createFile) {
|
||||
|
||||
try {
|
||||
String c = generateCreateDdl();
|
||||
writeFile(createFile, c);
|
||||
writeFile(createFile, generateCreateAllDdl());
|
||||
} catch (IOException e) {
|
||||
throw new PersistenceException("Error generating Create DDL", e);
|
||||
}
|
||||
}
|
||||
|
||||
protected String generateDropDdl() {
|
||||
protected String generateDropAllDdl() {
|
||||
|
||||
try {
|
||||
dropContent = currentModel().getDropDdl();
|
||||
return dropContent;
|
||||
dropAllContent = currentModel().getDropAllDdl();
|
||||
return dropAllContent;
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
protected String generateCreateDdl() {
|
||||
protected String generateCreateAllDdl() {
|
||||
|
||||
try {
|
||||
createContent = currentModel().getCreateDdl();
|
||||
return createContent;
|
||||
createAllContent = currentModel().getCreateDdl();
|
||||
return createAllContent;
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
@@ -12,32 +12,17 @@ public class DdlWrite {
|
||||
|
||||
private final ModelContainer currentModel;
|
||||
|
||||
private final DdlBuffer applyDropDependencies;
|
||||
|
||||
private final DdlBuffer apply;
|
||||
|
||||
private final DdlBuffer applyForeignKeys;
|
||||
|
||||
private final DdlBuffer applyHistory;
|
||||
|
||||
private final DdlBuffer rollbackForeignKeys;
|
||||
private final DdlBuffer dropAllForeignKeys;
|
||||
|
||||
private final DdlBuffer rollback;
|
||||
|
||||
/**
|
||||
* For DDL that drops tables and columns etc.
|
||||
*
|
||||
* This DDL typically can not run automatically in production as there is most commonly
|
||||
* existing servers running the application using these tables and columns. Typically
|
||||
* these drop statements may be executed AFTER all the servers in the application have
|
||||
* migrated onto new code.
|
||||
*/
|
||||
private final DdlBuffer drop;
|
||||
|
||||
/**
|
||||
* For use when History is turned off for a base table or history is no longer
|
||||
* desired on specific columns. This DDL should typically execute manually after review
|
||||
* by DBA's.
|
||||
*/
|
||||
private final DdlBuffer dropHistory;
|
||||
private final DdlBuffer dropAll;
|
||||
|
||||
/**
|
||||
* Create without any configuration or current model (no history support).
|
||||
@@ -51,13 +36,12 @@ public class DdlWrite {
|
||||
*/
|
||||
public DdlWrite(MConfiguration configuration, ModelContainer currentModel) {
|
||||
this.currentModel = currentModel;
|
||||
this.applyDropDependencies = new BaseDdlBuffer(configuration);
|
||||
this.apply = new BaseDdlBuffer(configuration);
|
||||
this.applyForeignKeys = new BaseDdlBuffer(configuration);
|
||||
this.applyHistory = new BaseDdlBuffer(configuration);
|
||||
this.rollbackForeignKeys = new BaseDdlBuffer(configuration);
|
||||
this.rollback = new BaseDdlBuffer(configuration);
|
||||
this.drop = new BaseDdlBuffer(configuration);
|
||||
this.dropHistory = new BaseDdlBuffer(configuration);
|
||||
this.dropAllForeignKeys = new BaseDdlBuffer(configuration);
|
||||
this.dropAll = new BaseDdlBuffer(configuration);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -77,22 +61,8 @@ public class DdlWrite {
|
||||
public boolean isApplyEmpty() {
|
||||
return apply.getBuffer().isEmpty()
|
||||
&& applyForeignKeys.getBuffer().isEmpty()
|
||||
&& applyHistory.getBuffer().isEmpty();
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true if the apply rollback buffers are all empty.
|
||||
*/
|
||||
public boolean isApplyRollbackEmpty() {
|
||||
return rollback.getBuffer().isEmpty()
|
||||
&& rollbackForeignKeys.getBuffer().isEmpty();
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true the drop buffers are empty.
|
||||
*/
|
||||
public boolean isDropEmpty() {
|
||||
return drop.getBuffer().isEmpty() && dropHistory.getBuffer().isEmpty();
|
||||
&& applyHistory.getBuffer().isEmpty()
|
||||
&& applyDropDependencies.getBuffer().isEmpty();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -102,6 +72,13 @@ public class DdlWrite {
|
||||
return apply;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the buffer that executes early to drop dependencies like views etc.
|
||||
*/
|
||||
public DdlBuffer applyDropDependencies() {
|
||||
return applyDropDependencies;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the buffer that APPLY DDL is written to for foreign keys and their associated indexes.
|
||||
* <p>
|
||||
@@ -120,41 +97,17 @@ public class DdlWrite {
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the buffer that ROLLBACK DDL is written to for foreign keys and associated indexes.
|
||||
* Return the buffer used for the 'drop all DDL' for dropping foreign keys and associated indexes.
|
||||
*/
|
||||
public DdlBuffer rollbackForeignKeys() {
|
||||
return rollbackForeignKeys;
|
||||
public DdlBuffer dropAllForeignKeys() {
|
||||
return dropAllForeignKeys;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the buffer that ROLLBACK DDL is written to which is considered safe to run when
|
||||
* apply changes fail to execute. This will reverse the apply changes typically dropping
|
||||
* newly created tables, foreign keys etc.
|
||||
* <p>
|
||||
* When apply changes are made against DB's that support transactional DDL you could argue
|
||||
* that these rollback statements are not necessary.
|
||||
* <p>
|
||||
* Note that statements added to this rollback buffer are executed after foreign key rollback
|
||||
* has been executed.
|
||||
* Return the buffer used for the 'drop all DDL' to drop tables, views and history triggers etc.
|
||||
*/
|
||||
public DdlBuffer rollback() {
|
||||
return rollback;
|
||||
public DdlBuffer dropAll() {
|
||||
return dropAll;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the buffer that destructive changes are written to. This is typically drop table and
|
||||
* drop column.
|
||||
*/
|
||||
public DdlBuffer drop() {
|
||||
return drop;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the buffer that is used when history is no longer required on a table or specific columns.
|
||||
*/
|
||||
public DdlBuffer dropHistory() {
|
||||
return dropHistory;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
+13
-42
@@ -140,7 +140,7 @@ public class BaseTableDdl implements TableDdl {
|
||||
|
||||
// add drop table to the rollback buffer - do this before
|
||||
// we drop the related sequence (if sequences are used)
|
||||
dropTable(writer.rollback(), tableName);
|
||||
dropTable(writer.dropAll(), tableName);
|
||||
|
||||
if (useSequence) {
|
||||
String pkCol = pk.get(0).getName();
|
||||
@@ -149,7 +149,7 @@ public class BaseTableDdl implements TableDdl {
|
||||
|
||||
// add blank line for a bit of whitespace between tables
|
||||
apply.end();
|
||||
writer.rollback().end();
|
||||
writer.dropAll().end();
|
||||
|
||||
writeAddForeignKeys(writer, createTable);
|
||||
|
||||
@@ -204,7 +204,7 @@ public class BaseTableDdl implements TableDdl {
|
||||
.append(platformDdl.alterTableAddUniqueConstraint(tableName, uqName, columnNames))
|
||||
.endOfStatement();
|
||||
|
||||
write.rollbackForeignKeys()
|
||||
write.dropAllForeignKeys()
|
||||
.append(platformDdl.dropIndex(uqName, tableName))
|
||||
.endOfStatement();
|
||||
}
|
||||
@@ -225,7 +225,7 @@ public class BaseTableDdl implements TableDdl {
|
||||
String createSeq = platformDdl.createSequence(seqName, initial, allocate);
|
||||
if (createSeq != null) {
|
||||
writer.apply().append(createSeq).newLine();
|
||||
writer.rollback().append(platformDdl.dropSequence(seqName)).endOfStatement();
|
||||
writer.dropAll().append(platformDdl.dropSequence(seqName)).endOfStatement();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -295,15 +295,15 @@ public class BaseTableDdl implements TableDdl {
|
||||
|
||||
fkeyBuffer.end();
|
||||
|
||||
write.rollbackForeignKeys()
|
||||
write.dropAllForeignKeys()
|
||||
.append(platformDdl.alterTableDropForeignKey(tableName, fkName)).endOfStatement();
|
||||
|
||||
if (indexName != null) {
|
||||
write.rollbackForeignKeys()
|
||||
write.dropAllForeignKeys()
|
||||
.append(platformDdl.dropIndex(indexName, tableName)).endOfStatement();
|
||||
}
|
||||
|
||||
write.rollbackForeignKeys().end();
|
||||
write.dropAllForeignKeys().end();
|
||||
|
||||
}
|
||||
|
||||
@@ -471,7 +471,7 @@ public class BaseTableDdl implements TableDdl {
|
||||
.append(platformDdl.createIndex(createIndex.getIndexName(), createIndex.getTableName(), cols))
|
||||
.endOfStatement();
|
||||
|
||||
writer.rollback()
|
||||
writer.dropAll()
|
||||
.append(platformDdl.dropIndex(createIndex.getIndexName(), createIndex.getTableName()))
|
||||
.endOfStatement();
|
||||
}
|
||||
@@ -520,7 +520,6 @@ public class BaseTableDdl implements TableDdl {
|
||||
List<Column> columns = addColumn.getColumn();
|
||||
for (Column column : columns) {
|
||||
alterTableAddColumn(writer.apply(), tableName, column, false);
|
||||
alterTableDropColumn(writer.rollback(), tableName, column.getName());
|
||||
}
|
||||
|
||||
if (isTrue(addColumn.isWithHistory())) {
|
||||
@@ -529,13 +528,11 @@ public class BaseTableDdl implements TableDdl {
|
||||
for (Column column : columns) {
|
||||
regenerateHistoryTriggers(tableName, HistoryTableUpdate.Change.ADD, column.getName());
|
||||
alterTableAddColumn(writer.apply(), historyTable, column, true);
|
||||
alterTableDropColumn(writer.rollback(), historyTable, column.getName());
|
||||
}
|
||||
}
|
||||
|
||||
// add a bit of whitespace
|
||||
writer.apply().end();
|
||||
writer.rollback().end();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -544,7 +541,7 @@ public class BaseTableDdl implements TableDdl {
|
||||
@Override
|
||||
public void generate(DdlWrite writer, DropTable dropTable) throws IOException {
|
||||
|
||||
dropTable(writer.drop(), dropTable.getName());
|
||||
dropTable(writer.apply(), dropTable.getName());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -555,14 +552,14 @@ public class BaseTableDdl implements TableDdl {
|
||||
|
||||
String tableName = dropColumn.getTableName();
|
||||
|
||||
alterTableDropColumn(writer.drop(), tableName, dropColumn.getColumnName());
|
||||
alterTableDropColumn(writer.apply(), tableName, dropColumn.getColumnName());
|
||||
if (isTrue(dropColumn.isWithHistory())) {
|
||||
// also drop from the history table
|
||||
regenerateHistoryTriggers(tableName, HistoryTableUpdate.Change.DROP, dropColumn.getColumnName());
|
||||
alterTableDropColumn(writer.drop(), historyTable(tableName), dropColumn.getColumnName());
|
||||
alterTableDropColumn(writer.apply(), historyTable(tableName), dropColumn.getColumnName());
|
||||
}
|
||||
|
||||
writer.drop().end();
|
||||
writer.apply().end();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -642,21 +639,6 @@ public class BaseTableDdl implements TableDdl {
|
||||
if (hasValue(ddl)) {
|
||||
writer.apply().append(ddl).endOfStatement();
|
||||
|
||||
// reverse and generate the rollback statement
|
||||
String currentType = alter.getCurrentType();
|
||||
String type = alter.getType();
|
||||
Boolean currentNotnull = alter.isCurrentNotnull();
|
||||
Boolean notnull = alter.isNotnull();
|
||||
|
||||
alter.setCurrentType(type);
|
||||
alter.setType(currentType);
|
||||
alter.setNotnull(currentNotnull);
|
||||
alter.setCurrentNotnull(notnull);
|
||||
|
||||
// write the rollback
|
||||
ddl = platformDdl.alterColumnBaseAttributes(alter);
|
||||
writer.rollback().append(ddl).endOfStatement();
|
||||
|
||||
if (isTrue(alter.isWithHistory()) && alter.getType() != null) {
|
||||
// mysql and sql server column type change allowing nulls in the history table column
|
||||
AlterColumn alterHistoryColumn = new AlterColumn();
|
||||
@@ -667,11 +649,6 @@ public class BaseTableDdl implements TableDdl {
|
||||
|
||||
// write the apply to history table
|
||||
writer.apply().append(histColumnDdl).endOfStatement();
|
||||
|
||||
// write the rollback from history table
|
||||
alterHistoryColumn.setType(currentType);
|
||||
histColumnDdl = platformDdl.alterColumnBaseAttributes(alterHistoryColumn);
|
||||
writer.rollback().append(histColumnDdl).endOfStatement();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -689,8 +666,6 @@ public class BaseTableDdl implements TableDdl {
|
||||
String ddl = platformDdl.alterColumnNotnull(alter.getTableName(), alter.getColumnName(), alter.isNotnull());
|
||||
if (hasValue(ddl)) {
|
||||
writer.apply().append(ddl).endOfStatement();
|
||||
ddl = platformDdl.alterColumnNotnull(alter.getTableName(), alter.getColumnName(), alter.isCurrentNotnull());
|
||||
writer.rollback().append(ddl).endOfStatement();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -699,14 +674,10 @@ public class BaseTableDdl implements TableDdl {
|
||||
String ddl = platformDdl.alterColumnType(alter.getTableName(), alter.getColumnName(), alter.getType());
|
||||
if (hasValue(ddl)) {
|
||||
writer.apply().append(ddl).endOfStatement();
|
||||
ddl = platformDdl.alterColumnType(alter.getTableName(), alter.getColumnName(), alter.getCurrentType());
|
||||
writer.rollback().append(ddl).endOfStatement();
|
||||
if (isTrue(alter.isWithHistory())) {
|
||||
// apply same type change to matching column in the history table
|
||||
ddl = platformDdl.alterColumnType(historyTable(alter.getTableName()), alter.getColumnName(), alter.getType());
|
||||
writer.apply().append(ddl).endOfStatement();
|
||||
ddl = platformDdl.alterColumnType(historyTable(alter.getTableName()), alter.getColumnName(), alter.getCurrentType());
|
||||
writer.rollback().append(ddl).endOfStatement();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -762,7 +733,7 @@ public class BaseTableDdl implements TableDdl {
|
||||
.append(platformDdl.alterTableAddUniqueConstraint(alter.getTableName(), uqName, cols))
|
||||
.endOfStatement();
|
||||
|
||||
writer.rollbackForeignKeys()
|
||||
writer.dropAllForeignKeys()
|
||||
.append(platformDdl.dropIndex(uqName, alter.getTableName()))
|
||||
.endOfStatement();
|
||||
}
|
||||
|
||||
+75
-30
@@ -10,7 +10,6 @@ import com.avaje.ebean.dbmigration.model.MColumn;
|
||||
import com.avaje.ebean.dbmigration.model.MTable;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
@@ -45,21 +44,43 @@ public abstract class DbTriggerBasedHistoryDdl implements PlatformHistoryDdl {
|
||||
this.historySuffix = serverConfig.getHistoryTableSuffix();
|
||||
this.constraintNaming = serverConfig.getConstraintNaming();
|
||||
|
||||
this.sysPeriodStart = sysPeriod+"_start";
|
||||
this.sysPeriodEnd = sysPeriod+"_end";
|
||||
this.sysPeriodStart = sysPeriod + "_start";
|
||||
this.sysPeriodEnd = sysPeriod + "_end";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void regenerateHistoryTriggers(DdlWrite writer, HistoryTableUpdate update) throws IOException {
|
||||
public void updateTriggers(DdlWrite writer, HistoryTableUpdate update) throws IOException {
|
||||
|
||||
MTable table = writer.getTable(update.getBaseTable());
|
||||
if (table == null) {
|
||||
throw new IllegalStateException("MTable "+update.getBaseTable()+" not found in writer? (required for history DDL)");
|
||||
throw new IllegalStateException("MTable " + update.getBaseTable() + " not found in writer? (required for history DDL)");
|
||||
}
|
||||
regenerateHistoryTriggers(writer, table, update);
|
||||
updateTriggers(writer, table, update);
|
||||
}
|
||||
|
||||
protected abstract void regenerateHistoryTriggers(DdlWrite writer, MTable table, HistoryTableUpdate update) throws IOException;
|
||||
/**
|
||||
* Replace the existing triggers/stored procedures/views for history table support given the included columns.
|
||||
*/
|
||||
protected abstract void updateHistoryTriggers(DbTriggerUpdate triggerUpdate) throws IOException;
|
||||
|
||||
/**
|
||||
* Process the HistoryTableUpdate which can result in changes to the apply, rollback
|
||||
* and drop scripts.
|
||||
*/
|
||||
protected void updateTriggers(DdlWrite writer, MTable table, HistoryTableUpdate update) throws IOException {
|
||||
|
||||
writer.applyHistory().append("-- changes: ").append(update.description()).newLine();
|
||||
|
||||
updateHistoryTriggers(createDbTriggerUpdate(writer, table));
|
||||
}
|
||||
|
||||
protected DbTriggerUpdate createDbTriggerUpdate(DdlWrite writer, MTable table) {
|
||||
|
||||
List<String> columns = columnNamesForApply(table);
|
||||
String baseTableName = table.getName();
|
||||
String historyTableName = historyTableName(baseTableName);
|
||||
return new DbTriggerUpdate(baseTableName, historyTableName, writer, columns);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void dropHistoryTable(DdlWrite writer, DropHistoryTable dropHistoryTable) throws IOException {
|
||||
@@ -67,18 +88,17 @@ public abstract class DbTriggerBasedHistoryDdl implements PlatformHistoryDdl {
|
||||
String baseTable = dropHistoryTable.getBaseTable();
|
||||
|
||||
// drop in appropriate order
|
||||
dropTriggers(writer.dropHistory(), baseTable);
|
||||
dropHistoryTableEtc(writer.dropHistory(), baseTable);
|
||||
dropTriggers(writer.applyDropDependencies(), baseTable);
|
||||
dropHistoryTableEtc(writer.applyDropDependencies(), baseTable);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void addHistoryTable(DdlWrite writer, AddHistoryTable addHistoryTable) throws IOException {
|
||||
|
||||
String baseTable = addHistoryTable.getBaseTable();
|
||||
MTable table = writer.getTable(baseTable);
|
||||
if (table == null) {
|
||||
throw new IllegalStateException("MTable "+baseTable+" not found in writer? (required for history DDL)");
|
||||
throw new IllegalStateException("MTable " + baseTable + " not found in writer? (required for history DDL)");
|
||||
}
|
||||
|
||||
createWithHistory(writer, table);
|
||||
@@ -90,12 +110,11 @@ public abstract class DbTriggerBasedHistoryDdl implements PlatformHistoryDdl {
|
||||
String baseTable = table.getName();
|
||||
String whenCreatedColumn = table.getWhenCreatedColumn();
|
||||
|
||||
// rollback changes in appropriate order
|
||||
dropTriggers(writer.rollback(), baseTable);
|
||||
dropHistoryTableEtc(writer.rollback(), baseTable);
|
||||
dropTriggers(writer.dropAll(), baseTable);
|
||||
dropHistoryTableEtc(writer.dropAll(), baseTable);
|
||||
|
||||
addHistoryTable(writer, table, whenCreatedColumn);
|
||||
addStoredFunction(writer, table, null);
|
||||
createStoredFunction(writer, table);
|
||||
createTriggers(writer, table);
|
||||
}
|
||||
|
||||
@@ -103,7 +122,7 @@ public abstract class DbTriggerBasedHistoryDdl implements PlatformHistoryDdl {
|
||||
|
||||
protected abstract void dropTriggers(DdlBuffer buffer, String baseTable) throws IOException;
|
||||
|
||||
protected void addStoredFunction(DdlWrite writer, MTable table, HistoryTableUpdate update) throws IOException {
|
||||
protected void createStoredFunction(DdlWrite writer, MTable table) throws IOException {
|
||||
// do nothing
|
||||
}
|
||||
|
||||
@@ -158,7 +177,7 @@ public abstract class DbTriggerBasedHistoryDdl implements PlatformHistoryDdl {
|
||||
|
||||
apply.append("create table ").append(table.getName()).append(historySuffix).append("(").newLine();
|
||||
|
||||
Collection<MColumn> cols = table.getColumns().values();
|
||||
Collection<MColumn> cols = table.allColumns();
|
||||
for (MColumn column : cols) {
|
||||
if (!column.isDraftOnly()) {
|
||||
writeColumnDefinition(apply, column.getName(), column.getType());
|
||||
@@ -191,6 +210,26 @@ public abstract class DbTriggerBasedHistoryDdl implements PlatformHistoryDdl {
|
||||
.endOfStatement().end();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create or replace the with_history view with explicit columns.
|
||||
*/
|
||||
protected void createWithHistoryView(DbTriggerUpdate update) throws IOException {
|
||||
|
||||
DdlBuffer apply = update.historyBuffer();
|
||||
apply.append("create or replace view ").append(update.getBaseTable()).append(viewSuffix).append(" as select ");
|
||||
appendColumnNames(apply, update.getColumns(), "");
|
||||
appendSysPeriodColumns(apply, ", ");
|
||||
apply.append(" from ").append(update.getBaseTable()).append(" union all select ");
|
||||
appendColumnNames(apply, update.getColumns(), "");
|
||||
appendSysPeriodColumns(apply, ", ");
|
||||
apply.append(" from ").append(update.getHistoryTable()).endOfStatement().end();
|
||||
}
|
||||
|
||||
protected void appendSysPeriodColumns(DdlBuffer apply, String prefix) throws IOException {
|
||||
appendColumnName(apply, prefix, sysPeriodStart);
|
||||
appendColumnName(apply, prefix, sysPeriodEnd);
|
||||
}
|
||||
|
||||
protected void dropHistoryTableEtc(DdlBuffer buffer, String baseTableName) throws IOException {
|
||||
|
||||
buffer.append("drop view ").append(baseTableName).append(viewSuffix).endOfStatement();
|
||||
@@ -203,8 +242,6 @@ public abstract class DbTriggerBasedHistoryDdl implements PlatformHistoryDdl {
|
||||
buffer.append("alter table ").append(baseTableName).append(" drop column ").append(sysPeriodEnd).endOfStatement();
|
||||
}
|
||||
|
||||
//protected abstract void addFunction(DdlBuffer apply, String procedureName, String historyTable, List<String> includedColumns) throws IOException;
|
||||
|
||||
protected void appendInsertIntoHistory(DdlBuffer buffer, String historyTable, List<String> columns) throws IOException {
|
||||
|
||||
buffer.append(" insert into ").append(historyTable).append(" (").append(sysPeriodStart).append(",").append(sysPeriodEnd).append(",");
|
||||
@@ -216,7 +253,7 @@ public abstract class DbTriggerBasedHistoryDdl implements PlatformHistoryDdl {
|
||||
|
||||
protected void appendColumnNames(DdlBuffer buffer, List<String> columns, String columnPrefix) throws IOException {
|
||||
|
||||
for (int i=0; i< columns.size(); i++) {
|
||||
for (int i = 0; i < columns.size(); i++) {
|
||||
if (i > 0) {
|
||||
buffer.append(", ");
|
||||
}
|
||||
@@ -226,18 +263,26 @@ public abstract class DbTriggerBasedHistoryDdl implements PlatformHistoryDdl {
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the list of included columns in order.
|
||||
* Append a single column to the buffer if it is not null.
|
||||
*/
|
||||
protected List<String> includedColumnNames(MTable table) throws IOException {
|
||||
protected void appendColumnName(DdlBuffer buffer, String prefix, String columnName) throws IOException {
|
||||
|
||||
Collection<MColumn> columns = table.getColumns().values();
|
||||
List<String> includedColumns = new ArrayList<String>(columns.size());
|
||||
|
||||
for (MColumn column : columns) {
|
||||
if (column.isIncludeInHistory()) {
|
||||
includedColumns.add(column.getName());
|
||||
}
|
||||
if (columnName != null) {
|
||||
buffer.append(prefix).append(columnName);
|
||||
}
|
||||
return includedColumns;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the column names included in history for the apply script.
|
||||
* <p>
|
||||
* Note that dropped columns are actually still included at this point as they are going
|
||||
* to be removed from the history handling when the drop script runs that also deletes
|
||||
* the column.
|
||||
* </p>
|
||||
*/
|
||||
protected List<String> columnNamesForApply(MTable table) {
|
||||
|
||||
return table.allHistoryColumns(true);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.avaje.ebean.dbmigration.ddlgeneration.platform;
|
||||
|
||||
import com.avaje.ebean.dbmigration.ddlgeneration.DdlBuffer;
|
||||
import com.avaje.ebean.dbmigration.ddlgeneration.DdlWrite;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* DB trigger update when a change occurs on a table with history.
|
||||
*/
|
||||
public class DbTriggerUpdate {
|
||||
|
||||
private final String baseTableName;
|
||||
|
||||
private final String historyTableName;
|
||||
|
||||
private final DdlWrite writer;
|
||||
|
||||
private final List<String> columns;
|
||||
|
||||
public DbTriggerUpdate(String baseTableName, String historyTableName, DdlWrite writer, List<String> columns) {
|
||||
this.baseTableName = baseTableName;
|
||||
this.historyTableName = historyTableName;
|
||||
this.writer = writer;
|
||||
this.columns = columns;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the appropriate buffer for the current mode.
|
||||
*/
|
||||
public DdlBuffer historyBuffer() {
|
||||
return writer.applyHistory();
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the appropriate drop dependency buffer for the current mode.
|
||||
*/
|
||||
public DdlBuffer dropDependencyBuffer() {
|
||||
return writer.applyDropDependencies();
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the base table name.
|
||||
*/
|
||||
public String getBaseTable() {
|
||||
return baseTableName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the history table name.
|
||||
*/
|
||||
public String getHistoryTable() {
|
||||
return historyTableName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the included columns.
|
||||
*/
|
||||
public List<String> getColumns() {
|
||||
return columns;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -6,7 +6,6 @@ import com.avaje.ebean.dbmigration.ddlgeneration.DdlWrite;
|
||||
import com.avaje.ebean.dbmigration.model.MTable;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* H2 history support using DB triggers to maintain a history table.
|
||||
@@ -28,40 +27,20 @@ public class H2HistoryDdl extends DbTriggerBasedHistoryDdl {
|
||||
protected void createTriggers(DdlWrite writer, MTable table) throws IOException {
|
||||
|
||||
String baseTableName = table.getName();
|
||||
String historyTableName = historyTableName(baseTableName);
|
||||
List<String> includedColumns = includedColumnNames(table);
|
||||
|
||||
DdlBuffer apply = writer.applyHistory();
|
||||
|
||||
addCreateTrigger(apply, updateTriggerName(baseTableName), baseTableName, historyTableName, includedColumns);
|
||||
addCreateTrigger(apply, updateTriggerName(baseTableName), baseTableName);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void regenerateHistoryTriggers(DdlWrite writer, MTable table, HistoryTableUpdate update) throws IOException {
|
||||
protected void updateHistoryTriggers(DbTriggerUpdate update) throws IOException {
|
||||
|
||||
String baseTableName = table.getName();
|
||||
String historyTableName = historyTableName(baseTableName);
|
||||
List<String> includedColumns = includedColumnNames(table);
|
||||
|
||||
DdlBuffer apply = writer.applyHistory();
|
||||
|
||||
apply.append("-- Regenerated ").newLine();
|
||||
apply.append("-- changes: ").append(update.description()).newLine();
|
||||
|
||||
dropTriggers(apply, baseTableName);
|
||||
addCreateTrigger(apply, updateTriggerName(baseTableName), baseTableName, historyTableName, includedColumns);
|
||||
|
||||
// put a reverted version into the rollback buffer
|
||||
update.toRevertedColumns(includedColumns);
|
||||
|
||||
DdlBuffer rollback = writer.rollback();
|
||||
rollback.append("-- Revert regenerated ").newLine();
|
||||
rollback.append("-- revert changes: ").append(update.description()).newLine();
|
||||
dropTriggers(rollback, baseTableName);
|
||||
addCreateTrigger(rollback, updateTriggerName(baseTableName), baseTableName, historyTableName, includedColumns);
|
||||
DdlBuffer buffer = update.historyBuffer();
|
||||
dropTriggers(buffer, update.getBaseTable());
|
||||
addCreateTrigger(buffer, updateTriggerName(update.getBaseTable()), update.getBaseTable());
|
||||
}
|
||||
|
||||
private void addCreateTrigger(DdlBuffer apply, String triggerName, String baseTable, String historyTable, List<String> includedColumns) throws IOException {
|
||||
private void addCreateTrigger(DdlBuffer apply, String triggerName, String baseTable) throws IOException {
|
||||
|
||||
// Note that this does not take into account the historyTable name (excepts _history suffix) and
|
||||
// does not take into account excluded columns (all columns included in history)
|
||||
|
||||
+11
-43
@@ -10,7 +10,6 @@ import java.util.List;
|
||||
*/
|
||||
public class HistoryTableUpdate {
|
||||
|
||||
|
||||
/**
|
||||
* Column change type.
|
||||
*/
|
||||
@@ -21,35 +20,25 @@ public class HistoryTableUpdate {
|
||||
EXCLUDE
|
||||
}
|
||||
|
||||
public static class Column {
|
||||
private static class Column {
|
||||
|
||||
final Change change;
|
||||
|
||||
final String column;
|
||||
|
||||
public final Change change;
|
||||
public final String column;
|
||||
public Column(Change change, String column) {
|
||||
this.change = change;
|
||||
this.column = column;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return description();
|
||||
}
|
||||
|
||||
public String description() {
|
||||
return change.name().toLowerCase()+" "+column;
|
||||
}
|
||||
|
||||
public void apply(List<String> includedColumns) {
|
||||
switch (change) {
|
||||
case ADD:
|
||||
case INCLUDE: {
|
||||
includedColumns.remove(column);
|
||||
break;
|
||||
}
|
||||
case DROP:
|
||||
case EXCLUDE: {
|
||||
includedColumns.add(column);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
throw new IllegalStateException("Unexpected change "+change);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private final String baseTable;
|
||||
@@ -65,27 +54,12 @@ public class HistoryTableUpdate {
|
||||
|
||||
/**
|
||||
* Return a description of the changes that cause the history trigger/function
|
||||
* to be regenerated (added, dropped, included or excluded columns).
|
||||
* to be regenerated (added, included, excluded and dropped columns).
|
||||
*/
|
||||
public String description() {
|
||||
StringBuilder sb = new StringBuilder(90);
|
||||
for (int i = 0; i < columnChanges.size(); i++) {
|
||||
if (i > 0) {
|
||||
sb.append(", ");
|
||||
}
|
||||
sb.append(columnChanges.get(i).description());
|
||||
}
|
||||
return sb.toString();
|
||||
return columnChanges.toString();
|
||||
}
|
||||
|
||||
public void toRevertedColumns(List<String> includedColumns) {
|
||||
|
||||
for (Column columnChange : columnChanges) {
|
||||
columnChange.apply(includedColumns);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Add a comment for column added, dropped, included or excluded.
|
||||
*/
|
||||
@@ -100,10 +74,4 @@ public class HistoryTableUpdate {
|
||||
return baseTable;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the comments.
|
||||
*/
|
||||
public List<Column> getColumnChanges() {
|
||||
return columnChanges;
|
||||
}
|
||||
}
|
||||
|
||||
+19
-41
@@ -5,7 +5,6 @@ import com.avaje.ebean.dbmigration.ddlgeneration.DdlWrite;
|
||||
import com.avaje.ebean.dbmigration.model.MTable;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* MySql history support using DB triggers to maintain a history table.
|
||||
@@ -26,67 +25,46 @@ public class MySqlHistoryDdl extends DbTriggerBasedHistoryDdl {
|
||||
@Override
|
||||
protected void createTriggers(DdlWrite writer, MTable table) throws IOException {
|
||||
|
||||
String baseTableName = table.getName();
|
||||
String historyTableName = historyTableName(baseTableName);
|
||||
List<String> includedColumns = includedColumnNames(table);
|
||||
DbTriggerUpdate update = createDbTriggerUpdate(writer, table);
|
||||
|
||||
DdlBuffer apply = writer.applyHistory();
|
||||
|
||||
addBeforeUpdate(apply, updateTriggerName(baseTableName), baseTableName, historyTableName, includedColumns);
|
||||
addBeforeDelete(apply, deleteTriggerName(baseTableName), baseTableName, historyTableName, includedColumns);
|
||||
addBeforeUpdate(updateTriggerName(update.getBaseTable()), update);
|
||||
addBeforeDelete(deleteTriggerName(update.getBaseTable()), update);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void regenerateHistoryTriggers(DdlWrite writer, MTable table, HistoryTableUpdate update) throws IOException {
|
||||
protected void updateHistoryTriggers(DbTriggerUpdate update) throws IOException {
|
||||
|
||||
String baseTableName = table.getName();
|
||||
String historyTableName = historyTableName(baseTableName);
|
||||
List<String> includedColumns = includedColumnNames(table);
|
||||
DdlBuffer buffer = update.historyBuffer();
|
||||
String baseTable = update.getBaseTable();
|
||||
|
||||
DdlBuffer apply = writer.applyHistory();
|
||||
|
||||
apply.append("-- Regenerated ").newLine();
|
||||
apply.append("-- changes: ").append(update.description()).newLine();
|
||||
// lock the base table while we drop and recreate the triggers
|
||||
apply.append("lock tables ").append(baseTableName).append(" write").endOfStatement();
|
||||
dropTriggers(apply, baseTableName);
|
||||
addBeforeUpdate(apply, updateTriggerName(baseTableName), baseTableName, historyTableName, includedColumns);
|
||||
addBeforeDelete(apply, deleteTriggerName(baseTableName), baseTableName, historyTableName, includedColumns);
|
||||
apply.append("unlock tables").endOfStatement();
|
||||
|
||||
// put a reverted version into the rollback buffer
|
||||
update.toRevertedColumns(includedColumns);
|
||||
|
||||
DdlBuffer rollback = writer.rollback();
|
||||
rollback.append("-- Revert regenerated ").newLine();
|
||||
rollback.append("-- revert changes: ").append(update.description()).newLine();
|
||||
// lock the base table while we drop and recreate the triggers
|
||||
rollback.append("lock tables ").append(baseTableName).append(" write").endOfStatement();
|
||||
dropTriggers(rollback, baseTableName);
|
||||
addBeforeUpdate(rollback, updateTriggerName(baseTableName), baseTableName, historyTableName, includedColumns);
|
||||
addBeforeDelete(rollback, deleteTriggerName(baseTableName), baseTableName, historyTableName, includedColumns);
|
||||
rollback.append("unlock tables").endOfStatement();
|
||||
buffer.append("lock tables ").append(baseTable).append(" write").endOfStatement();
|
||||
dropTriggers(buffer, baseTable);
|
||||
addBeforeUpdate(updateTriggerName(baseTable), update);
|
||||
addBeforeDelete(deleteTriggerName(baseTable), update);
|
||||
buffer.append("unlock tables").endOfStatement();
|
||||
}
|
||||
|
||||
private void addBeforeUpdate(DdlBuffer apply, String triggerName, String baseTable, String historyTable, List<String> includedColumns) throws IOException {
|
||||
private void addBeforeUpdate(String triggerName, DbTriggerUpdate update) throws IOException {
|
||||
|
||||
DdlBuffer apply = update.historyBuffer();
|
||||
apply
|
||||
.append("delimiter $$").newLine()
|
||||
.append("create trigger ").append(triggerName).append(" before update on ").append(baseTable)
|
||||
.append("create trigger ").append(triggerName).append(" before update on ").append(update.getBaseTable())
|
||||
.append(" for each row begin").newLine();
|
||||
appendInsertIntoHistory(apply, historyTable, includedColumns);
|
||||
appendInsertIntoHistory(apply, update.getHistoryTable(), update.getColumns());
|
||||
apply
|
||||
.append(" set NEW.").append(sysPeriod).append("_start = now(6)").endOfStatement()
|
||||
.append("end$$").newLine();
|
||||
}
|
||||
|
||||
private void addBeforeDelete(DdlBuffer apply, String triggerName, String baseTable, String historyTable, List<String> includedColumns) throws IOException {
|
||||
private void addBeforeDelete(String triggerName, DbTriggerUpdate update) throws IOException {
|
||||
|
||||
DdlBuffer apply = update.historyBuffer();
|
||||
apply
|
||||
.append("delimiter $$").newLine()
|
||||
.append("create trigger ").append(triggerName).append(" before delete on ").append(baseTable)
|
||||
.append("create trigger ").append(triggerName).append(" before delete on ").append(update.getBaseTable())
|
||||
.append(" for each row begin").newLine();
|
||||
appendInsertIntoHistory(apply, historyTable, includedColumns);
|
||||
appendInsertIntoHistory(apply, update.getHistoryTable(), update.getColumns());
|
||||
apply.append("end$$").newLine();
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -35,7 +35,7 @@ public class NoHistorySupportDdl implements PlatformHistoryDdl {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void regenerateHistoryTriggers(DdlWrite write, HistoryTableUpdate update) {
|
||||
public void updateTriggers(DdlWrite write, HistoryTableUpdate update) {
|
||||
// does nothing
|
||||
}
|
||||
}
|
||||
|
||||
@@ -200,7 +200,7 @@ public class PlatformDdl {
|
||||
* Regenerate the history triggers (or function) due to a column being added/dropped/excluded or included.
|
||||
*/
|
||||
public void regenerateHistoryTriggers(DdlWrite write, HistoryTableUpdate update) throws IOException {
|
||||
historyDdl.regenerateHistoryTriggers(write, update);
|
||||
historyDdl.updateTriggers(write, update);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+1
-1
@@ -36,5 +36,5 @@ public interface PlatformHistoryDdl {
|
||||
/**
|
||||
* Regenerate the history triggers/stored function due to column added/dropped/included or excluded.
|
||||
*/
|
||||
void regenerateHistoryTriggers(DdlWrite write, HistoryTableUpdate baseTable) throws IOException;
|
||||
void updateTriggers(DdlWrite write, HistoryTableUpdate baseTable) throws IOException;
|
||||
}
|
||||
|
||||
+26
-25
@@ -45,6 +45,11 @@ public class PostgresHistoryDdl extends DbTriggerBasedHistoryDdl {
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void appendSysPeriodColumns(DdlBuffer apply, String prefix) throws IOException {
|
||||
appendColumnName(apply, prefix, sysPeriod);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void dropSysPeriodColumns(DdlBuffer buffer, String baseTableName) throws IOException {
|
||||
buffer.append("alter table ").append(baseTableName).append(" drop column ").append(sysPeriod).endOfStatement();
|
||||
@@ -72,7 +77,7 @@ public class PostgresHistoryDdl extends DbTriggerBasedHistoryDdl {
|
||||
buffer.end();
|
||||
}
|
||||
|
||||
protected void addFunction(DdlBuffer apply, String procedureName, String historyTable, List<String> includedColumns) throws IOException {
|
||||
protected void createOrReplaceFunction(DdlBuffer apply, String procedureName, String historyTable, List<String> includedColumns) throws IOException {
|
||||
apply
|
||||
.append("create or replace function ").append(procedureName).append("() returns trigger as $$").newLine()
|
||||
.append("begin").newLine();
|
||||
@@ -96,40 +101,36 @@ public class PostgresHistoryDdl extends DbTriggerBasedHistoryDdl {
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void regenerateHistoryTriggers(DdlWrite writer, MTable table, HistoryTableUpdate update) throws IOException {
|
||||
|
||||
// just replace the stored function with 'create or replace'
|
||||
addStoredFunction(writer, table, update);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void addStoredFunction(DdlWrite writer, MTable table, HistoryTableUpdate update) throws IOException {
|
||||
protected void createStoredFunction(DdlWrite writer, MTable table) throws IOException {
|
||||
|
||||
String procedureName = procedureName(table.getName());
|
||||
String historyTable = historyTableName(table.getName());
|
||||
|
||||
List<String> includedColumns = includedColumnNames(table);
|
||||
List<String> columnNames = columnNamesForApply(table);
|
||||
createOrReplaceFunction(writer.applyHistory(), procedureName, historyTable, columnNames);
|
||||
}
|
||||
|
||||
DdlBuffer apply = writer.applyHistory();
|
||||
@Override
|
||||
protected void updateHistoryTriggers(DbTriggerUpdate update) throws IOException {
|
||||
|
||||
if (update != null) {
|
||||
apply.append("-- Regenerated ").append(procedureName).newLine();
|
||||
apply.append("-- changes: ").append(update.description()).newLine();
|
||||
}
|
||||
String procedureName = procedureName(update.getBaseTable());
|
||||
|
||||
addFunction(apply, procedureName, historyTable, includedColumns);
|
||||
recreateHistoryView(update);
|
||||
createOrReplaceFunction(update.historyBuffer(), procedureName, update.getHistoryTable(), update.getColumns());
|
||||
}
|
||||
|
||||
/**
|
||||
* For postgres we need to drop and recreate the view. Well, we could add columns to the end of the view
|
||||
* but otherwise we need to drop and create it.
|
||||
*/
|
||||
private void recreateHistoryView(DbTriggerUpdate update) throws IOException {
|
||||
|
||||
if (update != null) {
|
||||
// put a reverted version into the rollback buffer
|
||||
update.toRevertedColumns(includedColumns);
|
||||
DdlBuffer buffer = update.dropDependencyBuffer();
|
||||
// we need to drop the view early/first before any changes to the tables etc
|
||||
buffer.append("drop view if exists ").append(update.getBaseTable()).append(viewSuffix).endOfStatement();
|
||||
|
||||
DdlBuffer rollback = writer.rollback();
|
||||
rollback.append("-- Revert regenerated ").append(procedureName).newLine();
|
||||
rollback.append("-- revert changes: ").append(update.description()).newLine();
|
||||
|
||||
addFunction(rollback, procedureName, historyTable, includedColumns);
|
||||
}
|
||||
// recreate the view with specific columns specified (the columns generally are not dropped until later)
|
||||
createWithHistoryView(update);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -27,6 +27,8 @@ import javax.xml.bind.annotation.XmlType;
|
||||
* </choice>
|
||||
* </sequence>
|
||||
* <attribute name="type" use="required" type="{http://ebean-orm.github.io/xml/ns/dbmigration}changeSetType" />
|
||||
* <attribute name="dropsFor" type="{http://www.w3.org/2001/XMLSchema}string" />
|
||||
* <attribute name="suppressDropsForever" type="{http://www.w3.org/2001/XMLSchema}boolean" />
|
||||
* <attribute name="generated" type="{http://www.w3.org/2001/XMLSchema}boolean" />
|
||||
* <attribute name="author" type="{http://www.w3.org/2001/XMLSchema}string" />
|
||||
* <attribute name="comment" type="{http://www.w3.org/2001/XMLSchema}string" />
|
||||
@@ -62,6 +64,10 @@ public class ChangeSet {
|
||||
protected List<Object> changeSetChildren;
|
||||
@XmlAttribute(name = "type", required = true)
|
||||
protected ChangeSetType type;
|
||||
@XmlAttribute(name = "dropsFor")
|
||||
protected String dropsFor;
|
||||
@XmlAttribute(name = "suppressDropsForever")
|
||||
protected Boolean suppressDropsForever;
|
||||
@XmlAttribute(name = "generated")
|
||||
protected Boolean generated;
|
||||
@XmlAttribute(name = "author")
|
||||
@@ -134,6 +140,54 @@ public class ChangeSet {
|
||||
this.type = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value of the dropsFor property.
|
||||
*
|
||||
* @return
|
||||
* possible object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public String getDropsFor() {
|
||||
return dropsFor;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the dropsFor property.
|
||||
*
|
||||
* @param value
|
||||
* allowed object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public void setDropsFor(String value) {
|
||||
this.dropsFor = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value of the suppressDropsForever property.
|
||||
*
|
||||
* @return
|
||||
* possible object is
|
||||
* {@link Boolean }
|
||||
*
|
||||
*/
|
||||
public Boolean isSuppressDropsForever() {
|
||||
return suppressDropsForever;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the suppressDropsForever property.
|
||||
*
|
||||
* @param value
|
||||
* allowed object is
|
||||
* {@link Boolean }
|
||||
*
|
||||
*/
|
||||
public void setSuppressDropsForever(Boolean value) {
|
||||
this.suppressDropsForever = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value of the generated property.
|
||||
*
|
||||
|
||||
@@ -15,7 +15,7 @@ import javax.xml.bind.annotation.XmlType;
|
||||
* <simpleType name="changeSetType">
|
||||
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
|
||||
* <enumeration value="apply"/>
|
||||
* <enumeration value="drop"/>
|
||||
* <enumeration value="pendingDrops"/>
|
||||
* <enumeration value="baseline"/>
|
||||
* </restriction>
|
||||
* </simpleType>
|
||||
@@ -28,8 +28,8 @@ public enum ChangeSetType {
|
||||
|
||||
@XmlEnumValue("apply")
|
||||
APPLY("apply"),
|
||||
@XmlEnumValue("drop")
|
||||
DROP("drop"),
|
||||
@XmlEnumValue("pendingDrops")
|
||||
PENDING_DROPS("pendingDrops"),
|
||||
@XmlEnumValue("baseline")
|
||||
BASELINE("baseline");
|
||||
private final String value;
|
||||
|
||||
@@ -30,6 +30,7 @@ import javax.xml.bind.annotation.XmlType;
|
||||
* <attGroup ref="{http://ebean-orm.github.io/xml/ns/dbmigration}tablespaceAttributes"/>
|
||||
* <attribute name="name" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
|
||||
* <attribute name="withHistory" type="{http://www.w3.org/2001/XMLSchema}boolean" />
|
||||
* <attribute name="draft" type="{http://www.w3.org/2001/XMLSchema}boolean" />
|
||||
* <attribute name="identityType" type="{http://ebean-orm.github.io/xml/ns/dbmigration}identityType" />
|
||||
* <attribute name="sequenceName" type="{http://www.w3.org/2001/XMLSchema}string" />
|
||||
* <attribute name="sequenceInitial" type="{http://www.w3.org/2001/XMLSchema}positiveInteger" />
|
||||
@@ -59,6 +60,8 @@ public class CreateTable {
|
||||
protected String name;
|
||||
@XmlAttribute(name = "withHistory")
|
||||
protected Boolean withHistory;
|
||||
@XmlAttribute(name = "draft")
|
||||
protected Boolean draft;
|
||||
@XmlAttribute(name = "identityType")
|
||||
protected IdentityType identityType;
|
||||
@XmlAttribute(name = "sequenceName")
|
||||
@@ -213,6 +216,30 @@ public class CreateTable {
|
||||
this.withHistory = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value of the draft property.
|
||||
*
|
||||
* @return
|
||||
* possible object is
|
||||
* {@link Boolean }
|
||||
*
|
||||
*/
|
||||
public Boolean isDraft() {
|
||||
return draft;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the draft property.
|
||||
*
|
||||
* @param value
|
||||
* allowed object is
|
||||
* {@link Boolean }
|
||||
*
|
||||
*/
|
||||
public void setDraft(Boolean value) {
|
||||
this.draft = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value of the identityType property.
|
||||
*
|
||||
|
||||
@@ -7,22 +7,46 @@ import javax.xml.bind.JAXBContext;
|
||||
import javax.xml.bind.JAXBException;
|
||||
import javax.xml.bind.Marshaller;
|
||||
import java.io.File;
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* Simple writer for output of the Migration/ChangeSet as an XML document.
|
||||
*/
|
||||
public class MigrationXmlWriter {
|
||||
|
||||
private final String comment;
|
||||
|
||||
public MigrationXmlWriter(String comment) {
|
||||
this.comment = comment;
|
||||
}
|
||||
|
||||
/**
|
||||
* Write a Migration to a file as an xml document to the file.
|
||||
*/
|
||||
public void write(Migration migration, File file) {
|
||||
|
||||
try {
|
||||
|
||||
FileWriter writer = new FileWriter(file);
|
||||
writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n");
|
||||
if (comment != null) {
|
||||
writer.write("<!-- ");
|
||||
writer.write(comment);
|
||||
writer.write(" -->\n");
|
||||
}
|
||||
|
||||
JAXBContext jaxbContext = JAXBContext.newInstance(Migration.class);
|
||||
Marshaller marshaller = jaxbContext.createMarshaller();
|
||||
marshaller.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
|
||||
marshaller.marshal(migration, file);
|
||||
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
|
||||
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
|
||||
|
||||
marshaller.marshal(migration, writer);
|
||||
|
||||
writer.close();
|
||||
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
|
||||
} catch (JAXBException e) {
|
||||
throw new RuntimeException(e);
|
||||
|
||||
@@ -117,13 +117,13 @@ public class CurrentModel {
|
||||
/**
|
||||
* Return the 'Drop' DDL.
|
||||
*/
|
||||
public String getDropDdl() throws IOException {
|
||||
public String getDropAllDdl() throws IOException {
|
||||
|
||||
createDdl();
|
||||
|
||||
StringBuilder ddl = new StringBuilder(2000);
|
||||
ddl.append(write.rollbackForeignKeys().getBuffer());
|
||||
ddl.append(write.rollback().getBuffer());
|
||||
ddl.append(write.dropAllForeignKeys().getBuffer());
|
||||
ddl.append(write.dropAll().getBuffer());
|
||||
|
||||
return ddl.toString();
|
||||
}
|
||||
@@ -159,12 +159,7 @@ public class CurrentModel {
|
||||
ModelDiff diff = new ModelDiff();
|
||||
diff.compareTo(model);
|
||||
|
||||
List<Object> applyChanges = diff.getApplyChanges();
|
||||
|
||||
// put the changes into a ChangeSet
|
||||
ChangeSet applyChangeSet = new ChangeSet();
|
||||
applyChangeSet.getChangeSetChildren().addAll(applyChanges);
|
||||
return applyChangeSet;
|
||||
return diff.getApplyChangeSet();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -283,7 +283,6 @@ public class MColumn {
|
||||
/**
|
||||
* Compare the column meta data and return true if there is a change that means
|
||||
* the history table column needs
|
||||
|
||||
*/
|
||||
public void compare(ModelDiff modelDiff, MTable table, MColumn newColumn) {
|
||||
|
||||
|
||||
@@ -10,13 +10,14 @@ import com.avaje.ebean.dbmigration.migration.DropHistoryTable;
|
||||
import com.avaje.ebean.dbmigration.migration.DropTable;
|
||||
import com.avaje.ebean.dbmigration.migration.IdentityType;
|
||||
import com.avaje.ebean.dbmigration.migration.UniqueConstraint;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
@@ -38,6 +39,8 @@ import java.util.Set;
|
||||
*/
|
||||
public class MTable {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(MTable.class);
|
||||
|
||||
/**
|
||||
* Table name.
|
||||
*/
|
||||
@@ -118,6 +121,8 @@ public class MTable {
|
||||
*/
|
||||
private AddColumn addColumn;
|
||||
|
||||
private List<String> droppedColumns = new ArrayList<String>();
|
||||
|
||||
/**
|
||||
* Create a copy of this table structure as a 'draft' table.
|
||||
*
|
||||
@@ -126,14 +131,14 @@ public class MTable {
|
||||
*/
|
||||
public MTable createDraftTable() {
|
||||
|
||||
draftTable = new MTable(name+"_draft");
|
||||
draftTable = new MTable(name + "_draft");
|
||||
draftTable.draft = true;
|
||||
draftTable.whenCreatedColumn = whenCreatedColumn;
|
||||
// compoundKeys
|
||||
// compoundUniqueConstraints
|
||||
draftTable.identityType = identityType;
|
||||
|
||||
for (MColumn col: columns.values()) {
|
||||
for (MColumn col : allColumns()) {
|
||||
draftTable.addColumn(col.copyForDraft());
|
||||
}
|
||||
|
||||
@@ -150,6 +155,7 @@ public class MTable {
|
||||
this.tablespace = createTable.getTablespace();
|
||||
this.indexTablespace = createTable.getIndexTablespace();
|
||||
this.withHistory = Boolean.TRUE.equals(createTable.isWithHistory());
|
||||
this.draft = Boolean.TRUE.equals(createTable.isDraft());
|
||||
this.sequenceName = createTable.getSequenceName();
|
||||
this.sequenceInitial = toInt(createTable.getSequenceInitial());
|
||||
this.sequenceAllocate = toInt(createTable.getSequenceAllocate());
|
||||
@@ -194,8 +200,11 @@ public class MTable {
|
||||
if (withHistory) {
|
||||
createTable.setWithHistory(Boolean.TRUE);
|
||||
}
|
||||
if (draft) {
|
||||
createTable.setDraft(Boolean.TRUE);
|
||||
}
|
||||
|
||||
for (MColumn column : this.columns.values()) {
|
||||
for (MColumn column : allColumns()) {
|
||||
// filter out draftOnly columns from the base table
|
||||
if (draft || !column.isDraftOnly()) {
|
||||
createTable.getColumn().add(column.createColumn());
|
||||
@@ -244,26 +253,33 @@ public class MTable {
|
||||
|
||||
addColumn = null;
|
||||
|
||||
Set<String> mappedColumns = new LinkedHashSet<String>();
|
||||
Map<String, MColumn> newColumnMap = newTable.getColumns();
|
||||
|
||||
Collection<MColumn> newColumns = newTable.getColumns().values();
|
||||
for (MColumn newColumn : newColumns) {
|
||||
MColumn localColumn = columns.get(newColumn.getName());
|
||||
// compare newColumns to existing columns (look for new and diff columns)
|
||||
for (MColumn newColumn : newColumnMap.values()) {
|
||||
MColumn localColumn = getColumn(newColumn.getName());
|
||||
if (localColumn == null) {
|
||||
diffNewColumn(newColumn);
|
||||
// can ignore if draftOnly column and non-draft table
|
||||
if (!newColumn.isDraftOnly() || draft) {
|
||||
diffNewColumn(newColumn);
|
||||
}
|
||||
} else {
|
||||
// note that if there are alter column changes in here then
|
||||
// the table withHistory is taken into account
|
||||
localColumn.compare(modelDiff, this, newColumn);
|
||||
mappedColumns.add(newColumn.getName());
|
||||
}
|
||||
}
|
||||
|
||||
Collection<MColumn> existingColumns = columns.values();
|
||||
for (MColumn existingColumn : existingColumns) {
|
||||
if (!mappedColumns.contains(existingColumn.getName())) {
|
||||
diffDropColumn(modelDiff, existingColumn);
|
||||
// compare existing columns (look for dropped columns)
|
||||
int columnPosition = 0;
|
||||
for (MColumn existingColumn : allColumns()) {
|
||||
MColumn newColumn = newColumnMap.get(existingColumn.getName());
|
||||
if (newColumn == null) {
|
||||
diffDropColumn(modelDiff, existingColumn, columnPosition, newTable);
|
||||
} else if (newColumn.isDraftOnly() && !draft) {
|
||||
// effectively a drop column (draft only column on a non-draft table)
|
||||
logger.trace("... drop column {} from table {} as now draftOnly", newColumn.getName(), name);
|
||||
diffDropColumn(modelDiff, existingColumn, columnPosition, newTable);
|
||||
}
|
||||
columnPosition++;
|
||||
}
|
||||
|
||||
if (addColumn != null) {
|
||||
@@ -287,7 +303,7 @@ public class MTable {
|
||||
public void apply(AlterColumn alterColumn) {
|
||||
checkTableName(alterColumn.getTableName());
|
||||
String columnName = alterColumn.getColumnName();
|
||||
MColumn existingColumn = columns.get(columnName);
|
||||
MColumn existingColumn = getColumn(columnName);
|
||||
if (existingColumn == null) {
|
||||
throw new IllegalStateException("Column [" + columnName + "] does not exist for AlterColumn change?");
|
||||
}
|
||||
@@ -299,7 +315,10 @@ public class MTable {
|
||||
*/
|
||||
public void apply(DropColumn dropColumn) {
|
||||
checkTableName(dropColumn.getTableName());
|
||||
columns.remove(dropColumn.getColumnName());
|
||||
MColumn removed = columns.remove(dropColumn.getColumnName());
|
||||
if (removed == null) {
|
||||
throw new IllegalStateException("Column [" + dropColumn.getColumnName() + "] does not exist for DropColumn change on table [" + dropColumn.getTableName() + "]?");
|
||||
}
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
@@ -313,10 +332,6 @@ public class MTable {
|
||||
return draft;
|
||||
}
|
||||
|
||||
public String getPkName() {
|
||||
return pkName;
|
||||
}
|
||||
|
||||
public void setPkName(String pkName) {
|
||||
this.pkName = pkName;
|
||||
}
|
||||
@@ -341,11 +356,43 @@ public class MTable {
|
||||
return withHistory;
|
||||
}
|
||||
|
||||
public void setWithHistory(boolean withHistory) {
|
||||
public MTable setWithHistory(boolean withHistory) {
|
||||
this.withHistory = withHistory;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Map<String, MColumn> getColumns() {
|
||||
public List<String> allHistoryColumns(boolean includeDropped) {
|
||||
|
||||
List<String> columnNames = new ArrayList<String>(columns.size());
|
||||
for (MColumn column : columns.values()) {
|
||||
if (column.isIncludeInHistory()) {
|
||||
columnNames.add(column.getName());
|
||||
}
|
||||
}
|
||||
if (includeDropped && !droppedColumns.isEmpty()) {
|
||||
for (String droppedColumn : droppedColumns) {
|
||||
columnNames.add(droppedColumn);
|
||||
}
|
||||
}
|
||||
return columnNames;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return all the columns (excluding columns marked as dropped).
|
||||
*/
|
||||
public Collection<MColumn> allColumns() {
|
||||
|
||||
return columns.values();
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the column by name.
|
||||
*/
|
||||
public MColumn getColumn(String name) {
|
||||
return columns.get(name);
|
||||
}
|
||||
|
||||
private Map<String, MColumn> getColumns() {
|
||||
return columns;
|
||||
}
|
||||
|
||||
@@ -357,26 +404,14 @@ public class MTable {
|
||||
return compoundKeys;
|
||||
}
|
||||
|
||||
public String getSequenceName() {
|
||||
return sequenceName;
|
||||
}
|
||||
|
||||
public void setSequenceName(String sequenceName) {
|
||||
this.sequenceName = sequenceName;
|
||||
}
|
||||
|
||||
public int getSequenceInitial() {
|
||||
return sequenceInitial;
|
||||
}
|
||||
|
||||
public void setSequenceInitial(int sequenceInitial) {
|
||||
this.sequenceInitial = sequenceInitial;
|
||||
}
|
||||
|
||||
public int getSequenceAllocate() {
|
||||
return sequenceAllocate;
|
||||
}
|
||||
|
||||
public void setSequenceAllocate(int sequenceAllocate) {
|
||||
this.sequenceAllocate = sequenceAllocate;
|
||||
}
|
||||
@@ -399,22 +434,12 @@ public class MTable {
|
||||
this.identityType = identityType;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the identity type to use for this table.
|
||||
* <p>
|
||||
* If set then this overrides the platform default so for UUID generated values
|
||||
* or DB's supporting both sequences and autoincrement.
|
||||
*/
|
||||
public IdentityType getIdentityType() {
|
||||
return identityType;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the list of columns that make the primary key.
|
||||
*/
|
||||
public List<MColumn> primaryKeyColumns() {
|
||||
List<MColumn> pk = new ArrayList<MColumn>(3);
|
||||
for (MColumn column : columns.values()) {
|
||||
for (MColumn column : allColumns()) {
|
||||
if (column.isPrimaryKey()) {
|
||||
pk.add(column);
|
||||
}
|
||||
@@ -473,7 +498,7 @@ public class MTable {
|
||||
*/
|
||||
public MColumn addColumn(String dbCol, String columnDefn, boolean notnull) {
|
||||
|
||||
MColumn existingColumn = columns.get(dbCol);
|
||||
MColumn existingColumn = getColumn(dbCol);
|
||||
if (existingColumn != null) {
|
||||
if (notnull) {
|
||||
existingColumn.setNotnull(true);
|
||||
@@ -507,12 +532,12 @@ public class MTable {
|
||||
/**
|
||||
* Add a 'drop column' to the diff.
|
||||
*/
|
||||
private void diffDropColumn(ModelDiff modelDiff, MColumn existingColumn) {
|
||||
private void diffDropColumn(ModelDiff modelDiff, MColumn existingColumn, int columnPosition, MTable newTable) {
|
||||
|
||||
DropColumn dropColumn = new DropColumn();
|
||||
dropColumn.setTableName(name);
|
||||
dropColumn.setColumnName(existingColumn.getName());
|
||||
if (withHistory) {
|
||||
if (withHistory && !existingColumn.isHistoryExclude()) {
|
||||
// These dropColumns should occur on the history
|
||||
// table as well as the base table
|
||||
dropColumn.setWithHistory(Boolean.TRUE);
|
||||
@@ -521,6 +546,16 @@ public class MTable {
|
||||
modelDiff.addDropColumn(dropColumn);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a pending un-applied drop column.
|
||||
* <p>
|
||||
* This means this column still needs to be included in history views/triggers etc even
|
||||
* though it is not part of the current model.
|
||||
*/
|
||||
public void registerPendingDropColumn(String columnName) {
|
||||
droppedColumns.add(columnName);
|
||||
}
|
||||
|
||||
private int toInt(BigInteger value) {
|
||||
return (value == null) ? 0 : value.intValue();
|
||||
}
|
||||
@@ -532,7 +567,7 @@ public class MTable {
|
||||
/**
|
||||
* Check if there are duplicate foreign keys.
|
||||
* <p>
|
||||
* This can occur when an ManyToMany relates back to itself.
|
||||
* This can occur when an ManyToMany relates back to itself.
|
||||
* </p>
|
||||
*/
|
||||
public void checkDuplicateForeignKeys() {
|
||||
@@ -563,7 +598,7 @@ public class MTable {
|
||||
*/
|
||||
public void adjustReferences(ModelContainer modelContainer) {
|
||||
|
||||
Collection<MColumn> cols = columns.values();
|
||||
Collection<MColumn> cols = allColumns();
|
||||
for (MColumn col : cols) {
|
||||
String references = col.getReferences();
|
||||
if (references != null) {
|
||||
@@ -583,7 +618,7 @@ public class MTable {
|
||||
*/
|
||||
private String extractBaseTable(String references) {
|
||||
int lastDot = references.lastIndexOf('.');
|
||||
return references.substring(0,lastDot);
|
||||
return references.substring(0, lastDot);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -592,7 +627,7 @@ public class MTable {
|
||||
*/
|
||||
private String deriveReferences(String references, String draftTableName) {
|
||||
int lastDot = references.lastIndexOf('.');
|
||||
return draftTableName+"."+references.substring(lastDot+1);
|
||||
return draftTableName + "." + references.substring(lastDot + 1);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -52,7 +52,7 @@ public class MigrationModel {
|
||||
List<MigrationResource> resources = new ArrayList<MigrationResource>();
|
||||
|
||||
for (File xmlFile: xmlFiles) {
|
||||
resources.add(new MigrationResource(xmlFile));
|
||||
resources.add(new MigrationResource(xmlFile, createVersion(xmlFile)));
|
||||
}
|
||||
|
||||
// sort into version order before applying
|
||||
@@ -60,7 +60,7 @@ public class MigrationModel {
|
||||
|
||||
for (MigrationResource migrationResource: resources) {
|
||||
logger.debug("read {}", migrationResource);
|
||||
model.apply(migrationResource.read());
|
||||
model.apply(migrationResource.read(), migrationResource.getVersion());
|
||||
}
|
||||
|
||||
// remember the last version
|
||||
@@ -69,6 +69,12 @@ public class MigrationModel {
|
||||
}
|
||||
}
|
||||
|
||||
private MigrationVersion createVersion(File xmlFile) {
|
||||
String fileName = xmlFile.getName();
|
||||
String versionName = fileName.substring(0, fileName.length() - modelSuffix.length());
|
||||
return MigrationVersion.parse(versionName);
|
||||
}
|
||||
|
||||
public String getNextVersion(String initialVersion) {
|
||||
|
||||
return lastVersion == null ? initialVersion : lastVersion.nextVersion();
|
||||
|
||||
@@ -17,9 +17,9 @@ public class MigrationResource implements Comparable<MigrationResource> {
|
||||
/**
|
||||
* Construct with a migration xml file.
|
||||
*/
|
||||
public MigrationResource(File migrationFile) {
|
||||
public MigrationResource(File migrationFile, MigrationVersion version) {
|
||||
this.migrationFile = migrationFile;
|
||||
this.version = MigrationVersion.parse(migrationFile.getName());
|
||||
this.version = version;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package com.avaje.ebean.dbmigration.model;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
/**
|
||||
* The version of a migration used so that migrations are processed in order.
|
||||
*/
|
||||
@@ -15,23 +17,74 @@ public class MigrationVersion implements Comparable<MigrationVersion> {
|
||||
*/
|
||||
private final int[] ordering;
|
||||
|
||||
private MigrationVersion(String raw, int[] ordering) {
|
||||
private final boolean[] underscores;
|
||||
|
||||
private final String comment;
|
||||
|
||||
private MigrationVersion(String raw, int[] ordering, boolean[] underscores, String comment) {
|
||||
this.raw = raw;
|
||||
this.ordering = ordering;
|
||||
this.underscores = underscores;
|
||||
this.comment = comment;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return raw;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the version comment.
|
||||
*/
|
||||
public String getComment() {
|
||||
return comment;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the version in raw form.
|
||||
*/
|
||||
public String getRaw() {
|
||||
return raw;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the trimmed version excluding version comment and un-parsable string.
|
||||
*/
|
||||
public String asString() {
|
||||
return formattedVersion(false, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the trimmed version with any underscores replaced with '.'
|
||||
*/
|
||||
public String normalised() {
|
||||
return formattedVersion(true, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the next version based on this version.
|
||||
*/
|
||||
public String nextVersion() {
|
||||
return formattedVersion(false, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the version part of the string.
|
||||
*
|
||||
* Normalised means always use '.' delimiters (no underscores).
|
||||
* NextVersion means bump/increase the last version number by 1.
|
||||
*/
|
||||
private String formattedVersion(boolean normalised, boolean nextVersion) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (int i = 0; i < ordering.length; i++) {
|
||||
if (i < ordering.length -1 ) {
|
||||
sb.append(ordering[i]).append(".");
|
||||
if (i < ordering.length - 1) {
|
||||
sb.append(ordering[i]);
|
||||
if (normalised) {
|
||||
sb.append('.');
|
||||
} else {
|
||||
sb.append(underscores[i] ? '_' : '.');
|
||||
}
|
||||
} else {
|
||||
sb.append(ordering[i]+1);
|
||||
sb.append((nextVersion) ? ordering[i] + 1 : ordering[i]);
|
||||
}
|
||||
}
|
||||
return sb.toString();
|
||||
@@ -54,33 +107,54 @@ public class MigrationVersion implements Comparable<MigrationVersion> {
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse the raw version string and just return the leading version number;
|
||||
*/
|
||||
public static String trim(String raw) {
|
||||
return parse(raw).asString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse the raw version string into a MigrationVersion.
|
||||
*/
|
||||
public static MigrationVersion parse(String raw) {
|
||||
|
||||
String value = raw.replace("__",".");
|
||||
value = value.replace('_','.');
|
||||
String comment = "";
|
||||
String value = raw;
|
||||
int commentStart = raw.indexOf("__");
|
||||
if (commentStart > -1) {
|
||||
// trim off the trailing comment
|
||||
comment = raw.substring(commentStart + 2);
|
||||
value = value.substring(0, commentStart);
|
||||
}
|
||||
|
||||
value = value.replace('_', '.');
|
||||
|
||||
String[] sections = value.split("\\.");
|
||||
|
||||
boolean[] underscores = new boolean[sections.length];
|
||||
int[] ordering = new int[sections.length];
|
||||
|
||||
int delimiterPos = 0;
|
||||
int stopIndex = 0;
|
||||
for (int i = 0; i < sections.length; i++) {
|
||||
try {
|
||||
ordering[i] = Integer.parseInt(sections[i]);
|
||||
stopIndex++;
|
||||
|
||||
delimiterPos += sections[i].length();
|
||||
underscores[i] = (delimiterPos < raw.length() - 1 && raw.charAt(delimiterPos) == '_');
|
||||
delimiterPos++;
|
||||
} catch (NumberFormatException e) {
|
||||
// stop parsing
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
int[] actualOrder = new int[stopIndex];
|
||||
System.arraycopy(ordering, 0, actualOrder, 0, stopIndex);
|
||||
int[] actualOrder = Arrays.copyOf(ordering, stopIndex);
|
||||
boolean[] actualUnderscores = Arrays.copyOf(underscores, stopIndex);
|
||||
|
||||
return new MigrationVersion(raw, actualOrder);
|
||||
return new MigrationVersion(raw, actualOrder, actualUnderscores, comment);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import com.avaje.ebean.dbmigration.migration.AddColumn;
|
||||
import com.avaje.ebean.dbmigration.migration.AddHistoryTable;
|
||||
import com.avaje.ebean.dbmigration.migration.AlterColumn;
|
||||
import com.avaje.ebean.dbmigration.migration.ChangeSet;
|
||||
import com.avaje.ebean.dbmigration.migration.ChangeSetType;
|
||||
import com.avaje.ebean.dbmigration.migration.CreateIndex;
|
||||
import com.avaje.ebean.dbmigration.migration.CreateTable;
|
||||
import com.avaje.ebean.dbmigration.migration.DropColumn;
|
||||
@@ -12,7 +13,6 @@ import com.avaje.ebean.dbmigration.migration.DropIndex;
|
||||
import com.avaje.ebean.dbmigration.migration.DropTable;
|
||||
import com.avaje.ebean.dbmigration.migration.Migration;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -28,23 +28,23 @@ public class ModelContainer {
|
||||
/**
|
||||
* All the tables in the model.
|
||||
*/
|
||||
private Map<String, MTable> tables = new LinkedHashMap<String, MTable>();
|
||||
private final Map<String, MTable> tables = new LinkedHashMap<String, MTable>();
|
||||
|
||||
/**
|
||||
* All the non unique non foreign key indexes.
|
||||
*/
|
||||
private Map<String, MIndex> indexes = new LinkedHashMap<String, MIndex>();
|
||||
private final Map<String, MIndex> indexes = new LinkedHashMap<String, MIndex>();
|
||||
|
||||
private final PendingDrops pendingDrops = new PendingDrops();
|
||||
|
||||
public ModelContainer() {
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Adjust the FK references on all the draft tables.
|
||||
*/
|
||||
public void adjustDraftReferences() {
|
||||
Collection<MTable> tables = this.tables.values();
|
||||
for (MTable table : tables) {
|
||||
for (MTable table : this.tables.values()) {
|
||||
if (table.isDraft()) {
|
||||
table.adjustReferences(this);
|
||||
}
|
||||
@@ -82,14 +82,31 @@ public class ModelContainer {
|
||||
/**
|
||||
* Apply a migration with associated changeSets to the model.
|
||||
*/
|
||||
public void apply(Migration migration) {
|
||||
public void apply(Migration migration, MigrationVersion version) {
|
||||
|
||||
List<ChangeSet> changeSets = migration.getChangeSet();
|
||||
for (ChangeSet changeSet : changeSets) {
|
||||
applyChangeSet(changeSet);
|
||||
boolean pending = changeSet.getType() == ChangeSetType.PENDING_DROPS;
|
||||
if (pending) {
|
||||
// un-applied drop columns etc
|
||||
pendingDrops.add(version, changeSet);
|
||||
|
||||
} else if (isDropsFor(changeSet)) {
|
||||
pendingDrops.appliedDropsFor(changeSet);
|
||||
}
|
||||
if (!isDropsFor(changeSet)) {
|
||||
applyChangeSet(changeSet);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true if the changeSet contains drops for a previous PENDING_DROPS changeSet.
|
||||
*/
|
||||
private boolean isDropsFor(ChangeSet changeSet) {
|
||||
return changeSet.getDropsFor() != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply a changeSet to the model.
|
||||
*/
|
||||
@@ -245,4 +262,53 @@ public class ModelContainer {
|
||||
|
||||
indexes.put(indexName, new MIndex(indexName, tableName, columnNames));
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the list of versions containing un-applied pending drops.
|
||||
*/
|
||||
public List<String> getPendingDrops() {
|
||||
return pendingDrops.pendingDrops();
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the migration for the pending drops for a given version.
|
||||
*/
|
||||
public Migration migrationForPendingDrop(String pendingVersion) {
|
||||
return pendingDrops.migrationForVersion(pendingVersion);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the drop columns on history tables that have not been applied yet.
|
||||
*/
|
||||
public void registerPendingHistoryDropColumns(ModelContainer newModel) {
|
||||
pendingDrops.registerPendingHistoryDropColumns(newModel);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register any pending drop columns on history tables. These columns are now not in the current
|
||||
* logical model but we still need to include them in the history views and triggers until they
|
||||
* are actually dropped.
|
||||
*/
|
||||
public void registerPendingHistoryDropColumns(ChangeSet changeSet) {
|
||||
for (Object change : changeSet.getChangeSetChildren()) {
|
||||
if (change instanceof DropColumn) {
|
||||
DropColumn dropColumn = (DropColumn) change;
|
||||
if (Boolean.TRUE.equals(dropColumn.isWithHistory())) {
|
||||
registerPendingDropColumn(dropColumn);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a drop column on a history tables that has not been applied yet.
|
||||
*/
|
||||
private void registerPendingDropColumn(DropColumn dropColumn) {
|
||||
|
||||
MTable table = getTable(dropColumn.getTableName());
|
||||
if (table == null) {
|
||||
throw new IllegalArgumentException("Table ["+dropColumn.getTableName()+"] not found?");
|
||||
}
|
||||
table.registerPendingDropColumn(dropColumn.getColumnName());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -66,16 +66,14 @@ public class ModelDiff {
|
||||
public Migration getMigration() {
|
||||
|
||||
Migration migration = new Migration();
|
||||
ChangeSet applyChangeSet = getApplyChangeSet();
|
||||
if (!applyChangeSet.getChangeSetChildren().isEmpty()) {
|
||||
if (!applyChanges.isEmpty()) {
|
||||
// add a non empty apply changeSet
|
||||
migration.getChangeSet().add(applyChangeSet);
|
||||
migration.getChangeSet().add(getApplyChangeSet());
|
||||
}
|
||||
|
||||
ChangeSet dropChangeSet = getDropChangeSet();
|
||||
if (!dropChangeSet.getChangeSetChildren().isEmpty()) {
|
||||
if (!dropChanges.isEmpty()) {
|
||||
// add a non empty drop changeSet
|
||||
migration.getChangeSet().add(dropChangeSet);
|
||||
migration.getChangeSet().add(getDropChangeSet());
|
||||
}
|
||||
return migration;
|
||||
}
|
||||
@@ -83,14 +81,14 @@ public class ModelDiff {
|
||||
/**
|
||||
* Return the list of 'apply' changes.
|
||||
*/
|
||||
public List<Object> getApplyChanges() {
|
||||
List<Object> getApplyChanges() {
|
||||
return applyChanges;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the list of 'drop' changes.
|
||||
*/
|
||||
public List<Object> getDropChanges() {
|
||||
List<Object> getDropChanges() {
|
||||
return dropChanges;
|
||||
}
|
||||
|
||||
@@ -108,10 +106,10 @@ public class ModelDiff {
|
||||
/**
|
||||
* Return the 'drop' changeSet.
|
||||
*/
|
||||
public ChangeSet getDropChangeSet() {
|
||||
ChangeSet getDropChangeSet() {
|
||||
// put the changes into a ChangeSet
|
||||
ChangeSet createChangeSet = new ChangeSet();
|
||||
createChangeSet.setType(ChangeSetType.DROP);
|
||||
createChangeSet.setType(ChangeSetType.PENDING_DROPS);
|
||||
createChangeSet.getChangeSetChildren().addAll(dropChanges);
|
||||
return createChangeSet;
|
||||
}
|
||||
@@ -156,6 +154,12 @@ public class ModelDiff {
|
||||
}
|
||||
}
|
||||
|
||||
// register un-applied ones from the previous migrations
|
||||
baseModel.registerPendingHistoryDropColumns(newModel);
|
||||
if (!dropChanges.isEmpty()) {
|
||||
// register new ones created just now as part of this diff
|
||||
newModel.registerPendingHistoryDropColumns(getDropChangeSet());
|
||||
}
|
||||
}
|
||||
|
||||
protected void addDropTable(MTable existingTable) {
|
||||
|
||||
@@ -0,0 +1,263 @@
|
||||
package com.avaje.ebean.dbmigration.model;
|
||||
|
||||
import com.avaje.ebean.dbmigration.migration.ChangeSet;
|
||||
import com.avaje.ebean.dbmigration.migration.ChangeSetType;
|
||||
import com.avaje.ebean.dbmigration.migration.DropColumn;
|
||||
import com.avaje.ebean.dbmigration.migration.DropTable;
|
||||
import com.avaje.ebean.dbmigration.migration.Migration;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* The migrations with pending un-applied drops.
|
||||
*/
|
||||
public class PendingDrops {
|
||||
|
||||
private final LinkedHashMap<String, Entry> map = new LinkedHashMap<String, Entry>();
|
||||
|
||||
/**
|
||||
* Add a 'pending drops' changeSet for the given version.
|
||||
*/
|
||||
public void add(MigrationVersion version, ChangeSet changeSet) {
|
||||
|
||||
Entry entry = map.get(version.normalised());
|
||||
if (entry == null) {
|
||||
entry = new Entry(version);
|
||||
map.put(version.normalised(), entry);
|
||||
}
|
||||
entry.add(changeSet);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the list of versions with pending drops.
|
||||
*/
|
||||
public List<String> pendingDrops() {
|
||||
|
||||
List<String> versions = new ArrayList<String>();
|
||||
for (Entry value : map.values()) {
|
||||
if (value.hasPendingDrops()) {
|
||||
versions.add(value.version.asString());
|
||||
}
|
||||
}
|
||||
return versions;
|
||||
}
|
||||
|
||||
/**
|
||||
* All the pending drops for this migration version have been applied so we need
|
||||
* to remove the (unsuppressed) pending drops for this version.
|
||||
*/
|
||||
public boolean appliedDropsFor(ChangeSet changeSet) {
|
||||
|
||||
MigrationVersion version = MigrationVersion.parse(changeSet.getDropsFor());
|
||||
|
||||
Entry entry = map.get(version.normalised());
|
||||
if (entry.removeDrops(changeSet)) {
|
||||
// it had no suppressForever changeSets so remove completely
|
||||
map.remove(version.normalised());
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the migration for the pending drops from a version.
|
||||
* <p>
|
||||
* The value of version can be "next" to find the first un-applied pending drops.
|
||||
* </p>
|
||||
*/
|
||||
public Migration migrationForVersion(String pendingVersion) {
|
||||
|
||||
Entry entry = getEntry(pendingVersion);
|
||||
|
||||
Migration migration = new Migration();
|
||||
Iterator<ChangeSet> it = entry.list.iterator();
|
||||
while (it.hasNext()) {
|
||||
ChangeSet changeSet = it.next();
|
||||
if (!isSuppressForever(changeSet)) {
|
||||
it.remove();
|
||||
changeSet.setType(ChangeSetType.APPLY);
|
||||
changeSet.setDropsFor(entry.version.asString());
|
||||
migration.getChangeSet().add(changeSet);
|
||||
}
|
||||
}
|
||||
|
||||
if (migration.getChangeSet().isEmpty()) {
|
||||
throw new IllegalArgumentException("The remaining pendingDrops changeSets in migration ["+pendingVersion+"] are suppressDropsForever=true and can't be applied");
|
||||
}
|
||||
|
||||
if (!entry.containsSuppressForever()) {
|
||||
// we can remove it completely as it has no suppressForever changes
|
||||
map.remove(entry.version.normalised());
|
||||
}
|
||||
|
||||
return migration;
|
||||
}
|
||||
|
||||
private Entry getEntry(String pendingVersion) {
|
||||
|
||||
if ("next".equalsIgnoreCase(pendingVersion)) {
|
||||
Iterator<Entry> it = map.values().iterator();
|
||||
if (it.hasNext()) {
|
||||
return it.next();
|
||||
}
|
||||
} else {
|
||||
Entry remove = map.get(MigrationVersion.parse(pendingVersion).normalised());
|
||||
if (remove != null) {
|
||||
return remove;
|
||||
}
|
||||
}
|
||||
throw new IllegalArgumentException("No 'pendingDrops' changeSets for migration version [" + pendingVersion + "] found");
|
||||
}
|
||||
|
||||
/**
|
||||
* Register pending drop columns on history tables to the new model.
|
||||
*/
|
||||
public void registerPendingHistoryDropColumns(ModelContainer newModel) {
|
||||
|
||||
for (Entry entry : map.values()) {
|
||||
for (ChangeSet changeSet : entry.list) {
|
||||
newModel.registerPendingHistoryDropColumns(changeSet);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true if there is an Entry for the given version.
|
||||
*/
|
||||
boolean testContainsEntryFor(MigrationVersion version) {
|
||||
return map.containsKey(version.normalised());
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the Entry for the given version.
|
||||
*/
|
||||
Entry testGetEntryFor(MigrationVersion version) {
|
||||
return map.get(version.normalised());
|
||||
}
|
||||
|
||||
static class Entry {
|
||||
|
||||
final MigrationVersion version;
|
||||
|
||||
final List<ChangeSet> list = new ArrayList<ChangeSet>();
|
||||
|
||||
Entry(MigrationVersion version) {
|
||||
this.version = version;
|
||||
}
|
||||
|
||||
void add(ChangeSet changeSet) {
|
||||
list.add(changeSet);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true if this contains suppressForever changeSets.
|
||||
*/
|
||||
boolean containsSuppressForever() {
|
||||
for (ChangeSet changeSet : list) {
|
||||
if (isSuppressForever(changeSet)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true if this contains drops that can be applied / migrated.
|
||||
*/
|
||||
boolean hasPendingDrops() {
|
||||
for (ChangeSet changeSet : list) {
|
||||
if (!isSuppressForever(changeSet)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the drops that are not suppressForever and return true if that
|
||||
* removed all the changeSets (and there are no suppressForever ones).
|
||||
*/
|
||||
boolean removeDrops(ChangeSet appliedDrops) {
|
||||
|
||||
Iterator<ChangeSet> iterator = list.iterator();
|
||||
while (iterator.hasNext()) {
|
||||
ChangeSet next = iterator.next();
|
||||
if (!isSuppressForever(next)) {
|
||||
removeMatchingChanges(next, appliedDrops);
|
||||
if (next.getChangeSetChildren().isEmpty()) {
|
||||
iterator.remove();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return list.isEmpty();
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the applied drops from the pending ones matching by table name and column name.
|
||||
*/
|
||||
private void removeMatchingChanges(ChangeSet pendingDrops, ChangeSet appliedDrops) {
|
||||
|
||||
List<Object> pending = pendingDrops.getChangeSetChildren();
|
||||
Iterator<Object> iterator = pending.iterator();
|
||||
while (iterator.hasNext()) {
|
||||
Object pendingDrop = iterator.next();
|
||||
if (pendingDrop instanceof DropColumn && dropColumnIn((DropColumn)pendingDrop, appliedDrops)) {
|
||||
iterator.remove();
|
||||
|
||||
} else if (pendingDrop instanceof DropTable && dropTableIn((DropTable)pendingDrop, appliedDrops)) {
|
||||
iterator.remove();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true if the pendingDrop is contained in the appliedDrops.
|
||||
*/
|
||||
private boolean dropTableIn(DropTable pendingDrop, ChangeSet appliedDrops) {
|
||||
for (Object o : appliedDrops.getChangeSetChildren()) {
|
||||
if (o instanceof DropTable && sameTable(pendingDrop, (DropTable)o)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true if the pendingDrop is contained in the appliedDrops.
|
||||
*/
|
||||
private boolean dropColumnIn(DropColumn pendingDrop, ChangeSet appliedDrops) {
|
||||
for (Object o : appliedDrops.getChangeSetChildren()) {
|
||||
if (o instanceof DropColumn && sameColumn(pendingDrop, (DropColumn) o)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true if the DropTable match by table name.
|
||||
*/
|
||||
private boolean sameTable(DropTable pendingDrop, DropTable o) {
|
||||
return pendingDrop.getName().equals(o.getName());
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true if the DropColumns match by table and column name.
|
||||
*/
|
||||
private boolean sameColumn(DropColumn pending, DropColumn o) {
|
||||
return pending.getColumnName().equals(o.getColumnName())
|
||||
&& pending.getTableName().equals(o.getTableName());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private static boolean isSuppressForever(ChangeSet next) {
|
||||
return Boolean.TRUE.equals(next.isSuppressDropsForever());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -3,9 +3,11 @@ package com.avaje.ebean.dbmigration.model;
|
||||
import com.avaje.ebean.config.DbMigrationConfig;
|
||||
import com.avaje.ebean.config.ServerConfig;
|
||||
import com.avaje.ebean.config.dbplatform.DatabasePlatform;
|
||||
import com.avaje.ebean.dbmigration.ddlgeneration.DdlBuffer;
|
||||
import com.avaje.ebean.dbmigration.ddlgeneration.DdlHandler;
|
||||
import com.avaje.ebean.dbmigration.ddlgeneration.DdlWrite;
|
||||
import com.avaje.ebean.dbmigration.migration.ChangeSet;
|
||||
import com.avaje.ebean.dbmigration.migration.ChangeSetType;
|
||||
import com.avaje.ebean.dbmigration.migration.Migration;
|
||||
|
||||
import java.io.File;
|
||||
@@ -43,7 +45,7 @@ public class PlatformDdlWriter {
|
||||
|
||||
List<ChangeSet> changeSets = dbMigration.getChangeSet();
|
||||
for (ChangeSet changeSet : changeSets) {
|
||||
if (!changeSet.getChangeSetChildren().isEmpty()) {
|
||||
if (isApply(changeSet)) {
|
||||
handler.generate(write, changeSet);
|
||||
}
|
||||
}
|
||||
@@ -52,6 +54,13 @@ public class PlatformDdlWriter {
|
||||
writePlatformDdl(write, writePath, fullVersion);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true if the changeSet is APPLY and not empty.
|
||||
*/
|
||||
private boolean isApply(ChangeSet changeSet) {
|
||||
return changeSet.getType() == ChangeSetType.APPLY && !changeSet.getChangeSetChildren().isEmpty();
|
||||
}
|
||||
|
||||
/**
|
||||
* Write the ddl files.
|
||||
*/
|
||||
@@ -65,26 +74,6 @@ public class PlatformDdlWriter {
|
||||
} finally {
|
||||
applyWriter.close();
|
||||
}
|
||||
|
||||
if (!config.isSuppressRollback() && !write.isApplyRollbackEmpty()) {
|
||||
FileWriter applyRollbackWriter = createWriter(resourcePath, fullVersion, config.getRollbackPath(), config.getRollbackSuffix());
|
||||
try {
|
||||
writeApplyRollbackDdl(applyRollbackWriter, write);
|
||||
applyRollbackWriter.flush();
|
||||
} finally {
|
||||
applyRollbackWriter.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!write.isDropEmpty()) {
|
||||
FileWriter dropWriter = createWriter(resourcePath, fullVersion, config.getDropPath(), config.getDropSuffix());
|
||||
try {
|
||||
writeDropDdl(dropWriter, write);
|
||||
dropWriter.flush();
|
||||
} finally {
|
||||
dropWriter.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -116,29 +105,19 @@ public class PlatformDdlWriter {
|
||||
protected void writeApplyDdl(Writer writer, DdlWrite write) throws IOException {
|
||||
|
||||
// merge the apply buffers in the appropriate order
|
||||
prependDropDependencies(writer, write.applyDropDependencies());
|
||||
writer.append("-- apply changes\n");
|
||||
writer.append(write.apply().getBuffer());
|
||||
writer.append(write.applyForeignKeys().getBuffer());
|
||||
writer.append(write.applyHistory().getBuffer());
|
||||
}
|
||||
|
||||
/**
|
||||
* Write the 'Rollback' DDL buffers to the writer.
|
||||
*/
|
||||
protected void writeApplyRollbackDdl(Writer writer, DdlWrite write) throws IOException {
|
||||
|
||||
// merge the rollback buffers in the appropriate order
|
||||
writer.append(write.rollbackForeignKeys().getBuffer());
|
||||
writer.append(write.rollback().getBuffer());
|
||||
}
|
||||
|
||||
/**
|
||||
* Write the 'Drop' DDL buffers to the writer.
|
||||
*/
|
||||
protected void writeDropDdl(Writer writer, DdlWrite write) throws IOException {
|
||||
|
||||
// merge the rollback buffers in the appropriate order
|
||||
writer.append(write.dropHistory().getBuffer());
|
||||
writer.append(write.drop().getBuffer());
|
||||
private void prependDropDependencies(Writer writer, DdlBuffer buffer) throws IOException {
|
||||
if (!buffer.isEmpty()) {
|
||||
writer.append("-- drop dependencies\n");
|
||||
writer.append(buffer.getBuffer());
|
||||
writer.append("\n");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -158,7 +158,7 @@ public class ModelBuildContext {
|
||||
int fkCount = 0;
|
||||
int ixCount = 0;
|
||||
int uqCount = 0;
|
||||
Collection<MColumn> cols = draftTable.getColumns().values();
|
||||
Collection<MColumn> cols = draftTable.allColumns();
|
||||
for (MColumn col: cols) {
|
||||
if (col.getForeignKeyName() != null) {
|
||||
// Note that we adjust the 'references' table later in a second pass
|
||||
|
||||
+1
-1
@@ -84,7 +84,7 @@ public class ModelBuildPropertyVisitor extends BaseTablePropertyVisitor {
|
||||
table.setPkName(determinePrimaryKeyName());
|
||||
|
||||
// check if indexes on foreign keys should be suppressed
|
||||
for (MColumn column : table.getColumns().values()) {
|
||||
for (MColumn column : table.allColumns()) {
|
||||
if (hasValue(column.getForeignKeyIndex())) {
|
||||
if (indexSet.contains(column.getName())) {
|
||||
// suppress index on foreign key as there is already
|
||||
|
||||
@@ -12,7 +12,7 @@ public class HashQueryPlanBuilder {
|
||||
private String rawSql;
|
||||
|
||||
public HashQueryPlanBuilder() {
|
||||
this.planHash = 31;
|
||||
this.planHash = 92821;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
@@ -23,7 +23,7 @@ public class HashQueryPlanBuilder {
|
||||
* Add a class to the hash calculation.
|
||||
*/
|
||||
public HashQueryPlanBuilder add(Class<?> cls) {
|
||||
planHash = planHash * 31 + cls.getName().hashCode();
|
||||
planHash = planHash * 92821 + cls.getName().hashCode();
|
||||
return this;
|
||||
}
|
||||
|
||||
@@ -31,7 +31,7 @@ public class HashQueryPlanBuilder {
|
||||
* Add an object to the hash calculation.
|
||||
*/
|
||||
public HashQueryPlanBuilder add(Object object) {
|
||||
planHash = planHash * 31 + (object == null ? 0 : object.hashCode());
|
||||
planHash = planHash * 92821 + (object == null ? 0 : object.hashCode());
|
||||
return this;
|
||||
}
|
||||
|
||||
@@ -39,7 +39,7 @@ public class HashQueryPlanBuilder {
|
||||
* Add an integer to the hash calculation.
|
||||
*/
|
||||
public HashQueryPlanBuilder add(int hashValue) {
|
||||
planHash = planHash * 31 + (hashValue);
|
||||
planHash = planHash * 92821 + (hashValue);
|
||||
return this;
|
||||
}
|
||||
|
||||
@@ -47,7 +47,7 @@ public class HashQueryPlanBuilder {
|
||||
* Add a boolean to the hash calculation.
|
||||
*/
|
||||
public HashQueryPlanBuilder add(boolean booleanValue) {
|
||||
planHash = planHash * 31 + (booleanValue ? 31 : 0);
|
||||
planHash = planHash * 92821 + (booleanValue ? 92821 : 0);
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
@@ -8,7 +8,9 @@ import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Request for loading ManyToOne and OneToOne relationships.
|
||||
@@ -21,8 +23,6 @@ public class LoadBeanRequest extends LoadRequest {
|
||||
|
||||
private final LoadBeanBuffer loadBuffer;
|
||||
|
||||
private final int lazyLoadPropertyIndex;
|
||||
|
||||
private final String lazyLoadProperty;
|
||||
|
||||
private final boolean loadCache;
|
||||
@@ -30,24 +30,23 @@ public class LoadBeanRequest extends LoadRequest {
|
||||
/**
|
||||
* Construct for lazy load request.
|
||||
*/
|
||||
public LoadBeanRequest(LoadBeanBuffer LoadBuffer, int lazyLoadPropertyIndex, String lazyLoadProperty, boolean loadCache) {
|
||||
this(LoadBuffer, null, true, lazyLoadPropertyIndex, lazyLoadProperty, loadCache);
|
||||
public LoadBeanRequest(LoadBeanBuffer LoadBuffer, String lazyLoadProperty, boolean loadCache) {
|
||||
this(LoadBuffer, null, true, lazyLoadProperty, loadCache);
|
||||
}
|
||||
|
||||
/**
|
||||
* Construct for secondary query.
|
||||
*/
|
||||
public LoadBeanRequest(LoadBeanBuffer LoadBuffer, OrmQueryRequest<?> parentRequest) {
|
||||
this(LoadBuffer, parentRequest, false, -1, null, false);
|
||||
this(LoadBuffer, parentRequest, false, null, false);
|
||||
}
|
||||
|
||||
private LoadBeanRequest(LoadBeanBuffer loadBuffer, OrmQueryRequest<?> parentRequest, boolean lazy,
|
||||
int lazyLoadPropertyIndex, String lazyLoadProperty, boolean loadCache) {
|
||||
String lazyLoadProperty, boolean loadCache) {
|
||||
|
||||
super(parentRequest, lazy);
|
||||
this.loadBuffer = loadBuffer;
|
||||
this.batch = loadBuffer.getBatch();
|
||||
this.lazyLoadPropertyIndex = lazyLoadPropertyIndex;
|
||||
this.lazyLoadProperty = lazyLoadProperty;
|
||||
this.loadCache = loadCache;
|
||||
}
|
||||
@@ -96,7 +95,7 @@ public class LoadBeanRequest extends LoadRequest {
|
||||
*/
|
||||
public List<Object> getIdList(int batchSize) {
|
||||
|
||||
ArrayList<Object> idList = new ArrayList<Object>(batchSize);
|
||||
List<Object> idList = new ArrayList<Object>(batchSize);
|
||||
|
||||
BeanDescriptor<?> desc = loadBuffer.getBeanDescriptor();
|
||||
for (int i = 0; i < batch.size(); i++) {
|
||||
@@ -124,7 +123,7 @@ public class LoadBeanRequest extends LoadRequest {
|
||||
/**
|
||||
* Configure the query for lazy loading execution.
|
||||
*/
|
||||
public void configureQuery(SpiQuery<?> query) {
|
||||
public void configureQuery(SpiQuery<?> query, List<Object> idList) {
|
||||
|
||||
query.setMode(SpiQuery.Mode.LAZYLOAD_BEAN);
|
||||
query.setPersistenceContext(loadBuffer.getPersistenceContext());
|
||||
@@ -137,7 +136,13 @@ public class LoadBeanRequest extends LoadRequest {
|
||||
query.setLazyLoadBatchSize(getBatchSize());
|
||||
}
|
||||
|
||||
loadBuffer.configureQuery(query, getLazyLoadProperty());
|
||||
loadBuffer.configureQuery(query, lazyLoadProperty);
|
||||
|
||||
if (idList.size() == 1) {
|
||||
query.where().idEq(idList.get(0));
|
||||
} else {
|
||||
query.where().idIn(idList);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -145,25 +150,27 @@ public class LoadBeanRequest extends LoadRequest {
|
||||
*/
|
||||
public void postLoad(List<?> list) {
|
||||
|
||||
if (isLoadCache()) {
|
||||
BeanDescriptor<?> desc = loadBuffer.getBeanDescriptor();
|
||||
for (int i = 0; i < list.size(); i++) {
|
||||
desc.cacheBeanPutData((EntityBean) list.get(i));
|
||||
Set<Object> loadedIds = new HashSet<Object>();
|
||||
|
||||
BeanDescriptor<?> desc = loadBuffer.getBeanDescriptor();
|
||||
// collect Ids and maybe load bean cache
|
||||
for (int i = 0; i < list.size(); i++) {
|
||||
EntityBean loadedBean = (EntityBean) list.get(i);
|
||||
loadedIds.add(desc.getId(loadedBean));
|
||||
if (isLoadCache()) {
|
||||
desc.cacheBeanPutData(loadedBean);
|
||||
}
|
||||
}
|
||||
|
||||
if (lazyLoadPropertyIndex > -1) {
|
||||
// this is a lazy loading query so check for lazy loading failure (due to deleted rows)
|
||||
if (lazyLoadProperty != null) {
|
||||
for (int i = 0; i < batch.size(); i++) {
|
||||
// check if the underlying row in DB was deleted. Mark the bean as 'failed' if
|
||||
// necessary but allow processing to continue until it is accessed by client code
|
||||
EntityBeanIntercept ebi = batch.get(i);
|
||||
// all beans in the batch should have this property loaded now
|
||||
if (ebi.isLazyLoadFailure(lazyLoadPropertyIndex)) {
|
||||
BeanDescriptor<?> desc = loadBuffer.getBeanDescriptor();
|
||||
Object beanId = desc.getId(ebi.getOwner());
|
||||
ebi.setOwnerId(beanId);
|
||||
logger.info("Lazy loading unsuccessful for type:" + desc.getName() + " id:" + beanId + " - expecting when bean has been deleted");
|
||||
Object id = desc.getId(ebi.getOwner());
|
||||
if (!loadedIds.contains(id)) {
|
||||
logger.info("Lazy loading unsuccessful for type:" + desc.getName() + " id:" + id + " - expecting when bean has been deleted");
|
||||
ebi.setLazyLoadFailure(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -206,16 +206,9 @@ public class DefaultBeanLoader {
|
||||
}
|
||||
|
||||
SpiQuery<?> query = (SpiQuery<?>) server.createQuery(loadRequest.getBeanType());
|
||||
loadRequest.configureQuery(query);
|
||||
|
||||
if (idList.size() == 1) {
|
||||
query.where().idEq(idList.get(0));
|
||||
} else {
|
||||
query.where().idIn(idList);
|
||||
}
|
||||
loadRequest.configureQuery(query, idList);
|
||||
|
||||
List<?> list = executeQuery(loadRequest, query);
|
||||
|
||||
loadRequest.postLoad(list);
|
||||
|
||||
// log the query (for testing secondary queries)
|
||||
|
||||
@@ -42,7 +42,7 @@ public interface BeanCollectionHelp<T> {
|
||||
/**
|
||||
* Add a bean to the List Set or Map.
|
||||
*/
|
||||
void add(BeanCollection<?> collection, EntityBean bean);
|
||||
void add(BeanCollection<?> collection, EntityBean bean, boolean withCheck);
|
||||
|
||||
/**
|
||||
* Create a lazy loading proxy for a List Set or Map.
|
||||
|
||||
@@ -46,8 +46,12 @@ public final class BeanListHelp<T> implements BeanCollectionHelp<T> {
|
||||
* Internal add bypassing any modify listening.
|
||||
*/
|
||||
@Override
|
||||
public void add(BeanCollection<?> collection, EntityBean bean) {
|
||||
collection.internalAdd(bean);
|
||||
public void add(BeanCollection<?> collection, EntityBean bean, boolean withCheck) {
|
||||
if (withCheck) {
|
||||
collection.internalAddWithCheck(bean);
|
||||
} else {
|
||||
collection.internalAdd(bean);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -108,13 +108,14 @@ public final class BeanMapHelp<T> implements BeanCollectionHelp<T> {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void add(BeanCollection<?> collection, EntityBean bean) {
|
||||
public void add(BeanCollection<?> collection, EntityBean bean, boolean withCheck) {
|
||||
|
||||
if (bean == null) {
|
||||
((BeanMap<?, ?>) collection).internalPutNull();
|
||||
} else {
|
||||
Object keyValue = beanProperty.getValueIntercept(bean);
|
||||
((BeanMap<?, ?>) collection).internalPut(keyValue, bean);
|
||||
BeanMap<?, ?> map = ((BeanMap<?, ?>) collection);
|
||||
map.internalPutWithCheck(keyValue, bean);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -182,13 +182,13 @@ public class BeanPropertyAssocMany<T> extends BeanPropertyAssoc<T> {
|
||||
/**
|
||||
* Add the bean to the appropriate collection on the parent bean.
|
||||
*/
|
||||
public void addBeanToCollectionWithCreate(EntityBean parentBean, EntityBean detailBean) {
|
||||
public void addBeanToCollectionWithCreate(EntityBean parentBean, EntityBean detailBean, boolean withCheck) {
|
||||
BeanCollection<?> bc = (BeanCollection<?>) super.getValue(parentBean);
|
||||
if (bc == null) {
|
||||
bc = help.createEmpty(parentBean);
|
||||
setValue(parentBean, bc);
|
||||
}
|
||||
help.add(bc, detailBean);
|
||||
help.add(bc, detailBean, withCheck);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -416,7 +416,7 @@ public class BeanPropertyAssocMany<T> extends BeanPropertyAssoc<T> {
|
||||
}
|
||||
|
||||
public void add(BeanCollection<?> collection, EntityBean bean) {
|
||||
help.add(collection, bean);
|
||||
help.add(collection, bean, false);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -61,8 +61,12 @@ public final class BeanSetHelp<T> implements BeanCollectionHelp<T> {
|
||||
}
|
||||
}
|
||||
|
||||
public void add(BeanCollection<?> collection, EntityBean bean) {
|
||||
collection.internalAdd(bean);
|
||||
public void add(BeanCollection<?> collection, EntityBean bean, boolean withCheck) {
|
||||
if (withCheck) {
|
||||
collection.internalAddWithCheck(bean);
|
||||
} else {
|
||||
collection.internalAdd(bean);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
+45
-46
@@ -1,13 +1,12 @@
|
||||
package com.avaje.ebeaninternal.server.deploy.generatedproperty;
|
||||
|
||||
import com.avaje.ebeaninternal.server.deploy.meta.DeployBeanProperty;
|
||||
|
||||
import javax.persistence.PersistenceException;
|
||||
import java.math.BigDecimal;
|
||||
import java.math.BigInteger;
|
||||
import java.sql.Types;
|
||||
|
||||
import javax.persistence.PersistenceException;
|
||||
|
||||
import com.avaje.ebeaninternal.server.deploy.meta.DeployBeanProperty;
|
||||
|
||||
/**
|
||||
* Creates "Counter" GeneratedProperty for various types of number.
|
||||
* <p>
|
||||
@@ -16,49 +15,49 @@ import com.avaje.ebeaninternal.server.deploy.meta.DeployBeanProperty;
|
||||
*/
|
||||
public class CounterFactory {
|
||||
|
||||
final GeneratedCounterInteger integerCounter = new GeneratedCounterInteger();
|
||||
final GeneratedCounterInteger integerCounter = new GeneratedCounterInteger();
|
||||
|
||||
final GeneratedCounterLong longCounter = new GeneratedCounterLong();
|
||||
final GeneratedCounterLong longCounter = new GeneratedCounterLong();
|
||||
|
||||
public void setCounter(DeployBeanProperty property) {
|
||||
public void setCounter(DeployBeanProperty property) {
|
||||
|
||||
property.setGeneratedProperty(createCounter(property));
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the GeneratedProperty based on the property type.
|
||||
*/
|
||||
private GeneratedProperty createCounter(DeployBeanProperty property) {
|
||||
|
||||
Class<?> propType = property.getPropertyType();
|
||||
if (propType.equals(Integer.class) || propType.equals(int.class)) {
|
||||
return integerCounter;
|
||||
}
|
||||
if (propType.equals(Long.class) || propType.equals(long.class)) {
|
||||
return longCounter;
|
||||
}
|
||||
|
||||
int type = getType(propType);
|
||||
return new GeneratedCounter(type);
|
||||
}
|
||||
|
||||
private int getType(Class<?> propType){
|
||||
if (propType.equals(Short.class) || propType.equals(short.class)){
|
||||
return Types.TINYINT;
|
||||
}
|
||||
if (propType.equals(BigDecimal.class)){
|
||||
return Types.DECIMAL;
|
||||
}
|
||||
if (propType.equals(Double.class) || propType.equals(double.class)){
|
||||
return Types.DOUBLE;
|
||||
}
|
||||
if (propType.equals(Float.class) || propType.equals(float.class)){
|
||||
return Types.REAL;
|
||||
}
|
||||
if (propType.equals(BigInteger.class)){
|
||||
return Types.BIGINT;
|
||||
}
|
||||
String msg = "Can not support Counter for type "+propType.getName();
|
||||
throw new PersistenceException(msg);
|
||||
}
|
||||
property.setGeneratedProperty(createCounter(property));
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the GeneratedProperty based on the property type.
|
||||
*/
|
||||
private GeneratedProperty createCounter(DeployBeanProperty property) {
|
||||
|
||||
Class<?> propType = property.getPropertyType();
|
||||
if (propType.equals(Integer.class) || propType.equals(int.class)) {
|
||||
return integerCounter;
|
||||
}
|
||||
if (propType.equals(Long.class) || propType.equals(long.class)) {
|
||||
return longCounter;
|
||||
}
|
||||
|
||||
int type = getType(propType);
|
||||
return new GeneratedCounter(type);
|
||||
}
|
||||
|
||||
private int getType(Class<?> propType) {
|
||||
if (propType.equals(Short.class) || propType.equals(short.class)) {
|
||||
return Types.TINYINT;
|
||||
}
|
||||
if (propType.equals(BigDecimal.class)) {
|
||||
return Types.DECIMAL;
|
||||
}
|
||||
if (propType.equals(Double.class) || propType.equals(double.class)) {
|
||||
return Types.DOUBLE;
|
||||
}
|
||||
if (propType.equals(Float.class) || propType.equals(float.class)) {
|
||||
return Types.REAL;
|
||||
}
|
||||
if (propType.equals(BigInteger.class)) {
|
||||
return Types.BIGINT;
|
||||
}
|
||||
String msg = "Can not support Counter for type " + propType.getName();
|
||||
throw new PersistenceException(msg);
|
||||
}
|
||||
}
|
||||
|
||||
+39
-37
@@ -9,49 +9,51 @@ import com.avaje.ebeaninternal.server.deploy.BeanProperty;
|
||||
*/
|
||||
public class GeneratedCounter implements GeneratedProperty {
|
||||
|
||||
final int numberType;
|
||||
final int numberType;
|
||||
|
||||
public GeneratedCounter(int numberType) {
|
||||
this.numberType = numberType;
|
||||
}
|
||||
public GeneratedCounter(int numberType) {
|
||||
this.numberType = numberType;
|
||||
}
|
||||
|
||||
/**
|
||||
* Always returns a 1.
|
||||
*/
|
||||
public Object getInsertValue(BeanProperty prop, EntityBean bean) {
|
||||
return BasicTypeConverter.convert(1, numberType);
|
||||
}
|
||||
/**
|
||||
* Always returns a 1.
|
||||
*/
|
||||
@Override
|
||||
public Object getInsertValue(BeanProperty prop, EntityBean bean, long now) {
|
||||
return BasicTypeConverter.convert(1, numberType);
|
||||
}
|
||||
|
||||
/**
|
||||
* Increments the current value by one.
|
||||
*/
|
||||
public Object getUpdateValue(BeanProperty prop, EntityBean bean) {
|
||||
Number currVal = (Number) prop.getValue(bean);
|
||||
Integer nextVal = currVal.intValue() + 1;
|
||||
return BasicTypeConverter.convert(nextVal, numberType);
|
||||
}
|
||||
/**
|
||||
* Increments the current value by one.
|
||||
*/
|
||||
@Override
|
||||
public Object getUpdateValue(BeanProperty prop, EntityBean bean, long now) {
|
||||
Number currVal = (Number) prop.getValue(bean);
|
||||
Integer nextVal = currVal.intValue() + 1;
|
||||
return BasicTypeConverter.convert(nextVal, numberType);
|
||||
}
|
||||
|
||||
/**
|
||||
* Include this in every update.
|
||||
*/
|
||||
public boolean includeInUpdate() {
|
||||
return true;
|
||||
}
|
||||
/**
|
||||
* Include this in every update.
|
||||
*/
|
||||
public boolean includeInUpdate() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean includeInAllUpdates() {
|
||||
return false;
|
||||
}
|
||||
@Override
|
||||
public boolean includeInAllUpdates() {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Include this in every insert setting initial counter value to 1.
|
||||
*/
|
||||
public boolean includeInInsert() {
|
||||
return true;
|
||||
}
|
||||
/**
|
||||
* Include this in every insert setting initial counter value to 1.
|
||||
*/
|
||||
public boolean includeInInsert() {
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean isDDLNotNullable() {
|
||||
return true;
|
||||
}
|
||||
public boolean isDDLNotNullable() {
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+37
-35
@@ -8,46 +8,48 @@ import com.avaje.ebeaninternal.server.deploy.BeanProperty;
|
||||
*/
|
||||
public class GeneratedCounterInteger implements GeneratedProperty {
|
||||
|
||||
public GeneratedCounterInteger() {
|
||||
public GeneratedCounterInteger() {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Always returns a 1.
|
||||
*/
|
||||
public Object getInsertValue(BeanProperty prop, EntityBean bean) {
|
||||
return 1;
|
||||
}
|
||||
/**
|
||||
* Always returns a 1.
|
||||
*/
|
||||
@Override
|
||||
public Object getInsertValue(BeanProperty prop, EntityBean bean, long now) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Increments the current value by one.
|
||||
*/
|
||||
public Object getUpdateValue(BeanProperty prop, EntityBean bean) {
|
||||
Integer i = (Integer) prop.getValue(bean);
|
||||
return i + 1;
|
||||
}
|
||||
/**
|
||||
* Increments the current value by one.
|
||||
*/
|
||||
@Override
|
||||
public Object getUpdateValue(BeanProperty prop, EntityBean bean, long now) {
|
||||
Integer i = (Integer) prop.getValue(bean);
|
||||
return i + 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Include this in every update.
|
||||
*/
|
||||
public boolean includeInUpdate() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean includeInAllUpdates() {
|
||||
return false;
|
||||
}
|
||||
/**
|
||||
* Include this in every update.
|
||||
*/
|
||||
public boolean includeInUpdate() {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Include this in every insert setting initial counter value to 1.
|
||||
*/
|
||||
public boolean includeInInsert() {
|
||||
return true;
|
||||
}
|
||||
@Override
|
||||
public boolean includeInAllUpdates() {
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean isDDLNotNullable() {
|
||||
return true;
|
||||
}
|
||||
/**
|
||||
* Include this in every insert setting initial counter value to 1.
|
||||
*/
|
||||
public boolean includeInInsert() {
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean isDDLNotNullable() {
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+37
-35
@@ -8,46 +8,48 @@ import com.avaje.ebeaninternal.server.deploy.BeanProperty;
|
||||
*/
|
||||
public class GeneratedCounterLong implements GeneratedProperty {
|
||||
|
||||
public GeneratedCounterLong() {
|
||||
public GeneratedCounterLong() {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Always returns a 1.
|
||||
*/
|
||||
public Object getInsertValue(BeanProperty prop, EntityBean bean) {
|
||||
return (long) 1;
|
||||
}
|
||||
/**
|
||||
* Always returns a 1.
|
||||
*/
|
||||
@Override
|
||||
public Object getInsertValue(BeanProperty prop, EntityBean bean, long now) {
|
||||
return (long) 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Increments the current value by one.
|
||||
*/
|
||||
public Object getUpdateValue(BeanProperty prop, EntityBean bean) {
|
||||
Long i = (Long) prop.getValue(bean);
|
||||
return i + 1;
|
||||
}
|
||||
/**
|
||||
* Increments the current value by one.
|
||||
*/
|
||||
@Override
|
||||
public Object getUpdateValue(BeanProperty prop, EntityBean bean, long now) {
|
||||
Long i = (Long) prop.getValue(bean);
|
||||
return i + 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Include this in every update.
|
||||
*/
|
||||
public boolean includeInUpdate() {
|
||||
return true;
|
||||
}
|
||||
/**
|
||||
* Include this in every update.
|
||||
*/
|
||||
public boolean includeInUpdate() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean includeInAllUpdates() {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Include this in every insert setting initial counter value to 1.
|
||||
*/
|
||||
public boolean includeInInsert() {
|
||||
return true;
|
||||
}
|
||||
@Override
|
||||
public boolean includeInAllUpdates() {
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean isDDLNotNullable() {
|
||||
return true;
|
||||
}
|
||||
/**
|
||||
* Include this in every insert setting initial counter value to 1.
|
||||
*/
|
||||
public boolean includeInInsert() {
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean isDDLNotNullable() {
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+36
-34
@@ -1,50 +1,52 @@
|
||||
package com.avaje.ebeaninternal.server.deploy.generatedproperty;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
import com.avaje.ebean.bean.EntityBean;
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* Used to generate a (java.util.Date) timestamp when a bean is inserted.
|
||||
*/
|
||||
public class GeneratedInsertDate implements GeneratedProperty {
|
||||
|
||||
/**
|
||||
* Return the current time as a Timestamp.
|
||||
*/
|
||||
public Object getInsertValue(BeanProperty prop, EntityBean bean) {
|
||||
return new Date(System.currentTimeMillis());
|
||||
}
|
||||
/**
|
||||
* Return the current time as a Timestamp.
|
||||
*/
|
||||
@Override
|
||||
public Object getInsertValue(BeanProperty prop, EntityBean bean, long now) {
|
||||
return new Date(now);
|
||||
}
|
||||
|
||||
/**
|
||||
* Just returns the beans original insert timestamp value.
|
||||
*/
|
||||
public Object getUpdateValue(BeanProperty prop, EntityBean bean) {
|
||||
return prop.getValue(bean);
|
||||
}
|
||||
/**
|
||||
* Just returns the beans original insert timestamp value.
|
||||
*/
|
||||
@Override
|
||||
public Object getUpdateValue(BeanProperty prop, EntityBean bean, long now) {
|
||||
return prop.getValue(bean);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return false.
|
||||
*/
|
||||
public boolean includeInUpdate() {
|
||||
return false;
|
||||
}
|
||||
/**
|
||||
* Return false.
|
||||
*/
|
||||
public boolean includeInUpdate() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean includeInAllUpdates() {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true.
|
||||
*/
|
||||
public boolean includeInInsert() {
|
||||
return true;
|
||||
}
|
||||
@Override
|
||||
public boolean includeInAllUpdates() {
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean isDDLNotNullable() {
|
||||
return true;
|
||||
}
|
||||
/**
|
||||
* Return true.
|
||||
*/
|
||||
public boolean includeInInsert() {
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean isDDLNotNullable() {
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+7
-11
@@ -3,10 +3,6 @@ package com.avaje.ebeaninternal.server.deploy.generatedproperty;
|
||||
import com.avaje.ebean.bean.EntityBean;
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.time.ZonedDateTime;
|
||||
|
||||
/**
|
||||
* Support java.time types as GeneratedProperty.
|
||||
*/
|
||||
@@ -35,7 +31,7 @@ public class GeneratedInsertJavaTime {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getUpdateValue(BeanProperty prop, EntityBean bean) {
|
||||
public Object getUpdateValue(BeanProperty prop, EntityBean bean, long now) {
|
||||
return prop.getValue(bean);
|
||||
}
|
||||
}
|
||||
@@ -46,8 +42,8 @@ public class GeneratedInsertJavaTime {
|
||||
public static class LocalDT extends Base {
|
||||
|
||||
@Override
|
||||
public Object getInsertValue(BeanProperty prop, EntityBean bean) {
|
||||
return LocalDateTime.now();
|
||||
public Object getInsertValue(BeanProperty prop, EntityBean bean, long now) {
|
||||
return JavaTimeUtils.toLocalDateTime(now);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -57,8 +53,8 @@ public class GeneratedInsertJavaTime {
|
||||
public static class OffsetDT extends Base {
|
||||
|
||||
@Override
|
||||
public Object getInsertValue(BeanProperty prop, EntityBean bean) {
|
||||
return OffsetDateTime.now();
|
||||
public Object getInsertValue(BeanProperty prop, EntityBean bean, long now) {
|
||||
return JavaTimeUtils.toOffsetDateTime(now);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -69,8 +65,8 @@ public class GeneratedInsertJavaTime {
|
||||
public static class ZonedDT extends Base {
|
||||
|
||||
@Override
|
||||
public Object getInsertValue(BeanProperty prop, EntityBean bean) {
|
||||
return ZonedDateTime.now();
|
||||
public Object getInsertValue(BeanProperty prop, EntityBean bean, long now) {
|
||||
return JavaTimeUtils.toZonedDateTime(now);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+6
-7
@@ -2,9 +2,8 @@ package com.avaje.ebeaninternal.server.deploy.generatedproperty;
|
||||
|
||||
import com.avaje.ebean.bean.EntityBean;
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
|
||||
|
||||
import org.joda.time.LocalDateTime;
|
||||
import org.joda.time.DateTime;
|
||||
import org.joda.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* Support joda time types as GeneratedProperty.
|
||||
@@ -34,7 +33,7 @@ public class GeneratedInsertJodaTime {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getUpdateValue(BeanProperty prop, EntityBean bean) {
|
||||
public Object getUpdateValue(BeanProperty prop, EntityBean bean, long now) {
|
||||
return prop.getValue(bean);
|
||||
}
|
||||
}
|
||||
@@ -45,8 +44,8 @@ public class GeneratedInsertJodaTime {
|
||||
public static class LocalDT extends Base {
|
||||
|
||||
@Override
|
||||
public Object getInsertValue(BeanProperty prop, EntityBean bean) {
|
||||
return new LocalDateTime();
|
||||
public Object getInsertValue(BeanProperty prop, EntityBean bean, long now) {
|
||||
return new LocalDateTime(now);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -56,8 +55,8 @@ public class GeneratedInsertJodaTime {
|
||||
public static class DateTimeDT extends Base {
|
||||
|
||||
@Override
|
||||
public Object getInsertValue(BeanProperty prop, EntityBean bean) {
|
||||
return new DateTime();
|
||||
public Object getInsertValue(BeanProperty prop, EntityBean bean, long now) {
|
||||
return new DateTime(now);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+34
-32
@@ -8,41 +8,43 @@ import com.avaje.ebeaninternal.server.deploy.BeanProperty;
|
||||
*/
|
||||
public class GeneratedInsertLong implements GeneratedProperty {
|
||||
|
||||
/**
|
||||
* Return the current time as a Timestamp.
|
||||
*/
|
||||
public Object getInsertValue(BeanProperty prop, EntityBean bean) {
|
||||
return System.currentTimeMillis();
|
||||
}
|
||||
/**
|
||||
* Return the current time as a Timestamp.
|
||||
*/
|
||||
@Override
|
||||
public Object getInsertValue(BeanProperty prop, EntityBean bean, long now) {
|
||||
return now;
|
||||
}
|
||||
|
||||
/**
|
||||
* Just returns the beans original insert timestamp value.
|
||||
*/
|
||||
public Object getUpdateValue(BeanProperty prop, EntityBean bean) {
|
||||
return prop.getValue(bean);
|
||||
}
|
||||
/**
|
||||
* Just returns the beans original insert timestamp value.
|
||||
*/
|
||||
@Override
|
||||
public Object getUpdateValue(BeanProperty prop, EntityBean bean, long now) {
|
||||
return prop.getValue(bean);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return false.
|
||||
*/
|
||||
public boolean includeInUpdate() {
|
||||
return false;
|
||||
}
|
||||
/**
|
||||
* Return false.
|
||||
*/
|
||||
public boolean includeInUpdate() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean includeInAllUpdates() {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true.
|
||||
*/
|
||||
public boolean includeInInsert() {
|
||||
return true;
|
||||
}
|
||||
@Override
|
||||
public boolean includeInAllUpdates() {
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean isDDLNotNullable() {
|
||||
return true;
|
||||
}
|
||||
/**
|
||||
* Return true.
|
||||
*/
|
||||
public boolean includeInInsert() {
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean isDDLNotNullable() {
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+36
-34
@@ -1,50 +1,52 @@
|
||||
package com.avaje.ebeaninternal.server.deploy.generatedproperty;
|
||||
|
||||
import java.sql.Timestamp;
|
||||
|
||||
import com.avaje.ebean.bean.EntityBean;
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
|
||||
|
||||
import java.sql.Timestamp;
|
||||
|
||||
/**
|
||||
* Used to generate a timestamp when a bean is inserted.
|
||||
*/
|
||||
public class GeneratedInsertTimestamp implements GeneratedProperty, GeneratedWhenCreated {
|
||||
|
||||
/**
|
||||
* Return the current time as a Timestamp.
|
||||
*/
|
||||
public Object getInsertValue(BeanProperty prop, EntityBean bean) {
|
||||
return new Timestamp(System.currentTimeMillis());
|
||||
}
|
||||
/**
|
||||
* Return the current time as a Timestamp.
|
||||
*/
|
||||
@Override
|
||||
public Object getInsertValue(BeanProperty prop, EntityBean bean, long now) {
|
||||
return new Timestamp(now);
|
||||
}
|
||||
|
||||
/**
|
||||
* Just returns the beans original insert timestamp value.
|
||||
*/
|
||||
public Object getUpdateValue(BeanProperty prop, EntityBean bean) {
|
||||
return prop.getValue(bean);
|
||||
}
|
||||
/**
|
||||
* Just returns the beans original insert timestamp value.
|
||||
*/
|
||||
@Override
|
||||
public Object getUpdateValue(BeanProperty prop, EntityBean bean, long now) {
|
||||
return prop.getValue(bean);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return false.
|
||||
*/
|
||||
public boolean includeInUpdate() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean includeInAllUpdates() {
|
||||
return false;
|
||||
}
|
||||
/**
|
||||
* Return false.
|
||||
*/
|
||||
public boolean includeInUpdate() {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true.
|
||||
*/
|
||||
public boolean includeInInsert() {
|
||||
return true;
|
||||
}
|
||||
@Override
|
||||
public boolean includeInAllUpdates() {
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean isDDLNotNullable() {
|
||||
return true;
|
||||
}
|
||||
/**
|
||||
* Return true.
|
||||
*/
|
||||
public boolean includeInInsert() {
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean isDDLNotNullable() {
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+30
-30
@@ -9,39 +9,39 @@ import com.avaje.ebeaninternal.server.deploy.BeanProperty;
|
||||
*/
|
||||
public interface GeneratedProperty {
|
||||
|
||||
/**
|
||||
* Get the generated insert value for a specific property of a bean.
|
||||
*/
|
||||
Object getInsertValue(BeanProperty prop, EntityBean bean);
|
||||
/**
|
||||
* Get the generated insert value for a specific property of a bean.
|
||||
*/
|
||||
Object getInsertValue(BeanProperty prop, EntityBean bean, long now);
|
||||
|
||||
/**
|
||||
* Get the generated update value for a specific property of a bean.
|
||||
*/
|
||||
Object getUpdateValue(BeanProperty prop, EntityBean bean);
|
||||
/**
|
||||
* Get the generated update value for a specific property of a bean.
|
||||
*/
|
||||
Object getUpdateValue(BeanProperty prop, EntityBean bean, long now);
|
||||
|
||||
/**
|
||||
* Return true if this should always be includes in an update statement.
|
||||
* <p>
|
||||
* Used to include GeneratedUpdateTimestamp in dynamic table updates.
|
||||
* </p>
|
||||
*/
|
||||
boolean includeInUpdate();
|
||||
|
||||
/**
|
||||
* Return true if the property should be included in an update even if
|
||||
* it is not loaded (ie. Last Updated Timestamp).
|
||||
*/
|
||||
boolean includeInAllUpdates();
|
||||
/**
|
||||
* Return true if this should always be includes in an update statement.
|
||||
* <p>
|
||||
* Used to include GeneratedUpdateTimestamp in dynamic table updates.
|
||||
* </p>
|
||||
*/
|
||||
boolean includeInUpdate();
|
||||
|
||||
/**
|
||||
* Return true if this should be included in insert statements.
|
||||
*/
|
||||
boolean includeInInsert();
|
||||
/**
|
||||
* Return true if the property should be included in an update even if
|
||||
* it is not loaded (ie. Last Updated Timestamp).
|
||||
*/
|
||||
boolean includeInAllUpdates();
|
||||
|
||||
/**
|
||||
* Return true if the GeneratedProperty implies the DDL to create the DB
|
||||
* column should have a not null constraint.
|
||||
*/
|
||||
boolean isDDLNotNullable();
|
||||
/**
|
||||
* Return true if this should be included in insert statements.
|
||||
*/
|
||||
boolean includeInInsert();
|
||||
|
||||
/**
|
||||
* Return true if the GeneratedProperty implies the DDL to create the DB
|
||||
* column should have a not null constraint.
|
||||
*/
|
||||
boolean isDDLNotNullable();
|
||||
|
||||
}
|
||||
|
||||
+38
-38
@@ -1,19 +1,19 @@
|
||||
package com.avaje.ebeaninternal.server.deploy.generatedproperty;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.HashSet;
|
||||
|
||||
import com.avaje.ebean.config.ClassLoadConfig;
|
||||
import com.avaje.ebean.config.CurrentUserProvider;
|
||||
import com.avaje.ebean.config.ServerConfig;
|
||||
import com.avaje.ebeaninternal.server.deploy.meta.DeployBeanProperty;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.HashSet;
|
||||
|
||||
/**
|
||||
* Default implementation of GeneratedPropertyFactory.
|
||||
*/
|
||||
public class GeneratedPropertyFactory {
|
||||
|
||||
private final CounterFactory counterFactory = new CounterFactory();
|
||||
private final CounterFactory counterFactory = new CounterFactory();
|
||||
|
||||
private final InsertTimestampFactory insertFactory;
|
||||
|
||||
@@ -34,7 +34,7 @@ public class GeneratedPropertyFactory {
|
||||
this.updateFactory = new UpdateTimestampFactory(classLoadConfig);
|
||||
|
||||
CurrentUserProvider currentUserProvider = serverConfig.getCurrentUserProvider();
|
||||
if (currentUserProvider != null) {
|
||||
if (currentUserProvider != null) {
|
||||
generatedWhoCreated = new GeneratedWhoCreated(currentUserProvider);
|
||||
generatedWhoModified = new GeneratedWhoModified(currentUserProvider);
|
||||
} else {
|
||||
@@ -42,47 +42,47 @@ public class GeneratedPropertyFactory {
|
||||
generatedWhoModified = null;
|
||||
}
|
||||
|
||||
numberTypes.add(Integer.class.getName());
|
||||
numberTypes.add(int.class.getName());
|
||||
numberTypes.add(Long.class.getName());
|
||||
numberTypes.add(long.class.getName());
|
||||
numberTypes.add(Short.class.getName());
|
||||
numberTypes.add(short.class.getName());
|
||||
numberTypes.add(Double.class.getName());
|
||||
numberTypes.add(double.class.getName());
|
||||
numberTypes.add(BigDecimal.class.getName());
|
||||
}
|
||||
numberTypes.add(Integer.class.getName());
|
||||
numberTypes.add(int.class.getName());
|
||||
numberTypes.add(Long.class.getName());
|
||||
numberTypes.add(long.class.getName());
|
||||
numberTypes.add(Short.class.getName());
|
||||
numberTypes.add(short.class.getName());
|
||||
numberTypes.add(Double.class.getName());
|
||||
numberTypes.add(double.class.getName());
|
||||
numberTypes.add(BigDecimal.class.getName());
|
||||
}
|
||||
|
||||
public ClassLoadConfig getClassLoadConfig() {
|
||||
return classLoadConfig;
|
||||
}
|
||||
|
||||
private boolean isNumberType(String typeClassName) {
|
||||
return numberTypes.contains(typeClassName);
|
||||
}
|
||||
|
||||
public void setVersion(DeployBeanProperty property) {
|
||||
if (isNumberType(property.getPropertyType().getName())) {
|
||||
setCounter(property);
|
||||
} else {
|
||||
setUpdateTimestamp(property);
|
||||
}
|
||||
}
|
||||
|
||||
public void setCounter(DeployBeanProperty property) {
|
||||
|
||||
counterFactory.setCounter(property);
|
||||
}
|
||||
return numberTypes.contains(typeClassName);
|
||||
}
|
||||
|
||||
public void setInsertTimestamp(DeployBeanProperty property) {
|
||||
|
||||
insertFactory.setInsertTimestamp(property);
|
||||
}
|
||||
public void setVersion(DeployBeanProperty property) {
|
||||
if (isNumberType(property.getPropertyType().getName())) {
|
||||
setCounter(property);
|
||||
} else {
|
||||
setUpdateTimestamp(property);
|
||||
}
|
||||
}
|
||||
|
||||
public void setUpdateTimestamp(DeployBeanProperty property) {
|
||||
|
||||
updateFactory.setUpdateTimestamp(property);
|
||||
}
|
||||
public void setCounter(DeployBeanProperty property) {
|
||||
|
||||
counterFactory.setCounter(property);
|
||||
}
|
||||
|
||||
public void setInsertTimestamp(DeployBeanProperty property) {
|
||||
|
||||
insertFactory.setInsertTimestamp(property);
|
||||
}
|
||||
|
||||
public void setUpdateTimestamp(DeployBeanProperty property) {
|
||||
|
||||
updateFactory.setUpdateTimestamp(property);
|
||||
}
|
||||
|
||||
public void setWhoCreated(DeployBeanProperty property) {
|
||||
if (generatedWhoCreated == null) {
|
||||
|
||||
+34
-34
@@ -1,51 +1,51 @@
|
||||
package com.avaje.ebeaninternal.server.deploy.generatedproperty;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
import com.avaje.ebean.bean.EntityBean;
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* Generate a (java.util.Date) Timestamp whenever the bean is inserted or
|
||||
* updated.
|
||||
*/
|
||||
public class GeneratedUpdateDate implements GeneratedProperty {
|
||||
|
||||
/**
|
||||
* Return now as a Timestamp.
|
||||
*/
|
||||
public Object getInsertValue(BeanProperty prop, EntityBean bean) {
|
||||
return new Date(System.currentTimeMillis());
|
||||
}
|
||||
/**
|
||||
* Return now as a Timestamp.
|
||||
*/
|
||||
public Object getInsertValue(BeanProperty prop, EntityBean bean, long now) {
|
||||
return new Date(now);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return now as a Timestamp.
|
||||
*/
|
||||
public Object getUpdateValue(BeanProperty prop, EntityBean bean) {
|
||||
return new Date(System.currentTimeMillis());
|
||||
}
|
||||
/**
|
||||
* Return now as a Timestamp.
|
||||
*/
|
||||
public Object getUpdateValue(BeanProperty prop, EntityBean bean, long now) {
|
||||
return new Date(now);
|
||||
}
|
||||
|
||||
/**
|
||||
* For dynamic table updates make sure this is included.
|
||||
*/
|
||||
public boolean includeInUpdate() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean includeInAllUpdates() {
|
||||
return true;
|
||||
}
|
||||
/**
|
||||
* For dynamic table updates make sure this is included.
|
||||
*/
|
||||
public boolean includeInUpdate() {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Include this in every insert.
|
||||
*/
|
||||
public boolean includeInInsert() {
|
||||
return true;
|
||||
}
|
||||
@Override
|
||||
public boolean includeInAllUpdates() {
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean isDDLNotNullable() {
|
||||
return true;
|
||||
}
|
||||
/**
|
||||
* Include this in every insert.
|
||||
*/
|
||||
public boolean includeInInsert() {
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean isDDLNotNullable() {
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+12
-16
@@ -3,10 +3,6 @@ package com.avaje.ebeaninternal.server.deploy.generatedproperty;
|
||||
import com.avaje.ebean.bean.EntityBean;
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.time.ZonedDateTime;
|
||||
|
||||
/**
|
||||
* Support java.time DateTime types as GeneratedProperty.
|
||||
*/
|
||||
@@ -41,13 +37,13 @@ public class GeneratedUpdateJavaTime {
|
||||
public static class LocalDT extends Base {
|
||||
|
||||
@Override
|
||||
public Object getInsertValue(BeanProperty prop, EntityBean bean) {
|
||||
return LocalDateTime.now();
|
||||
public Object getInsertValue(BeanProperty prop, EntityBean bean, long now) {
|
||||
return JavaTimeUtils.toLocalDateTime(now);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getUpdateValue(BeanProperty prop, EntityBean bean) {
|
||||
return LocalDateTime.now();
|
||||
public Object getUpdateValue(BeanProperty prop, EntityBean bean, long now) {
|
||||
return JavaTimeUtils.toLocalDateTime(now);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -57,13 +53,13 @@ public class GeneratedUpdateJavaTime {
|
||||
public static class OffsetDT extends Base {
|
||||
|
||||
@Override
|
||||
public Object getInsertValue(BeanProperty prop, EntityBean bean) {
|
||||
return OffsetDateTime.now();
|
||||
public Object getInsertValue(BeanProperty prop, EntityBean bean, long now) {
|
||||
return JavaTimeUtils.toOffsetDateTime(now);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getUpdateValue(BeanProperty prop, EntityBean bean) {
|
||||
return OffsetDateTime.now();
|
||||
public Object getUpdateValue(BeanProperty prop, EntityBean bean, long now) {
|
||||
return JavaTimeUtils.toOffsetDateTime(now);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -73,13 +69,13 @@ public class GeneratedUpdateJavaTime {
|
||||
public static class ZonedDT extends Base {
|
||||
|
||||
@Override
|
||||
public Object getInsertValue(BeanProperty prop, EntityBean bean) {
|
||||
return ZonedDateTime.now();
|
||||
public Object getInsertValue(BeanProperty prop, EntityBean bean, long now) {
|
||||
return JavaTimeUtils.toZonedDateTime(now);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getUpdateValue(BeanProperty prop, EntityBean bean) {
|
||||
return ZonedDateTime.now();
|
||||
public Object getUpdateValue(BeanProperty prop, EntityBean bean, long now) {
|
||||
return JavaTimeUtils.toZonedDateTime(now);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+9
-10
@@ -2,9 +2,8 @@ package com.avaje.ebeaninternal.server.deploy.generatedproperty;
|
||||
|
||||
import com.avaje.ebean.bean.EntityBean;
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
|
||||
|
||||
import org.joda.time.LocalDateTime;
|
||||
import org.joda.time.DateTime;
|
||||
import org.joda.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* Support java.time DateTime types as GeneratedProperty.
|
||||
@@ -40,13 +39,13 @@ public class GeneratedUpdateJodaTime {
|
||||
public static class LocalDT extends Base {
|
||||
|
||||
@Override
|
||||
public Object getInsertValue(BeanProperty prop, EntityBean bean) {
|
||||
return new LocalDateTime();
|
||||
public Object getInsertValue(BeanProperty prop, EntityBean bean, long now) {
|
||||
return new LocalDateTime(now);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getUpdateValue(BeanProperty prop, EntityBean bean) {
|
||||
return new LocalDateTime();
|
||||
public Object getUpdateValue(BeanProperty prop, EntityBean bean, long now) {
|
||||
return new LocalDateTime(now);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -56,13 +55,13 @@ public class GeneratedUpdateJodaTime {
|
||||
public static class DateTimeDT extends Base {
|
||||
|
||||
@Override
|
||||
public Object getInsertValue(BeanProperty prop, EntityBean bean) {
|
||||
return new DateTime();
|
||||
public Object getInsertValue(BeanProperty prop, EntityBean bean, long now) {
|
||||
return new DateTime(now);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getUpdateValue(BeanProperty prop, EntityBean bean) {
|
||||
return new DateTime();
|
||||
public Object getUpdateValue(BeanProperty prop, EntityBean bean, long now) {
|
||||
return new DateTime(now);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+32
-32
@@ -8,41 +8,41 @@ import com.avaje.ebeaninternal.server.deploy.BeanProperty;
|
||||
*/
|
||||
public class GeneratedUpdateLong implements GeneratedProperty {
|
||||
|
||||
/**
|
||||
* Return now as a Timestamp.
|
||||
*/
|
||||
public Object getInsertValue(BeanProperty prop, EntityBean bean) {
|
||||
return System.currentTimeMillis();
|
||||
}
|
||||
/**
|
||||
* Return now as a Timestamp.
|
||||
*/
|
||||
public Object getInsertValue(BeanProperty prop, EntityBean bean, long now) {
|
||||
return now;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return now as a Timestamp.
|
||||
*/
|
||||
public Object getUpdateValue(BeanProperty prop, EntityBean bean) {
|
||||
return System.currentTimeMillis();
|
||||
}
|
||||
/**
|
||||
* Return now as a Timestamp.
|
||||
*/
|
||||
public Object getUpdateValue(BeanProperty prop, EntityBean bean, long now) {
|
||||
return now;
|
||||
}
|
||||
|
||||
/**
|
||||
* For dynamic table updates make sure this is included.
|
||||
*/
|
||||
public boolean includeInUpdate() {
|
||||
return true;
|
||||
}
|
||||
/**
|
||||
* For dynamic table updates make sure this is included.
|
||||
*/
|
||||
public boolean includeInUpdate() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean includeInAllUpdates() {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Include this in every insert.
|
||||
*/
|
||||
public boolean includeInInsert() {
|
||||
return true;
|
||||
}
|
||||
@Override
|
||||
public boolean includeInAllUpdates() {
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean isDDLNotNullable() {
|
||||
return true;
|
||||
}
|
||||
/**
|
||||
* Include this in every insert.
|
||||
*/
|
||||
public boolean includeInInsert() {
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean isDDLNotNullable() {
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+34
-34
@@ -1,50 +1,50 @@
|
||||
package com.avaje.ebeaninternal.server.deploy.generatedproperty;
|
||||
|
||||
import java.sql.Timestamp;
|
||||
|
||||
import com.avaje.ebean.bean.EntityBean;
|
||||
import com.avaje.ebeaninternal.server.deploy.BeanProperty;
|
||||
|
||||
import java.sql.Timestamp;
|
||||
|
||||
/**
|
||||
* Generate a Timestamp whenever the bean is inserted or updated.
|
||||
*/
|
||||
public class GeneratedUpdateTimestamp implements GeneratedProperty, GeneratedWhenModified {
|
||||
|
||||
/**
|
||||
* Return now as a Timestamp.
|
||||
*/
|
||||
public Object getInsertValue(BeanProperty prop, EntityBean bean) {
|
||||
return new Timestamp(System.currentTimeMillis());
|
||||
}
|
||||
/**
|
||||
* Return now as a Timestamp.
|
||||
*/
|
||||
public Object getInsertValue(BeanProperty prop, EntityBean bean, long now) {
|
||||
return new Timestamp(now);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return now as a Timestamp.
|
||||
*/
|
||||
public Object getUpdateValue(BeanProperty prop, EntityBean bean) {
|
||||
return new Timestamp(System.currentTimeMillis());
|
||||
}
|
||||
/**
|
||||
* Return now as a Timestamp.
|
||||
*/
|
||||
public Object getUpdateValue(BeanProperty prop, EntityBean bean, long now) {
|
||||
return new Timestamp(now);
|
||||
}
|
||||
|
||||
/**
|
||||
* For dynamic table updates make sure this is included.
|
||||
*/
|
||||
public boolean includeInUpdate() {
|
||||
return true;
|
||||
}
|
||||
/**
|
||||
* For dynamic table updates make sure this is included.
|
||||
*/
|
||||
public boolean includeInUpdate() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean includeInAllUpdates() {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Include this in every insert.
|
||||
*/
|
||||
public boolean includeInInsert() {
|
||||
return true;
|
||||
}
|
||||
@Override
|
||||
public boolean includeInAllUpdates() {
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean isDDLNotNullable() {
|
||||
return true;
|
||||
}
|
||||
/**
|
||||
* Include this in every insert.
|
||||
*/
|
||||
public boolean includeInInsert() {
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean isDDLNotNullable() {
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+2
-2
@@ -16,12 +16,12 @@ public class GeneratedWhoCreated implements GeneratedProperty {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getInsertValue(BeanProperty prop, EntityBean bean) {
|
||||
public Object getInsertValue(BeanProperty prop, EntityBean bean, long now) {
|
||||
return currentUserProvider.currentUser();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getUpdateValue(BeanProperty prop, EntityBean bean) {
|
||||
public Object getUpdateValue(BeanProperty prop, EntityBean bean, long now) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
+2
-2
@@ -16,12 +16,12 @@ public class GeneratedWhoModified implements GeneratedProperty {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getInsertValue(BeanProperty prop, EntityBean bean) {
|
||||
public Object getInsertValue(BeanProperty prop, EntityBean bean, long now) {
|
||||
return currentUserProvider.currentUser();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getUpdateValue(BeanProperty prop, EntityBean bean) {
|
||||
public Object getUpdateValue(BeanProperty prop, EntityBean bean, long now) {
|
||||
return currentUserProvider.currentUser();
|
||||
}
|
||||
|
||||
|
||||
+17
-18
@@ -1,5 +1,9 @@
|
||||
package com.avaje.ebeaninternal.server.deploy.generatedproperty;
|
||||
|
||||
import com.avaje.ebean.config.ClassLoadConfig;
|
||||
import com.avaje.ebeaninternal.server.deploy.meta.DeployBeanProperty;
|
||||
|
||||
import javax.persistence.PersistenceException;
|
||||
import java.sql.Timestamp;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.OffsetDateTime;
|
||||
@@ -7,17 +11,12 @@ import java.time.ZonedDateTime;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.persistence.PersistenceException;
|
||||
|
||||
import com.avaje.ebean.config.ClassLoadConfig;
|
||||
import com.avaje.ebeaninternal.server.deploy.meta.DeployBeanProperty;
|
||||
|
||||
/**
|
||||
* Helper for creating Insert timestamp GeneratedProperty objects.
|
||||
*/
|
||||
public class InsertTimestampFactory {
|
||||
|
||||
final GeneratedInsertLong longTime = new GeneratedInsertLong();
|
||||
final GeneratedInsertLong longTime = new GeneratedInsertLong();
|
||||
|
||||
final Map<Class<?>, GeneratedProperty> map = new HashMap<Class<?>, GeneratedProperty>();
|
||||
|
||||
@@ -41,21 +40,21 @@ public class InsertTimestampFactory {
|
||||
|
||||
public void setInsertTimestamp(DeployBeanProperty property) {
|
||||
|
||||
property.setGeneratedProperty(createInsertTimestamp(property));
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the insert GeneratedProperty depending on the property type.
|
||||
*/
|
||||
public GeneratedProperty createInsertTimestamp(DeployBeanProperty property) {
|
||||
|
||||
Class<?> propType = property.getPropertyType();
|
||||
property.setGeneratedProperty(createInsertTimestamp(property));
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the insert GeneratedProperty depending on the property type.
|
||||
*/
|
||||
public GeneratedProperty createInsertTimestamp(DeployBeanProperty property) {
|
||||
|
||||
Class<?> propType = property.getPropertyType();
|
||||
GeneratedProperty generatedProperty = map.get(propType);
|
||||
if (generatedProperty != null) {
|
||||
return generatedProperty;
|
||||
}
|
||||
|
||||
throw new PersistenceException("Generated Insert Timestamp not supported on "+propType.getName());
|
||||
}
|
||||
|
||||
throw new PersistenceException("Generated Insert Timestamp not supported on " + propType.getName());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package com.avaje.ebeaninternal.server.deploy.generatedproperty;
|
||||
|
||||
import java.sql.Timestamp;
|
||||
import java.time.Instant;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZonedDateTime;
|
||||
|
||||
/**
|
||||
* Helper methods for Java time conversion.
|
||||
*/
|
||||
public class JavaTimeUtils {
|
||||
|
||||
/**
|
||||
* Return the system millis time as a LocalDateTime.
|
||||
*/
|
||||
public static Object toLocalDateTime(long systemMillis) {
|
||||
return new Timestamp(systemMillis).toLocalDateTime();
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the system millis time as a OffsetDateTime.
|
||||
*/
|
||||
public static Object toOffsetDateTime(long systemMillis) {
|
||||
return OffsetDateTime.ofInstant(Instant.ofEpochMilli(systemMillis), ZoneId.systemDefault());
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the system millis time as a ZonedDateTime.
|
||||
*/
|
||||
public static Object toZonedDateTime(long systemMillis) {
|
||||
return ZonedDateTime.ofInstant(Instant.ofEpochMilli(systemMillis), ZoneId.systemDefault());
|
||||
}
|
||||
}
|
||||
+16
-17
@@ -1,5 +1,9 @@
|
||||
package com.avaje.ebeaninternal.server.deploy.generatedproperty;
|
||||
|
||||
import com.avaje.ebean.config.ClassLoadConfig;
|
||||
import com.avaje.ebeaninternal.server.deploy.meta.DeployBeanProperty;
|
||||
|
||||
import javax.persistence.PersistenceException;
|
||||
import java.sql.Timestamp;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.OffsetDateTime;
|
||||
@@ -7,17 +11,12 @@ import java.time.ZonedDateTime;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.persistence.PersistenceException;
|
||||
|
||||
import com.avaje.ebean.config.ClassLoadConfig;
|
||||
import com.avaje.ebeaninternal.server.deploy.meta.DeployBeanProperty;
|
||||
|
||||
/**
|
||||
* Helper for creating Update timestamp GeneratedProperty objects.
|
||||
*/
|
||||
public class UpdateTimestampFactory {
|
||||
|
||||
final GeneratedUpdateLong longTime = new GeneratedUpdateLong();
|
||||
final GeneratedUpdateLong longTime = new GeneratedUpdateLong();
|
||||
|
||||
final Map<Class<?>, GeneratedProperty> map = new HashMap<Class<?>, GeneratedProperty>();
|
||||
|
||||
@@ -38,15 +37,15 @@ public class UpdateTimestampFactory {
|
||||
}
|
||||
}
|
||||
|
||||
public void setUpdateTimestamp(DeployBeanProperty property) {
|
||||
public void setUpdateTimestamp(DeployBeanProperty property) {
|
||||
|
||||
property.setGeneratedProperty(createUpdateTimestamp(property));
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the update GeneratedProperty depending on the property type.
|
||||
*/
|
||||
protected GeneratedProperty createUpdateTimestamp(DeployBeanProperty property) {
|
||||
property.setGeneratedProperty(createUpdateTimestamp(property));
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the update GeneratedProperty depending on the property type.
|
||||
*/
|
||||
protected GeneratedProperty createUpdateTimestamp(DeployBeanProperty property) {
|
||||
|
||||
Class<?> propType = property.getPropertyType();
|
||||
GeneratedProperty generatedProperty = map.get(propType);
|
||||
@@ -54,7 +53,7 @@ public class UpdateTimestampFactory {
|
||||
return generatedProperty;
|
||||
}
|
||||
|
||||
throw new PersistenceException("Generated update Timestamp not supported on "+propType.getName());
|
||||
}
|
||||
|
||||
throw new PersistenceException("Generated update Timestamp not supported on " + propType.getName());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<HTML>
|
||||
<HEAD>
|
||||
<META HTTP-EQUIV="CONTENT-TYPE" CONTENT="text/html; charset=iso-8859-1">
|
||||
<TITLE>Counter, Insert Timestamp, Update Timestamp support</TITLE>
|
||||
<META HTTP-EQUIV="CONTENT-TYPE" CONTENT="text/html; charset=iso-8859-1">
|
||||
<TITLE>Counter, Insert Timestamp, Update Timestamp support</TITLE>
|
||||
</HEAD>
|
||||
<Body BGCOLOR="#ffffff">
|
||||
Counter, Insert Timestamp, Update Timestamp support
|
||||
|
||||
@@ -190,7 +190,7 @@ public class DLoadBeanContext extends DLoadBaseContext implements LoadBeanContex
|
||||
}
|
||||
}
|
||||
|
||||
LoadBeanRequest req = new LoadBeanRequest(this, ebi.getLazyLoadPropertyIndex(), ebi.getLazyLoadProperty(), context.hitCache);
|
||||
LoadBeanRequest req = new LoadBeanRequest(this, ebi.getLazyLoadProperty(), context.hitCache);
|
||||
context.desc.getEbeanServer().loadBean(req);
|
||||
}
|
||||
|
||||
|
||||
@@ -39,6 +39,8 @@ public abstract class DmlHandler implements PersistHandler, BindableRequest {
|
||||
|
||||
protected final boolean logLevelSql;
|
||||
|
||||
protected final long now;
|
||||
|
||||
/**
|
||||
* The PreparedStatement used for the dml.
|
||||
*/
|
||||
@@ -49,6 +51,7 @@ public abstract class DmlHandler implements PersistHandler, BindableRequest {
|
||||
protected ArrayList<UpdateGenValue> updateGenValues;
|
||||
|
||||
protected DmlHandler(PersistRequestBean<?> persistRequest, boolean emptyStringToNull) {
|
||||
this.now = System.currentTimeMillis();
|
||||
this.persistRequest = persistRequest;
|
||||
this.emptyStringToNull = emptyStringToNull;
|
||||
this.transaction = persistRequest.getTransaction();
|
||||
@@ -60,6 +63,11 @@ public abstract class DmlHandler implements PersistHandler, BindableRequest {
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public long now() {
|
||||
return now;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PersistRequestBean<?> getPersistRequest() {
|
||||
return persistRequest;
|
||||
|
||||
+1
-1
@@ -24,7 +24,7 @@ public class BindablePropertyInsertGenerated extends BindableProperty {
|
||||
|
||||
public void dmlBind(BindableRequest request, EntityBean bean) throws SQLException {
|
||||
|
||||
Object value = gen.getInsertValue(prop, bean);
|
||||
Object value = gen.getInsertValue(prop, bean, request.now());
|
||||
|
||||
// generated value should be the correct type
|
||||
if (bean != null) {
|
||||
|
||||
+1
-1
@@ -37,7 +37,7 @@ public class BindablePropertyUpdateGenerated extends BindableProperty {
|
||||
|
||||
public void dmlBind(BindableRequest request, EntityBean bean) throws SQLException {
|
||||
|
||||
Object value = gen.getUpdateValue(prop, bean);
|
||||
Object value = gen.getUpdateValue(prop, bean, request.now());
|
||||
|
||||
// generated value should be the correct type
|
||||
request.bind(value, prop);
|
||||
|
||||
@@ -56,4 +56,11 @@ public interface BindableRequest {
|
||||
PersistRequestBean<?> getPersistRequest();
|
||||
|
||||
void registerDerivedRelationship(DerivedRelationshipData assocBean);
|
||||
|
||||
/**
|
||||
* Return the system current time in millis. This is expected to the same time used
|
||||
* by multiple generated properties for a single request.
|
||||
*/
|
||||
long now();
|
||||
|
||||
}
|
||||
|
||||
@@ -399,7 +399,7 @@ public class CQuery<T> implements DbReadContext, CancelableQuery {
|
||||
}
|
||||
|
||||
// add the loadedBean to the appropriate collection of lazyLoadParentBean
|
||||
lazyLoadManyProperty.addBeanToCollectionWithCreate(lazyLoadParentBean, bean);
|
||||
lazyLoadManyProperty.addBeanToCollectionWithCreate(lazyLoadParentBean, bean, true);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -542,7 +542,7 @@ public class CQuery<T> implements DbReadContext, CancelableQuery {
|
||||
|
||||
while (hasNext()) {
|
||||
EntityBean bean = next();
|
||||
help.add(collection, bean);
|
||||
help.add(collection, bean, false);
|
||||
}
|
||||
|
||||
updateExecutionStatistics();
|
||||
|
||||
@@ -232,6 +232,7 @@ public class SqlTreeNodeBean implements SqlTreeNode {
|
||||
|
||||
PersistenceContext persistenceContext = (!readId || temporalVersions) ? null : ctx.getPersistenceContext();
|
||||
|
||||
boolean newBean = false;
|
||||
if (readId) {
|
||||
Object id = localIdBinder.readSet(ctx, localBean);
|
||||
if (id == null) {
|
||||
@@ -242,6 +243,7 @@ public class SqlTreeNodeBean implements SqlTreeNode {
|
||||
contextBean = (EntityBean) persistenceContext.putIfAbsent(id, localBean);
|
||||
if (contextBean == null) {
|
||||
// bean just added to the persistenceContext
|
||||
newBean = true;
|
||||
contextBean = localBean;
|
||||
} else {
|
||||
// bean already exists in persistenceContext
|
||||
|
||||
@@ -24,7 +24,7 @@ public final class SqlTreeNodeManyRoot extends SqlTreeNodeBean {
|
||||
// being set to the parentBean directly
|
||||
EntityBean detailBean = super.load(cquery, null, null);
|
||||
// initialise the collection and add detailBean if it is not null
|
||||
manyProp.addBeanToCollectionWithCreate(contextParent, detailBean);
|
||||
manyProp.addBeanToCollectionWithCreate(contextParent, detailBean, false);
|
||||
return detailBean;
|
||||
}
|
||||
|
||||
|
||||
@@ -24,6 +24,8 @@
|
||||
</xsd:choice>
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="type" type="changeSetType" use="required"/>
|
||||
<xsd:attribute name="dropsFor" type="xsd:string"/>
|
||||
<xsd:attribute name="suppressDropsForever" type="xsd:boolean"/>
|
||||
<xsd:attribute name="generated" type="xsd:boolean"/>
|
||||
<xsd:attribute name="author" type="xsd:string"/>
|
||||
<xsd:attribute name="comment" type="xsd:string"/>
|
||||
@@ -33,7 +35,7 @@
|
||||
<xsd:simpleType name="changeSetType">
|
||||
<xsd:restriction base="xsd:string">
|
||||
<xsd:enumeration value="apply"/>
|
||||
<xsd:enumeration value="drop"/>
|
||||
<xsd:enumeration value="pendingDrops"/>
|
||||
<xsd:enumeration value="baseline"/>
|
||||
</xsd:restriction>
|
||||
</xsd:simpleType>
|
||||
@@ -98,6 +100,7 @@
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" type="xsd:string" use="required"/>
|
||||
<xsd:attribute name="withHistory" type="xsd:boolean"/>
|
||||
<xsd:attribute name="draft" type="xsd:boolean"/>
|
||||
<xsd:attribute name="identityType" type="identityType"/>
|
||||
<xsd:attribute name="sequenceName" type="xsd:string"/>
|
||||
<xsd:attribute name="sequenceInitial" type="xsd:positiveInteger"/>
|
||||
|
||||
@@ -35,7 +35,7 @@ public class BaseDdlHandlerTest extends BaseTestCase {
|
||||
handler.generate(write, Helper.getAddColumn());
|
||||
|
||||
assertThat(write.apply().getBuffer()).isEqualTo("alter table foo add column added_to_foo varchar(20);\n\n");
|
||||
assertThat(write.rollback().getBuffer()).isEqualTo("alter table foo drop column added_to_foo;\n\n");
|
||||
assertThat(write.dropAll().getBuffer()).isEqualTo("");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -46,8 +46,8 @@ public class BaseDdlHandlerTest extends BaseTestCase {
|
||||
|
||||
handler.generate(write, Helper.getDropColumn());
|
||||
|
||||
assertThat(write.drop().getBuffer()).isEqualTo("alter table foo drop column col2;\n\n");
|
||||
assertThat(write.rollback().getBuffer()).isEqualTo("");
|
||||
assertThat(write.apply().getBuffer()).isEqualTo("alter table foo drop column col2;\n\n");
|
||||
assertThat(write.dropAll().getBuffer()).isEqualTo("");
|
||||
}
|
||||
|
||||
|
||||
@@ -62,7 +62,7 @@ public class BaseDdlHandlerTest extends BaseTestCase {
|
||||
String createTableDDL = Helper.asText(this, "/assert/create-table.txt");
|
||||
|
||||
assertThat(write.apply().getBuffer()).isEqualTo(createTableDDL);
|
||||
assertThat(write.rollback().getBuffer().trim()).isEqualTo("drop table if exists foo;\ndrop sequence if exists foo_seq;");
|
||||
assertThat(write.dropAll().getBuffer().trim()).isEqualTo("drop table if exists foo;\ndrop sequence if exists foo_seq;");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -73,12 +73,11 @@ public class BaseDdlHandlerTest extends BaseTestCase {
|
||||
|
||||
handler.generate(write, Helper.getChangeSet());
|
||||
|
||||
String apply = Helper.asText(this, "/assert/BaseDdlHandlerTest/apply.sql");
|
||||
String rollbackLast = Helper.asText(this, "/assert/BaseDdlHandlerTest/rollback.sql");
|
||||
String apply = Helper.asText(this, "/assert/BaseDdlHandlerTest/baseApply.sql");
|
||||
String rollbackLast = Helper.asText(this, "/assert/BaseDdlHandlerTest/baseDropAll.sql");
|
||||
|
||||
assertThat(write.apply().getBuffer()).isEqualTo(apply);
|
||||
assertThat(write.drop().getBuffer()).isEqualTo("alter table foo drop column col2;\n\n");
|
||||
assertThat(write.rollback().getBuffer()).isEqualTo(rollbackLast);
|
||||
assertThat(write.dropAll().getBuffer()).isEqualTo(rollbackLast);
|
||||
}
|
||||
|
||||
|
||||
@@ -96,10 +95,10 @@ public class BaseDdlHandlerTest extends BaseTestCase {
|
||||
handler.generate(write, createChangeSet);
|
||||
|
||||
String apply = Helper.asText(this, "/assert/changeset-apply.txt");
|
||||
String rollbackLast = Helper.asText(this, "/assert/changeset-rollback.txt");
|
||||
String rollbackLast = Helper.asText(this, "/assert/changeset-dropAll.txt");
|
||||
|
||||
assertThat(write.apply().getBuffer()).isEqualTo(apply);
|
||||
assertThat(write.rollback().getBuffer()).isEqualTo(rollbackLast);
|
||||
assertThat(write.dropAll().getBuffer()).isEqualTo(rollbackLast);
|
||||
}
|
||||
|
||||
@Ignore
|
||||
@@ -122,8 +121,8 @@ public class BaseDdlHandlerTest extends BaseTestCase {
|
||||
|
||||
assertThat(write.apply().getBuffer()).isEqualTo(apply);
|
||||
assertThat(write.applyForeignKeys().getBuffer()).isEqualTo(applyLast);
|
||||
assertThat(write.rollbackForeignKeys().getBuffer()).isEqualTo(rollbackFirst);
|
||||
assertThat(write.rollback().getBuffer()).isEqualTo(rollbackLast);
|
||||
assertThat(write.dropAllForeignKeys().getBuffer()).isEqualTo(rollbackFirst);
|
||||
assertThat(write.dropAll().getBuffer()).isEqualTo(rollbackLast);
|
||||
}
|
||||
|
||||
}
|
||||
+2
-2
@@ -29,8 +29,8 @@ public class BaseTableDdlTest {
|
||||
String apply = write.apply().getBuffer();
|
||||
String applyLast = write.applyForeignKeys().getBuffer();
|
||||
|
||||
String rollbackFirst = write.rollbackForeignKeys().getBuffer();
|
||||
String rollbackLast = write.rollback().getBuffer();
|
||||
String rollbackFirst = write.dropAllForeignKeys().getBuffer();
|
||||
String rollbackLast = write.dropAll().getBuffer();
|
||||
|
||||
assertThat(apply).isEqualTo(Helper.asText(this, "/assert/BaseTableDdlTest/createTable-apply.txt"));
|
||||
assertThat(applyLast).isEqualTo(Helper.asText(this, "/assert/BaseTableDdlTest/createTable-applyLast.txt"));
|
||||
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
package com.avaje.ebean.dbmigration.ddlgeneration.platform;
|
||||
|
||||
import com.avaje.ebean.Ebean;
|
||||
import com.avaje.ebean.config.dbplatform.H2Platform;
|
||||
import com.avaje.ebean.dbmigration.ddlgeneration.DdlWrite;
|
||||
import com.avaje.ebean.dbmigration.model.CurrentModel;
|
||||
import com.avaje.ebean.dbmigration.model.MConfiguration;
|
||||
import com.avaje.ebean.dbmigration.model.ModelContainer;
|
||||
import com.avaje.ebeaninternal.api.SpiEbeanServer;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.assertj.core.api.StrictAssertions.assertThat;
|
||||
|
||||
|
||||
public class H2HistoryDdlTest {
|
||||
|
||||
@Test
|
||||
public void testRegenerateHistoryTriggers() throws Exception {
|
||||
|
||||
SpiEbeanServer ebeanServer = (SpiEbeanServer)Ebean.getDefaultServer();
|
||||
|
||||
HistoryTableUpdate update = new HistoryTableUpdate("c_user");
|
||||
update.add(HistoryTableUpdate.Change.ADD, "one");
|
||||
update.add(HistoryTableUpdate.Change.DROP, "two");
|
||||
|
||||
|
||||
CurrentModel currentModel = new CurrentModel(ebeanServer);
|
||||
ModelContainer modelContainer = currentModel.read();
|
||||
DdlWrite write = new DdlWrite(new MConfiguration(), modelContainer);
|
||||
|
||||
H2Platform h2Platform = new H2Platform();
|
||||
PlatformDdl h2Ddl = h2Platform.getPlatformDdl();
|
||||
h2Ddl.configure(ebeanServer.getServerConfig());
|
||||
h2Ddl.regenerateHistoryTriggers(write, update);
|
||||
|
||||
assertThat(write.applyHistory().isEmpty()).isFalse();
|
||||
assertThat(write.applyHistory().getBuffer()).contains("add one");
|
||||
assertThat(write.dropAll().isEmpty()).isTrue();
|
||||
|
||||
}
|
||||
}
|
||||
+11
-55
@@ -2,59 +2,11 @@ package com.avaje.ebean.dbmigration.ddlgeneration.platform;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
|
||||
public class HistoryTableUpdateTest {
|
||||
|
||||
@Test
|
||||
public void testToRevertedColumns_add() throws Exception {
|
||||
|
||||
HistoryTableUpdate upd = new HistoryTableUpdate("mytab");
|
||||
upd.add(HistoryTableUpdate.Change.ADD, "two");
|
||||
|
||||
List<String> current = current();
|
||||
upd.toRevertedColumns(current);
|
||||
assertThat(current).contains("one","three");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testToRevertedColumns_include() throws Exception {
|
||||
|
||||
HistoryTableUpdate upd = new HistoryTableUpdate("mytab");
|
||||
upd.add(HistoryTableUpdate.Change.INCLUDE, "two");
|
||||
|
||||
List<String> current = current();
|
||||
upd.toRevertedColumns(current);
|
||||
assertThat(current).contains("one","three");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testToRevertedColumns_drop() throws Exception {
|
||||
|
||||
HistoryTableUpdate upd = new HistoryTableUpdate("mytab");
|
||||
upd.add(HistoryTableUpdate.Change.DROP, "four");
|
||||
|
||||
List<String> current = current();
|
||||
upd.toRevertedColumns(current);
|
||||
assertThat(current).contains("one","two","three","four");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testToRevertedColumns_exclude() throws Exception {
|
||||
|
||||
HistoryTableUpdate upd = new HistoryTableUpdate("mytab");
|
||||
upd.add(HistoryTableUpdate.Change.EXCLUDE, "four");
|
||||
|
||||
List<String> current = current();
|
||||
upd.toRevertedColumns(current);
|
||||
assertThat(current).contains("one","two","three","four");
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testDescription() throws Exception {
|
||||
|
||||
@@ -62,15 +14,19 @@ public class HistoryTableUpdateTest {
|
||||
upd.add(HistoryTableUpdate.Change.ADD, "two");
|
||||
upd.add(HistoryTableUpdate.Change.DROP, "four");
|
||||
|
||||
assertThat(upd.description()).isEqualTo("add two, drop four");
|
||||
assertThat(upd.description()).isEqualTo("[add two, drop four]");
|
||||
}
|
||||
|
||||
List<String> current() {
|
||||
@Test
|
||||
public void testDescription_withIncludeExclude() throws Exception {
|
||||
|
||||
List<String> currentColumns = new ArrayList<String>();
|
||||
currentColumns.add("one");
|
||||
currentColumns.add("two");
|
||||
currentColumns.add("three");
|
||||
return currentColumns;
|
||||
HistoryTableUpdate upd = new HistoryTableUpdate("mytab");
|
||||
upd.add(HistoryTableUpdate.Change.ADD, "two");
|
||||
upd.add(HistoryTableUpdate.Change.INCLUDE, "five");
|
||||
upd.add(HistoryTableUpdate.Change.EXCLUDE, "six");
|
||||
upd.add(HistoryTableUpdate.Change.DROP, "four");
|
||||
|
||||
assertThat(upd.description()).isEqualTo("[add two, include five, exclude six, drop four]");
|
||||
}
|
||||
|
||||
}
|
||||
+16
-2
@@ -5,16 +5,30 @@ import org.junit.Test;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class MigrationXmlWriterTest {
|
||||
|
||||
@Test
|
||||
public void testReadWrite() throws Exception {
|
||||
|
||||
Migration migration = MigrationXmlReader.read("/container/test-create-table.xml");
|
||||
assertThat(migration.getChangeSet()).hasSize(1);
|
||||
assertThat(migration.getChangeSet().get(0).getChangeSetChildren()).hasSize(3);
|
||||
|
||||
File temp = File.createTempFile("migrationWrite",".xml");
|
||||
MigrationXmlWriter writer = new MigrationXmlWriter();
|
||||
writer.write(migration, temp);
|
||||
new MigrationXmlWriter("THIS IS A GENERATED FILE - DO NOT MODIFY").write(migration, temp);
|
||||
|
||||
Migration migrationRead = MigrationXmlReader.read(temp);
|
||||
assertThat(migrationRead.getChangeSet()).hasSize(1);
|
||||
assertThat(migrationRead.getChangeSet().get(0).getChangeSetChildren()).hasSize(3);
|
||||
|
||||
temp = File.createTempFile("migrationWrite",".xml");
|
||||
new MigrationXmlWriter(null).write(migration, temp);
|
||||
|
||||
Migration migrationRead2 = MigrationXmlReader.read(temp);
|
||||
|
||||
assertThat(migrationRead2.getChangeSet()).hasSize(1);
|
||||
assertThat(migrationRead.getChangeSet().get(0).getChangeSetChildren()).hasSize(3);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
package com.avaje.ebean.dbmigration.model;
|
||||
|
||||
import com.avaje.ebean.dbmigration.migration.ChangeSet;
|
||||
import com.avaje.ebean.dbmigration.migration.DropColumn;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.assertj.core.api.StrictAssertions.assertThat;
|
||||
|
||||
public class EntryTest {
|
||||
|
||||
|
||||
@Test
|
||||
public void test_when_empty() throws Exception {
|
||||
|
||||
PendingDrops.Entry entry = createEntry();
|
||||
assertThat(entry.hasPendingDrops()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_when_normal() throws Exception {
|
||||
|
||||
PendingDrops.Entry entry = createEntry(new ChangeSet());
|
||||
|
||||
assertThat(entry.hasPendingDrops()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_when_suppressOnly() throws Exception {
|
||||
|
||||
ChangeSet cs = new ChangeSet();
|
||||
cs.setSuppressDropsForever(Boolean.TRUE);
|
||||
|
||||
PendingDrops.Entry entry = createEntry(cs);
|
||||
|
||||
assertThat(entry.hasPendingDrops()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_when_both() throws Exception {
|
||||
|
||||
ChangeSet cs = new ChangeSet();
|
||||
cs.setSuppressDropsForever(Boolean.TRUE);
|
||||
|
||||
PendingDrops.Entry entry = createEntry(cs, new ChangeSet());
|
||||
|
||||
assertThat(entry.hasPendingDrops()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_containsSuppressForever_when_empty() {
|
||||
|
||||
PendingDrops.Entry entry = createEntry();
|
||||
|
||||
assertThat(entry.containsSuppressForever()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_containsSuppressForever_when_notSuppress() {
|
||||
|
||||
PendingDrops.Entry entry = createEntry(new ChangeSet());
|
||||
|
||||
assertThat(entry.containsSuppressForever()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_containsSuppressForever_when_suppress() {
|
||||
|
||||
ChangeSet cs = new ChangeSet();
|
||||
cs.setSuppressDropsForever(Boolean.TRUE);
|
||||
PendingDrops.Entry entry = createEntry(cs);
|
||||
|
||||
assertThat(entry.containsSuppressForever()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_containsSuppressForever_when_mixed() {
|
||||
|
||||
ChangeSet cs = new ChangeSet();
|
||||
cs.setSuppressDropsForever(Boolean.TRUE);
|
||||
|
||||
PendingDrops.Entry entry = createEntry(cs, new ChangeSet());
|
||||
|
||||
assertThat(entry.containsSuppressForever()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_removeDrops_when_columnsMatch() {
|
||||
|
||||
ChangeSet pending = changeSet("one", "two");
|
||||
|
||||
PendingDrops.Entry entry = createEntry(pending);
|
||||
|
||||
assertThat(entry.removeDrops(changeSet("one","two"))).isTrue();
|
||||
assertThat(entry.list).asList().doesNotContain(pending);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_removeDrops_when_subset() {
|
||||
|
||||
DropColumn dropColumnTwo = col("two");
|
||||
ChangeSet pending = changeSet("one");
|
||||
pending.getChangeSetChildren().add(dropColumnTwo);
|
||||
|
||||
PendingDrops.Entry entry = createEntry(pending);
|
||||
|
||||
assertThat(entry.removeDrops(changeSet("one"))).isFalse();
|
||||
assertThat(entry.list).asList().containsExactly(pending);
|
||||
assertThat(pending.getChangeSetChildren()).asList().containsExactly(dropColumnTwo);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_removeDrops_when_columnsMatch_butSuppressed() {
|
||||
|
||||
ChangeSet pending = changeSet("one", "two");
|
||||
pending.setSuppressDropsForever(Boolean.TRUE);
|
||||
|
||||
PendingDrops.Entry entry = createEntry(pending);
|
||||
|
||||
assertThat(entry.removeDrops(changeSet("one","two"))).isFalse();
|
||||
assertThat(entry.list).asList().contains(pending);
|
||||
assertThat(pending.getChangeSetChildren()).asList().hasSize(2);
|
||||
|
||||
}
|
||||
|
||||
static ChangeSet changeSet(String... colName) {
|
||||
|
||||
ChangeSet cs = new ChangeSet();
|
||||
for (String col : colName) {
|
||||
cs.getChangeSetChildren().add(col(col));
|
||||
}
|
||||
return cs;
|
||||
}
|
||||
|
||||
static DropColumn col(String colName) {
|
||||
DropColumn drop = new DropColumn();
|
||||
drop.setColumnName(colName);
|
||||
drop.setTableName("tab");
|
||||
return drop;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
static PendingDrops.Entry createEntry(ChangeSet... pending) {
|
||||
|
||||
PendingDrops.Entry entry = new PendingDrops.Entry(MigrationVersion.parse("1.1"));
|
||||
for (ChangeSet changeSet: pending) {
|
||||
entry.add(changeSet);
|
||||
}
|
||||
return entry;
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,11 @@
|
||||
package com.avaje.ebean.dbmigration.model;
|
||||
|
||||
import com.avaje.ebean.dbmigration.migration.AddColumn;
|
||||
import com.avaje.ebean.dbmigration.migration.AddHistoryTable;
|
||||
import com.avaje.ebean.dbmigration.migration.AlterColumn;
|
||||
import com.avaje.ebean.dbmigration.migration.DropColumn;
|
||||
import com.avaje.ebean.dbmigration.migration.DropHistoryTable;
|
||||
import com.avaje.ebean.dbmigration.migration.DropTable;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.List;
|
||||
@@ -11,7 +14,7 @@ import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
public class MTableTest {
|
||||
|
||||
MTable base() {
|
||||
static MTable base() {
|
||||
MTable table = new MTable("tab");
|
||||
table.addColumn(new MColumn("id","bigint"));
|
||||
table.addColumn(new MColumn("name","varchar(20)"));
|
||||
@@ -20,7 +23,7 @@ public class MTableTest {
|
||||
return table;
|
||||
}
|
||||
|
||||
MTable newTable() {
|
||||
static MTable newTable() {
|
||||
MTable table = new MTable("tab");
|
||||
table.addColumn(new MColumn("id","bigint"));
|
||||
table.addColumn(new MColumn("name","varchar(20)"));
|
||||
@@ -29,7 +32,7 @@ public class MTableTest {
|
||||
return table;
|
||||
}
|
||||
|
||||
MTable newTableAdd2Columns() {
|
||||
static MTable newTableAdd2Columns() {
|
||||
MTable table = new MTable("tab");
|
||||
table.addColumn(new MColumn("id","bigint"));
|
||||
table.addColumn(new MColumn("name","varchar(20)"));
|
||||
@@ -39,7 +42,7 @@ public class MTableTest {
|
||||
return table;
|
||||
}
|
||||
|
||||
MTable newTableModifiedColumn() {
|
||||
static MTable newTableModifiedColumn() {
|
||||
MColumn modCol = new MColumn("name", "varchar(30)");// modified type
|
||||
modCol.setNotnull(true);
|
||||
|
||||
@@ -51,7 +54,26 @@ public class MTableTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCompare_addColumnDropColumn() throws Exception {
|
||||
public void test_allHistoryColumns() throws Exception {
|
||||
|
||||
MTable base = base();
|
||||
base.registerPendingDropColumn("fullName");
|
||||
base.registerPendingDropColumn("last");
|
||||
|
||||
assertThat(base.allHistoryColumns(false)).containsExactly("id","name","status");
|
||||
assertThat(base.allHistoryColumns(true)).containsExactly("id","name","status","fullName","last");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_dropTable() {
|
||||
|
||||
MTable base = base();
|
||||
DropTable dropTable = base.dropTable();
|
||||
assertThat(dropTable.getName()).isEqualTo(base.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_compare_addColumnDropColumn() throws Exception {
|
||||
|
||||
ModelDiff diff = new ModelDiff();
|
||||
diff.compareTables(base(), newTable());
|
||||
@@ -71,7 +93,7 @@ public class MTableTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCompare_addTwoColumnsToSameTable() throws Exception {
|
||||
public void test_compare_addTwoColumnsToSameTable() throws Exception {
|
||||
|
||||
ModelDiff diff = new ModelDiff();
|
||||
diff.compareTables(base(), newTableAdd2Columns());
|
||||
@@ -88,7 +110,7 @@ public class MTableTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCompare_modifyColumn() throws Exception {
|
||||
public void test_compare_modifyColumn() throws Exception {
|
||||
|
||||
ModelDiff diff = new ModelDiff();
|
||||
diff.compareTables(base(), newTableModifiedColumn());
|
||||
@@ -107,4 +129,99 @@ public class MTableTest {
|
||||
assertThat(diff.getDropChanges()).hasSize(0);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_apply_dropColumn() {
|
||||
|
||||
MTable base = base();
|
||||
|
||||
DropColumn dropColumn = new DropColumn();
|
||||
dropColumn.setTableName("tab");
|
||||
dropColumn.setColumnName("name");
|
||||
|
||||
base.apply(dropColumn);
|
||||
assertThat(base.getColumn("name")).isNull();
|
||||
}
|
||||
|
||||
@Test(expected = IllegalStateException.class)
|
||||
public void test_apply_dropColumn_doesNotExist() {
|
||||
|
||||
MTable base = base();
|
||||
|
||||
DropColumn dropColumn = new DropColumn();
|
||||
dropColumn.setTableName(base.getName());
|
||||
dropColumn.setColumnName("DoesNotExist");
|
||||
base.apply(dropColumn);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalStateException.class)
|
||||
public void test_apply_alterColumn_doesNotExist() {
|
||||
|
||||
MTable base = base();
|
||||
|
||||
AlterColumn alterColumn = new AlterColumn();
|
||||
alterColumn.setTableName(base.getName());
|
||||
alterColumn.setColumnName("DoesNotExist");
|
||||
alterColumn.setType("integer");
|
||||
base.apply(alterColumn);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_apply_alterColumn_type() {
|
||||
|
||||
MTable base = base();
|
||||
|
||||
AlterColumn alterColumn = new AlterColumn();
|
||||
alterColumn.setTableName(base.getName());
|
||||
alterColumn.setColumnName("id");
|
||||
alterColumn.setType("uuid");
|
||||
base.apply(alterColumn);
|
||||
|
||||
assertThat(base.getColumn("id").getType()).isEqualTo("uuid");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_compare_addAndDropColumn() throws Exception {
|
||||
|
||||
MTable base = base();
|
||||
MTable newTable = newTable();
|
||||
|
||||
ModelDiff diff = new ModelDiff();
|
||||
base.compare(diff, newTable);
|
||||
|
||||
assertThat(diff.getApplyChanges()).hasSize(1);
|
||||
assertThat(diff.getDropChanges()).hasSize(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_compare_addHistoryToTable() {
|
||||
|
||||
MTable base = base();
|
||||
MTable withHistory = base();
|
||||
withHistory.setWithHistory(true);
|
||||
|
||||
ModelDiff diff = new ModelDiff();
|
||||
base.compare(diff, withHistory);
|
||||
|
||||
assertThat(diff.getDropChanges()).isEmpty();
|
||||
assertThat(diff.getApplyChanges()).hasSize(1);
|
||||
assertThat(diff.getApplyChanges().get(0)).isInstanceOf(AddHistoryTable.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_compare_removeHistoryFromTable() throws Exception {
|
||||
|
||||
MTable withHistory = base();
|
||||
withHistory.setWithHistory(true);
|
||||
|
||||
MTable noHistory = base();
|
||||
|
||||
ModelDiff diff = new ModelDiff();
|
||||
withHistory.compare(diff, noHistory);
|
||||
|
||||
assertThat(diff.getApplyChanges()).isEmpty();
|
||||
assertThat(diff.getDropChanges()).hasSize(1);
|
||||
assertThat(diff.getDropChanges().get(0)).isInstanceOf(DropHistoryTable.class);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -6,8 +6,47 @@ import static org.assertj.core.api.StrictAssertions.assertThat;
|
||||
|
||||
public class MigrationVersionTest {
|
||||
|
||||
|
||||
|
||||
@Test
|
||||
public void testParse() throws Exception {
|
||||
public void test_parse_getComment() throws Exception {
|
||||
|
||||
assertThat(MigrationVersion.parse("1.1.1_2__Foo").getComment()).isEqualTo("Foo");
|
||||
assertThat(MigrationVersion.parse("1.1.1.2__junk").getComment()).isEqualTo("junk");
|
||||
assertThat(MigrationVersion.parse("1.1_1.2_foo").getComment()).isEqualTo("");
|
||||
assertThat(MigrationVersion.parse("1.1_1.2_d").getComment()).isEqualTo("");
|
||||
assertThat(MigrationVersion.parse("1.1_1.2_").getComment()).isEqualTo("");
|
||||
assertThat(MigrationVersion.parse("1.1_1.2").getComment()).isEqualTo("");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_nextVersion_expect_preserveUnderscores() {
|
||||
|
||||
assertThat(MigrationVersion.parse("2").nextVersion()).isEqualTo("3");
|
||||
assertThat(MigrationVersion.parse("1.0").nextVersion()).isEqualTo("1.1");
|
||||
assertThat(MigrationVersion.parse("2.0.b34").nextVersion()).isEqualTo("2.1");
|
||||
assertThat(MigrationVersion.parse("1.1.1_2__Foo").nextVersion()).isEqualTo("1.1.1_3");
|
||||
assertThat(MigrationVersion.parse("1.1.1.2_junk").nextVersion()).isEqualTo("1.1.1.3");
|
||||
assertThat(MigrationVersion.parse("1_2.3_4__Foo").nextVersion()).isEqualTo("1_2.3_5");
|
||||
assertThat(MigrationVersion.parse("1_2.3_4_").nextVersion()).isEqualTo("1_2.3_5");
|
||||
assertThat(MigrationVersion.parse("1_2_3_4__Foo").nextVersion()).isEqualTo("1_2_3_5");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_normalised_expect_periods() {
|
||||
|
||||
assertThat(MigrationVersion.parse("2").normalised()).isEqualTo("2");
|
||||
assertThat(MigrationVersion.parse("1.0").normalised()).isEqualTo("1.0");
|
||||
assertThat(MigrationVersion.parse("2.0.b34").normalised()).isEqualTo("2.0");
|
||||
assertThat(MigrationVersion.parse("1.1.1_2__Foo").normalised()).isEqualTo("1.1.1.2");
|
||||
assertThat(MigrationVersion.parse("1.1.1.2_junk").normalised()).isEqualTo("1.1.1.2");
|
||||
assertThat(MigrationVersion.parse("1_2.3_4__Foo").normalised()).isEqualTo("1.2.3.4");
|
||||
assertThat(MigrationVersion.parse("1_2.3_4_").normalised()).isEqualTo("1.2.3.4");
|
||||
assertThat(MigrationVersion.parse("1_2_3_4__Foo").normalised()).isEqualTo("1.2.3.4");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_compareTo_isEqual() throws Exception {
|
||||
|
||||
MigrationVersion v0 = MigrationVersion.parse("1.1.1_2__Foo");
|
||||
MigrationVersion v1 = MigrationVersion.parse("1.1.1.2_junk");
|
||||
@@ -16,32 +55,21 @@ public class MigrationVersionTest {
|
||||
assertThat(v0.compareTo(v1)).isEqualTo(0);
|
||||
assertThat(v1.compareTo(v0)).isEqualTo(0);
|
||||
assertThat(v1.compareTo(v2)).isEqualTo(0);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNextVersion() {
|
||||
|
||||
assertThat(MigrationVersion.parse("2").nextVersion()).isEqualTo("3");
|
||||
assertThat(MigrationVersion.parse("1.0").nextVersion()).isEqualTo("1.1");
|
||||
assertThat(MigrationVersion.parse("2.0.b34").nextVersion()).isEqualTo("2.1");
|
||||
assertThat(MigrationVersion.parse("1.1.1_2__Foo").nextVersion()).isEqualTo("1.1.1.3");
|
||||
assertThat(MigrationVersion.parse("1.1.1.2_junk").nextVersion()).isEqualTo("1.1.1.3");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCompareTo() throws Exception {
|
||||
public void test_compareTo() throws Exception {
|
||||
|
||||
MigrationVersion v0 = MigrationVersion.parse("1.1.1.1_junk");
|
||||
MigrationVersion v1 = MigrationVersion.parse("1.1.1.2_junk");
|
||||
MigrationVersion v2 = MigrationVersion.parse("2.1_1.2_junk");
|
||||
MigrationVersion v2 = MigrationVersion.parse("1.1_1.3_junk");
|
||||
MigrationVersion v3 = MigrationVersion.parse("1.2_1.2_junk");
|
||||
MigrationVersion v4 = MigrationVersion.parse("1.1_1.3_junk");
|
||||
MigrationVersion v5 = MigrationVersion.parse("1.1.1.1_junk");
|
||||
MigrationVersion v4 = MigrationVersion.parse("2.1_1.2_junk");
|
||||
|
||||
assertThat(v1.compareTo(v0)).isEqualTo(1);
|
||||
|
||||
assertThat(v1.compareTo(v2)).isEqualTo(-1);
|
||||
assertThat(v1.compareTo(v3)).isEqualTo(-1);
|
||||
assertThat(v1.compareTo(v4)).isEqualTo(-1);
|
||||
|
||||
assertThat(v1.compareTo(v5)).isEqualTo(1);
|
||||
}
|
||||
}
|
||||
@@ -29,13 +29,13 @@ public class ModelContainerApplyTest {
|
||||
assertThat(changeSetChildren.get(2)).isInstanceOf(DropColumn.class);
|
||||
|
||||
ModelContainer model = new ModelContainer();
|
||||
model.apply(migration);
|
||||
model.apply(migration, MigrationVersion.parse("1.1"));
|
||||
|
||||
MTable foo = model.getTable("foo");
|
||||
assertThat(foo.getComment()).isEqualTo("comment");
|
||||
assertThat(foo.getTablespace()).isEqualTo("fooSpace");
|
||||
assertThat(foo.getIndexTablespace()).isEqualTo("fooIndexSpace");
|
||||
assertThat(foo.isWithHistory()).isEqualTo(false);
|
||||
assertThat(foo.getColumns()).containsKeys("col1", "col3", "added_to_foo");
|
||||
assertThat(foo.allColumns()).extracting("name").contains("col1", "col3", "added_to_foo");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package com.avaje.ebean.dbmigration.model;
|
||||
|
||||
|
||||
import com.avaje.ebean.dbmigration.migration.Migration;
|
||||
import com.avaje.ebean.dbmigration.migrationreader.MigrationXmlReader;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class ModelContainerTest {
|
||||
|
||||
@Test
|
||||
public void apply_when_noPendingDrops_then_emptyPending() throws Exception {
|
||||
|
||||
ModelContainer container = new ModelContainer();
|
||||
container.apply(mig("1.0.model.xml"), ver("1.1"));
|
||||
|
||||
assertThat(container.getPendingDrops()).isEmpty();
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void apply_when_pendingDrops_then_registeredHistoryTable() throws Exception {
|
||||
|
||||
ModelContainer base = container_1_1();
|
||||
|
||||
MTable table = base.getTable("document");
|
||||
assertThat(table.allHistoryColumns(true)).doesNotContain("zing");
|
||||
|
||||
container_1_1().registerPendingHistoryDropColumns(base);
|
||||
assertThat(table.allHistoryColumns(true)).contains("zing");
|
||||
assertThat(table.allHistoryColumns(false)).doesNotContain("zing");
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void apply_when_pendingDropsApplied_then_droppedTableNotInHistory() throws Exception {
|
||||
|
||||
ModelContainer container = container_1_1();
|
||||
container.apply(mig("1.1_2__drops.model.xml"), ver("1.1_2"));
|
||||
|
||||
ModelContainer base = container_1_1();
|
||||
|
||||
container.registerPendingHistoryDropColumns(base);
|
||||
|
||||
assertThat(base.getTable("document").allHistoryColumns(false)).doesNotContain("zing");
|
||||
assertThat(base.getTable("document").allHistoryColumns(true)).doesNotContain("zing");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void apply_when_apply_partial_pendingDrops_then_some_remainder() throws Exception {
|
||||
|
||||
ModelContainer container = container_2_1();
|
||||
container.apply(mig("2.2__drops.model.xml"), ver("2.2"));
|
||||
|
||||
ModelContainer base = container_2_1();
|
||||
|
||||
container.registerPendingHistoryDropColumns(base);
|
||||
|
||||
List<String> normalColumns = base.getTable("document").allHistoryColumns(false);
|
||||
List<String> historyColumns = base.getTable("document").allHistoryColumns(true);
|
||||
|
||||
assertThat(historyColumns).contains("zong","boom","baz","bar");
|
||||
assertThat(normalColumns).doesNotContain("zing","zong","boom","baz","bar");
|
||||
}
|
||||
|
||||
@NotNull
|
||||
private ModelContainer container_2_1() {
|
||||
ModelContainer container = new ModelContainer();
|
||||
container.apply(mig("2.0.model.xml"), ver("2.0"));
|
||||
container.apply(mig("2.1.model.xml"), ver("2.1"));
|
||||
return container;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
private ModelContainer container_1_1() {
|
||||
ModelContainer container = new ModelContainer();
|
||||
container.apply(mig("1.0.model.xml"), ver("1.0"));
|
||||
container.apply(mig("1.1.model.xml"), ver("1.1"));
|
||||
return container;
|
||||
}
|
||||
|
||||
private MigrationVersion ver(String version) {
|
||||
return MigrationVersion.parse(version);
|
||||
}
|
||||
|
||||
private Migration mig(String path) {
|
||||
return MigrationXmlReader.read(ModelContainerTest.class.getResourceAsStream(path));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.avaje.ebean.dbmigration.model;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
|
||||
public class ModelDiffTest {
|
||||
|
||||
@Test
|
||||
public void test_compareTo_with_dropColumnOnHistoryTable_then_historyColumnRegistered() throws Exception {
|
||||
|
||||
ModelContainer base = new ModelContainer();
|
||||
base.addTable(MTableTest.base().setWithHistory(true));
|
||||
|
||||
ModelContainer newModel = new ModelContainer();
|
||||
newModel.addTable(MTableTest.newTable().setWithHistory(true));
|
||||
|
||||
ModelDiff diff = new ModelDiff(base);
|
||||
diff.compareTo(newModel);
|
||||
|
||||
MTable tab = newModel.getTable("tab");
|
||||
|
||||
assertThat(tab.allHistoryColumns(true)).contains("status");
|
||||
assertThat(tab.allColumns()).extracting("name").doesNotContain("status");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
package com.avaje.ebean.dbmigration.model;
|
||||
|
||||
import com.avaje.ebean.dbmigration.migration.ChangeSet;
|
||||
import com.avaje.ebean.dbmigration.migration.DropColumn;
|
||||
import com.avaje.ebean.dbmigration.migration.Migration;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
|
||||
public class PendingDropsTest {
|
||||
|
||||
static final MigrationVersion V1_1 = MigrationVersion.parse("1.1");
|
||||
|
||||
static final MigrationVersion V1_2 = MigrationVersion.parse("1.2");
|
||||
|
||||
@Test
|
||||
public void test_add() throws Exception {
|
||||
|
||||
PendingDrops pendingDrops = new PendingDrops();
|
||||
pendingDrops.add(V1_1, new ChangeSet());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_appliedDropsFor_when_matchesSome_then_removesMatched() throws Exception {
|
||||
|
||||
PendingDrops pendingDrops = new PendingDrops();
|
||||
|
||||
DropColumn one = col("one");
|
||||
DropColumn two = col("two");
|
||||
pendingDrops.add(V1_1, changeSet(one,two));
|
||||
pendingDrops.add(V1_1, changeSet("three","four"));
|
||||
assertThat(pendingDrops.testGetEntryFor(V1_1).list).asList().hasSize(2);
|
||||
|
||||
ChangeSet applied = changeSet("two");
|
||||
applied.setDropsFor("1.1");
|
||||
|
||||
assertThat(pendingDrops.appliedDropsFor(applied)).isFalse();
|
||||
assertThat(pendingDrops.testGetEntryFor(V1_1).list).asList().hasSize(2);
|
||||
assertThat(pendingDrops.testGetEntryFor(V1_1).list.get(0).getChangeSetChildren()).asList().containsExactly(one);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_appliedDropsFor_when_matchesAll_then_removesChangeSet() throws Exception {
|
||||
|
||||
PendingDrops pendingDrops = new PendingDrops();
|
||||
|
||||
DropColumn one = col("one");
|
||||
DropColumn two = col("two");
|
||||
pendingDrops.add(V1_1, changeSet(one,two));
|
||||
pendingDrops.add(V1_1, changeSet("three","four"));
|
||||
assertThat(pendingDrops.testGetEntryFor(V1_1).list).asList().hasSize(2);
|
||||
|
||||
ChangeSet applied = changeSet("two","one");
|
||||
applied.setDropsFor("1.1");
|
||||
|
||||
assertThat(pendingDrops.appliedDropsFor(applied)).isFalse();
|
||||
assertThat(pendingDrops.testGetEntryFor(V1_1).list).asList().hasSize(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_appliedDropsFor_when_changeSetSuppressed_isIgnored() throws Exception {
|
||||
|
||||
PendingDrops pendingDrops = new PendingDrops();
|
||||
|
||||
DropColumn one = col("one");
|
||||
ChangeSet changeSet = changeSet(one);
|
||||
changeSet.setSuppressDropsForever(true);
|
||||
pendingDrops.add(V1_1, changeSet);
|
||||
|
||||
ChangeSet applied = changeSet("one");
|
||||
applied.setDropsFor("1.1");
|
||||
|
||||
assertThat(pendingDrops.appliedDropsFor(applied)).isFalse();
|
||||
assertThat(pendingDrops.testGetEntryFor(V1_1).list).asList().hasSize(1);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void test_pendingDrops() throws Exception {
|
||||
|
||||
PendingDrops pendingDrops = new PendingDrops();
|
||||
assertThat(pendingDrops.pendingDrops()).isEmpty();
|
||||
|
||||
pendingDrops.add(V1_1, new ChangeSet());
|
||||
pendingDrops.add(V1_2, new ChangeSet());
|
||||
assertThat(pendingDrops.pendingDrops()).containsExactly("1.1", "1.2");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_pendingDrops_when_suppressForever() throws Exception {
|
||||
|
||||
PendingDrops pendingDrops = new PendingDrops();
|
||||
assertThat(pendingDrops.pendingDrops()).isEmpty();
|
||||
|
||||
pendingDrops.add(V1_1, newSuppressForeverChangeSet());
|
||||
assertThat(pendingDrops.pendingDrops()).isEmpty();
|
||||
|
||||
pendingDrops.add(V1_2, new ChangeSet());
|
||||
assertThat(pendingDrops.pendingDrops()).containsExactly("1.2");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_pendingDrops_when_both() throws Exception {
|
||||
|
||||
PendingDrops pendingDrops = new PendingDrops();
|
||||
assertThat(pendingDrops.pendingDrops()).isEmpty();
|
||||
|
||||
pendingDrops.add(V1_1, newSuppressForeverChangeSet());
|
||||
pendingDrops.add(V1_1, new ChangeSet());
|
||||
assertThat(pendingDrops.pendingDrops()).containsExactly("1.1");
|
||||
|
||||
pendingDrops.add(V1_2, new ChangeSet());
|
||||
assertThat(pendingDrops.pendingDrops()).containsExactly("1.1", "1.2");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_migrationForVersion() throws Exception {
|
||||
|
||||
PendingDrops pendingDrops = new PendingDrops();
|
||||
|
||||
ChangeSet applyDropChangeSet1 = new ChangeSet();
|
||||
ChangeSet applyDropChangeSet2 = new ChangeSet();
|
||||
|
||||
MigrationVersion version = V1_1;
|
||||
pendingDrops.add(version, applyDropChangeSet1);
|
||||
pendingDrops.add(version, applyDropChangeSet2);
|
||||
|
||||
Migration migration = pendingDrops.migrationForVersion("1_1");
|
||||
assertThat(migration.getChangeSet()).containsExactly(applyDropChangeSet1, applyDropChangeSet2);
|
||||
|
||||
assertThat(pendingDrops.testContainsEntryFor(version)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_migrationForVersion_when_both() throws Exception {
|
||||
|
||||
PendingDrops pendingDrops = new PendingDrops();
|
||||
|
||||
ChangeSet applyDropChangeSet = new ChangeSet();
|
||||
MigrationVersion version = V1_1;
|
||||
pendingDrops.add(version, newSuppressForeverChangeSet());
|
||||
pendingDrops.add(version, applyDropChangeSet);
|
||||
|
||||
Migration migration = pendingDrops.migrationForVersion("1_1");
|
||||
assertThat(migration.getChangeSet()).containsExactly(applyDropChangeSet);
|
||||
|
||||
assertThat(pendingDrops.testContainsEntryFor(version)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_migrationForVersion_when_next() throws Exception {
|
||||
|
||||
PendingDrops pendingDrops = new PendingDrops();
|
||||
MigrationVersion version = V1_1;
|
||||
|
||||
ChangeSet applyDropChangeSet = new ChangeSet();
|
||||
pendingDrops.add(version, newSuppressForeverChangeSet());
|
||||
pendingDrops.add(version, applyDropChangeSet);
|
||||
|
||||
|
||||
Migration migration = pendingDrops.migrationForVersion("next");
|
||||
assertThat(migration.getChangeSet()).containsExactly(applyDropChangeSet);
|
||||
assertThat(pendingDrops.testContainsEntryFor(version)).isTrue();
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void test_migrationForVersion_when_next_isSuppressForever() throws Exception {
|
||||
|
||||
PendingDrops pendingDrops = new PendingDrops();
|
||||
pendingDrops.add(V1_1, newSuppressForeverChangeSet());
|
||||
pendingDrops.migrationForVersion("next");
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void test_migrationForVersion_when_doesNotExist() throws Exception {
|
||||
|
||||
PendingDrops pendingDrops = new PendingDrops();
|
||||
pendingDrops.migrationForVersion("1_1");
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void test_migrationForVersion_when_next_doesNotExist() throws Exception {
|
||||
|
||||
PendingDrops pendingDrops = new PendingDrops();
|
||||
pendingDrops.migrationForVersion("next");
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void test_registerPendingHistoryDropColumns() throws Exception {
|
||||
|
||||
TDModelContainer modelContainer = new TDModelContainer();
|
||||
|
||||
DropColumn drop1 = col("one");
|
||||
drop1.setWithHistory(Boolean.TRUE);
|
||||
|
||||
DropColumn drop2 = col("two");
|
||||
|
||||
ChangeSet changeSet = changeSet(drop1, drop2);
|
||||
|
||||
PendingDrops pendingDrops = new PendingDrops();
|
||||
pendingDrops.add(V1_1, changeSet);
|
||||
pendingDrops.registerPendingHistoryDropColumns(modelContainer);
|
||||
|
||||
assertThat(modelContainer.drops).containsExactly(changeSet);
|
||||
}
|
||||
|
||||
class TDModelContainer extends ModelContainer {
|
||||
|
||||
List<ChangeSet> drops = new ArrayList<ChangeSet>();
|
||||
|
||||
@Override
|
||||
public void registerPendingHistoryDropColumns(ChangeSet changeSet) {
|
||||
drops.add(changeSet);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private ChangeSet newSuppressForeverChangeSet() {
|
||||
ChangeSet changeSet = new ChangeSet();
|
||||
changeSet.setSuppressDropsForever(Boolean.TRUE);
|
||||
return changeSet;
|
||||
}
|
||||
|
||||
static ChangeSet changeSet(String... colNames) {
|
||||
return EntryTest.changeSet(colNames);
|
||||
}
|
||||
|
||||
static ChangeSet changeSet(DropColumn... drops) {
|
||||
ChangeSet changeSet = new ChangeSet();
|
||||
for (DropColumn dropColumn : drops) {
|
||||
changeSet.getChangeSetChildren().add(dropColumn);
|
||||
}
|
||||
|
||||
return changeSet;
|
||||
}
|
||||
|
||||
static DropColumn col(String colName) {
|
||||
return EntryTest.col(colName);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -37,8 +37,6 @@ public class ModelBuildBeanVisitorTest extends BaseTestCase {
|
||||
assertThat(item.primaryKeyColumns()).hasSize(2);
|
||||
|
||||
MTable customer = model.getTable("o_customer");
|
||||
|
||||
assertThat(customer).isNotNull();
|
||||
assertThat(customer.getSequenceName()).isNull();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.avaje.ebeaninternal.api;
|
||||
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class HashQueryPlanBuilderTest {
|
||||
|
||||
int combine(int v0, int v1) {
|
||||
return new HashQueryPlanBuilder().add(v0).add(v1).build().hashCode();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_pair_0_1() {
|
||||
assertThat(combine(0, 31)).isNotEqualTo(combine(1,0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_pair_0_10_adjust_0() {
|
||||
assertThat(combine(0, 310)).isNotEqualTo(combine(10,0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_pair_0_10_adjust_10() {
|
||||
assertThat(combine(0, 320)).isNotEqualTo(combine(10,10));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_pair_0_10_adjust_40() {
|
||||
assertThat(combine(0, 350)).isNotEqualTo(combine(10,40));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_pair_0_10_adjust_90() {
|
||||
assertThat(combine(0, 400)).isNotEqualTo(combine(10,90));
|
||||
}
|
||||
|
||||
}
|
||||
+5
-5
@@ -8,7 +8,7 @@ import java.sql.Timestamp;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.OffsetDateTime;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class InsertTimestampFactoryTest {
|
||||
|
||||
@@ -20,7 +20,7 @@ public class InsertTimestampFactoryTest {
|
||||
DeployBeanProperty prop = new DeployBeanProperty(null, LocalDateTime.class, null, null);
|
||||
|
||||
GeneratedProperty insertTimestamp = factory.createInsertTimestamp(prop);
|
||||
Object value = insertTimestamp.getInsertValue(null, null);
|
||||
Object value = insertTimestamp.getInsertValue(null, null, System.currentTimeMillis());
|
||||
assertTrue(value instanceof LocalDateTime);
|
||||
}
|
||||
|
||||
@@ -30,7 +30,7 @@ public class InsertTimestampFactoryTest {
|
||||
DeployBeanProperty prop = new DeployBeanProperty(null, OffsetDateTime.class, null, null);
|
||||
|
||||
GeneratedProperty insertTimestamp = factory.createInsertTimestamp(prop);
|
||||
Object value = insertTimestamp.getInsertValue(null, null);
|
||||
Object value = insertTimestamp.getInsertValue(null, null, System.currentTimeMillis());
|
||||
assertTrue(value instanceof OffsetDateTime);
|
||||
}
|
||||
|
||||
@@ -40,7 +40,7 @@ public class InsertTimestampFactoryTest {
|
||||
DeployBeanProperty prop = new DeployBeanProperty(null, Timestamp.class, null, null);
|
||||
|
||||
GeneratedProperty insertTimestamp = factory.createInsertTimestamp(prop);
|
||||
Object value = insertTimestamp.getInsertValue(null, null);
|
||||
Object value = insertTimestamp.getInsertValue(null, null, System.currentTimeMillis());
|
||||
assertTrue(value instanceof Timestamp);
|
||||
}
|
||||
|
||||
@@ -50,7 +50,7 @@ public class InsertTimestampFactoryTest {
|
||||
DeployBeanProperty prop = new DeployBeanProperty(null, java.util.Date.class, null, null);
|
||||
|
||||
GeneratedProperty insertTimestamp = factory.createInsertTimestamp(prop);
|
||||
Object value = insertTimestamp.getInsertValue(null, null);
|
||||
Object value = insertTimestamp.getInsertValue(null, null, System.currentTimeMillis());
|
||||
assertTrue(value instanceof java.util.Date);
|
||||
}
|
||||
|
||||
|
||||
+4
-4
@@ -21,7 +21,7 @@ public class UpdateTimestampFactoryTest {
|
||||
DeployBeanProperty prop = new DeployBeanProperty(null, LocalDateTime.class, null, null);
|
||||
|
||||
GeneratedProperty generatedProperty = factory.createUpdateTimestamp(prop);
|
||||
Object value = generatedProperty.getInsertValue(null, null);
|
||||
Object value = generatedProperty.getInsertValue(null, null, System.currentTimeMillis());
|
||||
assertTrue(value instanceof LocalDateTime);
|
||||
}
|
||||
|
||||
@@ -31,7 +31,7 @@ public class UpdateTimestampFactoryTest {
|
||||
DeployBeanProperty prop = new DeployBeanProperty(null, OffsetDateTime.class, null, null);
|
||||
|
||||
GeneratedProperty generatedProperty = factory.createUpdateTimestamp(prop);
|
||||
Object value = generatedProperty.getInsertValue(null, null);
|
||||
Object value = generatedProperty.getInsertValue(null, null, System.currentTimeMillis());
|
||||
assertTrue(value instanceof OffsetDateTime);
|
||||
}
|
||||
|
||||
@@ -41,7 +41,7 @@ public class UpdateTimestampFactoryTest {
|
||||
DeployBeanProperty prop = new DeployBeanProperty(null, Timestamp.class, null, null);
|
||||
|
||||
GeneratedProperty generatedProperty = factory.createUpdateTimestamp(prop);
|
||||
Object value = generatedProperty.getInsertValue(null, null);
|
||||
Object value = generatedProperty.getInsertValue(null, null, System.currentTimeMillis());
|
||||
assertTrue(value instanceof Timestamp);
|
||||
}
|
||||
|
||||
@@ -51,7 +51,7 @@ public class UpdateTimestampFactoryTest {
|
||||
DeployBeanProperty prop = new DeployBeanProperty(null, java.util.Date.class, null, null);
|
||||
|
||||
GeneratedProperty generatedProperty = factory.createUpdateTimestamp(prop);
|
||||
Object value = generatedProperty.getInsertValue(null, null);
|
||||
Object value = generatedProperty.getInsertValue(null, null, System.currentTimeMillis());
|
||||
assertTrue(value instanceof java.util.Date);
|
||||
}
|
||||
}
|
||||
@@ -37,4 +37,28 @@ public class DefaultOrmQueryTest {
|
||||
assertThat(hash1).isNotEqualTo(hash2);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test_AutofetchHash_diffFirstRows() throws Exception {
|
||||
|
||||
SpiQuery<?> query1 = (SpiQuery<?>)Ebean.find(Order.class)
|
||||
.setFirstRow(0)
|
||||
.setMaxRows(31);
|
||||
|
||||
HashQueryPlanBuilder b1 = new HashQueryPlanBuilder();
|
||||
query1.queryAutoTuneHash(b1);
|
||||
HashQueryPlan hash1 = b1.build();
|
||||
|
||||
SpiQuery<?> query2 = (SpiQuery<?>)Ebean.find(Order.class)
|
||||
.setFirstRow(1)
|
||||
.setMaxRows(0);
|
||||
|
||||
HashQueryPlanBuilder b2 = new HashQueryPlanBuilder();
|
||||
query2.queryAutoTuneHash(b2);
|
||||
HashQueryPlan hash2 = b2.build();
|
||||
|
||||
assertThat(hash1).isNotEqualTo(hash2);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import com.avaje.ebean.Ebean;
|
||||
import com.avaje.tests.model.EGenProps;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.assertj.core.api.StrictAssertions.assertThat;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
public class TestGeneratedProperties extends BaseTestCase {
|
||||
@@ -31,9 +32,16 @@ public class TestGeneratedProperties extends BaseTestCase {
|
||||
assertNotNull(bean.getLongCreated());
|
||||
assertNotNull(bean.getLongUpdated());
|
||||
|
||||
assertThat(bean.getWhenCreated().toInstant().toEpochMilli()).isEqualTo(bean.getLongCreated());
|
||||
assertThat(bean.getWhenModified().toInstant().toEpochMilli()).isEqualTo(bean.getLongCreated());
|
||||
assertThat(bean.getWhenModified().toInstant().toEpochMilli()).isEqualTo(bean.getLongCreated());
|
||||
|
||||
bean.setName("updating...");
|
||||
Ebean.save(bean);
|
||||
|
||||
assertThat(bean.getWhenModified()).isNotEqualTo(bean.getLongCreated());
|
||||
assertThat(bean.getWhenModified().toInstant().toEpochMilli()).isEqualTo(bean.getLongUpdated());
|
||||
|
||||
Ebean.delete(bean);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.avaje.tests.inheritance;
|
||||
|
||||
import com.avaje.ebean.Ebean;
|
||||
import com.avaje.tests.model.basic.Car;
|
||||
import com.avaje.tests.model.basic.Truck;
|
||||
import com.avaje.tests.model.basic.Vehicle;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
|
||||
public class TestInheritanceBatchLazyLoad {
|
||||
|
||||
@Test
|
||||
public void lazyLoadProperty_when_propertyNotOnAllInheritanceTypes() {
|
||||
|
||||
Car c = new Car();
|
||||
c.setLicenseNumber("VZVZ1");
|
||||
c.setDriver("CarDriver");
|
||||
Ebean.save(c);
|
||||
|
||||
Truck t = new Truck();
|
||||
t.setLicenseNumber("VZVZ2");
|
||||
t.setCapacity(20D);
|
||||
Ebean.save(t);
|
||||
|
||||
|
||||
List<Vehicle> list = Ebean.find(Vehicle.class)
|
||||
.select("licenseNumber")
|
||||
.where().startsWith("licenseNumber","VZVZ")
|
||||
.order().asc("licenseNumber")
|
||||
.findList();
|
||||
|
||||
assertThat(list).hasSize(2);
|
||||
|
||||
Car car = (Car)list.get(0);
|
||||
car.getNotes();
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user