org.hibernate.tool.schema.TargetType Java Examples

The following examples show how to use org.hibernate.tool.schema.TargetType. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SpannerTableExporterTests.java    From google-cloud-spanner-hibernate with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Test
public void generateDeleteStringsWithIndices() throws IOException, SQLException {
  this.connection.setMetaData(MockJdbcUtils.metaDataBuilder()
      .setTables("Employee", "hibernate_sequence")
      .setIndices("name_index")
      .build());

  Metadata employeeMetadata =
      new MetadataSources(this.registry).addAnnotatedClass(Employee.class).buildMetadata();
  String testFileName = UUID.randomUUID().toString();
  new SchemaExport().setOutputFile(testFileName)
      .drop(EnumSet.of(TargetType.STDOUT, TargetType.SCRIPT), employeeMetadata);
  File scriptFile = new File(testFileName);
  scriptFile.deleteOnExit();
  List<String> statements = Files.readAllLines(scriptFile.toPath());

  assertThat(statements).containsExactly(
      "START BATCH DDL",
      "drop index name_index",
      "drop table Employee",
      "drop table hibernate_sequence",
      "RUN BATCH");
}
 
Example #2
Source File: HibernateUtil.java    From tutorials with MIT License 6 votes vote down vote up
/**
 * Generates database create commands for the specified entities using Hibernate native API, SchemaExport.
 * Creation commands are exported into the create.sql file.
 */
public static void generateSchema() {
    Map<String, String> settings = new HashMap<>();
    settings.put(Environment.URL, "jdbc:h2:mem:schema");

    StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(settings).build();

    MetadataSources metadataSources = new MetadataSources(serviceRegistry);
    metadataSources.addAnnotatedClass(Account.class);
    metadataSources.addAnnotatedClass(AccountSetting.class);
    Metadata metadata = metadataSources.buildMetadata();

    SchemaExport schemaExport = new SchemaExport();
    schemaExport.setFormat(true);
    schemaExport.setOutputFile("create.sql");
    schemaExport.createOnly(EnumSet.of(TargetType.SCRIPT), metadata);
}
 
Example #3
Source File: App.java    From juddi with Apache License 2.0 6 votes vote down vote up
/**
 * Method that actually creates the file.
 *
 * @param dbDialect to use
 */
private void generate(Dialect dialect) {

        StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder();
        ssrb.applySetting("hibernate.dialect", dialect.getDialectClass());
        StandardServiceRegistry standardServiceRegistry = ssrb.build();

        MetadataSources metadataSources = new MetadataSources(standardServiceRegistry);
        for (Class clzz : jpaClasses) {
                metadataSources.addAnnotatedClass(clzz);
        }

        Metadata metadata = metadataSources.buildMetadata();

        SchemaExport export = new SchemaExport();

        export.setDelimiter(";");
        export.setOutputFile(dialect.name().toLowerCase() + ".ddl");
        //export.execute(true, false, false, true);
        export.execute(EnumSet.of(TargetType.SCRIPT), Action.BOTH, metadata);
}
 
Example #4
Source File: DdlExporter.java    From sample-boot-hibernate with MIT License 6 votes vote down vote up
private void outputDdl(String packageName, String dialect, String fileName) {
    LocalSessionFactoryBean sfBean = sfBean(packageName, dialect);
    StandardServiceRegistry serviceRegistry = sfBean.getConfiguration().getStandardServiceRegistryBuilder().build();
    try {
        String outputFile = OutputRoot + fileName;
        Files.deleteIfExists(Paths.get(outputFile));
        Metadata metadata = metadata(serviceRegistry, sfBean.getMetadataSources());
        
        SchemaExport export = new SchemaExport();
        export.setDelimiter(";");
        export.setFormat(FormatSql);
        export.setOutputFile(outputFile);
        export.create(EnumSet.of(TargetType.SCRIPT, TargetType.STDOUT), metadata);
    } catch (Exception e) {
        throw new InvocationException(e);
    } finally {
        StandardServiceRegistryBuilder.destroy(serviceRegistry);
    }
}
 
Example #5
Source File: DdlExporter.java    From sample-boot-micro with MIT License 6 votes vote down vote up
private void outputDdl(String packageName, String dialect, String fileName) {
    LocalSessionFactoryBean sfBean = sfBean(packageName, dialect);
    StandardServiceRegistry serviceRegistry = sfBean.getConfiguration().getStandardServiceRegistryBuilder().build();
    try {
        String outputFile = OutputRoot + fileName;
        Files.deleteIfExists(Paths.get(outputFile));
        Metadata metadata = metadata(serviceRegistry, sfBean.getMetadataSources());
        
        SchemaExport export = new SchemaExport();
        export.setDelimiter(";");
        export.setFormat(FormatSql);
        export.setOutputFile(outputFile);
        export.create(EnumSet.of(TargetType.SCRIPT, TargetType.STDOUT), metadata);
    } catch (Exception e) {
        throw new InvocationException(e);
    } finally {
        StandardServiceRegistryBuilder.destroy(serviceRegistry);
    }
}
 
Example #6
Source File: TargetTypeHelper.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public static EnumSet<TargetType> parseCommandLineOptions(String targetTypeText) {
	final EnumSet<TargetType> options = EnumSet.noneOf( TargetType.class );

	if ( !targetTypeText.equalsIgnoreCase( "none" ) ) {
		for ( String option : targetTypeText.split( "," ) ) {
			if ( option.equalsIgnoreCase( "database" ) ) {
				options.add( TargetType.DATABASE );
			}
			else if ( option.equalsIgnoreCase( "stdout" ) ) {
				options.add( TargetType.STDOUT );
			}
			else if ( option.equalsIgnoreCase( "script" ) ) {
				options.add( TargetType.SCRIPT );
			}
			else {
				throw new IllegalArgumentException( "Unrecognized --target option : " + option );
			}
		}
	}

	return options;
}
 
Example #7
Source File: SchemaExport.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public static TargetDescriptor buildTargetDescriptor(
		EnumSet<TargetType> targetTypes,
		String outputFile,
		ServiceRegistry serviceRegistry) {
	final ScriptTargetOutput scriptTarget;
	if ( targetTypes.contains( TargetType.SCRIPT ) ) {
		if ( outputFile == null ) {
			throw new SchemaManagementException( "Writing to script was requested, but no script file was specified" );
		}
		scriptTarget = Helper.interpretScriptTargetSetting(
				outputFile,
				serviceRegistry.getService( ClassLoaderService.class ),
				(String) serviceRegistry.getService( ConfigurationService.class ).getSettings().get( AvailableSettings.HBM2DDL_CHARSET_NAME )
		);
	}
	else {
		scriptTarget = null;
	}

	return new TargetDescriptorImpl( targetTypes, scriptTarget );
}
 
Example #8
Source File: SchemaExport.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public void execute(EnumSet<TargetType> targetTypes, Action action, Metadata metadata, ServiceRegistry serviceRegistry) {
	if ( action == Action.NONE ) {
		LOG.debug( "Skipping SchemaExport as Action.NONE was passed" );
		return;
	}

	if ( targetTypes.isEmpty() ) {
		LOG.debug( "Skipping SchemaExport as no targets were specified" );
		return;
	}

	exceptions.clear();

	LOG.runningHbm2ddlSchemaExport();

	final TargetDescriptor targetDescriptor = buildTargetDescriptor( targetTypes, outputFile, serviceRegistry );

	doExecution( action, needsJdbcConnection( targetTypes ), metadata, serviceRegistry, targetDescriptor );
}
 
Example #9
Source File: DefaultPersistManager.java    From onedev with MIT License 6 votes vote down vote up
protected void cleanDatabase(Metadata metadata) {
	File tempFile = null;
   	try {
       	tempFile = File.createTempFile("schema", ".sql");
       	new SchemaExport().setOutputFile(tempFile.getAbsolutePath())
       			.setFormat(false).drop(EnumSet.of(TargetType.SCRIPT), metadata);
       	List<String> sqls = new ArrayList<>();
       	for (String sql: FileUtils.readLines(tempFile, Charset.defaultCharset())) {
       		sqls.add(sql);
       	}
       	execute(sqls, false);
   	} catch (IOException e) {
   		throw new RuntimeException(e);
   	} finally {
   		if (tempFile != null)
   			tempFile.delete();
   	}
}
 
Example #10
Source File: DefaultPersistManager.java    From onedev with MIT License 6 votes vote down vote up
protected void createTables(Metadata metadata) {
	File tempFile = null;
   	try {
       	tempFile = File.createTempFile("schema", ".sql");
       	new SchemaExport().setOutputFile(tempFile.getAbsolutePath())
       			.setFormat(false).createOnly(EnumSet.of(TargetType.SCRIPT), metadata);
       	List<String> sqls = new ArrayList<>();
       	for (String sql: FileUtils.readLines(tempFile, Charset.defaultCharset())) {
       		if (shouldInclude(sql) && !isApplyingConstraints(sql))
       			sqls.add(sql);
       	}
       	execute(sqls, true);
   	} catch (IOException e) {
   		throw new RuntimeException(e);
   	} finally {
   		if (tempFile != null)
   			FileUtils.deleteFile(tempFile);
   	}
}
 
Example #11
Source File: SpannerTableExporterTests.java    From google-cloud-spanner-hibernate with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Test
public void generateDropStringsTest() throws IOException, SQLException {

  this.connection.setMetaData(MockJdbcUtils.metaDataBuilder()
      .setTables("test_table", "TestEntity_stringList")
      .build());

  String testFileName = UUID.randomUUID().toString();
  new SchemaExport().setOutputFile(testFileName)
      .drop(EnumSet.of(TargetType.STDOUT, TargetType.SCRIPT), this.metadata);
  File scriptFile = new File(testFileName);
  scriptFile.deleteOnExit();
  List<String> statements = Files.readAllLines(scriptFile.toPath());
  assertThat(statements)
      .containsExactly(
          "START BATCH DDL",
          "drop table `TestEntity_stringList`",
          "drop table `test_table`",
          "RUN BATCH");
}
 
Example #12
Source File: SpannerTableExporterTests.java    From google-cloud-spanner-hibernate with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Test
public void omitCreatingPreexistingTables() throws IOException, SQLException {
  this.connection.setMetaData(MockJdbcUtils.metaDataBuilder()
      .setTables("Employee")
      .build());

  Metadata employeeMetadata =
      new MetadataSources(this.registry).addAnnotatedClass(Employee.class).buildMetadata();
  String testFileName = UUID.randomUUID().toString();
  new SchemaExport().setOutputFile(testFileName)
      .createOnly(EnumSet.of(TargetType.STDOUT, TargetType.SCRIPT), employeeMetadata);
  File scriptFile = new File(testFileName);
  scriptFile.deleteOnExit();
  List<String> statements = Files.readAllLines(scriptFile.toPath());

  assertThat(statements).containsExactly(
      // This omits creating the Employee table since it is declared to exist in metadata.
      "START BATCH DDL",
      "create table hibernate_sequence (next_val INT64) PRIMARY KEY ()",
      "create index name_index on Employee (name)",
      "alter table Employee add constraint FKiralam2duuhr33k8a10aoc2t6 "
          + "foreign key (manager_id) references Employee (id)",
      "RUN BATCH",
      "INSERT INTO hibernate_sequence (next_val) VALUES(1)"
  );
}
 
Example #13
Source File: SpannerTableExporterTests.java    From google-cloud-spanner-hibernate with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Test
public void generateCreateStringsNoPkEntityTest() {
  assertThatThrownBy(() -> {
    Metadata metadata = new MetadataSources(this.registry)
        .addAnnotatedClass(NoPkEntity.class)
        .buildMetadata();

    new SchemaExport()
        .setOutputFile("unused")
        .createOnly(EnumSet.of(TargetType.STDOUT, TargetType.SCRIPT), metadata);
  })
      .isInstanceOf(AnnotationException.class)
      .hasMessage(
          "No identifier specified for entity: "
              + "com.google.cloud.spanner.hibernate.SpannerTableExporterTests$NoPkEntity");
}
 
Example #14
Source File: DefaultPersistManager.java    From onedev with MIT License 6 votes vote down vote up
protected void applyConstraints(Metadata metadata) {
	File tempFile = null;
   	try {
       	tempFile = File.createTempFile("schema", ".sql");
       	new SchemaExport().setOutputFile(tempFile.getAbsolutePath())
       			.setFormat(false).createOnly(EnumSet.of(TargetType.SCRIPT), metadata);
       	List<String> sqls = new ArrayList<>();
       	for (String sql: FileUtils.readLines(tempFile, Charset.defaultCharset())) {
       		if (isApplyingConstraints(sql)) {
       			sqls.add(sql);
       		}
       	}
       	execute(sqls, true);
   	} catch (IOException e) {
   		throw new RuntimeException(e);
   	} finally {
   		if (tempFile != null)
   			tempFile.delete();
   	}
}
 
Example #15
Source File: DefaultPersistManager.java    From onedev with MIT License 6 votes vote down vote up
protected void dropConstraints(Metadata metadata) {
	File tempFile = null;
   	try {
       	tempFile = File.createTempFile("schema", ".sql");
       	new SchemaExport().setOutputFile(tempFile.getAbsolutePath())
       			.setFormat(false).drop(EnumSet.of(TargetType.SCRIPT), metadata);
       	List<String> sqls = new ArrayList<>();
       	for (String sql: FileUtils.readLines(tempFile, Charset.defaultCharset())) {
       		if (isDroppingConstraints(sql))
       			sqls.add(sql);
       	}
       	execute(sqls, false);
   	} catch (IOException e) {
   		throw new RuntimeException(e);
   	} finally {
   		if (tempFile != null)
   			tempFile.delete();
   	}
}
 
Example #16
Source File: Hbm2ddl.java    From wallride with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
	String locationPattern = "classpath:/org/wallride/domain/*";

	final BootstrapServiceRegistry registry = new BootstrapServiceRegistryBuilder().build();
	final MetadataSources metadataSources = new MetadataSources(registry);
	final StandardServiceRegistryBuilder registryBuilder = new StandardServiceRegistryBuilder(registry);

	registryBuilder.applySetting(AvailableSettings.DIALECT, ExtendedMySQL5InnoDBDialect.class.getCanonicalName());
	registryBuilder.applySetting(AvailableSettings.GLOBALLY_QUOTED_IDENTIFIERS, true);
	registryBuilder.applySetting(AvailableSettings.PHYSICAL_NAMING_STRATEGY, PhysicalNamingStrategySnakeCaseImpl.class);

	final PathMatchingResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
	final Resource[] resources = resourcePatternResolver.getResources(locationPattern);
	final SimpleMetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory();
	for (Resource resource : resources) {
		MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
		AnnotationMetadata metadata = metadataReader.getAnnotationMetadata();
		if (metadata.hasAnnotation(Entity.class.getName())) {
			metadataSources.addAnnotatedClass(Class.forName(metadata.getClassName()));
		}
	}

	final StandardServiceRegistryImpl registryImpl = (StandardServiceRegistryImpl) registryBuilder.build();
	final MetadataBuilder metadataBuilder = metadataSources.getMetadataBuilder(registryImpl);

	new SchemaExport()
			.setHaltOnError(true)
			.setDelimiter(";")
			.create(EnumSet.of(TargetType.STDOUT), metadataBuilder.build());
}
 
Example #17
Source File: SchemaExport.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * For testing use
 */
public void perform(Action action, Metadata metadata, ScriptTargetOutput target) {
	doExecution(
			action,
			false,
			metadata,
			( (MetadataImplementor) metadata ).getMetadataBuildingOptions().getServiceRegistry(),
			new TargetDescriptorImpl( EnumSet.of( TargetType.SCRIPT ), target )
	);
}
 
Example #18
Source File: SchemaExport.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public TargetDescriptorImpl(
		EnumSet<TargetType> targetTypes,
		ScriptTargetOutput scriptTarget) {

	this.targetTypes = targetTypes;
	this.scriptTarget = scriptTarget;
}
 
Example #19
Source File: SpannerTableExporterTests.java    From google-cloud-spanner-hibernate with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
public void generateCreateStringsTest() throws IOException {
  String testFileName = UUID.randomUUID().toString();
  new SchemaExport().setOutputFile(testFileName)
      .createOnly(EnumSet.of(TargetType.STDOUT, TargetType.SCRIPT), this.metadata);
  File scriptFile = new File(testFileName);
  scriptFile.deleteOnExit();
  List<String> statements = Files.readAllLines(scriptFile.toPath());

  // The types in the following string need to be updated when SpannerDialect
  // implementation maps types.
  String expectedCreateString = "create table `test_table` (`ID1` INT64 not null,id2"
      + " STRING(255) not null,`boolColumn` BOOL,longVal INT64 not null,stringVal"
      + " STRING(255)) PRIMARY KEY (`ID1`,id2)";

  String expectedCollectionCreateString = "create table `TestEntity_stringList` "
      + "(`TestEntity_ID1` INT64 not null,`TestEntity_id2` STRING(255) not null,"
      + "stringList STRING(255)) PRIMARY KEY (`TestEntity_ID1`,`TestEntity_id2`,stringList)";

  String foreignKeyString =
      "alter table `TestEntity_stringList` add constraint FK2is6fwy3079dmfhjot09x5och "
          + "foreign key (`TestEntity_ID1`, `TestEntity_id2`) "
          + "references `test_table` (`ID1`, id2)";

  assertThat(statements.get(0)).isEqualTo("START BATCH DDL");
  assertThat(statements.subList(1, 4))
      .containsExactlyInAnyOrder(
          expectedCreateString, expectedCollectionCreateString, foreignKeyString);
  assertThat(statements.get(4)).isEqualTo("RUN BATCH");
}
 
Example #20
Source File: SchemaUpdate.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public void execute(EnumSet<TargetType> targetTypes, Metadata metadata, ServiceRegistry serviceRegistry) {
	if ( targetTypes.isEmpty() ) {
		LOG.debug( "Skipping SchemaExport as no targets were specified" );
		return;
	}

	exceptions.clear();
	LOG.runningHbm2ddlSchemaUpdate();

	Map config = new HashMap();
	config.putAll( serviceRegistry.getService( ConfigurationService.class ).getSettings() );
	config.put( AvailableSettings.HBM2DDL_DELIMITER, delimiter );
	config.put( AvailableSettings.FORMAT_SQL, format );

	final SchemaManagementTool tool = serviceRegistry.getService( SchemaManagementTool.class );

	final ExceptionHandler exceptionHandler = haltOnError
			? ExceptionHandlerHaltImpl.INSTANCE
			: new ExceptionHandlerCollectingImpl();

	final ExecutionOptions executionOptions = SchemaManagementToolCoordinator.buildExecutionOptions(
			config,
			exceptionHandler
	);

	final TargetDescriptor targetDescriptor = SchemaExport.buildTargetDescriptor( targetTypes, outputFile, serviceRegistry );

	try {
		tool.getSchemaMigrator( config ).doMigration( metadata, executionOptions, targetDescriptor );
	}
	finally {
		if ( exceptionHandler instanceof ExceptionHandlerCollectingImpl ) {
			exceptions.addAll( ( (ExceptionHandlerCollectingImpl) exceptionHandler ).getExceptions() );
		}
	}
}
 
Example #21
Source File: TargetTypeHelper.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public static EnumSet<TargetType> parseLegacyCommandLineOptions(boolean script, boolean export, String outputFile) {
	final EnumSet<TargetType> options = EnumSet.noneOf( TargetType.class );

	final Target target = Target.interpret( script, export );
	if ( outputFile != null ) {
		options.add( TargetType.SCRIPT );
	}
	if ( target.doScript() ) {
		options.add( TargetType.STDOUT );
	}
	if ( target.doExport() ) {
		options.add( TargetType.DATABASE );
	}
	return options;
}
 
Example #22
Source File: ModelDBHibernateUtil.java    From modeldb with Apache License 2.0 5 votes vote down vote up
private static void exportSchema(Metadata buildMetadata) {
  String rootPath = System.getProperty(ModelDBConstants.userDir);
  rootPath = rootPath + "\\src\\main\\resources\\liquibase\\hibernate-base-db-schema.sql";
  new SchemaExport()
      .setDelimiter(";")
      .setOutputFile(rootPath)
      .create(EnumSet.of(TargetType.SCRIPT), buildMetadata);
}
 
Example #23
Source File: SpannerTableExporterTests.java    From google-cloud-spanner-hibernate with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
public void generateCreateStringsEmptyEntityTest() {
  assertThatThrownBy(() -> {
    Metadata metadata = new MetadataSources(this.registry)
        .addAnnotatedClass(EmptyEntity.class)
        .buildMetadata();
    new SchemaExport()
        .setOutputFile("unused")
        .createOnly(EnumSet.of(TargetType.STDOUT, TargetType.SCRIPT), metadata);
  })
      .isInstanceOf(AnnotationException.class)
      .hasMessage(
          "No identifier specified for entity: "
              + "com.google.cloud.spanner.hibernate.SpannerTableExporterTests$EmptyEntity");
}
 
Example #24
Source File: HibernateSchemaManagementTool.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
GenerationTarget[] buildGenerationTargets(
		TargetDescriptor targetDescriptor,
		DdlTransactionIsolator ddlTransactionIsolator,
		Map options) {
	final String scriptDelimiter = ConfigurationHelper.getString( HBM2DDL_DELIMITER, options );

	final GenerationTarget[] targets = new GenerationTarget[ targetDescriptor.getTargetTypes().size() ];

	int index = 0;

	if ( targetDescriptor.getTargetTypes().contains( TargetType.STDOUT ) ) {
		targets[index] = new GenerationTargetToStdout( scriptDelimiter );
		index++;
	}

	if ( targetDescriptor.getTargetTypes().contains( TargetType.SCRIPT ) ) {
		if ( targetDescriptor.getScriptTargetOutput() == null ) {
			throw new SchemaManagementException( "Writing to script was requested, but no script file was specified" );
		}
		targets[index] = new GenerationTargetToScript( targetDescriptor.getScriptTargetOutput(), scriptDelimiter );
		index++;
	}

	if ( targetDescriptor.getTargetTypes().contains( TargetType.DATABASE ) ) {
		targets[index] = new GenerationTargetToDatabase( ddlTransactionIsolator, false );
	}

	return targets;
}
 
Example #25
Source File: HibernateSchemaManagementTool.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
GenerationTarget[] buildGenerationTargets(
		TargetDescriptor targetDescriptor,
		JdbcContext jdbcContext,
		Map options,
		boolean needsAutoCommit) {
	final String scriptDelimiter = ConfigurationHelper.getString( HBM2DDL_DELIMITER, options );

	final GenerationTarget[] targets = new GenerationTarget[ targetDescriptor.getTargetTypes().size() ];

	int index = 0;

	if ( targetDescriptor.getTargetTypes().contains( TargetType.STDOUT ) ) {
		targets[index] = new GenerationTargetToStdout( scriptDelimiter );
		index++;
	}

	if ( targetDescriptor.getTargetTypes().contains( TargetType.SCRIPT ) ) {
		if ( targetDescriptor.getScriptTargetOutput() == null ) {
			throw new SchemaManagementException( "Writing to script was requested, but no script file was specified" );
		}
		targets[index] = new GenerationTargetToScript( targetDescriptor.getScriptTargetOutput(), scriptDelimiter );
		index++;
	}

	if ( targetDescriptor.getTargetTypes().contains( TargetType.DATABASE ) ) {
		targets[index] = new GenerationTargetToDatabase( getDdlTransactionIsolator( jdbcContext ), true );
	}

	return targets;
}
 
Example #26
Source File: SchemaManagementToolCoordinator.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
private static JpaTargetAndSourceDescriptor buildScriptTargetDescriptor(
		Map configurationValues,
		SettingSelector settingSelector,
		ServiceRegistry serviceRegistry) {
	final Object scriptSourceSetting = settingSelector.getScriptSourceSetting( configurationValues );
	final SourceType sourceType = SourceType.interpret(
			settingSelector.getSourceTypeSetting( configurationValues ),
			scriptSourceSetting != null ? SourceType.SCRIPT : SourceType.METADATA
	);

	final boolean includesScripts = sourceType != SourceType.METADATA;
	if ( includesScripts && scriptSourceSetting == null ) {
		throw new SchemaManagementException(
				"Schema generation configuration indicated to include CREATE scripts, but no script was specified"
		);
	}

	String charsetName = (String) configurationValues.get( AvailableSettings.HBM2DDL_CHARSET_NAME );

	final ScriptSourceInput scriptSourceInput = includesScripts
			? Helper.interpretScriptSourceSetting( scriptSourceSetting, serviceRegistry.getService( ClassLoaderService.class ), charsetName )
			: null;

	final ScriptTargetOutput scriptTargetOutput = Helper.interpretScriptTargetSetting(
			settingSelector.getScriptTargetSetting( configurationValues ),
			serviceRegistry.getService( ClassLoaderService.class ),
			charsetName
	);

	return new JpaTargetAndSourceDescriptor() {
		@Override
		public EnumSet<TargetType> getTargetTypes() {
			return EnumSet.of( TargetType.SCRIPT );
		}

		@Override
		public ScriptTargetOutput getScriptTargetOutput() {
			return scriptTargetOutput;
		}

		@Override
		public SourceType getSourceType() {
			return sourceType;
		}

		@Override
		public ScriptSourceInput getScriptSourceInput() {
			return scriptSourceInput;
		}
	};
}
 
Example #27
Source File: SchemaExport.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public void drop(EnumSet<TargetType> targetTypes, Metadata metadata) {
	execute( targetTypes, Action.DROP, metadata );
}
 
Example #28
Source File: HibernateDatabase.java    From livingdoc-confluence with GNU General Public License v3.0 4 votes vote down vote up
public void createDatabase() throws HibernateException {
    // executes a drop and a create!
    new SchemaExport().create(EnumSet.of(TargetType.DATABASE), metadata);
}
 
Example #29
Source File: SchemaGenerator.java    From jpa2ddl with Apache License 2.0 4 votes vote down vote up
void generate(GeneratorSettings settings) throws Exception {
	validateSettings(settings);

	if (settings.getJpaProperties().getProperty(HIBERNATE_DIALECT) == null) {
		settings.getJpaProperties().setProperty(HIBERNATE_DIALECT, "org.hibernate.dialect.H2Dialect");
	}

	if (settings.isSkipSequences() && settings.getJpaProperties().getProperty(HIBERNATE_SCHEMA_FILTER_PROVIDER) == null) {
		settings.getJpaProperties().setProperty(HIBERNATE_SCHEMA_FILTER_PROVIDER, NoSequenceFilterProvider.class.getCanonicalName());
	}

	File outputFile = settings.getOutputPath();

	EngineDecorator engineDecorator = EngineDecorator.getEngineDecorator(settings.getJpaProperties().getProperty(HIBERNATE_DIALECT));

	if (settings.getGenerationMode() == GenerationMode.DATABASE) {

		String dbUrl = engineDecorator.decorateConnectionString(DB_URL);

		if (settings.getAction() == Action.UPDATE) {
			outputFile = FileResolver.resolveNextMigrationFile(settings.getOutputPath());
		}

		settings.getJpaProperties().setProperty("hibernate.connection.url", dbUrl);
		settings.getJpaProperties().setProperty("hibernate.connection.username", "sa");
		settings.getJpaProperties().setProperty("hibernate.connection.password", "");
		settings.getJpaProperties().setProperty("javax.persistence.schema-generation.scripts.action", settings.getAction().toSchemaGenerationAction());

		settings.getJpaProperties().setProperty("javax.persistence.schema-generation.scripts.create-target", outputFile.getAbsolutePath());
		settings.getJpaProperties().setProperty("javax.persistence.schema-generation.scripts.drop-target", outputFile.getAbsolutePath());

		settings.getJpaProperties().setProperty("hibernate.hbm2ddl.delimiter", settings.getDelimiter());
		settings.getJpaProperties().setProperty("hibernate.format_sql", String.valueOf(settings.isFormatOutput()));
	}

	MetadataSources metadata = new MetadataSources(
			new StandardServiceRegistryBuilder()
					.applySettings(settings.getJpaProperties())
					.build());

	for (String packageName: settings.getPackages().stream().sorted().collect(Collectors.toList())) {
		FileResolver.listClassNamesInPackage(packageName).stream().sorted().forEach(metadata::addAnnotatedClassName);
		metadata.addPackage(packageName);
	}

	if (settings.getAction() != Action.UPDATE) {
		Files.deleteIfExists(settings.getOutputPath().toPath());
	}

	if (settings.getGenerationMode() == GenerationMode.METADATA) {
		SchemaExport export = new SchemaExport();
		export.setFormat(settings.isFormatOutput());
		export.setDelimiter(settings.getDelimiter());
		export.setOutputFile(outputFile.getAbsolutePath());
		export.execute(EnumSet.of(TargetType.SCRIPT), settings.getAction().toSchemaExportAction(), metadata.buildMetadata());
	} else {
		Connection connection = null;
		if (settings.getAction() == Action.UPDATE) {
			connection = DriverManager.getConnection(DB_URL, "SA", "");

			engineDecorator.decorateDatabaseInitialization(connection);

			List<Path> resolvedMigrations = FileResolver.resolveExistingMigrations(settings.getOutputPath(), false, true);
			for (Path resolvedMigration : resolvedMigrations) {
				String statement = new String(Files.readAllBytes(resolvedMigration));
				connection.prepareStatement(statement).execute();
			}
		}

		metadata.buildMetadata().buildSessionFactory().close();

		if (connection != null) {
			connection.close();
		}
	}

	if (outputFile.exists()) {
		if (outputFile.length() == 0) {
			Files.delete(outputFile.toPath());
		} else {
			List<String> lines = Files.readAllLines(outputFile.toPath())
					.stream()
					.map(line -> line.replaceAll("(?i)JPA2DDL\\.(PUBLIC\\.)?", ""))
					.collect(Collectors.toList());
			Files.write(outputFile.toPath(), lines);
		}
	}
}
 
Example #30
Source File: SchemaExport.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public void execute(EnumSet<TargetType> targetTypes, Action action, Metadata metadata) {
	execute( targetTypes, action, metadata, ( (MetadataImplementor) metadata ).getMetadataBuildingOptions().getServiceRegistry() );
}