PostgresDataStorage implements DataStorage<R> { @Override public DataAndId<R> getCurrentData() { try { try (Connection connection = dataSource.getConnection()){ ensureTablesAreAvailable(connection); try ( PreparedStatement pstmt = connection.prepareStatement("select cast (root as text) as root, cast (metadata as text) as metadata from currentconfiguration"); ResultSet rs = pstmt.executeQuery()) { if (!rs.next()) { StoredDataMetadata metadata = new StoredDataMetadata(LocalDateTime.now(), UUID.randomUUID().toString(), "System", "initial factory", UUID.randomUUID().toString(), null, initialData.internal().createDataStorageMetadataDictionaryFromRoot(),null ); updateCurrentFactory(connection, new DataAndStoredMetadata<>(initialData,metadata)); connection.commit(); return new DataAndId<>(initialData, metadata.id); } else { StoredDataMetadata metaData = migrationManager.readStoredFactoryMetadata(rs.getString(2)); return new DataAndId<>(migrationManager.read(rs.getString(1),metaData.dataStorageMetadataDictionary), metaData.id); } } } } catch (SQLException e) { throw new RuntimeException("Cannot read current factory",e); } } PostgresDataStorage(DataSource dataSource, R initialDataParam, MigrationManager<R> migrationManager, SimpleObjectMapper objectMapper); @Override R getHistoryData(String id); @Override Collection<StoredDataMetadata> getHistoryDataList(); @Override DataAndId<R> getCurrentData(); @Override void updateCurrentData(DataUpdate<R> update, UpdateSummary changeSummary); @Override void patchAll(DataStoragePatcher consumer); @Override void patchCurrentData(DataStoragePatcher consumer); @Override Collection<ScheduledUpdateMetadata> getFutureDataList(); @Override void deleteFutureData(String id); R getFutureData(String id); @Override void addFutureData(ScheduledUpdate<R> futureFactory);  }
@Test public void test_init_no_existing_factory() throws SQLException { PostgresDataStorage<ExampleFactoryA> postgresFactoryStorage = new PostgresDataStorage<>(postgresDatasource, createInitialExampleFactoryA(), createDataMigrationManager(),ObjectMapperBuilder.build()); postgresFactoryStorage.getCurrentData(); try (Connection con = postgresDatasource.getConnection()) { for (String sql : Arrays.asList("select * from currentconfiguration" ,"select * from configurationmetadata" ,"select * from configuration")) { PreparedStatement pstmt = con.prepareStatement(sql); try (ResultSet rs = pstmt.executeQuery()) { Assertions.assertTrue(rs.next()); } } } }
@Test public void test_init_existing_factory() { PostgresDataStorage<ExampleFactoryA> postgresFactoryStorage = new PostgresDataStorage<>(postgresDatasource, createInitialExampleFactoryA(), createDataMigrationManager(),ObjectMapperBuilder.build()); String id=postgresFactoryStorage.getCurrentData().id; PostgresDataStorage<ExampleFactoryA> restored = new PostgresDataStorage<>(postgresDatasource, null, createDataMigrationManager(),ObjectMapperBuilder.build()); Assertions.assertEquals(id,restored.getCurrentData().id); }