001package io.ebeaninternal.dbmigration.model;
002
003import org.slf4j.Logger;
004import org.slf4j.LoggerFactory;
005
006import io.ebean.migration.MigrationVersion;
007
008import java.io.File;
009import java.util.ArrayList;
010import java.util.Collections;
011import java.util.List;
012
013/**
014 * Build the model from the series of migrations.
015 */
016public class MigrationModel {
017
018  private static final Logger logger = LoggerFactory.getLogger(MigrationModel.class);
019
020  private final ModelContainer model = new ModelContainer();
021  private final File modelDirectory;
022  private final String modelSuffix;
023
024  public MigrationModel(File modelDirectory, String modelSuffix) {
025    this.modelDirectory = modelDirectory;
026    this.modelSuffix = modelSuffix;
027  }
028
029  /**
030   * Read all the migrations returning the model with all
031   * the migrations applied in version order.
032   *
033   * @param initMigration If true we don't apply model changes, migration is from scratch.
034   */
035  public ModelContainer read(boolean initMigration) {
036    readMigrations(initMigration);
037    return model;
038  }
039
040  private void readMigrations(boolean initMigration) {
041    // find all the migration xml files
042    File[] xmlFiles = modelDirectory.listFiles(pathname -> pathname.getName().toLowerCase().endsWith(modelSuffix));
043    if (xmlFiles == null || xmlFiles.length == 0) {
044      return;
045    }
046    List<MigrationResource> resources = new ArrayList<>(xmlFiles.length);
047    for (File xmlFile : xmlFiles) {
048      resources.add(new MigrationResource(xmlFile, createVersion(xmlFile)));
049    }
050
051    // sort into version order before applying
052    Collections.sort(resources);
053
054    if (!initMigration) {
055      for (MigrationResource migrationResource : resources) {
056        logger.debug("read {}", migrationResource);
057        model.apply(migrationResource.read(), migrationResource.version());
058      }
059    }
060  }
061
062  private MigrationVersion createVersion(File xmlFile) {
063    String fileName = xmlFile.getName();
064    String versionName = fileName.substring(0, fileName.length() - modelSuffix.length());
065    return MigrationVersion.parse(versionName);
066  }
067}