Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(datastore): add table migration #3003

Merged
merged 2 commits into from
Nov 21, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import ai.starwhale.mlops.exception.SwProcessException;
import ai.starwhale.mlops.exception.SwProcessException.ErrorType;
import ai.starwhale.mlops.exception.SwValidationException;
import ai.starwhale.mlops.exception.SwValidationException.ValidSubject;
import ai.starwhale.mlops.storage.StorageAccessService;
import java.io.IOException;
import java.lang.ref.SoftReference;
Expand Down Expand Up @@ -223,6 +224,63 @@ public void flush() {
this.walManager.flush();
}

public int migration(DataStoreMigrationRequest req) {
if (req.getSrcTableName().equals(req.getTargetTableName())) {
throw new SwValidationException(
ValidSubject.DATASTORE, "Source and target table names cannot be the same");
}
var srcTable = this.getTable(req.getSrcTableName(), false, false);
var targetTable = this.getTable(req.getTargetTableName(), true, req.isCreateNonExistingTargetTable());
if (srcTable == null || targetTable == null) {
throw new SwValidationException(ValidSubject.DATASTORE, "Source or target table doesn't exist");
}
this.updateHandle.offer(new Object());
srcTable.lock(true);
targetTable.lock(false);
try {
int skipCount = req.getStart();
if (skipCount < 0) {
skipCount = 0;
}

var schema = srcTable.getSchema();
var columns = this.getColumnAliases(schema, req.getColumns());
var records = new ArrayList<Map<String, BaseValue>>();
var revision = req.getSrcRevision();
if (revision == 0) {
revision = srcTable.getLastRevision();
}
var iterator = srcTable.query(
revision,
columns,
null,
req.getFilter(),
true);
while (iterator.hasNext() && skipCount > 0) {
iterator.next();
--skipCount;
}
while (iterator.hasNext()) {
var r = iterator.next();
if (r.isDeleted()) {
continue;
}
records.add(r.getValues());
}
if (!records.isEmpty()) {
targetTable.updateWithObject(srcTable.getSchema().toTableSchemaDesc(), records);
}
return records.size();
} finally {
this.updateHandle.poll();
synchronized (updateHandle) {
updateHandle.notifyAll();
}
targetTable.unlock(false);
srcTable.unlock(true);
}
}

public RecordList query(DataStoreQueryRequest req) {
var table = this.getTable(req.getTableName(), req.isIgnoreNonExistingTable(), false);
if (table == null) {
Expand Down Expand Up @@ -254,8 +312,7 @@ public RecordList query(DataStoreQueryRequest req) {
columns,
req.getOrderBy(),
req.getFilter(),
req.isKeepNone(),
req.isRawResult());
req.isKeepNone());
while (iterator.hasNext() && skipCount > 0) {
iterator.next();
--skipCount;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/*
* Copyright 2022 Starwhale, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package ai.starwhale.mlops.datastore;

import java.util.Map;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class DataStoreMigrationRequest {

private String srcTableName;
private long srcRevision;
private Map<String, String> columns;
private TableQueryFilter filter;
@Builder.Default
private int start = -1;

private String targetTableName;
private boolean createNonExistingTargetTable;
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

package ai.starwhale.mlops.datastore;

import ai.starwhale.mlops.datastore.type.BaseValue;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
Expand All @@ -32,12 +33,13 @@ public interface MemoryTable {
// update records, returns the timestamp in milliseconds
long update(TableSchemaDesc schema, List<Map<String, Object>> records);

long updateWithObject(TableSchemaDesc schema, List<Map<String, BaseValue>> records);

Iterator<RecordResult> query(long timestamp,
Map<String, String> columns,
List<OrderByDesc> orderBy,
TableQueryFilter filter,
boolean keepNone,
boolean rawResult);
boolean keepNone);

Iterator<RecordResult> scan(
long timestamp,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -378,6 +378,11 @@ public long update(TableSchemaDesc schema, @NonNull List<Map<String, Object>> re
}
decodedRecords.add(decodedRecord);
}
return this.updateWithObject(schema, decodedRecords);
}

@Override
public long updateWithObject(TableSchemaDesc schema, @NonNull List<Map<String, BaseValue>> records) {
var revision = this.useTimestampAsRevision ? System.currentTimeMillis() : this.lastRevision + 1;
var logEntryBuilder = Wal.WalEntry.newBuilder()
.setEntryType(Wal.WalEntry.Type.UPDATE)
Expand All @@ -394,7 +399,7 @@ public long update(TableSchemaDesc schema, @NonNull List<Map<String, Object>> re
recordSchema = new TableSchema(this.schema);
recordSchema.update(logSchemaBuilder.build());
}
for (var record : decodedRecords) {
for (var record : records) {
logEntryBuilder.addRecords(WalRecordEncoder.encodeRecord(recordSchema, record));
}
this.lastWalLogId = this.walManager.append(logEntryBuilder);
Expand All @@ -403,8 +408,8 @@ public long update(TableSchemaDesc schema, @NonNull List<Map<String, Object>> re
}
this.lastUpdateTime = System.currentTimeMillis();
this.schema = recordSchema;
if (!decodedRecords.isEmpty()) {
this.insertRecords(revision, decodedRecords);
if (!records.isEmpty()) {
this.insertRecords(revision, records);
}
return revision;
}
Expand Down Expand Up @@ -493,8 +498,7 @@ public Iterator<RecordResult> query(
@NonNull Map<String, String> columns,
List<OrderByDesc> orderBy,
TableQueryFilter filter,
boolean keepNone,
boolean rawResult) {
boolean keepNone) {
if (this.schema.getKeyColumn() == null) {
return Collections.emptyIterator();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,87 @@ public void testUpdate() {
is(List.of(Map.of("k", "3", "x", "00000002"))));
}

@Test
public void testMigration() {
var srcTable = "t1";
var srcDesc = new TableSchemaDesc("k",
List.of(ColumnSchemaDesc.string().name("k").build(),
ColumnSchemaDesc.int32().name("a").build()));
this.dataStore.update(srcTable,
srcDesc,
List.of(Map.of("k", "0", "a", "5"),
Map.of("k", "1", "a", "4"),
Map.of("k", "2", "a", "3"),
Map.of("k", "3", "a", "2"),
Map.of("k", "4", "a", "1"))
);
var targetTable = "t2";

// case: target table doesn't exist and don't allow to create
assertThrows(
SwValidationException.class,
() -> this.dataStore.migration(DataStoreMigrationRequest.builder()
.srcTableName(srcTable)
.targetTableName(targetTable)
.createNonExistingTargetTable(false)
.build())
);

// case: target table doesn't exist but allow to create, migration with filter
var length = this.dataStore.migration(DataStoreMigrationRequest.builder()
.srcTableName(srcTable)
.targetTableName(targetTable)
.filter(TableQueryFilter.builder()
.operator(Operator.OR)
.operands(List.of(
TableQueryFilter.builder()
.operator(Operator.EQUAL)
.operands(List.of(
new TableQueryFilter.Column("k"),
new TableQueryFilter.Constant(
ColumnType.STRING, "0")
))
.build(),
TableQueryFilter.builder()
.operator(Operator.EQUAL)
.operands(List.of(
new TableQueryFilter.Column("k"),
new TableQueryFilter.Constant(
ColumnType.STRING, "2")
))
.build()
))
.build()
)
.createNonExistingTargetTable(true)
.build());
assertEquals(2, length);

var recordList = this.dataStore.query(
DataStoreQueryRequest.builder()
.tableName(targetTable)
.columns(Map.of("a", "a"))
.build()
);
assertEquals(2, recordList.getRecords().size());

// case: migration all records without filter
length = this.dataStore.migration(DataStoreMigrationRequest.builder()
.srcTableName(srcTable)
.targetTableName(targetTable)
.createNonExistingTargetTable(true)
.build());
assertEquals(5, length);

recordList = this.dataStore.query(
DataStoreQueryRequest.builder()
.tableName(targetTable)
.columns(Map.of("a", "a"))
.build()
);
assertEquals(5, recordList.getRecords().size());
}

@Test
public void testQuery() {
var desc = new TableSchemaDesc("k",
Expand Down
Loading
Loading