source stringlengths 14 113 | code stringlengths 10 21.3k |
|---|---|
application-dev\database\data-persistence-by-graph-store.md | const CREATE_GRAPH = "CREATE GRAPH test " +
"{ (person:Person {name STRING, age INT}),(person)-[:Friend {year INT}]->(person) };"
if(store != null) {
(store as graphStore.GraphStore).write(CREATE_GRAPH).then(() => {
console.info('Create graph successfully');
}).catch((err: BusinessError) => {
console.error(`Create graph failed, code is ${err.code}, message is ${err.message}`);
})
} |
application-dev\database\data-persistence-by-graph-store.md | const INSERT_VERTEX_1 = "INSERT (:Person {name: 'name_1', age: 11});";
const INSERT_VERTEX_2 = "INSERT (:Person {name: 'name_2', age: 22});";
const INSERT_VERTEX_3 = "INSERT (:Person {name: 'name_3', age: 0});";
const UPDATE_VERTEX_3 = "MATCH (p:Person) WHERE p.name='name_3' SET p.age=33;"
const INSERT_EDGE_12 = "MATCH (p1:Person {name: 'name_1'}), (p2:Person {name: 'name_2'}) " +
"INSERT (p1)-[:Friend {year: 12}]->(p2);";
const INSERT_EDGE_23 = "MATCH (p2:Person {name: 'name_2'}), (p3:Person {name: 'name_3'}) " +
"INSERT (p2)-[:Friend {year: 0}]->(p3);";
const UPDATE_EDGE_23 = "MATCH (p2:Person {name: 'name_2'})-[relation:Friend]->(p3:Person {name: 'name_3'})" +
" SET relation.year=23;";
let writeList = [
INSERT_VERTEX_1,
INSERT_VERTEX_2,
INSERT_VERTEX_3,
UPDATE_VERTEX_3,
INSERT_EDGE_12,
INSERT_EDGE_23,
UPDATE_EDGE_23,
]
if(store != null) {
writeList.forEach((gql) => {
(store as graphStore.GraphStore).write(gql).then(() => {
console.info('Write successfully');
}).catch((err: BusinessError) => {
console.error(`Write failed, code is ${err.code}, message is ${err.message}`);
});
});
} |
application-dev\database\data-persistence-by-graph-store.md | const QUERY_VERTEX = "MATCH (person:Person) RETURN person;"
const QUERY_EDGE = "MATCH ()-[relation:Friend]->() RETURN relation;"
const QUERY_PATH = "MATCH path=(a:Person {name: 'name_1'})-[]->{2, 2}(b:Person {name: 'name_3'}) RETURN path;"
if(store != null) {
(store as graphStore.GraphStore).read(QUERY_VERTEX).then((result: graphStore.Result) => {
console.info('Query vertex successfully');
result.records?.forEach((data) => {
for (let item of Object.entries(data)) {
const key = item[0];
const value = item[1];
const vertex = value as graphStore.Vertex;
console.info(`key : ${key}, vertex.properties : ${JSON.stringify(vertex.properties)}`);
}
});
}).catch((err: BusinessError) => {
console.error(`Query vertex failed, code is ${err.code}, message is ${err.message}`);
});
(store as graphStore.GraphStore).read(QUERY_EDGE).then((result: graphStore.Result) => {
console.info('Query edge successfully');
result.records?.forEach((data) => {
for (let item of Object.entries(data)) {
const key = item[0];
const value = item[1];
const edge = value as graphStore.Edge;
console.info(`key : ${key}, edge.properties : ${JSON.stringify(edge.properties)}`);
}
});
}).catch((err: BusinessError) => {
console.error(`Query edge failed, code is ${err.code}, message is ${err.message}`);
});
(store as graphStore.GraphStore).read(QUERY_PATH).then((result: graphStore.Result) => {
console.info('Query path successfully');
result.records?.forEach((data) => {
for (let item of Object.entries(data)) {
const key = item[0];
const value = item[1];
const path = value as graphStore.Path;
console.info(`key : ${key}, path.length : ${path.length}`);
}
});
}).catch((err: BusinessError) => {
console.error(`Query path failed, code is ${err.code}, message is ${err.message}`);
})
} |
application-dev\database\data-persistence-by-graph-store.md | const DELETE_VERTEX_AND_RELATED_EDGE = "MATCH (p:Person {name: 'name_1'}) DETACH DELETE p;"
const DELETE_EDGE_ONLY = "MATCH (p2:Person {name: 'name_2'})-[relation: Friend]->(p3:Person {name: 'name_3'})" +
" DETACH DELETE relation;"
if(store != null) {
(store as graphStore.GraphStore).write(DELETE_VERTEX_AND_RELATED_EDGE).then(() => {
console.info('Delete vertex and related edge successfully');
}).catch((err: BusinessError) => {
console.error(`Delete vertex and related edge failed, code is ${err.code}, message is ${err.message}`);
});
(store as graphStore.GraphStore).write(DELETE_EDGE_ONLY).then(() => {
console.info('Delete edge only successfully');
}).catch((err: BusinessError) => {
console.error(`Delete edge only failed, code is ${err.code}, message is ${err.message}`);
})
} |
application-dev\database\data-persistence-by-graph-store.md | let transactionRead: graphStore.Transaction | null = null;
let transactionWrite: graphStore.Transaction | null = null;
const INSERT = "INSERT (:Person {name: 'name_5', age: 55});";
const QUERY = "MATCH (person:Person) RETURN person;";
if(store != null) {
(store as graphStore.GraphStore).createTransaction().then((trans: graphStore.Transaction) => {
transactionRead = trans;
console.info('Create transactionRead successfully');
}).catch((err: BusinessError) => {
console.error(`Create transactionRead failed, code is ${err.code}, message is ${err.message}`);
});
(store as graphStore.GraphStore).createTransaction().then((trans: graphStore.Transaction) => {
transactionWrite = trans;
console.info('Create transactionWrite successfully');
}).catch((err: BusinessError) => {
console.error(`Create transactionWrite failed, code is ${err.code}, message is ${err.message}`);
});
if(transactionRead != null) {
(transactionRead as graphStore.Transaction).read(QUERY).then((result: graphStore.Result) => {
console.info('Transaction read successfully');
result.records?.forEach((data) => {
for (let item of Object.entries(data)) {
const key = item[0];
const value = item[1];
const vertex = value as graphStore.Vertex;
console.info(`key : ${key}, vertex.properties : ${JSON.stringify(vertex.properties)}`);
}
});
}).catch((err: BusinessError) => {
console.error(`Transaction read failed, code is ${err.code}, message is ${err.message}`);
});
(transactionRead as graphStore.Transaction).rollback().then(() => {
console.info(`Rollback successfully`);
transactionRead = null;
}).catch ((err: BusinessError) => {
console.error(`Rollback failed, code is ${err.code}, message is ${err.message}`);
})
}
if(transactionWrite != null) {
(transactionWrite as graphStore.Transaction).write(INSERT).then(() => {
console.info('Transaction write successfully');
}).catch((err: BusinessError) => {
console.error(`Transaction write failed, code is ${err.code}, message is ${err.message}`);
});
(transactionWrite as graphStore.Transaction).commit().then(() => {
console.info(`Commit successfully`);
transactionWrite = null;
}).catch ((err: BusinessError) => {
console.error(`Commit failed, code is ${err.code}, message is ${err.message}`);
})
}
} |
application-dev\database\data-persistence-by-graph-store.md | const DROP_GRAPH_GQL = "DROP GRAPH test;"
class EntryAbility extends UIAbility {
onWindowStageDestroy() {
if(store != null) {
// Delete the graph. This process is skipped here.
(store as graphStore.GraphStore).write(DROP_GRAPH_GQL).then(() => {
console.info('Drop graph successfully');
}).catch((err: BusinessError) => {
console.error(`Drop graph failed, code is ${err.code}, message is ${err.message}`);
});
// Close the database. EntryAbility is used as an example.
(store as graphStore.GraphStore).close().then(() => {
console.info(`Close successfully`);
}).catch ((err: BusinessError) => {
console.error(`Close failed, code is ${err.code}, message is ${err.message}`);
})
}
// The StoreConfig used for deleting a database must be the same as that used for creating the database.
graphStore.deleteStore(this.context, STORE_CONFIG_NEW).then(() => {
store = null;
console.info('Delete GraphStore successfully.');
}).catch((err: BusinessError) => {
console.error(`Delete GraphStore failed, code is ${err.code},message is ${err.message}`);
})
}
} |
application-dev\database\data-persistence-by-preferences.md | import { preferences } from '@kit.ArkData'; |
application-dev\database\data-persistence-by-preferences.md | let isGskvSupported = preferences.isStorageTypeSupported(preferences.StorageType.GSKV);
console.info("Is gskv supported on this platform: " + isGskvSupported); |
application-dev\database\data-persistence-by-preferences.md | import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { window } from '@kit.ArkUI';
let dataPreferences: preferences.Preferences | null = null;
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage: window.WindowStage) {
let options: preferences.Options = { name: 'myStore' };
dataPreferences = preferences.getPreferencesSync(this.context, options);
}
} |
application-dev\database\data-persistence-by-preferences.md | // Obtain the context.
import { featureAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
let context = featureAbility.getContext();
let options: preferences.Options = { name: 'myStore' };
let dataPreferences: preferences.Preferences = preferences.getPreferencesSync(context, options); |
application-dev\database\data-persistence-by-preferences.md | import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { window } from '@kit.ArkUI';
let dataPreferences: preferences.Preferences | null = null;
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage: window.WindowStage) {
let options: preferences.Options = { name: 'myStore' , storageType: preferences.StorageType.GSKV};
dataPreferences = preferences.getPreferencesSync(this.context, options);
}
} |
application-dev\database\data-persistence-by-preferences.md | // Obtain the context.
import { featureAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
let context = featureAbility.getContext();
let options: preferences.Options = { name: 'myStore' , storageType: preferences.StorageType.GSKV};
let dataPreferences: preferences.Preferences = preferences.getPreferencesSync(context, options); |
application-dev\database\data-persistence-by-preferences.md | import { util } from '@kit.ArkTS';
if (dataPreferences.hasSync('startup')) {
console.info("The key 'startup' is contained.");
} else {
console.info("The key 'startup' does not contain.");
// Add a KV pair.
dataPreferences.putSync('startup', 'auto');
// If a string contains special characters, convert the string to Uint8Array format and store it. The length of the string cannot exceed 16 x 1024 x 1024 bytes.
let uInt8Array1 = new util.TextEncoder().encodeInto("~! @#¥%......&* () --+? ");
dataPreferences.putSync('uInt8', uInt8Array1);
} |
application-dev\database\data-persistence-by-preferences.md | let val = dataPreferences.getSync('startup', 'default');
console.info("The 'startup' value is " + val);
// If the value is a string containing special characters, it is stored in the Uint8Array format. Convert the obtained Uint8Array into a string.
let uInt8Array2 : preferences.ValueType = dataPreferences.getSync('uInt8', new Uint8Array(0));
let textDecoder = util.TextDecoder.create('utf-8');
val = textDecoder.decodeToString(uInt8Array2 as Uint8Array);
console.info("The 'uInt8' value is " + val); |
application-dev\database\data-persistence-by-preferences.md | dataPreferences.deleteSync('startup'); |
application-dev\database\data-persistence-by-preferences.md | dataPreferences.flush((err: BusinessError) => {
if (err) {
console.error(`Failed to flush. Code:${err.code}, message:${err.message}`);
return;
}
console.info('Succeeded in flushing.');
}) |
application-dev\database\data-persistence-by-preferences.md | let observer = (key: string) => {
console.info('The key' + key + 'changed.');
}
dataPreferences.on('change', observer);
// The data is changed from 'auto' to 'manual'.
dataPreferences.put('startup', 'manual', (err: BusinessError) => {
if (err) {
console.error(`Failed to put the value of 'startup'. Code:${err.code},message:${err.message}`);
return;
}
console.info("Succeeded in putting the value of 'startup'.");
if (dataPreferences !== null) {
dataPreferences.flush((err: BusinessError) => {
if (err) {
console.error(`Failed to flush. Code:${err.code}, message:${err.message}`);
return;
}
console.info('Succeeded in flushing.');
})
}
}) |
application-dev\database\data-persistence-by-preferences.md | let observer = (key: string) => {
console.info('The key' + key + 'changed.');
}
dataPreferences.on('change', observer);
// The data is changed from 'auto' to 'manual'.
dataPreferences.put('startup', 'manual', (err: BusinessError) => {
if (err) {
console.error(`Failed to put the value of 'startup'. Code:${err.code},message:${err.message}`);
return;
}
console.info("Succeeded in putting the value of 'startup'.");
}) |
application-dev\database\data-persistence-by-preferences.md | preferences.deletePreferences(this.context, options, (err: BusinessError) => {
if (err) {
console.error(`Failed to delete preferences. Code:${err.code}, message:${err.message}`);
return;
}
console.info('Succeeded in deleting preferences.');
}) |
application-dev\database\data-persistence-by-rdb-store.md | import { relationalStore} from '@kit.ArkData'; // Import the relationalStore module.
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { window } from '@kit.ArkUI';
// In this example, Ability is used to obtain an RdbStore instance. You can use other implementations as required.
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage: window.WindowStage) {
// Before using a tokenizer, call isStorageTypeSupported to check whether the tokenizer is supported by the current platform.
let tokenType = relationalStore.Tokenizer.ICU_TOKENIZER;
let tokenTypeSupported = relationalStore.isTokenizerSupported(tokenType);
if (!tokenTypeSupported) {
console.error(`ICU_TOKENIZER is not supported on this platform.`);
}
const STORE_CONFIG: relationalStore.StoreConfig = {
name: 'RdbTest.db', // Database file name.
securityLevel: relationalStore.SecurityLevel.S3, // Database security level.
encrypt: false, // Whether to encrypt the database. This parameter is optional. By default, the database is not encrypted.
customDir: 'customDir/subCustomDir' // (Optional) Customized database path. The database is created in the context.databaseDir + '/rdb/' + customDir directory, where context.databaseDir indicates the application sandbox path, '/rdb/' indicates a relational database, and customDir indicates the customized path. If this parameter is not specified, an RdbStore instance is created in the sandbox directory of the application.
isReadOnly: false // (Optional) Specify whether the RDB store is opened in read-only mode. The default value is false, which means the RDB store is readable and writable. If this parameter is true, data can only be read from the RDB store. If write operation is performed, error code 801 is returned.
tokenizer: tokenType // (Optional) Type of the tokenizer used in full-text search (FTS). If this parameter is left blank, only English word segmentation is supported in FTS.
};
// Check the RDB store version. If the version is incorrect, upgrade or downgrade the RDB store.
// For example, the RDB store version is 3 and the table structure is EMPLOYEE (NAME, AGE, SALARY, CODES, IDENTITY).
const SQL_CREATE_TABLE = 'CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB, IDENTITY UNLIMITED INT)'; // SQL statement used to create a table. In the statement, the IDENTITY type bigint should be UNLIMITED INT.
relationalStore.getRdbStore(this.context, STORE_CONFIG, (err, store) => {
if (err) {
console.error(`Failed to get RdbStore. Code:${err.code}, message:${err.message}`);
return;
}
console.info('Succeeded in getting RdbStore.');
// When the RDB store is created, the default version is 0.
if (store.version === 0) {
store.executeSql(SQL_CREATE_TABLE); // Create a table.
.then(() => {
// Set the RDB store version, which must be an integer greater than 0.
store.version = 3;
})
.catch((err: BusinessError) => {
console.error(`Failed to executeSql. Code:${err.code}, message:${err.message}`);
});
}
// If the RDB store version is not 0 and does not match the current version, upgrade or downgrade the RDB store.
// For example, upgrade the RDB store from version 1 to version 2.
if (store.version === 1) {
// Upgrade the RDB store from version 1 to version 2, and change the table structure from EMPLOYEE (NAME, SALARY, CODES, ADDRESS) to EMPLOYEE (NAME, AGE, SALARY, CODES, ADDRESS).
store.executeSql('ALTER TABLE EMPLOYEE ADD COLUMN AGE INTEGER')
.then(() => {
store.version = 2;
}).catch((err: BusinessError) => {
console.error(`Failed to executeSql. Code:${err.code}, message:${err.message}`);
});
}
// For example, upgrade the RDB store from version 2 to version 3.
if (store.version === 2) {
// Upgrade the RDB store from version 2 to version 3, and change the table structure from EMPLOYEE (NAME, AGE, SALARY, CODES, ADDRESS) to EMPLOYEE (NAME, AGE, SALARY, CODES).
store.executeSql('ALTER TABLE EMPLOYEE DROP COLUMN ADDRESS')
.then(() => {
store.version = 3;
}).catch((err: BusinessError) => {
console.error(`Failed to executeSql. Code:${err.code}, message:${err.message}`);
});
}
// Before adding, deleting, modifying, and querying data in an RDB store, obtain an RdbStore instance and create a table.
});
}
} |
application-dev\database\data-persistence-by-rdb-store.md | import { relationalStore} from '@kit.ArkData'; // Import the relationalStore module.
import { featureAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
let context = featureAbility.getContext();
const STORE_CONFIG: relationalStore.StoreConfig = {
name: 'RdbTest.db', // Database file name.
securityLevel: relationalStore.SecurityLevel.S3 // Database security level.
};
// For example, the RDB store version is 3 and the table structure is EMPLOYEE (NAME, AGE, SALARY, CODES, IDENTITY).
const SQL_CREATE_TABLE = 'CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB, IDENTITY UNLIMITED INT)'; // SQL statement used to create a table. In the statement, the IDENTITY type bigint should be UNLIMITED INT.
relationalStore.getRdbStore(context, STORE_CONFIG, (err, store) => {
if (err) {
console.error(`Failed to get RdbStore. Code:${err.code}, message:${err.message}`);
return;
}
console.info('Succeeded in getting RdbStore.');
// When the RDB store is created, the default version is 0.
if (store.version === 0) {
store.executeSql(SQL_CREATE_TABLE); // Create a table.
.then(() => {
// Set the RDB store version, which must be an integer greater than 0.
store.version = 3;
})
.catch((err: BusinessError) => {
console.error(`Failed to executeSql. Code:${err.code}, message:${err.message}`);
});
}
// If the RDB store version is not 0 and does not match the current version, upgrade or downgrade the RDB store.
// For example, upgrade the RDB store from version 1 to version 2.
if (store.version === 1) {
// Upgrade the RDB store from version 1 to version 2, and change the table structure from EMPLOYEE (NAME, SALARY, CODES, ADDRESS) to EMPLOYEE (NAME, AGE, SALARY, CODES, ADDRESS).
store.executeSql('ALTER TABLE EMPLOYEE ADD COLUMN AGE INTEGER')
.then(() => {
store.version = 2;
}).catch((err: BusinessError) => {
console.error(`Failed to executeSql. Code:${err.code}, message:${err.message}`);
});
}
// For example, upgrade the RDB store from version 2 to version 3.
if (store.version === 2) {
// Upgrade the RDB store from version 2 to version 3, and change the table structure from EMPLOYEE (NAME, AGE, SALARY, CODES, ADDRESS) to EMPLOYEE (NAME, AGE, SALARY, CODES).
store.executeSql('ALTER TABLE EMPLOYEE DROP COLUMN ADDRESS')
.then(() => {
store.version = 3;
}).catch((err: BusinessError) => {
console.error(`Failed to executeSql. Code:${err.code}, message:${err.message}`);
});
}
// Before adding, deleting, modifying, and querying data in an RDB store, obtain an RdbStore instance and create a table.
}); |
application-dev\database\data-persistence-by-rdb-store.md | let store: relationalStore.RdbStore | undefined = undefined;
let value1 = 'Lisa';
let value2 = 18;
let value3 = 100.5;
let value4 = new Uint8Array([1, 2, 3, 4, 5]);
let value5 = BigInt('15822401018187971961171');
// You can use either of the following:
const valueBucket1: relationalStore.ValuesBucket = {
'NAME': value1,
'AGE': value2,
'SALARY': value3,
'CODES': value4,
'IDENTITY': value5,
};
const valueBucket2: relationalStore.ValuesBucket = {
NAME: value1,
AGE: value2,
SALARY: value3,
CODES: value4,
IDENTITY: value5,
};
const valueBucket3: relationalStore.ValuesBucket = {
"NAME": value1,
"AGE": value2,
"SALARY": value3,
"CODES": value4,
"IDENTITY": value5,
};
if (store !== undefined) {
(store as relationalStore.RdbStore).insert('EMPLOYEE', valueBucket1, (err: BusinessError, rowId: number) => {
if (err) {
console.error(`Failed to insert data. Code:${err.code}, message:${err.message}`);
return;
}
console.info(`Succeeded in inserting data. rowId:${rowId}`);
})
} |
application-dev\database\data-persistence-by-rdb-store.md | let value6 = 'Rose';
let value7 = 22;
let value8 = 200.5;
let value9 = new Uint8Array([1, 2, 3, 4, 5]);
let value10 = BigInt('15822401018187971967863');
// You can use either of the following:
const valueBucket4: relationalStore.ValuesBucket = {
'NAME': value6,
'AGE': value7,
'SALARY': value8,
'CODES': value9,
'IDENTITY': value10,
};
const valueBucket5: relationalStore.ValuesBucket = {
NAME: value6,
AGE: value7,
SALARY: value8,
CODES: value9,
IDENTITY: value10,
};
const valueBucket6: relationalStore.ValuesBucket = {
"NAME": value6,
"AGE": value7,
"SALARY": value8,
"CODES": value9,
"IDENTITY": value10,
};
// Modify data.
let predicates1 = new relationalStore.RdbPredicates('EMPLOYEE'); // Create predicates for the table named EMPLOYEE.
predicates1.equalTo('NAME', 'Lisa'); // Modify the data of Lisa in the EMPLOYEE table to the specified data.
if (store !== undefined) {
(store as relationalStore.RdbStore).update(valueBucket4, predicates1, (err: BusinessError, rows: number) => {
if (err) {
console.error(`Failed to update data. Code:${err.code}, message:${err.message}`);
return;
}
console.info(`Succeeded in updating data. row count: ${rows}`);
})
}
// Delete data.
predicates1 = new relationalStore.RdbPredicates('EMPLOYEE');
predicates1.equalTo('NAME', 'Lisa');
if (store !== undefined) {
(store as relationalStore.RdbStore).delete(predicates1, (err: BusinessError, rows: number) => {
if (err) {
console.error(`Failed to delete data. Code:${err.code}, message:${err.message}`);
return;
}
console.info(`Delete rows: ${rows}`);
})
} |
application-dev\database\data-persistence-by-rdb-store.md | let predicates2 = new relationalStore.RdbPredicates('EMPLOYEE');
predicates2.equalTo('NAME', 'Rose');
if (store !== undefined) {
(store as relationalStore.RdbStore).query(predicates2, ['ID', 'NAME', 'AGE', 'SALARY', 'IDENTITY'], (err: BusinessError, resultSet) => {
if (err) {
console.error(`Failed to query data. Code:${err.code}, message:${err.message}`);
return;
}
console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
// resultSet is a cursor of a data set. By default, the cursor points to the -1st record. Valid data starts from 0.
while (resultSet.goToNextRow()) {
const id = resultSet.getLong(resultSet.getColumnIndex('ID'));
const name = resultSet.getString(resultSet.getColumnIndex('NAME'));
const age = resultSet.getLong(resultSet.getColumnIndex('AGE'));
const salary = resultSet.getDouble(resultSet.getColumnIndex('SALARY'));
const identity = resultSet.getValue(resultSet.getColumnIndex('IDENTITY'));
console.info(`id=${id}, name=${name}, age=${age}, salary=${salary}, identity=${identity}`);
}
// Release the data set memory.
resultSet.close();
})
} |
application-dev\database\data-persistence-by-rdb-store.md | let store: relationalStore.RdbStore | undefined = undefined;
if (store !== undefined) {
// Create an FTS table.
const SQL_CREATE_TABLE = "CREATE VIRTUAL TABLE example USING fts4(name, content, tokenize=icu zh_CN)";
(store as relationalStore.RdbStore).executeSql(SQL_CREATE_TABLE, (err: BusinessError) => {
if (err) {
console.error(`Failed to creating fts table.`);
return;
}
console.info(`Succeeded in creating fts table.`);
})
}
if(store != undefined) {
(store as relationalStore.RdbStore).querySql("SELECT name FROM example WHERE example MATCH '测试'", (err, resultSet) => {
if (err) {
console.error(`Query failed.`);
return;
}
while (resultSet.goToNextRow()) {
const name = resultSet.getString(resultSet.getColumnIndex("name"));
console.info(`name=${name}`);
}
resultSet.close();
})
} |
application-dev\database\data-persistence-by-rdb-store.md | if (store !== undefined) {
// Backup.db indicates the name of the database backup file. By default, it is in the same directory as the RdbStore file. You can also specify the directory, which is in the customDir + backup.db format.
(store as relationalStore.RdbStore).backup("Backup.db", (err: BusinessError) => {
if (err) {
console.error(`Failed to backup RdbStore. Code:${err.code}, message:${err.message}`);
return;
}
console.info(`Succeeded in backing up RdbStore.`);
})
} |
application-dev\database\data-persistence-by-rdb-store.md | if (store !== undefined) {
(store as relationalStore.RdbStore).restore("Backup.db", (err: BusinessError) => {
if (err) {
console.error(`Failed to restore RdbStore. Code:${err.code}, message:${err.message}`);
return;
}
console.info(`Succeeded in restoring RdbStore.`);
})
} |
application-dev\database\data-persistence-by-rdb-store.md | relationalStore.deleteRdbStore(this.context, 'RdbTest.db', (err: BusinessError) => {
if (err) {
console.error(`Failed to delete RdbStore. Code:${err.code}, message:${err.message}`);
return;
}
console.info('Succeeded in deleting RdbStore.');
}); |
application-dev\database\data-persistence-by-rdb-store.md | relationalStore.deleteRdbStore(context, 'RdbTest.db', (err: BusinessError) => {
if (err) {
console.error(`Failed to delete RdbStore. Code:${err.code}, message:${err.message}`);
return;
}
console.info('Succeeded in deleting RdbStore.');
}); |
application-dev\database\data-persistence-by-vector-store.md | import { relationalStore } from '@kit.ArkData'; // Import the relationalStore module.
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { window } from '@kit.ArkUI';
// In this example, Ability is used to obtain an RdbStore instance. You can use other implementations as required.
class EntryAbility extends UIAbility {
async onWindowStageCreate(windowStage: window.WindowStage) {
// Check whether the current system supports vector stores.
let ret = relationalStore.isVectorSupported();
if (!ret) {
console.error(`vectorDB is not supported .`);
return;
}
// Open the database, and add, delete, and modify data.
}
} |
application-dev\database\data-persistence-by-vector-store.md | let store: relationalStore.RdbStore | undefined = undefined;
const STORE_CONFIG :relationalStore.StoreConfig= {
name: 'VectorTest.db', // Database file name.
securityLevel: relationalStore.SecurityLevel.S1 // Database security level.
vector: true // Optional. This parameter must be true for a vector store.
};
relationalStore.getRdbStore(this.context, STORE_CONFIG).then(async (rdbStore: relationalStore.RdbStore) => {
store = rdbStore;
// Create a table. floatvector (2) indicates that repr is 2-dimensional.
const SQL_CREATE_TABLE = 'CREATE TABLE IF NOT EXISTS test (id INTEGER PRIMARY KEY, repr floatvector(2));';
// The second parameter indicates that transaction is not enabled. The third parameter undefined indicates that parameter binding is not used.
await store!.execute(SQL_CREATE_TABLE, 0, undefined);
}).catch((err: BusinessError) => {
console.error(`Get RdbStore failed, code is ${err.code}, message is ${err.message}`);
}); |
application-dev\database\data-persistence-by-vector-store.md | try {
// Use parameter binding.
const vectorValue: Float32Array = Float32Array.from([1.2, 2.3]);
await store!.execute("insert into test VALUES(?, ?);", 0, [0, vectorValue]);
// Do not use parameter binding.
await store!.execute("insert into test VALUES(1, '[1.3, 2.4]');", 0, undefined);
} catch (err) {
console.error(`execute insert failed, code is ${err.code}, message is ${err.message}`);
} |
application-dev\database\data-persistence-by-vector-store.md | // Modify data.
try {
// Use parameter binding.
const vectorValue1: Float32Array = Float32Array.from([2.1, 3.2]);
await store!.execute("update test set repr = ? where id = ?", 0, [vectorValue1, 0]);
// Do not use parameter binding.
await store!.execute("update test set repr = '[5.1, 6.1]' where id = 0", 0, undefined);
} catch (err) {
console.error(`execute update failed, code is ${err.code}, message is ${err.message}`);
}
// Delete data.
try {
// Use parameter binding.
await store!.execute("delete from test where id = ?", 0, [0]);
// Do not use parameter binding.
await store!.execute("delete from test where id = 0", 0, undefined);
} catch (err) {
console.error(`execute delete failed, code is ${err.code}, message is ${err.message}`);
} |
application-dev\database\data-persistence-by-vector-store.md | // Perform single-table queries.
try {
// Use parameter binding.
const QUERY_SQL = "select id, repr <-> ? as distance from test where id > ? order by repr <-> ? limit 5;";
const vectorValue2: Float32Array = Float32Array.from([6.2, 7.3]);
let resultSet = await store!.querySql(QUERY_SQL, [vectorValue2, 0, vectorValue2]);
while (resultSet!.goToNextRow()) {
let id = resultSet.getValue(0);
let dis = resultSet.getValue(1);
}
resultSet!.close();
// Do not use parameter binding.
const QUERY_SQL1 = "select id, repr <-> '[6.2, 7.3]' as distance from test where id > 0 order by repr <-> '[6.2, 7.3]' limit 5;";
resultSet = await store!.querySql(QUERY_SQL1);
resultSet!.close();
} catch (err) {
console.error(`query failed, code is ${err.code}, message is ${err.message}`);
}
// Perform subqueries.
try {
// Create the second table.
let CREATE_SQL = "CREATE TABLE IF NOT EXISTS test1(id text PRIMARY KEY);";
await store!.execute(CREATE_SQL);
let resultSet = await store!.querySql("select * from test where id in (select id from test1);");
resultSet!.close();
} catch (err) {
console.error(`query failed, code is ${err.code}, message is ${err.message}`);
}
// Perform aggregate queries.
try {
let resultSet = await store!.querySql("select * from test where repr <-> '[1.0, 1.0]' > 0 group by id having max(repr <=> '[1.0, 1.0]');");
resultSet!.close();
} catch (err) {
console.error(`query failed, code is ${err.code}, message is ${err.message}`);
}
// Perform multi-table queries.
try {
// Different union all, union will delete duplicate data.
let resultSet = await store!.querySql("select id, repr <-> '[1.5, 5.6]' as distance from test union select id, repr <-> '[1.5, 5.6]' as distance from test order by distance limit 5;");
resultSet!.close();
} catch (err) {
console.error(`query failed, code is ${err.code}, message is ${err.message}`);
} |
application-dev\database\data-persistence-by-vector-store.md | // Perform view queries.
try {
// Create a view.
await store!.execute("CREATE VIEW v1 as select * from test where id > 0;");
let resultSet = await store!.querySql("select * from v1;");
resultSet!.close();
} catch (err) {
console.error(`query failed, code is ${err.code}, message is ${err.message}`);
} |
application-dev\database\data-persistence-by-vector-store.md | // Basic syntax
try {
// Create an index using the basic syntax. The index name is diskann_l2_idx, index column is repr, type is gsdiskann, and the distance metric is L2.
await store!.execute("CREATE INDEX diskann_l2_idx ON test USING GSDISKANN(repr L2);");
// Delete the diskann_l2_idx index from the test table.
await store!.execute("DROP INDEX test.diskann_l2_idx;");
} catch (err) {
console.error(`create index failed, code is ${err.code}, message is ${err.message}`);
}
// Extended syntax
try {
// Set QUEUE_SIZE to 20 and OUT_DEGREE to 50.
await store!.execute("CREATE INDEX diskann_l2_idx ON test USING GSDISKANN(repr L2) WITH (queue_size=20, out_degree=50);");
} catch (err) {
console.error(`create ext index failed, code is ${err.code}, message is ${err.message}`);
} |
application-dev\database\data-persistence-by-vector-store.md | try {
// The write operation performed every 5 minutes will trigger a data aging task.
await store!.execute("CREATE TABLE test2(rec_time integer not null) WITH (time_col = 'rec_time', interval = '5 minute');");
} catch (err) {
console.error(`configure data aging failed, code is ${err.code}, message is ${err.message}`);
} |
application-dev\database\data-persistence-by-vector-store.md | try {
await relationalStore.deleteRdbStore(this.context, STORE_CONFIG);
} catch (err) {
console.error(`delete rdbStore failed, code is ${err.code},message is ${err.message}`);
} |
application-dev\database\data-sync-of-distributed-data-object.md | dataObject['parents'] = {mom: "amy"}; // Supported modification
dataObject['parents']['mon'] = "amy"; // Unsupported modification |
application-dev\database\data-sync-of-distributed-data-object.md | import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { window } from '@kit.ArkUI';
import { commonType, distributedDataObject } from '@kit.ArkData';
import { fileIo, fileUri } from '@kit.CoreFileKit';
import { BusinessError } from '@kit.BasicServicesKit';
// Define service data.
class Data {
title: string | undefined;
text: string | undefined;
attachment: commonType.Asset; // Use data of the commonType.Asset to record files in the distributed file directory. When asset data is migrated, the corresponding files are also migrated to the target device. (If files do not need to be migrated, do not set this field and createAttachment and createEmptyAttachment.)
// attachment2: commonType.Asset; // The asset array is not supported currently. If multiple files need to be migrated, define an asset data record for each file to migrate.
constructor(title: string | undefined, text: string | undefined, attachment: commonType.Asset) {
this.title = title;
this.text = text;
this.attachment = attachment;
}
}
const TAG = '[DistributedDataObject]';
let dataObject: distributedDataObject.DataObject;
export default class EntryAbility extends UIAbility {
// 1. Create a distributed data object in **onContinue()** for the application on the source device, and save data to the target device.
onContinue(wantParam: Record<string, Object>): AbilityConstant.OnContinueResult | Promise<AbilityConstant.OnContinueResult> {
// 1.1 Call create() to create a distributed data object instance.
let attachment = this.createAttachment();
let data = new Data('The title', 'The text', attachment);
dataObject = distributedDataObject.create(this.context, data);
// 1.2 Call genSessionId() to generate a sessionId, call setSessionId() to set a sessionId, and add the sessionId to wantParam.
let sessionId = distributedDataObject.genSessionId();
console.log(TAG + `gen sessionId: ${sessionId}`);
dataObject.setSessionId(sessionId);
wantParam.distributedSessionId = sessionId;
// 1.3 Obtain networkId from **wantParam** for the application on the target device and call save() with this network ID to save data to the target device.
let deviceId = wantParam.targetDevice as string;
console.log(TAG + `get deviceId: ${deviceId}`);
dataObject.save(deviceId);
return AbilityConstant.OnContinueResult.AGREE;
}
// 2. Create a distributed data object in onCreate() for the application on the target device (for cold start), and add it to the network for data migration.
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
if (launchParam.launchReason == AbilityConstant.LaunchReason.CONTINUATION) {
if (want.parameters && want.parameters.distributedSessionId) {
this.restoreDistributedDataObject(want);
}
}
}
// 2. Create a distributed data object in onNewWant() for the application on the target device (for hot start), and add it to the network for data migration.
onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void {
if (launchParam.launchReason == AbilityConstant.LaunchReason.CONTINUATION) {
if (want.parameters && want.parameters.distributedSessionId) {
this.restoreDistributedDataObject(want);
}
}
}
restoreDistributedDataObject(want: Want) {
if (!want.parameters || !want.parameters.distributedSessionId) {
console.error(TAG + 'missing sessionId');
return;
}
// 2.1 Call create() to create a distributed data object instance for the application on the target device.
let attachment = this.createEmptyAttachment(); // Set each attribute of the asset data to an empty string so that the asset data saved on the source device can be restored on the target device.
let data = new Data(undefined, undefined, attachment);
dataObject = distributedDataObject.create(this.context, data);
// 2.2 Register a listener callback for the data recovery state. If "restored" is returned by the listener callback registered, the distributed data object of the target device has obtained the data transferred from the source device. If asset data is migrated, the file is also transferred to the target device.
dataObject.on('status', (sessionId: string, networkId: string, status: string) => {
if (status == 'restored') {// "restored" indicates that the data saved on the source device is restored on the target device.
console.log(TAG + `title: ${dataObject['title']}, text: ${dataObject['text']}`);
}
});
// 2.3 Obtain the sessionId of the source device from want.parameters and call setSessionId to set the same sessionId for the target device.
let sessionId = want.parameters.distributedSessionId as string;
console.log(TAG + `get sessionId: ${sessionId}`);
dataObject.setSessionId(sessionId);
}
// Create a file in the distributed file directory and use data of the asset type to record the file information. (You can also use the data of asset type to record an existing file in the distributed file directory or copy or move a file from another directory to the distributed file directory and then migrate it.)
createAttachment() {
let attachment = this.createEmptyAttachment();
try {
let distributedDir: string = this.context.distributedFilesDir; // Distributed file directory.
let fileName: string = 'text_attachment.txt'; // File name.
let filePath: string = distributedDir + '/' + fileName; // File path.
let file = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
fileIo.writeSync(file.fd, 'The text in attachment');
fileIo.closeSync(file.fd);
let uri: string = fileUri.getUriFromPath(filePath); // Obtain the file URI.
let stat = fileIo.statSync(filePath); // Obtain detailed file attribute information.
// Write asset data.
attachment = {
name: fileName,
uri: uri,
path: filePath,
createTime: stat.ctime.toString(),
modifyTime: stat.mtime.toString(),
size: stat.size.toString()
}
} catch (e) {
let err = e as BusinessError;
console.error(TAG + `file error, error code: ${err.code}, error message: ${err.message}`);
}
return attachment;
}
createEmptyAttachment() {
let attachment: commonType.Asset = {
name: '',
uri: '',
path: '',
createTime: '',
modifyTime: '',
size: ''
}
return attachment;
}
} |
application-dev\database\data-sync-of-distributed-data-object.md | import { AbilityConstant, Caller, common, UIAbility, Want } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { window } from '@kit.ArkUI';
import { distributedDataObject } from '@kit.ArkData';
import { distributedDeviceManager } from '@kit.DistributedServiceKit';
import { BusinessError } from '@kit.BasicServicesKit';
// Define service data.
class Data {
title: string | undefined;
text: string | undefined;
constructor(title: string | undefined, text: string | undefined) {
this.title = title;
this.text = text;
}
}
const TAG = '[DistributedDataObject]';
let sessionId: string;
let caller: Caller;
let dataObject: distributedDataObject.DataObject;
export default class EntryAbility extends UIAbility {
// 1. Call startAbilityByCall() to start an ability on another device.
callRemote() {
if (caller) {
console.error(TAG + 'call remote already');
return;
}
// 1.1 Call genSessionId() to create a sessionId and call getRemoteDeviceId() to obtain the network ID of the peer device.
sessionId = distributedDataObject.genSessionId();
console.log(TAG + `gen sessionId: ${sessionId}`);
let deviceId = getRemoteDeviceId();
if (deviceId == "") {
console.warn(TAG + 'no remote device');
return;
}
console.log(TAG + `get remote deviceId: ${deviceId}`);
// 1.2 Assemble want and put sessionId into want.
let want: Want = {
bundleName: 'com.example.collaboration',
abilityName: 'EntryAbility',
deviceId: deviceId,
parameters: {
'ohos.aafwk.param.callAbilityToForeground': true, // Start the ability in the foreground. This parameter is optional.
'distributedSessionId': sessionId
}
}
try {
// 1.3 Call startAbilityByCall() to start the peer ability.
this.context.startAbilityByCall(want).then((res) => {
if (!res) {
console.error(TAG + 'startAbilityByCall failed');
}
caller = res;
})
} catch (e) {
let err = e as BusinessError;
console.error(TAG + `get remote deviceId error, error code: ${err.code}, error message: ${err.message}`);
}
}
// 2. Create a distributed data object after starting the peer ability.
createDataObject() {
if (!caller) {
console.error(TAG + 'call remote first');
return;
}
if (dataObject) {
console.error(TAG + 'create dataObject already');
return;
}
// 2.1 Create a distributed data object instance.
let data = new Data('The title', 'The text');
dataObject = distributedDataObject.create(this.context, data);
// 2.2 Register a listener callback for data changes.
dataObject.on('change', (sessionId: string, fields: Array<string>) => {
fields.forEach((field) => {
console.log(TAG + `${field}: ${dataObject[field]}`);
});
});
// 2.3 Set a sessionId for the distributed data object and add it to the network.
dataObject.setSessionId(sessionId);
}
// 3. Create a distributed data object on the peer device and restore the data saved on the caller device.
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
if (want.parameters && want.parameters.distributedSessionId) {
// 3.1 Create a distributed data object instance on the peer device.
let data = new Data(undefined, undefined);
dataObject = distributedDataObject.create(this.context, data);
// 3.2 Register a listener callback for data changes.
dataObject.on('change', (sessionId: string, fields: Array<string>) => {
fields.forEach((field) => {
console.log(TAG + `${field}: ${dataObject[field]}`);
});
});
// 3.3 Obtain sessionId of the caller device from **want** and add the distributed data object instance to the network with the sessionId.
let sessionId = want.parameters.distributedSessionId as string;
console.log(TAG + `onCreate get sessionId: ${sessionId}`);
dataObject.setSessionId(sessionId);
}
}
}
// Obtain devices on the trusted network.
function getRemoteDeviceId() {
let deviceId = "";
try {
let deviceManager = distributedDeviceManager.createDeviceManager('com.example.collaboration');
let devices = deviceManager.getAvailableDeviceListSync();
if (devices[0] && devices[0].networkId) {
deviceId = devices[0].networkId;
}
} catch (e) {
let err = e as BusinessError;
console.error(TAG + `get remote deviceId error, error code: ${err.code}, error message: ${err.message}`);
}
return deviceId;
} |
application-dev\database\data-sync-of-kv-store.md | import { distributedKVStore } from '@kit.ArkData'; |
application-dev\database\data-sync-of-kv-store.md | // Obtain the context of the stage model.
import { window } from '@kit.ArkUI';
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
let kvManager: distributedKVStore.KVManager | undefined = undefined;
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage:window.WindowStage) {
let context = this.context;
}
}
// Obtain the context of the FA model.
import { featureAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
let context = featureAbility.getContext();
// Construct a kvManager instance.
try {
const kvManagerConfig: distributedKVStore.KVManagerConfig = {
bundleName: 'com.example.datamanagertest',
context: context
}
kvManager = distributedKVStore.createKVManager(kvManagerConfig);
console.info('Succeeded in creating KVManager.');
// Create and obtain the KV store.
} catch (e) {
let error = e as BusinessError;
console.error(`Failed to create KVManager. Code:${error.code},message:${error.message}`);
}
if (kvManager !== undefined) {
kvManager = kvManager as distributedKVStore.KVManager;
// Perform subsequent operations such as creating a KV store.
// ...
} |
application-dev\database\data-sync-of-kv-store.md | let kvStore: distributedKVStore.SingleKVStore | undefined = undefined;
try {
let child1 = new distributedKVStore.FieldNode('id');
child1.type = distributedKVStore.ValueType.INTEGER;
child1.nullable = false;
child1.default = '1';
let child2 = new distributedKVStore.FieldNode('name');
child2.type = distributedKVStore.ValueType.STRING;
child2.nullable = false;
child2.default = 'zhangsan';
let schema = new distributedKVStore.Schema();
schema.root.appendChild(child1);
schema.root.appendChild(child2);
schema.indexes = ['$.id', '$.name'];
// The value 0 indicates the compatible mode, and 1 indicates the strict mode.
schema.mode = 1;
// Set the number of bytes to be skipped during the value check. The value range is [0, 4M-2].
schema.skip = 0;
const options: distributedKVStore.Options = {
createIfMissing: true,
encrypt: false,
backup: false,
autoSync: false,
// If kvStoreType is left empty, a device KV store is created by default.
// Device KV store: kvStoreType: distributedKVStore.KVStoreType.DEVICE_COLLABORATION,
kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION,
// The schema parameter is optional. You need to set this parameter when the schema function is required, for example, when predicates are used for query.
schema: schema,
securityLevel: distributedKVStore.SecurityLevel.S3
};
kvManager.getKVStore<distributedKVStore.SingleKVStore>('storeId', options, (err, store: distributedKVStore.SingleKVStore) => {
if (err) {
console.error(`Failed to get KVStore: Code:${err.code},message:${err.message}`);
return;
}
console.info('Succeeded in getting KVStore.');
kvStore = store;
// Before performing related data operations, obtain a KV store instance.
});
} catch (e) {
let error = e as BusinessError;
console.error(`An unexpected error occurred. Code:${error.code},message:${error.message}`);
}
if (kvStore !== undefined) {
kvStore = kvStore as distributedKVStore.SingleKVStore;
// Perform subsequent data operations, such as adding, deleting, modifying, and querying data, and subscribing to data changes.
// ...
} |
application-dev\database\data-sync-of-kv-store.md | try {
kvStore.on('dataChange', distributedKVStore.SubscribeType.SUBSCRIBE_TYPE_ALL, (data) => {
console.info(`dataChange callback call data: ${data}`);
});
} catch (e) {
let error = e as BusinessError;
console.error(`An unexpected error occurred. code:${error.code},message:${error.message}`);
} |
application-dev\database\data-sync-of-kv-store.md | const KEY_TEST_STRING_ELEMENT = 'key_test_string';
// If schema is not defined, pass in other values that meet the requirements.
const VALUE_TEST_STRING_ELEMENT = '{"id":0, "name":"lisi"}';
try {
kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, (err) => {
if (err !== undefined) {
console.error(`Failed to put data. Code:${err.code},message:${err.message}`);
return;
}
console.info('Succeeded in putting data.');
});
} catch (e) {
let error = e as BusinessError;
console.error(`An unexpected error occurred. Code:${error.code},message:${error.message}`);
} |
application-dev\database\data-sync-of-kv-store.md | try {
kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, (err) => {
if (err !== undefined) {
console.error(`Failed to put data. Code:${err.code},message:${err.message}`);
return;
}
console.info('Succeeded in putting data.');
kvStore = kvStore as distributedKVStore.SingleKVStore;
kvStore.get(KEY_TEST_STRING_ELEMENT, (err, data) => {
if (err != undefined) {
console.error(`Failed to get data. Code:${err.code},message:${err.message}`);
return;
}
console.info(`Succeeded in getting data. Data:${data}`);
});
});
} catch (e) {
let error = e as BusinessError;
console.error(`Failed to get data. Code:${error.code},message:${error.message}`);
} |
application-dev\database\data-sync-of-kv-store.md | import { distributedDeviceManager } from '@kit.DistributedServiceKit';
let devManager: distributedDeviceManager.DeviceManager;
try {
// create deviceManager
devManager = distributedDeviceManager.createDeviceManager(context.applicationInfo.name);
// deviceIds is obtained by devManager.getAvailableDeviceListSync.
let deviceIds: string[] = [];
if (devManager != null) {
let devices = devManager.getAvailableDeviceListSync();
for (let i = 0; i < devices.length; i++) {
deviceIds[i] = devices[i].networkId as string;
}
}
try {
// 1000 indicates the maximum delay, in ms.
kvStore.sync(deviceIds, distributedKVStore.SyncMode.PUSH_ONLY, 1000);
} catch (e) {
let error = e as BusinessError;
console.error(`An unexpected error occurred. Code:${error.code},message:${error.message}`);
}
} catch (err) {
let error = err as BusinessError;
console.error("createDeviceManager errCode:" + error.code + ",errMessage:" + error.message);
} |
application-dev\database\data-sync-of-rdb-store.md | import { relationalStore } from '@kit.ArkData'; |
application-dev\database\data-sync-of-rdb-store.md | import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { window } from '@kit.ArkUI';
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage: window.WindowStage) {
const STORE_CONFIG: relationalStore.StoreConfig = {
name: "RdbTest.db",
securityLevel: relationalStore.SecurityLevel.S3
};
relationalStore.getRdbStore(this.context, STORE_CONFIG, (err: BusinessError, store: relationalStore.RdbStore) => {
store.executeSql('CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB)', (err) => {
// Set the table for distributed sync.
store.setDistributedTables(['EMPLOYEE']);
// Perform related operations.
})
})
}
} |
application-dev\database\data-sync-of-rdb-store.md | // Construct the predicate object for synchronizing the distributed table.
let predicates = new relationalStore.RdbPredicates('EMPLOYEE');
// Call sync() to synchronize data.
if(store != undefined)
{
(store as relationalStore.RdbStore).sync(relationalStore.SyncMode.SYNC_MODE_PUSH, predicates, (err, result) => {
// Check whether data sync is successful.
if (err) {
console.error(`Failed to sync data. Code:${err.code},message:${err.message}`);
return;
}
console.info('Succeeded in syncing data.');
for (let i = 0; i < result.length; i++) {
console.info(`device:${result[i][0]},status:${result[i][1]}`);
}
})
} |
application-dev\database\data-sync-of-rdb-store.md | let devices: string | undefined = undefined;
try {
// Register an observer to listen for the changes of the distributed data.
// When data in the RDB store changes, the registered callback will be invoked to return the data changes.
if(store != undefined) {
(store as relationalStore.RdbStore).on('dataChange', relationalStore.SubscribeType.SUBSCRIBE_TYPE_REMOTE, (storeObserver)=>{
if(devices != undefined){
for (let i = 0; i < devices.length; i++) {
console.info(`The data of device:${devices[i]} has been changed.`);
}
}
});
}
} catch (err) {
console.error('Failed to register observer. Code:${err.code},message:${err.message}');
}
// You can unsubscribe from the data changes if required.
try {
if(store != undefined) {
(store as relationalStore.RdbStore).off('dataChange', relationalStore.SubscribeType.SUBSCRIBE_TYPE_REMOTE, (storeObserver)=>{
});
}
} catch (err) {
console.error('Failed to register observer. Code:${err.code},message:${err.message}');
} |
application-dev\database\data-sync-of-rdb-store.md | // Obtain device IDs.
import { distributedDeviceManager } from '@kit.DistributedServiceKit';
import { BusinessError } from '@kit.BasicServicesKit';
let dmInstance: distributedDeviceManager.DeviceManager;
let deviceId: string | undefined = undefined ;
try {
dmInstance = distributedDeviceManager.createDeviceManager("com.example.appdatamgrverify");
let devices = dmInstance.getAvailableDeviceListSync();
deviceId = devices[0].networkId;
// Construct a predicate object for querying the distributed table.
let predicates = new relationalStore.RdbPredicates('EMPLOYEE');
// Query data from the specified remote device and return the query result.
if(store != undefined && deviceId != undefined) {
(store as relationalStore.RdbStore).remoteQuery(deviceId, 'EMPLOYEE', predicates, ['ID', 'NAME', 'AGE', 'SALARY', 'CODES'],
(err: BusinessError, resultSet: relationalStore.ResultSet) => {
if (err) {
console.error(`Failed to remoteQuery data. Code:${err.code},message:${err.message}`);
return;
}
console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
}
)
}
} catch (err) {
let code = (err as BusinessError).code;
let message = (err as BusinessError).message;
console.error("createDeviceManager errCode:" + code + ",errMessage:" + message);
} |
application-dev\database\encrypted_estore_guidelines.md | // module.json5
"requestPermissions": [
{
"name": "ohos.permission.PROTECT_SCREEN_LOCK_DATA"
}
] |
application-dev\database\encrypted_estore_guidelines.md | // Mover.ts
import { distributedKVStore } from '@kit.ArkData';
export class Mover {
async move(eStore: distributedKVStore.SingleKVStore, cStore: distributedKVStore.SingleKVStore): Promise<void> {
if (eStore != null && cStore != null) {
let entries: distributedKVStore.Entry[] = await cStore.getEntries('key_test_string');
await eStore.putBatch(entries);
console.info(`ECDB_Encry move success`);
}
}
} |
application-dev\database\encrypted_estore_guidelines.md | // Store.ts
import { distributedKVStore } from '@kit.ArkData';
import { BusinessError } from '@kit.BasicServicesKit';
let kvManager: distributedKVStore.KVManager;
export class StoreInfo {
kvManagerConfig: distributedKVStore.KVManagerConfig;
storeId: string;
option: distributedKVStore.Options;
}
export class Store {
async getECStore(storeInfo: StoreInfo): Promise<distributedKVStore.SingleKVStore> {
try {
kvManager = distributedKVStore.createKVManager(storeInfo.kvManagerConfig);
console.info("Succeeded in creating KVManager");
} catch (e) {
let error = e as BusinessError;
console.error(`Failed to create KVManager.code is ${error.code},message is ${error.message}`);
}
if (kvManager !== undefined) {
kvManager = kvManager as distributedKVStore.KVManager;
let kvStore: distributedKVStore.SingleKVStore | null;
try {
kvStore = await kvManager.getKVStore<distributedKVStore.SingleKVStore>(storeInfo.storeId, storeInfo.option);
if (kvStore != undefined) {
console.info(`ECDB_Encry succeeded in getting store : ${storeInfo.storeId}`);
return kvStore;
}
} catch (e) {
let error = e as BusinessError;
console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`);
}
}
}
putOnedata(kvStore: distributedKVStore.SingleKVStore): void {
if (kvStore != undefined) {
const KEY_TEST_STRING_ELEMENT = 'key_test_string' + String(Date.now());
const VALUE_TEST_STRING_ELEMENT = 'value_test_string' + String(Date.now());
try {
kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, (err) => {
if (err !== undefined) {
console.error(`Failed to put data. Code:${err.code},message:${err.message}`);
return;
}
console.info(`ECDB_Encry Succeeded in putting data.${KEY_TEST_STRING_ELEMENT}`);
});
} catch (e) {
let error = e as BusinessError;
console.error(`An unexpected error occurred. Code:${error.code},message:${error.message}`);
}
}
}
getDataNum(kvStore: distributedKVStore.SingleKVStore): void {
if (kvStore != undefined) {
let resultSet: distributedKVStore.KVStoreResultSet;
kvStore.getResultSet("key_test_string").then((result: distributedKVStore.KVStoreResultSet) => {
console.info(`ECDB_Encry Succeeded in getting result set num ${result.getCount()}`);
resultSet = result;
if (kvStore != null) {
kvStore.closeResultSet(resultSet).then(() => {
console.info('Succeeded in closing result set');
}).catch((err: BusinessError) => {
console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`);
});
}
}).catch((err: BusinessError) => {
console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`);
});
}
}
deleteOnedata(kvStore: distributedKVStore.SingleKVStore): void {
if (kvStore != undefined) {
kvStore.getEntries('key_test_string', (err: BusinessError, entries: distributedKVStore.Entry[]) => {
if (err != undefined) {
console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`);
return;
}
if (kvStore != null && entries.length != 0) {
kvStore.delete(entries[0].key, (err: BusinessError) => {
if (err != undefined) {
console.error(`Failed to delete.code is ${err.code},message is ${err.message}`);
return;
}
console.info('ECDB_Encry Succeeded in deleting');
});
}
});
}
}
updateOnedata(kvStore: distributedKVStore.SingleKVStore): void {
if (kvStore != undefined) {
kvStore.getEntries('key_test_string', async (err: BusinessError, entries: distributedKVStore.Entry[]) => {
if (err != undefined) {
console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`);
return;
}
if (kvStore != null && entries.length != 0) {
console.info(`ECDB_Encry old data:${entries[0].key},value :${entries[0].value.value.toString()}`)
await kvStore.put(entries[0].key, "new value_test_string" + String(Date.now()) + 'new').then(() => {
}).catch((err: BusinessError) => {
console.error(`Failed to put.code is ${err.code},message is ${err.message}`);
});
}
console.info(`ECDB_Encry update success`)
});
}
}
} |
application-dev\database\encrypted_estore_guidelines.md | // SecretKeyObserver.ts
import { ECStoreManager } from './ECStoreManager';
export enum SecretStatus {
Lock,
UnLock
}
export class SecretKeyObserver {
onLock(): void {
this.lockStatuas = SecretStatus.Lock;
this.storeManager.closeEStore();
}
onUnLock(): void {
this.lockStatuas = SecretStatus.UnLock;
}
getCurrentStatus(): number {
return this.lockStatuas;
}
initialize(storeManager: ECStoreManager): void {
this.storeManager = storeManager;
}
updatelockStatus(code: number) {
if (code === SecretStatus.Lock) {
this.onLock();
} else {
this.lockStatuas = code;
}
}
// Obtain the screen lock status.
private lockStatuas: number = SecretStatus.UnLock;
private storeManager: ECStoreManager;
}
export let lockObserve = new SecretKeyObserver(); |
application-dev\database\encrypted_estore_guidelines.md | // ECStoreManager.ts
import { distributedKVStore } from '@kit.ArkData';
import { Mover } from './Mover';
import { BusinessError } from '@kit.BasicServicesKit';
import { StoreInfo, Store } from './Store';
import { SecretStatus } from './SecretKeyObserver';
let store = new Store();
export class ECStoreManager {
config(cInfo: StoreInfo, other: StoreInfo): void {
this.cInfo = cInfo;
this.eInfo = other;
}
configDataMover(mover: Mover): void {
this.mover = mover;
}
async getCurrentStore(screanStatus: number): Promise<distributedKVStore.SingleKVStore> {
console.info(`ECDB_Encry GetCurrentStore start screanStatus: ${screanStatus}`);
if (screanStatus === SecretStatus.UnLock) {
try {
this.eStore = await store.getECStore(this.eInfo);
} catch (e) {
let error = e as BusinessError;
console.error(`Failed to GetECStore.code is ${error.code},message is ${error.message}`);
}
// Obtain an EL5 database when the screen is unlocked.
if (this.needMove) {
if (this.eStore != undefined && this.cStore != undefined) {
await this.mover.move(this.eStore, this.cStore);
}
this.deleteCStore();
console.info(`ECDB_Encry Data migration is complete. Destroy cstore`);
this.needMove = false;
}
return this.eStore;
} else {
// Obtain an EL2 database when the screen is locked.
this.needMove = true;
try {
this.cStore = await store.getECStore(this.cInfo);
} catch (e) {
let error = e as BusinessError;
console.error(`Failed to GetECStore.code is ${error.code},message is ${error.message}`);
}
return this.cStore;
}
}
closeEStore(): void {
try {
let kvManager = distributedKVStore.createKVManager(this.eInfo.kvManagerConfig);
console.info("Succeeded in creating KVManager");
if (kvManager != undefined) {
kvManager.closeKVStore(this.eInfo.kvManagerConfig.bundleName, this.eInfo.storeId);
this.eStore = null;
console.info(`ECDB_Encry close EStore success`)
}
} catch (e) {
let error = e as BusinessError;
console.error(`Failed to create KVManager.code is ${error.code},message is ${error.message}`);
}
}
deleteCStore(): void {
try {
let kvManager = distributedKVStore.createKVManager(this.cInfo.kvManagerConfig);
console.info("Succeeded in creating KVManager");
if (kvManager != undefined) {
kvManager.deleteKVStore(this.cInfo.kvManagerConfig.bundleName, this.cInfo.storeId);
this.cStore = null;
console.info("ECDB_Encry delete cStore success");
}
} catch (e) {
let error = e as BusinessError;
console.error(`Failed to create KVManager.code is ${error.code},message is ${error.message}`);
}
}
private eStore: distributedKVStore.SingleKVStore = null;
private cStore: distributedKVStore.SingleKVStore = null;
private cInfo: StoreInfo | null = null;
private eInfo: StoreInfo | null = null;
private needMove: boolean = false;
private mover: Mover | null = null;
} |
application-dev\database\encrypted_estore_guidelines.md | // EntryAbility.ets
import { AbilityConstant, application, contextConstant, UIAbility, Want } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { window } from '@kit.ArkUI';
import { distributedKVStore } from '@kit.ArkData';
import { ECStoreManager } from './ECStoreManager';
import { StoreInfo } from './Store';
import { Mover } from './Mover';
import { SecretKeyObserver } from './SecretKeyObserver';
import { commonEventManager } from '@kit.BasicServicesKit';
import { BusinessError } from '@kit.BasicServicesKit';
export let storeManager = new ECStoreManager();
export let e_secretKeyObserver = new SecretKeyObserver();
let mover = new Mover();
let subscriber: commonEventManager.CommonEventSubscriber;
export function createCB(err: BusinessError, commonEventSubscriber: commonEventManager.CommonEventSubscriber) {
if (!err) {
console.info('ECDB_Encry createSubscriber');
subscriber = commonEventSubscriber;
try {
commonEventManager.subscribe(subscriber, (err: BusinessError, data: commonEventManager.CommonEventData) => {
if (err) {
console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`);
} else {
console.info(`ECDB_Encry SubscribeCB ${data.code}`);
e_secretKeyObserver.updatelockStatus(data.code);
}
});
} catch (error) {
const err: BusinessError = error as BusinessError;
console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`);
}
} else {
console.error(`createSubscriber failed, code is ${err.code}, message is ${err.message}`);
}
}
let cInfo: StoreInfo | null = null;
let eInfo: StoreInfo | null = null;
export default class EntryAbility extends UIAbility {
async onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): Promise<void> {
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
let cContext = this.context;
cInfo = {
"kvManagerConfig": {
context: cContext,
bundleName: 'com.example.ecstoredemo',
},
"storeId": "cstore",
"option": {
createIfMissing: true,
encrypt: false,
backup: false,
autoSync: false,
// If kvStoreType is left empty, a device KV store is created by default.
kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION,
// The value distributedKVStore.KVStoreType.DEVICE_COLLABORATION indicates a device KV store.
securityLevel: distributedKVStore.SecurityLevel.S3
}
}
let eContext = await application.createModuleContext(this.context,"entry");
eContext.area = contextConstant.AreaMode.EL5;
eInfo = {
"kvManagerConfig": {
context: eContext,
bundleName: 'com.example.ecstoredemo',
},
"storeId": "estore",
"option": {
createIfMissing: true,
encrypt: false,
backup: false,
autoSync: false,
// If kvStoreType is left empty, a device KV store is created by default.
kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION,
// The value distributedKVStore.KVStoreType.DEVICE_COLLABORATION indicates a device KV store.
securityLevel: distributedKVStore.SecurityLevel.S3
}
}
console.info(`ECDB_Encry store area : estore:${eContext.area},cstore${cContext.area}`);
// Listen for the COMMON_EVENT_SCREEN_LOCK_FILE_ACCESS_STATE_CHANGED event. code == 1 indicates the screen is unlocked, and code==0 indicates the screen is locked.
try {
commonEventManager.createSubscriber({
events: ['COMMON_EVENT_SCREEN_LOCK_FILE_ACCESS_STATE_CHANGED']
}, createCB);
console.info(`ECDB_Encry success subscribe`);
} catch (error) {
const err: BusinessError = error as BusinessError;
console.error(`createSubscriber failed, code is ${err.code}, message is ${err.message}`);
}
storeManager.config(cInfo, eInfo);
storeManager.configDataMover(mover);
e_secretKeyObserver.initialize(storeManager);
}
onDestroy(): void {
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onDestroy');
}
onWindowStageCreate(windowStage: window.WindowStage): void {
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
windowStage.loadContent('pages/Index', (err) => {
if (err.code) {
hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
return;
}
hilog.info(0x0000, 'testTag', 'Succeeded in loading the content.');
});
}
onWindowStageDestroy(): void {
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageDestroy');
}
onForeground(): void {
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onForeground');
}
onBackground(): void {
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onBackground');
}
} |
application-dev\database\encrypted_estore_guidelines.md | // Index.ets
import { storeManager, e_secretKeyObserver } from "../entryability/EntryAbility";
import { distributedKVStore } from '@kit.ArkData';
import { Store } from '../entryability/Store';
let storeOption = new Store();
let lockStatus: number = 1;
@Entry
@Component
struct Index {
@State message: string = 'Hello World';
build() {
Row() {
Column() {
Button ('Lock/Unlock').onClick ((event: ClickEvent) => {
if (lockStatus) {
e_secretKeyObserver.onLock();
lockStatus = 0;
} else {
e_secretKeyObserver.onUnLock();
lockStatus = 1;
}
lockStatus? this.message = "Unlocked": this.message = "Locked";
}).margin("5");
Button('store type').onClick(async (event: ClickEvent) => {
e_secretKeyObserver.getCurrentStatus() ? this.message = "estroe" : this.message = "cstore";
}).margin("5");
Button("put").onClick(async (event: ClickEvent) => {
let store: distributedKVStore.SingleKVStore = await storeManager.getCurrentStore(e_secretKeyObserver.getCurrentStatus());
storeOption.putOnedata(store);
}).margin(5)
Button("Get").onClick(async (event: ClickEvent) => {
let store: distributedKVStore.SingleKVStore = await storeManager.getCurrentStore(e_secretKeyObserver.getCurrentStatus());
storeOption.getDataNum(store);
}).margin(5)
Button("delete").onClick(async (event: ClickEvent) => {
let store: distributedKVStore.SingleKVStore = await storeManager.getCurrentStore(e_secretKeyObserver.getCurrentStatus());
storeOption.deleteOnedata(store);
}).margin(5)
Button("update").onClick(async (event: ClickEvent) => {
let store: distributedKVStore.SingleKVStore = await storeManager.getCurrentStore(e_secretKeyObserver.getCurrentStatus());
storeOption.updateOnedata(store);
}).margin(5)
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
}
.width('100%')
}
.height('100%')
}
} |
application-dev\database\encrypted_estore_guidelines.md | // Mover.ts
import { relationalStore } from '@kit.ArkData';
export class Mover {
async move(eStore: relationalStore.RdbStore, cStore: relationalStore.RdbStore) {
if (eStore != null && cStore != null) {
let predicates = new relationalStore.RdbPredicates('employee');
let resultSet = await cStore.query(predicates);
while (resultSet.goToNextRow()) {
let bucket = resultSet.getRow();
await eStore.insert('employee', bucket);
}
}
}
} |
application-dev\database\encrypted_estore_guidelines.md | // Store.ts
import { relationalStore } from '@kit.ArkData';
import { BusinessError } from '@kit.BasicServicesKit';
import { Context } from '@kit.AbilityKit';
export class StoreInfo {
context: Context;
config: relationalStore.StoreConfig;
storeId: string;
}
let id = 1;
const SQL_CREATE_TABLE = 'CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB)';
export class Store {
async getECStore(storeInfo: StoreInfo): Promise<relationalStore.RdbStore> {
let rdbStore: relationalStore.RdbStore | null;
try {
rdbStore = await relationalStore.getRdbStore(storeInfo.context, storeInfo.config);
if (rdbStore.version == 0) {
await rdbStore.executeSql(SQL_CREATE_TABLE);
console.info(`ECDB_Encry succeeded in getting Store : ${storeInfo.storeId}`);
rdbStore.version = 1;
}
} catch (e) {
let error = e as BusinessError;
console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`);
}
return rdbStore;
}
async putOnedata(rdbStore: relationalStore.RdbStore) {
if (rdbStore != undefined) {
const valueBucket: relationalStore.ValuesBucket = {
ID: id++,
NAME: 'Lisa',
AGE: 18,
SALARY: 100.5,
CODES: new Uint8Array([1, 2, 3, 4, 5]),
};
try {
await rdbStore.insert("EMPLOYEE", valueBucket);
console.info(`ECDB_Encry insert success`);
} catch (e) {
let error = e as BusinessError;
console.error(`An unexpected error occurred. Code:${error.code},message:${error.message}`);
}
}
}
async getDataNum(rdbStore: relationalStore.RdbStore) {
if (rdbStore != undefined) {
try {
let predicates = new relationalStore.RdbPredicates('EMPLOYEE');
let resultSet = await rdbStore.query(predicates);
let count = resultSet.rowCount;
console.info(`ECDB_Encry getdatanum success count : ${count}`);
} catch (e) {
let error = e as BusinessError;
console.error(`An unexpected error occurred. Code:${error.code},message:${error.message}`);
}
}
}
async deleteAlldata(rdbStore: relationalStore.RdbStore) {
if (rdbStore != undefined) {
try {
let predicates = new relationalStore.RdbPredicates('EMPLOYEE');
predicates.equalTo('AGE', 18);
await rdbStore.delete(predicates);
console.info(`ECDB_Encry delete Success`);
} catch (e) {
let error = e as BusinessError;
console.error(`An unexpected error occurred. Code:${error.code},message:${error.message}`);
}
}
}
async updateOnedata(rdbStore: relationalStore.RdbStore) {
if (rdbStore != undefined) {
try {
let predicates = new relationalStore.RdbPredicates('EMPLOYEE');
predicates.equalTo('NAME', 'Lisa');
const valueBucket: relationalStore.ValuesBucket = {
NAME: 'Anna',
SALARY: 100.5,
CODES: new Uint8Array([1, 2, 3, 4, 5]),
};
await rdbStore.update(valueBucket, predicates);
console.info(`ECDB_Encry update success`);
} catch (e) {
let error = e as BusinessError;
console.error(`An unexpected error occurred. Code:${error.code},message:${error.message}`);
}
}
}
} |
application-dev\database\encrypted_estore_guidelines.md | // SecretKeyObserver.ts
import { ECStoreManager } from './ECStoreManager';
export enum SecretStatus {
Lock,
UnLock
}
export class SecretKeyObserver {
onLock(): void {
this.lockStatuas = SecretStatus.Lock;
this.storeManager.closeEStore();
}
onUnLock(): void {
this.lockStatuas = SecretStatus.UnLock;
}
getCurrentStatus(): number {
return this.lockStatuas;
}
initialize(storeManager: ECStoreManager): void {
this.storeManager = storeManager;
}
updatelockStatus(code: number) {
if (this.lockStatuas === SecretStatus.Lock) {
this.onLock();
} else {
this.lockStatuas = code;
}
}
private lockStatuas: number = SecretStatus.UnLock;
private storeManager: ECStoreManager;
}
export let lockObserve = new SecretKeyObserver(); |
application-dev\database\encrypted_estore_guidelines.md | // ECStoreManager.ts
import { relationalStore } from '@kit.ArkData';
import { Mover } from './Mover';
import { BusinessError } from '@kit.BasicServicesKit';
import { StoreInfo, Store } from './Store';
import { SecretStatus } from './SecretKeyObserver';
let store = new Store();
export class ECStoreManager {
config(cInfo: StoreInfo, other: StoreInfo): void {
this.cInfo = cInfo;
this.eInfo = other;
}
configDataMover(mover: Mover): void {
this.mover = mover;
}
async getCurrentStore(screanStatus: number): Promise<relationalStore.RdbStore> {
if (screanStatus === SecretStatus.UnLock) {
try {
this.eStore = await store.getECStore(this.eInfo);
} catch (e) {
let error = e as BusinessError;
console.error(`Failed to GetECStore.code is ${error.code},message is ${error.message}`);
}
// Obtain an EL5 database when the screen is unlocked.
if (this.needMove) {
if (this.eStore != undefined && this.cStore != undefined) {
await this.mover.move(this.eStore, this.cStore);
console.info(`ECDB_Encry cstore data move to estore success`);
}
this.deleteCStore();
this.needMove = false;
}
return this.eStore;
} else {
// Obtain an EL2 database when the screen is locked.
this.needMove = true;
try {
this.cStore = await store.getECStore(this.cInfo);
} catch (e) {
let error = e as BusinessError;
console.error(`Failed to GetECStore.code is ${error.code},message is ${error.message}`);
}
return this.cStore;
}
}
closeEStore(): void {
this.eStore = undefined;
}
async deleteCStore() {
try {
await relationalStore.deleteRdbStore(this.cInfo.context, this.cInfo.storeId)
} catch (e) {
let error = e as BusinessError;
console.error(`Failed to create KVManager.code is ${error.code},message is ${error.message}`);
}
}
private eStore: relationalStore.RdbStore = null;
private cStore: relationalStore.RdbStore = null;
private cInfo: StoreInfo | null = null;
private eInfo: StoreInfo | null = null;
private needMove: boolean = false;
private mover: Mover | null = null;
} |
application-dev\database\encrypted_estore_guidelines.md | // EntryAbility.ets
import { AbilityConstant, contextConstant, UIAbility, Want, application } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { window } from '@kit.ArkUI';
import { relationalStore } from '@kit.ArkData';
import { ECStoreManager } from './ECStoreManager';
import { StoreInfo } from './Store';
import { Mover } from './Mover';
import { SecretKeyObserver } from './SecretKeyObserver';
import { commonEventManager } from '@kit.BasicServicesKit';
import { BusinessError } from '@kit.BasicServicesKit';
export let storeManager = new ECStoreManager();
export let e_secretKeyObserver = new SecretKeyObserver();
let mover = new Mover();
let subscriber: commonEventManager.CommonEventSubscriber;
export function createCB(err: BusinessError, commonEventSubscriber: commonEventManager.CommonEventSubscriber) {
if (!err) {
console.info('ECDB_Encry createSubscriber');
subscriber = commonEventSubscriber;
try {
commonEventManager.subscribe(subscriber, (err: BusinessError, data: commonEventManager.CommonEventData) => {
if (err) {
console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`);
} else {
console.info(`ECDB_Encry SubscribeCB ${data.code}`);
e_secretKeyObserver.updatelockStatus(data.code);
}
});
} catch (error) {
const err: BusinessError = error as BusinessError;
console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`);
}
} else {
console.error(`createSubscriber failed, code is ${err.code}, message is ${err.message}`);
}
}
let cInfo: StoreInfo | null = null;
let eInfo: StoreInfo | null = null;
export default class EntryAbility extends UIAbility {
async onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): Promise<void> {
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
let cContext = this.context;
cInfo = {
context: cContext,
config: {
name: 'cstore.db',
securityLevel: relationalStore.SecurityLevel.S3,
},
storeId: "cstore.db"
};
let eContext = await application.createModuleContext(this.context, "entry");
eContext.area = contextConstant.AreaMode.EL5;
eInfo = {
context: eContext,
config: {
name: 'estore.db',
securityLevel: relationalStore.SecurityLevel.S3,
},
storeId: "estore.db",
};
// Listen for the COMMON_EVENT_SCREEN_LOCK_FILE_ACCESS_STATE_CHANGED event. code == 1 indicates the screen is unlocked, and code==0 indicates the screen is locked.
console.info(`ECDB_Encry store area : estore:${eContext.area},cstore${cContext.area}`)
try {
commonEventManager.createSubscriber({
events: ['COMMON_EVENT_SCREEN_LOCK_FILE_ACCESS_STATE_CHANGED']
}, createCB);
console.info(`ECDB_Encry success subscribe`);
} catch (error) {
const err: BusinessError = error as BusinessError;
console.error(`createSubscriber failed, code is ${err.code}, message is ${err.message}`);
}
storeManager.config(cInfo, eInfo);
storeManager.configDataMover(mover);
e_secretKeyObserver.initialize(storeManager);
}
onDestroy(): void {
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onDestroy');
}
onWindowStageCreate(windowStage: window.WindowStage): void {
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
windowStage.loadContent('pages/Index', (err) => {
if (err.code) {
hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
return;
}
hilog.info(0x0000, 'testTag', 'Succeeded in loading the content.');
});
}
onWindowStageDestroy(): void {
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageDestroy');
}
onForeground(): void {
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onForeground');
}
onBackground(): void {
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onBackground');
}
} |
application-dev\database\encrypted_estore_guidelines.md | // Index.ets
import { storeManager, e_secretKeyObserver } from "../entryability/EntryAbility";
import { relationalStore } from '@kit.ArkData';
import { Store } from '../entryability/Store';
let storeOption = new Store();
let lockStatus: number = 1;
@Entry
@Component
struct Index {
@State message: string = 'Hello World';
build() {
Row() {
Column() {
Button ('Lock/Unlock').onClick ((event: ClickEvent) => {
if (lockStatus) {
e_secretKeyObserver.onLock();
lockStatus = 0;
} else {
e_secretKeyObserver.onUnLock();
lockStatus = 1;
}
lockStatus? this.message = "Unlocked": this.message = "Locked";
}).margin("5");
Button('store type').onClick(async (event: ClickEvent) => {
e_secretKeyObserver.getCurrentStatus() ? this.message = "estroe" : this.message = "cstore";
console.info(`ECDB_Encry current store : ${this.message}`);
}).margin("5");
Button("put").onClick(async (event: ClickEvent) => {
let store: relationalStore.RdbStore = await storeManager.getCurrentStore(e_secretKeyObserver.getCurrentStatus());
storeOption.putOnedata(store);
}).margin(5)
Button("Get").onClick(async (event: ClickEvent) => {
let store: relationalStore.RdbStore = await storeManager.getCurrentStore(e_secretKeyObserver.getCurrentStatus());
storeOption.getDataNum(store);
}).margin(5)
Button("delete").onClick(async (event: ClickEvent) => {
let store: relationalStore.RdbStore = await storeManager.getCurrentStore(e_secretKeyObserver.getCurrentStatus());
storeOption.deleteAlldata(store);
}).margin(5)
Button("update").onClick(async (event: ClickEvent) => {
let store: relationalStore.RdbStore = await storeManager.getCurrentStore(e_secretKeyObserver.getCurrentStatus());
storeOption.updateOnedata(store);
}).margin(5)
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
}
.width('100%')
}
.height('100%')
}
} |
application-dev\database\share-data-by-datashareextensionability.md | import { DataShareExtensionAbility, dataShare, dataSharePredicates, relationalStore, DataShareResultSet } from '@kit.ArkData';
import { Want } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit' |
application-dev\database\share-data-by-datashareextensionability.md | const DB_NAME = 'DB00.db';
const TBL_NAME = 'TBL00';
const DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS "
+ TBL_NAME
+ ' (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, isStudent BOOLEAN, Binary BINARY)';
let rdbStore: relationalStore.RdbStore;
let result: string;
export default class DataShareExtAbility extends DataShareExtensionAbility {
// Override onCreate().
onCreate(want: Want, callback: Function) {
result = this.context.cacheDir + '/datashare.txt';
// Create an RDB store.
relationalStore.getRdbStore(this.context, {
name: DB_NAME,
securityLevel: relationalStore.SecurityLevel.S3
}, (err:BusinessError, data:relationalStore.RdbStore) => {
rdbStore = data;
rdbStore.executeSql(DDL_TBL_CREATE, [], (err) => {
console.info(`DataShareExtAbility onCreate, executeSql done err:${err}`);
});
if (callback) {
callback();
}
});
}
// Override query().
query(uri: string, predicates: dataSharePredicates.DataSharePredicates, columns: Array<string>, callback: Function) {
if (predicates === null || predicates === undefined) {
console.info('invalid predicates');
}
try {
rdbStore.query(TBL_NAME, predicates, columns, (err:BusinessError, resultSet:relationalStore.ResultSet) => {
if (resultSet !== undefined) {
console.info(`resultSet.rowCount:${resultSet.rowCount}`);
}
if (callback !== undefined) {
callback(err, resultSet);
}
});
} catch (err) {
let code = (err as BusinessError).code;
let message = (err as BusinessError).message
console.error(`Failed to query. Code:${code},message:${message}`);
}
}
// Override the batchUpdate API.
batchUpdate(operations:Record<string, Array<dataShare.UpdateOperation>>, callback:Function) {
let recordOps : Record<string, Array<dataShare.UpdateOperation>> = operations;
let results : Record<string, Array<number>> = {};
let a = Object.entries(recordOps);
for (let i = 0; i < a.length; i++) {
let key = a[i][0];
let values = a[i][1];
let result : number[] = [];
for (const value of values) {
rdbStore.update(TBL_NAME, value.values, value.predicates).then(async (rows) => {
console.info('Update row count is ' + rows);
result.push(rows);
}).catch((err:BusinessError) => {
console.info('Update failed, err is ' + JSON.stringify(err));
result.push(-1)
})
}
results[key] = result;
}
callback(null, results);
}
batchInsert(uri: string, valueBuckets:Array<ValuesBucket>, callback:Function) {
if (valueBuckets == null || valueBuckets.length == undefined) {
return;
}
let resultNum = valueBuckets.length
rdbStore.batchInsert(TBL_NAME, valueBuckets, (err, ret) => {
if (callback !== undefined) {
callback(err, ret);
}
});
}
async normalizeUri(uri: string, callback:Function) {
let ret = "normalize+" + uri;
let err:BusinessError = {
message: "message",
code: 0,
name: 'name'
};
await callback(err, ret);
}
async denormalizeUri(uri: string, callback:Function) {
let ret = "denormalize+" + uri;
let err:BusinessError = {
message: "message",
code: 0,
name: 'name'
};
await callback(err, ret);
}
// Override other APIs as required.
}; |
application-dev\database\share-data-by-datashareextensionability.md | import { UIAbility } from '@kit.AbilityKit';
import { dataShare, dataSharePredicates, DataShareResultSet, ValuesBucket } from '@kit.ArkData';
import { window } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit'; |
application-dev\database\share-data-by-datashareextensionability.md | // Different from the URI defined in the module.json5 file, the URI passed in the parameter has an extra slash (/), because there is a DeviceID parameter between the second and the third slash (/).
let dseUri = ('datashare:///com.ohos.settingsdata.DataAbility'); |
application-dev\database\share-data-by-datashareextensionability.md | let dsHelper: dataShare.DataShareHelper | undefined = undefined;
let abilityContext: Context;
export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage: window.WindowStage) {
abilityContext = this.context;
dataShare.createDataShareHelper(abilityContext, dseUri, (err, data) => {
dsHelper = data;
});
}
} |
application-dev\database\share-data-by-datashareextensionability.md | // Construct a piece of data.
let key1 = 'name';
let key2 = 'age';
let key3 = 'isStudent';
let key4 = 'Binary';
let valueName1 = 'ZhangSan';
let valueName2 = 'LiSi';
let valueAge1 = 21;
let valueAge2 = 18;
let valueIsStudent1 = false;
let valueIsStudent2 = true;
let valueBinary = new Uint8Array([1, 2, 3]);
let valuesBucket: ValuesBucket = { key1: valueName1, key2: valueAge1, key3: valueIsStudent1, key4: valueBinary };
let updateBucket: ValuesBucket = { key1: valueName2, key2: valueAge2, key3: valueIsStudent2, key4: valueBinary };
let predicates = new dataSharePredicates.DataSharePredicates();
let valArray = ['*'];
let record: Record<string, Array<dataShare.UpdateOperation>> = {};
let operations1: Array<dataShare.UpdateOperation> = [];
let operations2: Array<dataShare.UpdateOperation> = [];
let operation1: dataShare.UpdateOperation = {
values: valuesBucket,
predicates: predicates
}
operations1.push(operation1);
let operation2: dataShare.UpdateOperation = {
values: updateBucket,
predicates: predicates
}
operations2.push(operation2);
record["uri1"] = operations1;
record["uri2"] = operations2;
if (dsHelper != undefined) {
// Insert a piece of data.
(dsHelper as dataShare.DataShareHelper).insert(dseUri, valuesBucket, (err:BusinessError, data:number) => {
console.info(`dsHelper insert result:${data}`);
});
// Update data.
(dsHelper as dataShare.DataShareHelper).update(dseUri, predicates, updateBucket, (err:BusinessError, data:number) => {
console.info(`dsHelper update result:${data}`);
});
// Query data.
(dsHelper as dataShare.DataShareHelper).query(dseUri, predicates, valArray, (err:BusinessError, data:DataShareResultSet) => {
console.info(`dsHelper query result:${data}`);
});
// Delete data.
(dsHelper as dataShare.DataShareHelper).delete(dseUri, predicates, (err:BusinessError, data:number) => {
console.info(`dsHelper delete result:${data}`);
});
// Update data in batches.
(dsHelper as dataShare.DataShareHelper).batchUpdate(record).then((data: Record<string, Array<number>>) => {
// Traverse data to obtain the update result of each data record. value indicates the number of data records that are successfully updated. If value is less than 0, the update fails.
let a = Object.entries(data);
for (let i = 0; i < a.length; i++) {
let key = a[i][0];
let values = a[i][1]
console.info(`Update uri:${key}`);
for (const value of values) {
console.info(`Update result:${value}`);
}
}
});
// Close the DataShareHelper instance.
(dsHelper as dataShare.DataShareHelper).close();
} |
application-dev\database\share-data-by-silent-access.md | import { dataShare, dataSharePredicates, ValuesBucket } from '@kit.ArkData';
import { UIAbility } from '@kit.AbilityKit';
import { window } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit' |
application-dev\database\share-data-by-silent-access.md | let dseUri = ('datashareproxy://com.ohos.settingsdata/entry/settingsdata/USER_SETTINGSDATA_SECURE'); |
application-dev\database\share-data-by-silent-access.md | let dsHelper: dataShare.DataShareHelper | undefined = undefined;
let abilityContext: Context;
export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage: window.WindowStage) {
abilityContext = this.context;
dataShare.createDataShareHelper(abilityContext, dseUri, {
isProxy: true
}, (err, data) => {
dsHelper = data;
});
}
} |
application-dev\database\share-data-by-silent-access.md | // Construct a piece of data.
let key1 = 'name';
let key2 = 'age';
let key3 = 'isStudent';
let key4 = 'Binary';
let valueName1 = 'ZhangSan';
let valueName2 = 'LiSi';
let valueAge1 = 21;
let valueAge2 = 18;
let valueIsStudent1 = false;
let valueIsStudent2 = true;
let valueBinary = new Uint8Array([1, 2, 3]);
let valuesBucket: ValuesBucket = { key1: valueName1, key2: valueAge1, key3: valueIsStudent1, key4: valueBinary };
let updateBucket: ValuesBucket = { key1: valueName2, key2: valueAge2, key3: valueIsStudent2, key4: valueBinary };
let predicates = new dataSharePredicates.DataSharePredicates();
let valArray = ['*'];
if (dsHelper != undefined) {
// Insert a piece of data.
(dsHelper as dataShare.DataShareHelper).insert(dseUri, valuesBucket, (err, data) => {
console.info(`dsHelper insert result:${data}`);
});
// Update data.
(dsHelper as dataShare.DataShareHelper).update(dseUri, predicates, updateBucket, (err, data) => {
console.info(`dsHelper update result:${data}`);
});
// Query data.
(dsHelper as dataShare.DataShareHelper).query(dseUri, predicates, valArray, (err, data) => {
console.info(`dsHelper query result:${data}`);
});
// Delete data.
(dsHelper as dataShare.DataShareHelper).delete(dseUri, predicates, (err, data) => {
console.info(`dsHelper delete result:${data}`);
});
} |
application-dev\database\share-data-by-silent-access.md | function onCallback(err: BusinessError, node: dataShare.RdbDataChangeNode) {
console.info("uri " + JSON.stringify(node.uri));
console.info("templateId " + JSON.stringify(node.templateId));
console.info("data length " + node.data.length);
for (let i = 0; i < node.data.length; i++) {
console.info("data " + node.data[i]);
}
}
let key21: string = "p1";
let value21: string = "select * from TBL00";
let key22: string = "p2";
let value22: string = "select name from TBL00";
let template: dataShare.Template = {
predicates: {
key21: value21,
key22: value22,
},
scheduler: ""
}
if(dsHelper != undefined)
{
(dsHelper as dataShare.DataShareHelper).addTemplate(dseUri, "111", template);
}
let templateId: dataShare.TemplateId = {
subscriberId: "111",
bundleNameOfOwner: "com.ohos.settingsdata"
}
if(dsHelper != undefined) {
// When DatamgrService modifies data, onCallback is invoked to return the data queried based on the rules in the template.
let result: Array<dataShare.OperationResult> = (dsHelper as dataShare.DataShareHelper).on("rdbDataChange", [dseUri], templateId, onCallback);
} |
application-dev\database\share-data-by-silent-access.md | import { dataShare } from '@kit.ArkData';
import { UIAbility } from '@kit.AbilityKit';
import { window } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit'; |
application-dev\database\share-data-by-silent-access.md | let dseUri = ('datashareproxy://com.acts.ohos.data.datasharetest/weather'); |
application-dev\database\share-data-by-silent-access.md | let dsHelper: dataShare.DataShareHelper | undefined = undefined;
let abilityContext: Context;
export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage: window.WindowStage) {
abilityContext = this.context;
dataShare.createDataShareHelper(abilityContext, dseUri, {isProxy : true}, (err, data) => {
dsHelper = data;
});
}
} |
application-dev\database\share-data-by-silent-access.md | // Construct two pieces of data. The first data is not configured with proxyDatas and cannot be accessed by other applications.
let data : Array<dataShare.PublishedItem> = [
{key:"city", subscriberId:"11", data:"xian"},
{key:"datashareproxy://com.acts.ohos.data.datasharetest/weather", subscriberId:"11", data:JSON.stringify("Qing")}];
// Publish data.
if (dsHelper != undefined) {
let result: Array<dataShare.OperationResult> = await (dsHelper as dataShare.DataShareHelper).publish(data, "com.acts.ohos.data.datasharetestclient");
} |
application-dev\database\share-data-by-silent-access.md | function onPublishCallback(err: BusinessError, node:dataShare.PublishedDataChangeNode) {
console.info("onPublishCallback");
}
let uris:Array<string> = ["city", "datashareproxy://com.acts.ohos.data.datasharetest/weather"];
if (dsHelper != undefined) {
let result: Array<dataShare.OperationResult> = (dsHelper as dataShare.DataShareHelper).on("publishedDataChange", uris, "11", onPublishCallback);
} |
application-dev\database\share-data-by-silent-access.md | import { dataShare } from '@kit.ArkData';
import { UIAbility } from '@kit.AbilityKit';
import { window } from '@kit.ArkUI'; |
application-dev\database\share-data-by-silent-access.md | let dseUri = ('datashareproxy:///com.ohos.settingsdata/entry/DB00/TBL00'); |
application-dev\database\share-data-by-silent-access.md | let abilityContext: Context;
export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage: window.WindowStage) {
abilityContext = this.context;
dataShare.enableSilentProxy(abilityContext, dseUri);
}
} |
application-dev\database\unified-data-channels.md | import { unifiedDataChannel, uniformTypeDescriptor, uniformDataStruct } from '@kit.ArkData'; |
application-dev\database\unified-data-channels.md | import { BusinessError } from '@kit.BasicServicesKit';
import { image } from '@kit.ImageKit';
// Create plaintext data.
let plainTextObj : uniformDataStruct.PlainText = {
uniformDataType: 'general.plain-text',
textContent : 'Hello world',
abstract : 'This is abstract',
}
let record = new unifiedDataChannel.UnifiedRecord(uniformTypeDescriptor.UniformDataType.PLAIN_TEXT, plainTextObj);
// Create HTML data.
let htmlObj : uniformDataStruct.HTML = {
uniformDataType :'general.html',
htmlContent : '<div><p>Hello world</p></div>',
plainContent : 'Hello world',
}
// Add a new entry to the data record, storing the same data in another format.
record.addEntry(uniformTypeDescriptor.UniformDataType.HTML, htmlObj);
let unifiedData = new unifiedDataChannel.UnifiedData(record);
// Create pixelMap data.
let arrayBuffer = new ArrayBuffer(4*3*3);
let opt : image.InitializationOptions = { editable: true, pixelFormat: 3, size: { height: 3, width: 3 }, alphaType: 3 };
let pixelMap : uniformDataStruct.PixelMap = {
uniformDataType : 'openharmony.pixel-map',
pixelMap : image.createPixelMapSync(arrayBuffer, opt),
}
unifiedData.addRecord(new unifiedDataChannel.UnifiedRecord(uniformTypeDescriptor.UniformDataType.OPENHARMONY_PIXEL_MAP, pixelMap));
// Specify the type of the data channel to which the data is to be inserted.
let options: unifiedDataChannel.Options = {
intention: unifiedDataChannel.Intention.DATA_HUB
}
try {
unifiedDataChannel.insertData(options, unifiedData, (err, key) => {
if (err === undefined) {
console.info(`Succeeded in inserting data. key = ${key}`);
} else {
console.error(`Failed to insert data. code is ${err.code},message is ${err.message} `);
}
});
} catch (e) {
let error: BusinessError = e as BusinessError;
console.error(`Insert data throws an exception. code is ${error.code},message is ${error.message} `);
} |
application-dev\database\unified-data-channels.md | let plainTextUpdate : uniformDataStruct.PlainText = {
uniformDataType: 'general.plain-text',
textContent : 'How are you',
abstract : 'This is abstract',
}
let recordUpdate = new unifiedDataChannel.UnifiedRecord(uniformTypeDescriptor.UniformDataType.PLAIN_TEXT, plainTextUpdate);
let htmlUpdate : uniformDataStruct.HTML = {
uniformDataType :'general.html',
htmlContent : '<div><p>How are you</p></div>',
plainContent : 'How are you',
}
recordUpdate.addEntry(uniformTypeDescriptor.UniformDataType.HTML, htmlUpdate);
let unifiedDataUpdate = new unifiedDataChannel.UnifiedData(recordUpdate);
// Specify the URI of the UnifiedData object to update.
let optionsUpdate: unifiedDataChannel.Options = {
//The key here is an example and cannot be directly used. Use the value in the callback of insertData().
key: 'udmf://DataHub/com.ohos.test/0123456789'
};
try {
unifiedDataChannel.updateData(optionsUpdate, unifiedDataUpdate, (err) => {
if (err === undefined) {
console.info('Succeeded in updating data.');
} else {
console.error(`Failed to update data. code is ${err.code},message is ${err.message} `);
}
});
} catch (e) {
let error: BusinessError = e as BusinessError;
console.error(`Update data throws an exception. code is ${error.code},message is ${error.message} `);
} |
application-dev\database\unified-data-channels.md | // Specify the type of the data channel whose data is to be deleted.
let optionsDelete: unifiedDataChannel.Options = {
intention: unifiedDataChannel.Intention.DATA_HUB
};
try {
unifiedDataChannel.deleteData(optionsDelete, (err, data) => {
if (err === undefined) {
console.info(`Succeeded in deleting data. size = ${data.length}`);
for (let i = 0; i < data.length; i++) {
let records = data[i].getRecords();
for (let j = 0; j < records.length; j++) {
let types = records[j].getTypes();
// Obtain data of the specified format from the record based on service requirements.
if (types.includes(uniformTypeDescriptor.UniformDataType.PLAIN_TEXT)) {
let text = records[j].getEntry(uniformTypeDescriptor.UniformDataType.PLAIN_TEXT) as uniformDataStruct.PlainText;
console.info(`${i + 1}.${text.textContent}`);
}
if (types.includes(uniformTypeDescriptor.UniformDataType.HTML)) {
let html = records[j].getEntry(uniformTypeDescriptor.UniformDataType.HTML) as uniformDataStruct.HTML;
console.info(`${i + 1}.${html.htmlContent}`);
}
}
}
} else {
console.error(`Failed to delete data. code is ${err.code},message is ${err.message} `);
}
});
} catch (e) {
let error: BusinessError = e as BusinessError;
console.error(`Delete data throws an exception. code is ${error.code},message is ${error.message} `);
} |
application-dev\database\unified-data-channels.md | import { unifiedDataChannel, uniformTypeDescriptor, uniformDataStruct } from '@kit.ArkData'; |
application-dev\database\unified-data-channels.md | import { BusinessError } from '@kit.BasicServicesKit';
// Specify the type of the data channel whose data is to be queried.
let options: unifiedDataChannel.Options = {
intention: unifiedDataChannel.Intention.DATA_HUB
};
try {
unifiedDataChannel.queryData(options, (err, data) => {
if (err === undefined) {
console.info(`Succeeded in querying data. size = ${data.length}`);
for (let i = 0; i < data.length; i++) {
let records = data[i].getRecords();
for (let j = 0; j < records.length; j++) {
let types = records[j].getTypes();
// Obtain data of the specified format from the record based on service requirements.
if (types.includes(uniformTypeDescriptor.UniformDataType.PLAIN_TEXT)) {
let text = records[j].getEntry(uniformTypeDescriptor.UniformDataType.PLAIN_TEXT) as uniformDataStruct.PlainText;
console.info(`${i + 1}.${text.textContent}`);
}
if (types.includes(uniformTypeDescriptor.UniformDataType.HTML)) {
let html = records[j].getEntry(uniformTypeDescriptor.UniformDataType.HTML) as uniformDataStruct.HTML;
console.info(`${i + 1}.${html.htmlContent}`);
}
}
}
} else {
console.error(`Failed to query data. code is ${err.code},message is ${err.message} `);
}
});
} catch(e) {
let error: BusinessError = e as BusinessError;
console.error(`Query data throws an exception. code is ${error.code},message is ${error.message} `);
} |
application-dev\database\uniform-data-structure.md | // 1. Import the unifiedDataChannel and uniformTypeDescriptor modules.
import { uniformDataStruct, uniformTypeDescriptor, unifiedDataChannel } from '@kit.ArkData';
// 2. Create a data record for a hyperlink.
let hyperlinkDetails : Record<string, string> = {
'attr1': 'value1',
'attr2': 'value2',
}
let hyperlink : uniformDataStruct.Hyperlink = {
uniformDataType:'general.hyperlink',
url : 'www.XXX.com',
description : 'This is the description of this hyperlink',
details : hyperlinkDetails,
}
hyperlink.description = '...'; // Set description of the hyperlink.
console.info(`hyperlink url = ${hyperlink.url}`); // Access object attributes.
// 3. Create a data record for a plain text and add it to the UnifiedData instance created.
let plainTextDetails : Record<string, string> = {
'attr1': 'value1',
'attr2': 'value2',
}
let plainText : uniformDataStruct.PlainText = {
uniformDataType: 'general.plain-text',
textContent : 'This is plainText textContent example',
abstract : 'this is abstract',
details : plainTextDetails,
}
// 4. Create a UnifiedData instance.
let unifiedData = new unifiedDataChannel.UnifiedData();
let hyperlinkRecord = new unifiedDataChannel.UnifiedRecord(uniformTypeDescriptor.UniformDataType.HYPERLINK, hyperlink);
let plainTextRecord = new unifiedDataChannel.UnifiedRecord(uniformTypeDescriptor.UniformDataType.PLAIN_TEXT, plainText);
// 5. Add a plainText data record.
unifiedData.addRecord(hyperlinkRecord);
unifiedData.addRecord(plainTextRecord);
// 6. Obtain all data records in this UnifiedData instance.
let records = unifiedData.getRecords();
// 7. Traverse all records, determine the data type of the record, and convert the record into a child class object to obtain the original data record.
for (let i = 0; i < records.length; i ++) {
let unifiedDataRecord = records[i] as unifiedDataChannel.UnifiedRecord;
let record = unifiedDataRecord.getValue() as object;
if (record != undefined) {
// Obtain the type of each data record.
let type : string = record["uniformDataType"];
switch (type) {
case uniformTypeDescriptor.UniformDataType.HYPERLINK:
Object.keys(record).forEach(key => {
console.info('show records: ' + key + ', value:' + record[key]);
});
break;
case uniformTypeDescriptor.UniformDataType.PLAIN_TEXT:
Object.keys(record).forEach(key => {
console.info('show records: ' + key + ', value:' + record[key]);
});
break;
default:
break;
}
}
} |
application-dev\database\uniform-data-type-descriptors.md | // 1. Import the module.
import { uniformTypeDescriptor } from '@kit.ArkData';
try {
// 2. Obtain the UTD type ID (typeId) based on the file name extension .mp3, and then obtain properties of the UTD.
let fileExtention = '.mp3';
let typeId1 = uniformTypeDescriptor.getUniformDataTypeByFilenameExtension(fileExtention);
let typeObj1 = uniformTypeDescriptor.getTypeDescriptor(typeId1);
console.info('typeId:' + typeObj1.typeId);
console.info('belongingToTypes:' + typeObj1.belongingToTypes);
console.info('description:' + typeObj1.description);
console.info('referenceURL:' + typeObj1.referenceURL);
console.info('filenameExtensions:' + typeObj1.filenameExtensions);
console.info('mimeTypes:' + typeObj1.mimeTypes);
// 3. Obtain the UTD type ID based on audio/mp3, and then obtain properties of the UTD.
let mineType = 'audio/mp3';
let typeId2 = uniformTypeDescriptor.getUniformDataTypeByMIMEType(mineType);
let typeObj2 = uniformTypeDescriptor.getTypeDescriptor(typeId2);
console.info('typeId:' + typeObj2.typeId);
console.info('belongingToTypes:' + typeObj2.belongingToTypes);
console.info('description:' + typeObj2.description);
console.info('filenameExtensions:' + typeObj2.filenameExtensions);
console.info('mimeTypes:' + typeObj2.mimeTypes);
// 4. Compare the two UTDs to check whether they are the same.
if (typeObj1 != null && typeObj2 != null) {
let ret = typeObj1.equals(typeObj2);
console.info('typeObj1 equals typeObj2, ret:' + ret);
}
// 5. Check whether general.mp3 belongs to general.audio.
if (typeObj1 != null) {
let ret = typeObj1.belongsTo('general.audio');
console.info('belongsTo, ret:' + ret);
let mediaTypeObj = uniformTypeDescriptor.getTypeDescriptor('general.media');
ret = mediaTypeObj.isHigherLevelType('general.audio'); // Check the relationship between them.
console.info('isHigherLevelType, ret:' + ret);
}
} catch (err) {
console.error('err message:' + err.message + ', err code:' + err.code);
} |
application-dev\database\uniform-data-type-descriptors.md | // 1. Import the module.
import { uniformTypeDescriptor } from '@kit.ArkData';
try {
// 2. Obtain the UTD type ID based on the file name extension .ts.
let fileExtention = '.ts';
let typeIds = uniformTypeDescriptor.getUniformDataTypesByFilenameExtension(fileExtention);
for (let typeId of typeIds) {
// 3. Obtain the MIME types based on the UTD type ID.
let typeObj = uniformTypeDescriptor.getTypeDescriptor(typeId);
let mimeTypes = typeObj.mimeTypes;
console.info('mimeTypes:' + mimeTypes);
}
} catch (err) {
console.error('err message:' + err.message + ', err code:' + err.code);
} |
application-dev\database\uniform-data-type-descriptors.md | // 1. Import the module.
import { uniformTypeDescriptor } from '@kit.ArkData';
try {
// 2. Obtain the UTD type ID based on the MIME type text/plain.
let mineType = 'text/plain';
let typeIds = uniformTypeDescriptor.getUniformDataTypesByMIMEType(mineType);
for (let typeId of typeIds) {
// 3. Obtain the MIME types based on the UTD type ID.
let typeObj = uniformTypeDescriptor.getTypeDescriptor(typeId);
let filenameExtensions = typeObj.filenameExtensions;
console.info('filenameExtensions:' + filenameExtensions);
}
} catch (err) {
console.error('err message:' + err.message + ', err code:' + err.code);
} |
application-dev\device\driver\driverextensionability.md | import { DriverExtensionAbility } from '@kit.DriverDevelopmentKit';
import { Want } from '@kit.AbilityKit';
import { rpc } from '@kit.IPCKit';
const REQUEST_CODE = 99; // Negotiate the request code with the peripheral client. |
application-dev\device\driver\driverextensionability.md | class StubTest extends rpc.RemoteObject {
// Receive a message from the application and return the processing result to the client.
onRemoteMessageRequest(code: number, data: rpc.MessageSequence, reply: rpc.MessageSequence,
option: rpc.MessageOption) {
if (code === REQUEST_CODE) {
// Receive the data sent from the application.
// When the application calls data.writeString() multiple times to write data, the driver can receive the corresponding data by calling data.readString() for multiple times.
let optFir: string = data.readString();
// The driver returns the data processing result to the application.
// In the example, Hello is received and Hello World is returned to the application.
reply.writeString(optFir + ` World`);
}
return true;
}
} |
application-dev\device\driver\driverextensionability.md | export default class DriverExtAbility extends DriverExtensionAbility {
onInit(want: Want) {
console.info('testTag', `onInit, want: ${want.abilityName}`);
}
onRelease() {
console.info('testTag', `onRelease`);
}
onConnect(want: Want) {
console.info('testTag', `onConnect, want: ${want.abilityName}`);
return new StubTest("test");
}
onDisconnect(want: Want) {
console.info('testTag', `onDisconnect, want: ${want.abilityName}`);
}
onDump(params: Array<string>) {
console.info('testTag', `onDump, params:` + JSON.stringify(params));
return ['params'];
}
} |
application-dev\device\driver\externaldevice-guidelines.md | import { hilog } from '@kit.PerformanceAnalysisKit';
import { deviceManager } from '@kit.DriverDevelopmentKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { rpc } from '@kit.IPCKit';
const REQUEST_CODE: number = 99; // Custom communication code, which is for reference only.
const productId: number = 4258; // Declare the product ID of the connected USB device.
const vendorId: number = 4817; // Declare the vendor ID of the connected USB device. |
application-dev\device\driver\externaldevice-guidelines.md | @State message: string = 'Hello';
private remote: rpc.IRemoteObject | null = null; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.