diff --git a/data_object/frameworks/innerkitsimpl/include/adaptor/hitrace.h b/data_object/frameworks/innerkitsimpl/include/adaptor/hitrace.h index 85ac55e8ff9f6399943dff98083b1f17f3788f73..7ceb5980aa3b4a68beca3ea49dd196da29acdc90 100644 --- a/data_object/frameworks/innerkitsimpl/include/adaptor/hitrace.h +++ b/data_object/frameworks/innerkitsimpl/include/adaptor/hitrace.h @@ -19,14 +19,14 @@ namespace OHOS { namespace ObjectStore { -class HiTrace final { +class DataObjectHiTrace final { public: - inline HiTrace(const std::string &value) + inline DataObjectHiTrace(const std::string &value) { StartTrace(HITRACE_TAG_DISTRIBUTEDDATA, value); } - inline ~HiTrace() + inline ~DataObjectHiTrace() { FinishTrace(HITRACE_TAG_DISTRIBUTEDDATA); } diff --git a/data_object/frameworks/innerkitsimpl/src/adaptor/distributed_object_impl.cpp b/data_object/frameworks/innerkitsimpl/src/adaptor/distributed_object_impl.cpp index 1e1722ab1d4cba1f1c54f99fd1e4b1af639d2e56..d7c0e464e1acede27cfcb5d37a8198e17889ad1c 100644 --- a/data_object/frameworks/innerkitsimpl/src/adaptor/distributed_object_impl.cpp +++ b/data_object/frameworks/innerkitsimpl/src/adaptor/distributed_object_impl.cpp @@ -55,7 +55,7 @@ uint32_t GetNum(Bytes &data, uint32_t offset, void *val, uint32_t valLen) uint32_t DistributedObjectImpl::PutDouble(const std::string &key, double value) { - HiTrace trace(std::string(__FUNCTION__)); + DataObjectHiTrace trace(std::string(__FUNCTION__)); Bytes data; Type type = Type::TYPE_DOUBLE; PutNum(&type, 0, sizeof(type), data); @@ -69,7 +69,7 @@ uint32_t DistributedObjectImpl::PutDouble(const std::string &key, double value) uint32_t DistributedObjectImpl::PutBoolean(const std::string &key, bool value) { - HiTrace trace(std::string(__FUNCTION__)); + DataObjectHiTrace trace(std::string(__FUNCTION__)); Bytes data; Type type = Type::TYPE_BOOLEAN; PutNum(&type, 0, sizeof(type), data); @@ -83,7 +83,7 @@ uint32_t DistributedObjectImpl::PutBoolean(const std::string &key, bool value) uint32_t DistributedObjectImpl::PutString(const std::string &key, const std::string &value) { - HiTrace trace(std::string(__FUNCTION__)); + DataObjectHiTrace trace(std::string(__FUNCTION__)); Bytes data; Type type = Type::TYPE_STRING; PutNum(&type, 0, sizeof(type), data); @@ -172,7 +172,7 @@ DistributedObjectImpl::DistributedObjectImpl(const std::string &sessionId, FlatO uint32_t DistributedObjectImpl::PutComplex(const std::string &key, const std::vector &value) { - HiTrace trace(std::string(__FUNCTION__)); + DataObjectHiTrace trace(std::string(__FUNCTION__)); Bytes data; Type type = Type::TYPE_COMPLEX; PutNum(&type, 0, sizeof(type), data); diff --git a/data_object/frameworks/innerkitsimpl/src/adaptor/distributed_object_store_impl.cpp b/data_object/frameworks/innerkitsimpl/src/adaptor/distributed_object_store_impl.cpp index 5c51ac09b02c2eb700408ab0ceb182e2db013b13..c99c4019dfadf2c51b225f6c0e4dcbcf001c6f65 100644 --- a/data_object/frameworks/innerkitsimpl/src/adaptor/distributed_object_store_impl.cpp +++ b/data_object/frameworks/innerkitsimpl/src/adaptor/distributed_object_store_impl.cpp @@ -62,7 +62,7 @@ void DistributedObjectStoreImpl::RemoveCacheObject(const std::string &sessionId) DistributedObject *DistributedObjectStoreImpl::CreateObject(const std::string &sessionId) { - HiTrace trace(std::string(__FUNCTION__)); + DataObjectHiTrace trace(std::string(__FUNCTION__)); if (flatObjectStore_ == nullptr) { LOG_ERROR("DistributedObjectStoreImpl::CreateObject store not opened!"); return nullptr; @@ -83,7 +83,7 @@ DistributedObject *DistributedObjectStoreImpl::CreateObject(const std::string &s DistributedObject *DistributedObjectStoreImpl::CreateObject(const std::string &sessionId, uint32_t &status) { - HiTrace trace(std::string(__FUNCTION__)); + DataObjectHiTrace trace(std::string(__FUNCTION__)); if (flatObjectStore_ == nullptr) { LOG_ERROR("DistributedObjectStoreImpl::CreateObject store not opened!"); status = ERR_NULL_OBJECTSTORE; @@ -106,7 +106,7 @@ DistributedObject *DistributedObjectStoreImpl::CreateObject(const std::string &s uint32_t DistributedObjectStoreImpl::DeleteObject(const std::string &sessionId) { - HiTrace trace(std::string(__FUNCTION__)); + DataObjectHiTrace trace(std::string(__FUNCTION__)); if (flatObjectStore_ == nullptr) { LOG_ERROR("DistributedObjectStoreImpl::Sync object err "); return ERR_NULL_OBJECTSTORE; diff --git a/data_object/frameworks/jskitsimpl/include/adaptor/js_common.h b/data_object/frameworks/jskitsimpl/include/adaptor/js_common.h index 74016c64dace7dbfea31f362e9e06bcc36d0866a..dddd4732bec322bbff44bf9340f6945f119b5e74 100644 --- a/data_object/frameworks/jskitsimpl/include/adaptor/js_common.h +++ b/data_object/frameworks/jskitsimpl/include/adaptor/js_common.h @@ -65,7 +65,7 @@ namespace OHOS::ObjectStore { } \ } -#define CHECK_API_VALID(assertion) \ +#define CHECK_API_VALID_ELSE_RETURN_VOID(assertion) \ do { \ if (!(assertion)) { \ std::shared_ptr apiError = std::make_shared(); \ @@ -75,7 +75,7 @@ namespace OHOS::ObjectStore { } \ } while (0) -#define CHECK_VALID(assertion, msg) \ +#define CHECK_VALID_ELSE_RETURN_VOID(assertion, msg) \ do { \ if (!(assertion)) { \ std::shared_ptr innerError = std::make_shared(); \ diff --git a/data_object/frameworks/jskitsimpl/src/adaptor/js_distributedobject.cpp b/data_object/frameworks/jskitsimpl/src/adaptor/js_distributedobject.cpp index 334369e600c58704e15ad2f5177e67799d7b1e39..d6686780892de2d9bb94bc61a99dc1959d697ef3 100644 --- a/data_object/frameworks/jskitsimpl/src/adaptor/js_distributedobject.cpp +++ b/data_object/frameworks/jskitsimpl/src/adaptor/js_distributedobject.cpp @@ -253,8 +253,8 @@ napi_value JSDistributedObject::JSSave(napi_env env, napi_callback_info info) CHECH_STATUS_RETURN_VOID(env, ctxt->wrapper != nullptr, ctxt, "wrapper is null"); CHECH_STATUS_RETURN_VOID(env, ctxt->wrapper->GetObject() != nullptr, ctxt, "object is null"); uint32_t status = ctxt->wrapper->GetObject()->Save(ctxt->deviceId); - CHECK_API_VALID(status != ERR_PROCESSING); - CHECK_VALID(status == SUCCESS, "operation failed"); + CHECK_API_VALID_ELSE_RETURN_VOID(status != ERR_PROCESSING); + CHECK_VALID_ELSE_RETURN_VOID(status == SUCCESS, "operation failed"); ctxt->status = napi_ok; LOG_INFO("end"); }; @@ -298,8 +298,8 @@ napi_value JSDistributedObject::JSRevokeSave(napi_env env, napi_callback_info in CHECH_STATUS_RETURN_VOID(env, ctxt->wrapper != nullptr, ctxt, "wrapper is null"); CHECH_STATUS_RETURN_VOID(env, ctxt->wrapper->GetObject() != nullptr, ctxt, "object is null"); uint32_t status = ctxt->wrapper->GetObject()->RevokeSave(); - CHECK_API_VALID(status != ERR_PROCESSING); - CHECK_VALID(status == SUCCESS, "operation failed"); + CHECK_API_VALID_ELSE_RETURN_VOID(status != ERR_PROCESSING); + CHECK_VALID_ELSE_RETURN_VOID(status == SUCCESS, "operation failed"); ctxt->status = napi_ok; LOG_INFO("end"); }; diff --git a/data_object/interfaces/innerkits/BUILD.gn b/data_object/interfaces/innerkits/BUILD.gn index 2051c3efb9e06a9e7b8e9afdfa0525abd96d6918..0869ce974a377be658c07530428fd5ba8f1821ba 100644 --- a/data_object/interfaces/innerkits/BUILD.gn +++ b/data_object/interfaces/innerkits/BUILD.gn @@ -13,7 +13,7 @@ import("//build/ohos.gni") config("objectstore_config") { - visibility = [ "//foundation/distributeddatamgr/data_object:*" ] + visibility = [ ":*" ] cflags = [ "-DHILOG_ENABLE" ] diff --git a/data_object/interfaces/jskits/BUILD.gn b/data_object/interfaces/jskits/BUILD.gn index 52f503a4df55e5d1f4d72d75dce764793bff3ded..d8d771bfafd3649e7e3eff58de715fd6244885fc 100644 --- a/data_object/interfaces/jskits/BUILD.gn +++ b/data_object/interfaces/jskits/BUILD.gn @@ -43,7 +43,7 @@ action("gen_distributed_data_object_abc") { } config("objectstore_config") { - visibility = [ "//foundation/distributeddatamgr/objectstore:*" ] + visibility = [ ":*" ] cflags = [ "-DHILOG_ENABLE" ] diff --git a/data_object/interfaces/jskits/distributed_data_object.js b/data_object/interfaces/jskits/distributed_data_object.js index a7e2a89fc753a98b856afa9a8465d1c094dcb4f0..f32a1ce45b47cd425a4000a449a4620f6844c59c 100644 --- a/data_object/interfaces/jskits/distributed_data_object.js +++ b/data_object/interfaces/jskits/distributed_data_object.js @@ -13,328 +13,331 @@ * limitations under the License. */ -const distributedObject = requireInternal("data.distributedDataObject"); -const SESSION_ID = "__sessionId"; -const VERSION = "__version"; -const COMPLEX_TYPE = "[COMPLEX]"; -const STRING_TYPE = "[STRING]"; -const NULL_TYPE = "[NULL]" +const distributedObject = requireInternal('data.distributedDataObject'); +const SESSION_ID = '__sessionId'; +const VERSION = '__version'; +const COMPLEX_TYPE = '[COMPLEX]'; +const STRING_TYPE = '[STRING]'; +const NULL_TYPE = '[NULL]'; const JS_ERROR = 1; +const SDK_VERSION_8 = 8; +const SDK_VERSION_9 = 9; class Distributed { - constructor(obj) { - constructorMethod(this, obj); - } + constructor(obj) { + constructorMethod(this, obj); + } - setSessionId(sessionId) { - if (sessionId == null || sessionId == "") { - leaveSession(this.__sdkVersion, this.__proxy); - return false; - } - if (this.__proxy[SESSION_ID] == sessionId) { - console.info("same session has joined " + sessionId); - return true; - } - leaveSession(this.__sdkVersion, this.__proxy); - let object = joinSession(this.__sdkVersion, this.__proxy, this.__objectId, sessionId); - if (object != null) { - this.__proxy = object; - return true; - } - return false; + setSessionId(sessionId) { + if (sessionId == null || sessionId === '') { + leaveSession(this.__sdkVersion, this.__proxy); + return false; } - - on(type, callback) { - onWatch(this.__sdkVersion, type, this.__proxy, callback); - distributedObject.recordCallback(this.__sdkVersion, type, this.__objectId, callback); + if (this.__proxy[SESSION_ID] === sessionId) { + console.info('same session has joined ' + sessionId); + return true; + } + leaveSession(this.__sdkVersion, this.__proxy); + let object = joinSession(this.__sdkVersion, this.__proxy, this.__objectId, sessionId); + if (object != null) { + this.__proxy = object; + return true; } + return false; + } - off(type, callback) { - offWatch(this.__sdkVersion, type, this.__proxy, callback); - if (callback != undefined || callback != null) { - distributedObject.deleteCallback(this.__sdkVersion, type, this.__objectId, callback); - } else { - distributedObject.deleteCallback(this.__sdkVersion, type, this.__objectId); - } + on(type, callback) { + onWatch(this.__sdkVersion, type, this.__proxy, callback); + distributedObject.recordCallback(this.__sdkVersion, type, this.__objectId, callback); + } + + off(type, callback) { + offWatch(this.__sdkVersion, type, this.__proxy, callback); + if (callback !== undefined || callback != null) { + distributedObject.deleteCallback(this.__sdkVersion, type, this.__objectId, callback); + } else { + distributedObject.deleteCallback(this.__sdkVersion, type, this.__objectId); } + } - save(deviceId, callback) { - if (this.__proxy[SESSION_ID] == null || this.__proxy[SESSION_ID] == "") { - console.info("not join a session, can not do save"); - return JS_ERROR; - } - return this.__proxy.save(deviceId, this[VERSION], callback); + save(deviceId, callback) { + if (this.__proxy[SESSION_ID] == null || this.__proxy[SESSION_ID] === '') { + console.info('not join a session, can not do save'); + return JS_ERROR; } + return this.__proxy.save(deviceId, this[VERSION], callback); + } - revokeSave(callback) { - if (this.__proxy[SESSION_ID] == null || this.__proxy[SESSION_ID] == "") { - console.info("not join a session, can not do revoke save"); - return JS_ERROR; - } - return this.__proxy.revokeSave(callback); + revokeSave(callback) { + if (this.__proxy[SESSION_ID] == null || this.__proxy[SESSION_ID] === '') { + console.info('not join a session, can not do revoke save'); + return JS_ERROR; } + return this.__proxy.revokeSave(callback); + } - __proxy; - __objectId; - __version; - __sdkVersion = 8 ; + __proxy; + __objectId; + __version; + __sdkVersion = SDK_VERSION_8; } function constructorMethod(result, obj) { - result.__proxy = obj; - Object.keys(obj).forEach(key => { - Object.defineProperty(result, key, { - enumerable: true, - configurable: true, - get: function () { - return result.__proxy[key]; - }, - set: function (newValue) { - result[VERSION]++; - result.__proxy[key] = newValue; - } - }); + result.__proxy = obj; + Object.keys(obj).forEach(key => { + Object.defineProperty(result, key, { + enumerable: true, + configurable: true, + get: function () { + return result.__proxy[key]; + }, + set: function (newValue) { + result[VERSION]++; + result.__proxy[key] = newValue; + } }); - Object.defineProperty(result, SESSION_ID, { - enumerable: true, - configurable: true, - get: function () { - return result.__proxy[SESSION_ID]; - }, - set: function (newValue) { - result.__proxy[SESSION_ID] = newValue; - } - }); - result.__objectId = randomNum(); - result[VERSION] = 0; - console.info("constructor success "); + }); + Object.defineProperty(result, SESSION_ID, { + enumerable: true, + configurable: true, + get: function () { + return result.__proxy[SESSION_ID]; + }, + set: function (newValue) { + result.__proxy[SESSION_ID] = newValue; + } + }); + result.__objectId = randomNum(); + result[VERSION] = 0; + console.info('constructor success '); } function randomNum() { - return distributedObject.sequenceNum(); + return distributedObject.sequenceNum(); } function newDistributed(obj) { - console.info("start newDistributed"); - if (obj == null) { - console.error("object is null"); - return null; - } - return new Distributed(obj); + console.info('start newDistributed'); + if (obj == null) { + console.error('object is null'); + return null; + } + return new Distributed(obj); } function joinSession(version, obj, objectId, sessionId, context) { - console.info("start joinSession " + sessionId); - if (obj == null || sessionId == null || sessionId == "") { - console.error("object is null"); - return null; - } + console.info('start joinSession ' + sessionId); + if (obj == null || sessionId == null || sessionId === '') { + console.error('object is null'); + return null; + } - let object = null; - if (context != undefined || context != null) { - object = distributedObject.createObjectSync(version, sessionId, objectId, context); - } else { - object = distributedObject.createObjectSync(version, sessionId, objectId); - } + let object = null; + if (context !== undefined || context != null) { + object = distributedObject.createObjectSync(version, sessionId, objectId, context); + } else { + object = distributedObject.createObjectSync(version, sessionId, objectId); + } - if (object == null) { - console.error("create fail"); - return null; - } - Object.keys(obj).forEach(key => { - console.info("start define " + key); - Object.defineProperty(object, key, { - enumerable: true, - configurable: true, - get: function () { - console.info("start get " + key); - let result = object.get(key); - console.info("get " + result); - if (typeof result == "string") { - if (result.startsWith(STRING_TYPE)) { - result = result.substr(STRING_TYPE.length); - } else if (result.startsWith(COMPLEX_TYPE)) { - result = JSON.parse(result.substr(COMPLEX_TYPE.length)) - } else if (result.startsWith(NULL_TYPE)) { - result = null; - } else { - console.error("error type " + result); - } - } - console.info("get " + result + " success"); - return result; - }, - set: function (newValue) { - console.info("start set " + key + " " + newValue); - if (typeof newValue == "object") { - let value = COMPLEX_TYPE + JSON.stringify(newValue); - object.put(key, value); - console.info("set " + key + " " + value); - } else if (typeof newValue == "string") { - let value = STRING_TYPE + newValue; - object.put(key, value); - console.info("set " + key + " " + value); - } else if (newValue === null) { - let value = NULL_TYPE; - object.put(key, value); - console.info("set " + key + " " + value); - } else { - object.put(key, newValue); - console.info("set " + key + " " + newValue); - } - } - }); - if (obj[key] != undefined) { - object[key] = obj[key]; + if (object == null) { + console.error('create fail'); + return null; + } + Object.keys(obj).forEach(key => { + console.info('start define ' + key); + Object.defineProperty(object, key, { + enumerable: true, + configurable: true, + get: function () { + console.info('start get ' + key); + let result = object.get(key); + console.info('get ' + result); + if (typeof result === 'string') { + if (result.startsWith(STRING_TYPE)) { + result = result.substr(STRING_TYPE.length); + } else if (result.startsWith(COMPLEX_TYPE)) { + result = JSON.parse(result.substr(COMPLEX_TYPE.length)); + } else if (result.startsWith(NULL_TYPE)) { + result = null; + } else { + console.error('error type ' + result); + } } + console.info('get ' + result + ' success'); + return result; + }, + set: function (newValue) { + console.info('start set ' + key + ' ' + newValue); + if (typeof newValue === 'object') { + let value = COMPLEX_TYPE + JSON.stringify(newValue); + object.put(key, value); + console.info('set ' + key + ' ' + value); + } else if (typeof newValue === 'string') { + let value = STRING_TYPE + newValue; + object.put(key, value); + console.info('set ' + key + ' ' + value); + } else if (newValue == null) { + let value = NULL_TYPE; + object.put(key, value); + console.info('set ' + key + ' ' + value); + } else { + object.put(key, newValue); + console.info('set ' + key + ' ' + newValue); + } + } }); + if (obj[key] !== undefined) { + object[key] = obj[key]; + } + }); - Object.defineProperty(object, SESSION_ID, { - value: sessionId, - configurable: true, - }); - return object; + Object.defineProperty(object, SESSION_ID, { + value: sessionId, + configurable: true, + }); + return object; } function leaveSession(version, obj) { - console.info("start leaveSession"); - if (obj == null || obj[SESSION_ID] == null || obj[SESSION_ID] == "") { - console.warn("object is null"); - return; - } - Object.keys(obj).forEach(key => { - Object.defineProperty(obj, key, { - value: obj[key], - configurable: true, - writable: true, - enumerable: true, - }); + console.info('start leaveSession'); + if (obj == null || obj[SESSION_ID] == null || obj[SESSION_ID] === '') { + console.warn('object is null'); + return; + } + Object.keys(obj).forEach(key => { + Object.defineProperty(obj, key, { + value: obj[key], + configurable: true, + writable: true, + enumerable: true, }); - // disconnect,delete object - distributedObject.destroyObjectSync(version, obj); - delete obj[SESSION_ID]; + }); + // disconnect,delete object + distributedObject.destroyObjectSync(version, obj); + delete obj[SESSION_ID]; } function onWatch(version, type, obj, callback) { - console.info("start on " + obj[SESSION_ID]); - if (obj[SESSION_ID] != null && obj[SESSION_ID] != undefined && obj[SESSION_ID].length > 0) { - distributedObject.on(version, type, obj, callback); - } + console.info('start on ' + obj[SESSION_ID]); + if (obj[SESSION_ID] != null && obj[SESSION_ID] !== undefined && obj[SESSION_ID].length > 0) { + distributedObject.on(version, type, obj, callback); + } } function offWatch(version, type, obj, callback = undefined) { - console.info("start off " + obj[SESSION_ID] + " " + callback); - if (obj[SESSION_ID] != null && obj[SESSION_ID] != undefined && obj[SESSION_ID].length > 0) { - if (callback != undefined || callback != null) { - distributedObject.off(version, type, obj, callback); - } else { - distributedObject.off(version, type, obj); - } + console.info('start off ' + obj[SESSION_ID] + ' ' + callback); + if (obj[SESSION_ID] != null && obj[SESSION_ID] !== undefined && obj[SESSION_ID].length > 0) { + if (callback !== undefined || callback != null) { + distributedObject.off(version, type, obj, callback); + } else { + distributedObject.off(version, type, obj); } + } } function newDistributedV9(context, obj) { - console.info("start newDistributed"); - let checkparameter = function(parameter, type) { - throw { code : 401, - message :"Parameter error. The type of '" + parameter + "' must be '" + type + "'."}; - } - if(typeof context != "object") { - checkparameter("context", "Context"); - } - if(typeof obj != "object") { - checkparameter("source", "object"); - } - if (obj == null) { - console.error("object is null"); - return null; - } - return new DistributedV9(obj, context); + console.info('start newDistributed'); + let checkparameter = function(parameter, type) { + throw { + code: 401, + message :"Parameter error. The type of '" + parameter + "' must be '" + type + "'."}; + }; + if (typeof context !== 'object') { + checkparameter('context', 'Context'); + } + if (typeof obj !== 'object') { + checkparameter('source', 'object'); + } + if (obj == null) { + console.error('object is null'); + return null; + } + return new DistributedV9(obj, context); } class DistributedV9 { - constructor(obj, context) { - this.__context = context; - constructorMethod(this, obj); - } + constructor(obj, context) { + this.__context = context; + constructorMethod(this, obj); + } - setSessionId(sessionId, callback) { - if (typeof sessionId == "function" || sessionId == null || sessionId == "") { - leaveSession(this.__sdkVersion, this.__proxy); - if (typeof sessionId == "function") { - return sessionId(this.__proxy); - } else if (typeof callback == "function") { - return callback(null, this.__proxy); - } else { - return Promise.resolve(null, this.__proxy); - } - } - if (this.__proxy[SESSION_ID] == sessionId) { - console.info("same session has joined " + sessionId); - if (typeof callback == "function") { - return callback(null, this.__proxy); - } else { - return Promise.resolve(null, this.__proxy); - } - } - leaveSession(this.__sdkVersion, this.__proxy); - let object = joinSession(this.__sdkVersion, this.__proxy, this.__objectId, sessionId, this.__context); - if (object != null) { - this.__proxy = object; - if (typeof callback == "function") { - return callback(null, this.__proxy) - } else { - return Promise.resolve(null, object); - } - } else { - if (typeof callback == "function") { - return callback(null, null); - } else { - return Promise.reject(null, null); - } - } + setSessionId(sessionId, callback) { + if (typeof sessionId === 'function' || sessionId == null || sessionId === '') { + leaveSession(this.__sdkVersion, this.__proxy); + if (typeof sessionId === 'function') { + return sessionId(this.__proxy); + } else if (typeof callback === 'function') { + return callback(null, this.__proxy); + } else { + return Promise.resolve(null, this.__proxy); + } } - - on(type, callback) { - onWatch(this.__sdkVersion, type, this.__proxy, callback); - distributedObject.recordCallback(this.__sdkVersion, type, this.__objectId, callback); + if (this.__proxy[SESSION_ID] === sessionId) { + console.info('same session has joined ' + sessionId); + if (typeof callback === 'function') { + return callback(null, this.__proxy); + } else { + return Promise.resolve(null, this.__proxy); + } } + leaveSession(this.__sdkVersion, this.__proxy); + let object = joinSession(this.__sdkVersion, this.__proxy, this.__objectId, sessionId, this.__context); + if (object != null) { + this.__proxy = object; + if (typeof callback === 'function') { + return callback(null, this.__proxy); + } else { + return Promise.resolve(null, object); + } + } else { + if (typeof callback === 'function') { + return callback(null, null); + } else { + return Promise.reject(null, null); + } + } + } - off(type, callback) { - offWatch(this.__sdkVersion, type, this.__proxy, callback); - if (callback != undefined || callback != null) { - distributedObject.deleteCallback(this.__sdkVersion, type, this.__objectId, callback); - } else { - distributedObject.deleteCallback(this.__sdkVersion, type, this.__objectId); - } + on(type, callback) { + onWatch(this.__sdkVersion, type, this.__proxy, callback); + distributedObject.recordCallback(this.__sdkVersion, type, this.__objectId, callback); + } + + off(type, callback) { + offWatch(this.__sdkVersion, type, this.__proxy, callback); + if (callback !== undefined || callback != null) { + distributedObject.deleteCallback(this.__sdkVersion, type, this.__objectId, callback); + } else { + distributedObject.deleteCallback(this.__sdkVersion, type, this.__objectId); } + } - save(deviceId, callback) { - if (this.__proxy[SESSION_ID] == null || this.__proxy[SESSION_ID] == "") { - console.info("not join a session, can not do save"); - return JS_ERROR; - } - return this.__proxy.save(deviceId, this[VERSION], callback); + save(deviceId, callback) { + if (this.__proxy[SESSION_ID] == null || this.__proxy[SESSION_ID] === '') { + console.info('not join a session, can not do save'); + return JS_ERROR; } + return this.__proxy.save(deviceId, this[VERSION], callback); + } - revokeSave(callback) { - if (this.__proxy[SESSION_ID] == null || this.__proxy[SESSION_ID] == "") { - console.info("not join a session, can not do revoke save"); - return JS_ERROR; - } - return this.__proxy.revokeSave(callback); + revokeSave(callback) { + if (this.__proxy[SESSION_ID] == null || this.__proxy[SESSION_ID] === '') { + console.info('not join a session, can not do revoke save'); + return JS_ERROR; } + return this.__proxy.revokeSave(callback); + } - __context; - __proxy; - __objectId; - __version; - __sdkVersion = 9; + __context; + __proxy; + __objectId; + __version; + __sdkVersion = SDK_VERSION_9; } export default { - createDistributedObject: newDistributed, - create: newDistributedV9, - genSessionId: randomNum -} \ No newline at end of file + createDistributedObject: newDistributed, + create: newDistributedV9, + genSessionId: randomNum +}; diff --git a/data_object/samples/distributedNotepad/ReadMe.md b/data_object/samples/distributedNotepad/ReadMe.md index 06f24a7b20809b41934bf9cc930ea19f4077cbff..247fe16e85c15308d377bd1cc0d556ed4b1554b2 100644 --- a/data_object/samples/distributedNotepad/ReadMe.md +++ b/data_object/samples/distributedNotepad/ReadMe.md @@ -150,10 +150,10 @@ changeCallback(sessionId, changeData) { changeData.forEach(element => { if (element == "documentList") { // 刷新界面上的备忘录数据列表 - this.dataModel.documentList = distr.g_dataModel.distributedObject.documentList; + this.dataModel.documentList = distr.dataModel.distributedObject.documentList; } else if (element == "documentSize") { - let size = distr.g_dataModel.distributedObject.documentSize; + let size = distr.dataModel.distributedObject.documentSize; // 刷新界面上列表总数 this.dataModel.distributedObject.documentSize = size; } @@ -168,9 +168,9 @@ changeCallback(sessionId, changeData) { onInit() { // 监听对端设备的数据变更 // 发起方要在changeCallback里刷新界面,则需要将正确的this绑定给changeCallback - distr.g_dataModel.setCallback(this.changeCallback.bind(this)); + distr.dataModel.setCallback(this.changeCallback.bind(this)); // 监听分布式对象的上下线状态 - distr.g_dataModel.setStatusCallback((sessionId, networkId, status) => { + distr.dataModel.setStatusCallback((sessionId, networkId, status) => { // 刷新红绿灯界面 if (status == "online") { this.dataModel.imgSrc = "common/green.png"; @@ -188,7 +188,7 @@ onInit() { ```js doAdd: function () { - distr.g_dataModel.add(this.title, this.content); + distr.dataModel.add(this.title, this.content); ... } ``` @@ -209,7 +209,7 @@ add(title, content) { ```js save: function () { // 使用页面数据更新分布式对象属性数据 - distr.g_dataModel.update(this.editIndex, this.title, this.content); + distr.dataModel.update(this.editIndex, this.title, this.content); ... } ``` @@ -230,7 +230,7 @@ update(index, title, content) { clear: function () { // 触发界面刷新 this.dataModel.documentList = []; - distr.g_dataModel.clear(); + distr.dataModel.clear(); this.dataModel.distributedObject.documentSize = 0; }, ``` diff --git a/data_object/samples/distributedNotepad/entry/src/main/js/MainAbility/app.js b/data_object/samples/distributedNotepad/entry/src/main/js/MainAbility/app.js index e3a0891c0350ac6dec03b34963b6e570653355f2..b8b9fcdb4a19a30d35f8bf82af8ed6532fca25da 100644 --- a/data_object/samples/distributedNotepad/entry/src/main/js/MainAbility/app.js +++ b/data_object/samples/distributedNotepad/entry/src/main/js/MainAbility/app.js @@ -14,10 +14,10 @@ */ export default { - onCreate() { - console.info("Application onCreate"); - }, - onDestroy() { - console.info("Application onDestroy"); - } + onCreate() { + console.info('Application onCreate'); + }, + onDestroy() { + console.info('Application onDestroy'); + } }; diff --git a/data_object/samples/distributedNotepad/entry/src/main/js/MainAbility/pages/add/add.js b/data_object/samples/distributedNotepad/entry/src/main/js/MainAbility/pages/add/add.js index 1dcc4d7aea1dd7cb4c506275091f82119914036c..073c120b2d81f11e1c2a2e6def4e014b351e7522 100644 --- a/data_object/samples/distributedNotepad/entry/src/main/js/MainAbility/pages/add/add.js +++ b/data_object/samples/distributedNotepad/entry/src/main/js/MainAbility/pages/add/add.js @@ -13,30 +13,30 @@ * limitations under the License. */ -import router from '@system.router' -import * as distr from '../../../model/DistributedDataModel.js' +import router from '@system.router'; +import * as distr from '../../../model/DistributedDataModel.js'; export default { - data: { - title: "天气不错奥", - content: "今天天气不错" - }, - onInit() { - console.info("objectstore in add page"); - }, - doAdd: function () { - console.info("doAdd " + JSON.stringify(distr.g_dataModel)); - distr.g_dataModel.add(this.title, this.content); - router.replace({ - uri: "pages/index/index", - params: { - dataModel: distr.g_dataModel - } - }) - }, - changeTitle: function (e) { - this.title = e.text; - }, - changeContent: function (e) { - this.content = e.text; - } -} + data: { + title: '天气不错奥', + content: '今天天气不错' + }, + onInit() { + console.info('objectstore in add page'); + }, + doAdd: function () { + console.info('doAdd ' + JSON.stringify(distr.dataModel)); + distr.dataModel.add(this.title, this.content); + router.replace({ + uri: 'pages/index/index', + params: { + dataModel: distr.dataModel + } + }); + }, + changeTitle: function (e) { + this.title = e.text; + }, + changeContent: function (e) { + this.content = e.text; + } +}; diff --git a/data_object/samples/distributedNotepad/entry/src/main/js/MainAbility/pages/detail/detail.js b/data_object/samples/distributedNotepad/entry/src/main/js/MainAbility/pages/detail/detail.js index 461f1798e8fa629c68e36587ef067ef67184663e..a808b7a08e8c37682d66761a904cddc40e95306f 100644 --- a/data_object/samples/distributedNotepad/entry/src/main/js/MainAbility/pages/detail/detail.js +++ b/data_object/samples/distributedNotepad/entry/src/main/js/MainAbility/pages/detail/detail.js @@ -13,40 +13,40 @@ * limitations under the License. */ -import router from '@system.router' -import * as distr from '../../../model/DistributedDataModel.js' +import router from '@system.router'; +import * as distr from '../../../model/DistributedDataModel.js'; export default { - data: { - title: "天气不错奥", - content: "今天天气不错", - edit: "保存" - }, - onInit() { - console.info("objectstore in detail page"); - }, - back: function () { - router.replace({ - uri: "pages/index/index", - params: { - dataModel: distr.g_dataModel - } - }) - }, - change: function (e) { - this.title = e.text; - }, - changeContent: function (e) { - this.content = e.text; - }, - save: function () { - console.info("start save "+ JSON.stringify(this.data)); - distr.g_dataModel.update(this.editIndex, this.title, this.content); - router.replace({ - uri: "pages/index/index", - params: { - dataModel: distr.g_dataModel - } - }) - } -} + data: { + title: '天气不错奥', + content: '今天天气不错', + edit: '保存' + }, + onInit() { + console.info('objectstore in detail page'); + }, + back: function () { + router.replace({ + uri: 'pages/index/index', + params: { + dataModel: distr.dataModel + } + }); + }, + change: function (e) { + this.title = e.text; + }, + changeContent: function (e) { + this.content = e.text; + }, + save: function () { + console.info('start save ' + JSON.stringify(this.data)); + distr.dataModel.update(this.editIndex, this.title, this.content); + router.replace({ + uri: 'pages/index/index', + params: { + dataModel: distr.dataModel + } + }); + } +}; diff --git a/data_object/samples/distributedNotepad/entry/src/main/js/MainAbility/pages/index/index.js b/data_object/samples/distributedNotepad/entry/src/main/js/MainAbility/pages/index/index.js index 0818c2968a644129f92346bebed99764e1dc1a8d..c0b2223995a1dd820e97ca31a98d3b9040e671f9 100644 --- a/data_object/samples/distributedNotepad/entry/src/main/js/MainAbility/pages/index/index.js +++ b/data_object/samples/distributedNotepad/entry/src/main/js/MainAbility/pages/index/index.js @@ -13,69 +13,69 @@ * limitations under the License. */ -import router from '@system.router' -import * as distr from '../../../model/DistributedDataModel.js' +import router from '@system.router'; +import * as distr from '../../../model/DistributedDataModel.js'; export default { - data: { - dataModel: distr.g_dataModel - }, - changeCallback(sessionId, changeData) { - changeData.forEach(element => { - if (element == "documentList") { - console.info("newest data " + JSON.stringify(this.dataModel.distributedObject.documentList)); - // 触发界面刷新 - this.dataModel.documentList = distr.g_dataModel.distributedObject.documentList; - } else if (element == "documentSize") { - let size = distr.g_dataModel.distributedObject.documentSize; - console.info("newest size " + size); - // 触发界面刷新 - this.dataModel.distributedObject.documentSize = size; - } - }); - }, - onInit() { - console.info("objectstore in index page "); - console.info(JSON.stringify(this.dataModel.documentList)); - console.info(JSON.stringify(distr.g_dataModel.distributedObject.documentList)); - distr.g_dataModel.setCallback(this.changeCallback.bind(this)); - distr.g_dataModel.setStatusCallback((sessionId, networkId, status) => { - console.info("objectstore status change ${networkId} ${status}"); - if (status == "online") { - this.dataModel.imgSrc = "common/green.png"; - } else { - this.dataModel.imgSrc = "common/red.png"; - } - }) - }, - onDestroy() { - console.info("objectstore exit index page"); - distr.g_dataModel.clearCallback(); - }, - add: function () { - router.replace({ - uri: "pages/add/add" - }) - }, - clear: function () { + data: { + dataModel: distr.dataModel + }, + changeCallback(sessionId, changeData) { + changeData.forEach(element => { + if (element === 'documentList') { + console.info('newest data ' + JSON.stringify(this.dataModel.distributedObject.documentList)); // 触发界面刷新 - this.dataModel.documentList = []; - this.dataModel.distributedObject.documentSize = 0; - distr.g_dataModel.clear(); - }, - detail: function (msg) { - router.replace({ - uri: "pages/detail/detail", - params: { - title: msg.target.dataSet.title, - content: msg.target.dataSet.content, - oriTitle: msg.target.dataSet.title, - oriContent: msg.target.dataSet.content, - editIndex: msg.target.dataSet.index - } - }) - } -} + this.dataModel.documentList = distr.dataModel.distributedObject.documentList; + } else if (element === 'documentSize') { + let size = distr.dataModel.distributedObject.documentSize; + console.info('newest size ' + size); + // 触发界面刷新 + this.dataModel.distributedObject.documentSize = size; + } + }); + }, + onInit() { + console.info('objectstore in index page '); + console.info(JSON.stringify(this.dataModel.documentList)); + console.info(JSON.stringify(distr.dataModel.distributedObject.documentList)); + distr.dataModel.setCallback(this.changeCallback.bind(this)); + distr.dataModel.setStatusCallback((sessionId, networkId, status) => { + console.info('objectstore status change ${networkId} ${status}'); + if (status === 'online') { + this.dataModel.imgSrc = 'common/green.png'; + } else { + this.dataModel.imgSrc = 'common/red.png'; + } + }); + }, + onDestroy() { + console.info('objectstore exit index page'); + distr.dataModel.clearCallback(); + }, + add: function () { + router.replace({ + uri: 'pages/add/add' + }); + }, + clear: function () { + // 触发界面刷新 + this.dataModel.documentList = []; + this.dataModel.distributedObject.documentSize = 0; + distr.dataModel.clear(); + }, + detail: function (msg) { + router.replace({ + uri: 'pages/detail/detail', + params: { + title: msg.target.dataSet.title, + content: msg.target.dataSet.content, + oriTitle: msg.target.dataSet.title, + oriContent: msg.target.dataSet.content, + editIndex: msg.target.dataSet.index + } + }); + } +}; diff --git a/data_object/samples/distributedNotepad/entry/src/main/js/model/DistributedDataModel.js b/data_object/samples/distributedNotepad/entry/src/main/js/model/DistributedDataModel.js index 9881d32c38a625457277a849035b037eab3d13f5..e6b4e05dd24f78845330294f9f55d38c973a86e0 100644 --- a/data_object/samples/distributedNotepad/entry/src/main/js/model/DistributedDataModel.js +++ b/data_object/samples/distributedNotepad/entry/src/main/js/model/DistributedDataModel.js @@ -13,106 +13,108 @@ * limitations under the License. */ -import distributedObject from '@ohos.data.distributedDataObject' +import distributedObject from '@ohos.data.distributedDataObject'; import featureAbility from '@ohos.ability.featureAbility'; +const REQUEST_MODE = 666; + function grantPermission() { - console.info('grantPermission'); - let context = featureAbility.getContext(); - context.requestPermissionsFromUser(['ohos.permission.DISTRIBUTED_DATASYNC'], 666, function (result) { - console.info(`result.requestCode=${result.requestCode}`) + console.info('grantPermission'); + let context = featureAbility.getContext(); + context.requestPermissionsFromUser(['ohos.permission.DISTRIBUTED_DATASYNC'], REQUEST_MODE, function (result) { + console.info(`result.requestCode=${result.requestCode}`); - }) - console.info('end grantPermission'); + }); + console.info('end grantPermission'); } export default class DistributedDataModel { - documentList = []; - distributedObject; // distributed proxy - imgSrc = "common/red.png"; - #callback; - #statusCallback; + documentList = []; + distributedObject; // distributed proxy + imgSrc = 'common/red.png'; + #callback; + #statusCallback; - constructor() { - this.distributedObject = distributedObject.createDistributedObject({ - documentList: this.documentList, - documentSize: 0 - }); - this.share(); - } + constructor() { + this.distributedObject = distributedObject.createDistributedObject({ + documentList: this.documentList, + documentSize: 0 + }); + this.share(); + } - clearCallback() { - this.distributedObject.off("change"); - this.#callback = undefined; - this.distributedObject.off("status"); - this.#statusCallback = undefined; - } + clearCallback() { + this.distributedObject.off('change'); + this.#callback = undefined; + this.distributedObject.off('status'); + this.#statusCallback = undefined; + } - setCallback(callback) { - if (this.#callback == callback) { - console.info("same callback"); - return; - } - console.info("start off"); - if (this.#callback != undefined) { - this.distributedObject.off("change", this.#callback); - } - this.#callback = callback; - console.info("start watch change"); - this.distributedObject.on("change", this.#callback); + setCallback(callback) { + if (this.#callback === callback) { + console.info('same callback'); + return; } - - setStatusCallback(callback) { - if (this.#statusCallback == callback) { - console.info("same callback"); - return; - } - console.info("start off"); - if (this.#statusCallback != undefined) { - this.distributedObject.off("status", this.#statusCallback); - } - this.#statusCallback = callback; - console.info("start watch change"); - this.distributedObject.on("status", this.#statusCallback); + console.info('start off'); + if (this.#callback !== undefined) { + this.distributedObject.off('change', this.#callback); } + this.#callback = callback; + console.info('start watch change'); + this.distributedObject.on('change', this.#callback); + } - share() { - console.info("start share"); - if (this.distributedObject.__sessionId == undefined) { - grantPermission() - this.distributedObject.setSessionId("123456") - } + setStatusCallback(callback) { + if (this.#statusCallback === callback) { + console.info('same callback'); + return; } - - update(index, title, content) { - console.info("doUpdate " + title + index); - this.documentList = this.distributedObject.documentList; - this.documentList[index] = { - index: index, title: title, content: content - }; - this.distributedObject.documentList = this.documentList; - console.info("update my documentList " + JSON.stringify(this.documentList)); + console.info('start off'); + if (this.#statusCallback !== undefined) { + this.distributedObject.off('status', this.#statusCallback); } + this.#statusCallback = callback; + console.info('start watch change'); + this.distributedObject.on('status', this.#statusCallback); + } - add(title, content) { - console.info("doAdd " + title + content); - console.info("documentList " + JSON.stringify(this.documentList)); - this.documentList = this.distributedObject.documentList; - this.documentList[this.distributedObject.documentSize] = { - index: this.distributedObject.documentSize, title: title, content: content - }; - this.distributedObject.documentList = this.documentList; - this.distributedObject.documentSize++; - console.info("add my documentList " + JSON.stringify(this.documentList)); - } + share() { + console.info('start share'); + if (this.distributedObject.__sessionId === undefined) { + grantPermission(); + this.distributedObject.setSessionId('123456'); + } + } + update(index, title, content) { + console.info('doUpdate ' + title + index); + this.documentList = this.distributedObject.documentList; + this.documentList[index] = { + index: index, title: title, content: content + }; + this.distributedObject.documentList = this.documentList; + console.info('update my documentList ' + JSON.stringify(this.documentList)); + } - clear() { - console.info("doClear "); - this.documentList = []; - this.distributedObject.documentList = this.documentList; - this.distributedObject.documentSize = 0; - console.info("doClear finish"); - } + add(title, content) { + console.info('doAdd ' + title + content); + console.info('documentList ' + JSON.stringify(this.documentList)); + this.documentList = this.distributedObject.documentList; + this.documentList[this.distributedObject.documentSize] = { + index: this.distributedObject.documentSize, title: title, content: content + }; + this.distributedObject.documentList = this.documentList; + this.distributedObject.documentSize++; + console.info('add my documentList ' + JSON.stringify(this.documentList)); + } + + + clear() { + console.info('doClear '); + this.documentList = []; + this.distributedObject.documentList = this.documentList; + this.distributedObject.documentSize = 0; + console.info('doClear finish'); + } } -export var g_dataModel = new DistributedDataModel(); \ No newline at end of file +export let dataModel = new DistributedDataModel(); \ No newline at end of file diff --git a/data_share/frameworks/js/napi/dataShare/BUILD.gn b/data_share/frameworks/js/napi/dataShare/BUILD.gn index 0cdf6a90cb33090ef7968796a2d2ea0460687558..63ac72ccb749ff6457b9afc9c2def2b659ce6a07 100644 --- a/data_share/frameworks/js/napi/dataShare/BUILD.gn +++ b/data_share/frameworks/js/napi/dataShare/BUILD.gn @@ -43,6 +43,7 @@ ohos_shared_library("datashare") { "ability_runtime:abilitykit_native", "ability_runtime:napi_base_context", "c_utils:utils", + "common_event_service:cesfwk_innerkits", "data_share:datashare_common", "data_share:datashare_consumer", "hiviewdfx_hilog_native:libhilog", diff --git a/data_share/frameworks/js/napi/dataShare/src/napi_datashare_helper.cpp b/data_share/frameworks/js/napi/dataShare/src/napi_datashare_helper.cpp index 1539805875ccd0862bcf8a8913be7cc9ab2a605f..59b76a7e73f392a93d267957f4db674f90dd259f 100644 --- a/data_share/frameworks/js/napi/dataShare/src/napi_datashare_helper.cpp +++ b/data_share/frameworks/js/napi/dataShare/src/napi_datashare_helper.cpp @@ -199,6 +199,7 @@ napi_value NapiDataShareHelper::Initialize(napi_env env, napi_callback_info info auto finalize = [](napi_env env, void * data, void * hint) { NapiDataShareHelper *proxy = reinterpret_cast(data); delete proxy; + LOG_INFO("NapiDataShareHelper has been deleted successfully!"); }; if (napi_wrap(env, self, proxy, finalize, nullptr, nullptr) != napi_ok) { finalize(env, proxy, nullptr); diff --git a/data_share/frameworks/native/common/src/shared_block.cpp b/data_share/frameworks/native/common/src/shared_block.cpp index bdb418ac89ddddadd040124fb2d8b189b5ff4ad5..493802066f373b49ff207d8707633a2da9edba20 100644 --- a/data_share/frameworks/native/common/src/shared_block.cpp +++ b/data_share/frameworks/native/common/src/shared_block.cpp @@ -38,7 +38,7 @@ SharedBlock::~SharedBlock() if (ashmem_ != nullptr) { ashmem_->UnmapAshmem(); ashmem_->CloseAshmem(); - LOG_WARN("SharedBlock: close ashmem"); + LOG_DEBUG("SharedBlock: close ashmem"); } } diff --git a/data_share/frameworks/native/consumer/src/datashare_helper.cpp b/data_share/frameworks/native/consumer/src/datashare_helper.cpp index 312e4e9e75623f5f457da82c2bec9077da5e2cb9..829b1c36cf7086914f5fec786c9d01d2f660c82e 100644 --- a/data_share/frameworks/native/consumer/src/datashare_helper.cpp +++ b/data_share/frameworks/native/consumer/src/datashare_helper.cpp @@ -45,7 +45,6 @@ private: DataShareHelper::DataShareHelper(const sptr &token, const Uri &uri, std::shared_ptr dataShareConnection) { - LOG_INFO("DataShareHelper::DataShareHelper start"); token_ = token; uri_ = uri; isDataShareService_ = (uri_.GetQuery().find("Proxy=true") != std::string::npos); @@ -54,11 +53,9 @@ DataShareHelper::DataShareHelper(const sptr &token, const Uri &ur DataShareHelper::DataShareHelper(const sptr &token, const Uri &uri) { - LOG_INFO("DataShareHelper::DataShareHelper start"); token_ = token; uri_ = uri; isDataShareService_ = (uri_.GetQuery().find("Proxy=true") != std::string::npos); - LOG_INFO("DataShareHelper::DataShareHelper end"); } DataShareHelper::~DataShareHelper() @@ -136,7 +133,7 @@ std::shared_ptr DataShareHelper::Creator(const sptrSendRequest(CMD_BATCH_INSERT, data, reply, option); if (err != DATA_SHARE_NO_ERROR) { - LOG_ERROR("GetFileTypes fail to SendRequest. err: %{public}d", err); + LOG_ERROR("fail to SendRequest. err: %{public}d", err); return err == PERMISSION_ERR ? PERMISSION_ERR_CODE : ret; } diff --git a/data_share/frameworks/native/provider/include/datashare_stub.h b/data_share/frameworks/native/provider/include/datashare_stub.h index a1c0597833b86b6ceb4aec4f1f318f9ae567621d..668e86d7e2eb4a1199506c4a53010f5526251be9 100644 --- a/data_share/frameworks/native/provider/include/datashare_stub.h +++ b/data_share/frameworks/native/provider/include/datashare_stub.h @@ -47,6 +47,7 @@ private: using RequestFuncType = int (DataShareStub::*)(MessageParcel &data, MessageParcel &reply); std::map stubFuncMap_; + static constexpr int VALUEBUCKET_MAX_COUNT = 3000; }; } // namespace DataShare } // namespace OHOS diff --git a/data_share/frameworks/native/provider/src/datashare_stub.cpp b/data_share/frameworks/native/provider/src/datashare_stub.cpp index 531db554222fd9c3e1e3cafecd7362a5206957a7..459ee9ec977302635dab866e3c953d15d3022ac3 100644 --- a/data_share/frameworks/native/provider/src/datashare_stub.cpp +++ b/data_share/frameworks/native/provider/src/datashare_stub.cpp @@ -280,8 +280,12 @@ ErrCode DataShareStub::CmdBatchInsert(MessageParcel &data, MessageParcel &reply) LOG_ERROR("fail to ReadInt32 index"); return ERR_INVALID_VALUE; } + if (count > VALUEBUCKET_MAX_COUNT) { + return ERR_INVALID_VALUE; + } std::vector values; + values.reserve(static_cast(count)); for (int i = 0; i < count; i++) { DataShareValuesBucket value; if (!ITypesUtils::Unmarshalling(data, value)) { diff --git a/data_share/interfaces/inner_api/BUILD.gn b/data_share/interfaces/inner_api/BUILD.gn index cadbb1268bf09db10bcf8e94e009a9788a980e10..464a8ae321e65ef527e5235403a5ad2bff315434 100644 --- a/data_share/interfaces/inner_api/BUILD.gn +++ b/data_share/interfaces/inner_api/BUILD.gn @@ -76,6 +76,7 @@ ohos_shared_library("datashare_consumer") { "ability_runtime:app_context", "ability_runtime:dataobs_manager", "c_utils:utils", + "common_event_service:cesfwk_innerkits", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_single", "ipc_js:rpc", @@ -117,6 +118,7 @@ ohos_shared_library("datashare_provider") { "ability_runtime:runtime", "access_token:libaccesstoken_sdk", "c_utils:utils", + "common_event_service:cesfwk_innerkits", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_single", "ipc_js:rpc", @@ -144,6 +146,7 @@ ohos_shared_library("datashare_ext_ability_module") { "ability_base:want", "ability_runtime:runtime", "c_utils:utils", + "common_event_service:cesfwk_innerkits", "hiviewdfx_hilog_native:libhilog", ] diff --git a/datamgr_service/services/distributeddataservice/adapter/BUILD.gn b/datamgr_service/services/distributeddataservice/adapter/BUILD.gn index 34abe79d5b3dc8f50b7a22c52162c6fd530a1441..c1e309f1a58b5b3c4669f5fcb84baa069d8b45df 100644 --- a/datamgr_service/services/distributeddataservice/adapter/BUILD.gn +++ b/datamgr_service/services/distributeddataservice/adapter/BUILD.gn @@ -24,7 +24,7 @@ config("distributeddata_adapter_private_config") { } config("distributeddata_adapter_public_config") { - visibility = [ "//foundation/distributeddatamgr/datamgr_service:*" ] + visibility = [ ":*" ] include_dirs = [ "include/log", diff --git a/datamgr_service/services/distributeddataservice/app/distributed_data.cfg b/datamgr_service/services/distributeddataservice/app/distributed_data.cfg index 494bc79bf2a42f71ed981de3fae6f6cead270de6..a42d9dc441e2487fb04cb680903ae1817664aed7 100644 --- a/datamgr_service/services/distributeddataservice/app/distributed_data.cfg +++ b/datamgr_service/services/distributeddataservice/app/distributed_data.cfg @@ -30,7 +30,8 @@ "apl" : "system_basic", "permission" : [ "ohos.permission.DISTRIBUTED_DATASYNC", - "ohos.permission.MANAGE_LOCAL_ACCOUNTS" + "ohos.permission.MANAGE_LOCAL_ACCOUNTS", + "ohos.permission.ACCESS_SERVICE_DM" ] } ] diff --git a/datamgr_service/services/distributeddataservice/service/bootstrap/src/bootstrap.cpp b/datamgr_service/services/distributeddataservice/service/bootstrap/src/bootstrap.cpp index 7d39b94f828c12b853f1815677093c2867c583c7..961726490a93eb88466726b9109edd13e62bac11 100644 --- a/datamgr_service/services/distributeddataservice/service/bootstrap/src/bootstrap.cpp +++ b/datamgr_service/services/distributeddataservice/service/bootstrap/src/bootstrap.cpp @@ -58,9 +58,12 @@ void Bootstrap::LoadComponents() if (comp.lib.empty()) { continue; } - + char path[PATH_MAX] = { 0 }; + if (realpath(comp.lib.c_str(), path) == NULL) { + continue; + } // no need to close the component, so we don't keep the handles - auto handle = dlopen(comp.lib.c_str(), RTLD_LAZY); + auto handle = dlopen(path, RTLD_LAZY); if (handle == nullptr) { ZLOGE("dlopen(%{public}s) failed(%{public}d)!", comp.lib.c_str(), errno); continue; diff --git a/datamgr_service/services/distributeddataservice/service/rdb/irdb_result_set.h b/datamgr_service/services/distributeddataservice/service/rdb/irdb_result_set.h index c2e81993a4759d5f4db8699f8ac24c4095080110..5926784ca349d00e3617fc7f94068dfb254db5e8 100644 --- a/datamgr_service/services/distributeddataservice/service/rdb/irdb_result_set.h +++ b/datamgr_service/services/distributeddataservice/service/rdb/irdb_result_set.h @@ -17,10 +17,10 @@ #define DISTRIBUTED_RDB_IRDB_RESULT_SET_H #include "iremote_broker.h" -#include "result_set.h" +#include "remote_result_set.h" namespace OHOS::DistributedRdb { -class IRdbResultSet : public NativeRdb::ResultSet, public IRemoteBroker { +class IRdbResultSet : public NativeRdb::RemoteResultSet, public IRemoteBroker { public: using ColumnType = NativeRdb::ColumnType; virtual ~IRdbResultSet() = default; diff --git a/kv_store/frameworks/common/executor.h b/kv_store/frameworks/common/executor.h new file mode 100644 index 0000000000000000000000000000000000000000..a9f7be80a9f5e7a041b9f6e3f42e81a6bed6dc82 --- /dev/null +++ b/kv_store/frameworks/common/executor.h @@ -0,0 +1,131 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DISTRIBUTED_DATA_KV_STORE_FRAMEWORKS_COMMON_EXECUTOR_H +#define OHOS_DISTRIBUTED_DATA_KV_STORE_FRAMEWORKS_COMMON_EXECUTOR_H +#include +#include +#include +#include + +#include "priority_queue.h" +namespace OHOS { + +class Executor : public std::enable_shared_from_this { +public: + using TaskId = uint64_t; + using Task = std::function; + using Duration = std::chrono::steady_clock::duration; + using Time = std::chrono::steady_clock::time_point; + static constexpr Time INVALID_TIME = std::chrono::time_point(); + static constexpr Duration INVALID_INTERVAL = std::chrono::milliseconds(0); + static constexpr uint64_t UNLIMITED_TIMES = std::numeric_limits::max(); + static constexpr Duration INVALID_DELAY = std::chrono::seconds(0); + static constexpr TaskId INVALID_TASK_ID = static_cast(0l); + + enum Status { + RUNNING, + IS_STOPPING, + STOPPED + }; + struct InnerTask { + std::function exec; + Duration interval = INVALID_INTERVAL; + uint64_t times = UNLIMITED_TIMES; + TaskId taskId = INVALID_TASK_ID; + Time startTime = INVALID_TIME; + InnerTask() = default; + + bool Valid() const + { + return taskId != INVALID_TASK_ID; + } + }; + + Executor() + : thread_([this] { + Run(); + thread_.detach(); + self_ = nullptr; + }) + { + } + + void Bind(PriorityQueue *queue, std::function)> idle, + std::function, bool)> release) + { + std::unique_lock lock(mutex_); + self_ = shared_from_this(); + waits_ = queue; + idle_ = std::move(idle); + release_ = std::move(release); + condition_.notify_one(); + } + + void Stop(bool wait = false) + { + { + std::unique_lock lock(mutex_); + running_ = IS_STOPPING; + condition_.notify_one(); + } + if (wait) { + thread_.join(); + } + } + +private: + static constexpr Duration TIME_OUT = std::chrono::seconds(2); + void Run() + { + std::unique_lock lock(mutex_); + do { + do { + condition_.wait(lock, [this] { + return running_ == IS_STOPPING || waits_ != nullptr; + }); + while (running_ == RUNNING && waits_ != nullptr && waits_->Size() > 0) { + auto currentTask = waits_->Pop(); + if (!currentTask.Valid()) { + break; + } + lock.unlock(); + currentTask.exec(currentTask); + lock.lock(); + waits_->Finish(currentTask.taskId); + } + if (!idle_(self_) && running_ == RUNNING) { + continue; + } + waits_ = nullptr; + } while (running_ == RUNNING && + condition_.wait_until(lock, std::chrono::steady_clock::now() + TIME_OUT, [this]() { + return waits_ != nullptr; + })); + } while (!release_(self_, running_ == IS_STOPPING)); + running_ = STOPPED; + } + + Status running_ = RUNNING; + std::mutex mutex_; + std::condition_variable condition_; + std::shared_ptr self_; + PriorityQueue *waits_ = nullptr; + std::function)> idle_; + std::function, bool)> release_; + std::thread thread_; +}; +} // namespace OHOS +#endif // OHOS_DISTRIBUTED_DATA_KV_STORE_FRAMEWORKS_COMMON_EXECUTOR_H diff --git a/kv_store/frameworks/common/executor_pool.h b/kv_store/frameworks/common/executor_pool.h new file mode 100644 index 0000000000000000000000000000000000000000..776f893f7cd3fbbb3b1697a645bf9ffb6aca3106 --- /dev/null +++ b/kv_store/frameworks/common/executor_pool.h @@ -0,0 +1,218 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DISTRIBUTED_DATA_KV_STORE_FRAMEWORKS_COMMON_EXECUTOR_POOL_H +#define OHOS_DISTRIBUTED_DATA_KV_STORE_FRAMEWORKS_COMMON_EXECUTOR_POOL_H +#include +#include +#include +#include +#include + +#include "executor.h" +#include "pool.h" +#include "priority_queue.h" +namespace OHOS { +class ExecutorPool { +public: + using TaskId = Executor::TaskId; + using Task = Executor::Task; + using Duration = Executor::Duration; + using Time = Executor::Time; + using InnerTask = Executor::InnerTask; + using Status = Executor::Status; + static constexpr Time INVALID_TIME = std::chrono::time_point(); + static constexpr Duration INVALID_INTERVAL = std::chrono::milliseconds(0); + static constexpr uint64_t UNLIMITED_TIMES = std::numeric_limits::max(); + static constexpr Duration INVALID_DELAY = std::chrono::seconds(0); + static constexpr TaskId INVALID_TASK_ID = static_cast(0l); + + ExecutorPool(size_t max, size_t min) + { + pool_ = new (std::nothrow) Pool(max, min); + execs_ = new PriorityQueue(InnerTask()); + delayTasks_ = new PriorityQueue(InnerTask()); + taskId_ = INVALID_TASK_ID; + } + ~ExecutorPool() + { + poolStatus = Status::IS_STOPPING; + execs_->Clean(); + delayTasks_->Clean(); + std::shared_ptr scheduler; + { + std::lock_guard scheduleLock(mtx_); + scheduler = std::move(scheduler_); + } + if (scheduler != nullptr) { + scheduler->Stop(true); + } + pool_->Clean([](std::shared_ptr executor) { + executor->Stop(true); + }); + delete execs_; + delete delayTasks_; + delete pool_; + poolStatus = Status::STOPPED; + } + + TaskId Execute(Task task) + { + if (poolStatus != Status::RUNNING) { + return INVALID_TASK_ID; + } + auto run = [task](InnerTask innerTask) { + task(); + }; + return Execute(std::move(run), GenTaskId()); + } + + TaskId Execute(Task task, Duration delay) + { + return Schedule(std::move(task), delay, INVALID_INTERVAL, 1); + } + + TaskId Schedule(Task task, Duration interval) + { + return Schedule(std::move(task), INVALID_DELAY, interval, UNLIMITED_TIMES); + } + + TaskId Schedule(Task task, Duration delay, Duration interval) + { + return Schedule(std::move(task), delay, interval, UNLIMITED_TIMES); + } + + TaskId Schedule(Task task, Duration delay, Duration interval, uint64_t times) + { + InnerTask innerTask; + auto run = [task](InnerTask innerTask) { + task(); + }; + innerTask.exec = std::move(run); + innerTask.startTime = std::chrono::steady_clock::now() + delay; + innerTask.interval = interval; + innerTask.times = times; + innerTask.taskId = GenTaskId(); + return Schedule(std::move(innerTask)); + } + + bool Remove(TaskId taskId, bool wait = false) + { + bool res = true; + auto delay = delayTasks_->Find(taskId); + if (!delay.Valid()) { + res = false; + } + delayTasks_->Remove(taskId, wait); + execs_->Remove(taskId, wait); + return res; + } + + TaskId Reset(TaskId taskId, Duration interval) + { + return Reset(taskId, INVALID_DELAY, interval); + } + + TaskId Reset(TaskId taskId, Duration delay, Duration interval) + { + auto innerTask = delayTasks_->Find(taskId); + if (!innerTask.Valid()) { + return INVALID_TASK_ID; + } + delayTasks_->Remove(taskId, false); + auto startTime = std::chrono::steady_clock::now() + delay; + innerTask.startTime = startTime; + innerTask.interval = interval; + delayTasks_->Push(std::move(innerTask), taskId, startTime); + return taskId; + } + +private: + TaskId Execute(std::function task, TaskId taskId) + { + InnerTask innerTask; + innerTask.exec = task; + innerTask.taskId = taskId; + execs_->Push(std::move(innerTask), taskId, INVALID_TIME); + auto executor = pool_->Get(); + if (executor == nullptr) { + return taskId; + } + executor->Bind( + execs_, + [this](std::shared_ptr exe) { + pool_->Idle(exe); + return true; + }, + [this](std::shared_ptr exe, bool force) -> bool { + return pool_->Release(exe, force); + }); + return taskId; + } + + TaskId Schedule(InnerTask innerTask) + { + auto func = innerTask.exec; + auto id = innerTask.taskId; + auto run = [this, func, id](InnerTask task) { + if (task.interval != INVALID_INTERVAL && --task.times > 0) { + task.startTime = std::chrono::steady_clock::now() + task.interval; + delayTasks_->Push(task, task.taskId, task.startTime); + } + Execute(func, id); + }; + innerTask.exec = run; + delayTasks_->Push(innerTask, innerTask.taskId, innerTask.startTime); + std::lock_guard scheduleLock(mtx_); + if (scheduler_ == nullptr) { + scheduler_ = pool_->Get(true); + scheduler_->Bind( + delayTasks_, + [this](std::shared_ptr exe) { + std::unique_lock lock(mtx_); + if (delayTasks_->Size() != 0) { + return false; + } + scheduler_ = nullptr; + pool_->Idle(exe); + return true; + }, + [this](std::shared_ptr exe, bool force) -> bool { + return pool_->Release(exe, force); + }); + } + return innerTask.taskId; + } + + TaskId GenTaskId() + { + auto taskId = ++taskId_; + if (taskId == INVALID_TASK_ID) { + taskId = ++taskId_; + } + return taskId; + } + + Status poolStatus = Status::RUNNING; + std::mutex mtx_; + Pool *pool_; + std::shared_ptr scheduler_ = nullptr; + PriorityQueue *execs_; + PriorityQueue *delayTasks_; + std::atomic taskId_; +}; +} // namespace OHOS + +#endif // OHOS_DISTRIBUTED_DATA_KV_STORE_FRAMEWORKS_COMMON_EXECUTOR_POOL_H diff --git a/kv_store/frameworks/common/pool.h b/kv_store/frameworks/common/pool.h new file mode 100644 index 0000000000000000000000000000000000000000..3f7619274f2a3a7b41eaec1b0cc9b4bad9c6ef0f --- /dev/null +++ b/kv_store/frameworks/common/pool.h @@ -0,0 +1,139 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DISTRIBUTED_DATA_KV_STORE_FRAMEWORKS_COMMON_POOL_H +#define OHOS_DISTRIBUTED_DATA_KV_STORE_FRAMEWORKS_COMMON_POOL_H +#include +#include +namespace OHOS { +template +class Pool { +public: + Pool(uint32_t capability, uint32_t min) : capability_(capability), min_(min) {} + + std::shared_ptr Get(bool isForce = false) + { + std::unique_lock lock(mutex_); + if (idle_ == nullptr) { + if (!isForce && current_ >= capability_) { + return nullptr; + } + auto cur = new Node(); + idle_ = cur; + current_++; + } + Node *cur = idle_; + idle_ = idle_->next; + if (idle_ == nullptr) { + } + if (idle_ != nullptr) { + idle_->prev = nullptr; + } + cur->next = busy_; + if (busy_ != nullptr) { + cur->prev = busy_->prev; + busy_->prev = cur; + } + busy_ = cur; + return cur->data; + }; + + int32_t Release(std::shared_ptr data, bool force = false) + { + std::unique_lock lock(mutex_); + Node *cur = idle_; + if (!force && current_ <= min_) { + return false; + } + while (cur != nullptr) { + if (cur->data == data) { + if (cur->next != nullptr) { + cur->next->prev = cur->prev; + } + if (cur->prev != nullptr) { + cur->prev->next = cur->next; + } + if (idle_ == cur) { + idle_ = cur->next; + } + current_--; + delete cur; + return true; + } else { + cur = cur->next; + continue; + } + } + return false; + } + + void Idle(std::shared_ptr data) + { + std::unique_lock lock(mutex_); + Node *cur = busy_; + while (cur != nullptr && cur->data != data) { + cur = cur->next; + } + if (cur == nullptr) { + return; + } + if (cur == busy_) { + busy_ = busy_->next; + } + if (cur->next != nullptr) { + cur->next->prev = cur->prev; + } + if (cur->prev != nullptr) { + cur->prev->next = cur->next; + } + cur->prev = nullptr; + cur->next = idle_; + if (idle_ != nullptr) { + idle_->prev = cur; + } + idle_ = cur; + } + + int32_t Clean(std::function)> close) + { + auto temp = min_; + min_ = 0; + while (busy_ != nullptr) { + close(busy_->data); + } + while (idle_ != nullptr) { + close(idle_->data); + } + min_ = temp; + return true; + } + +private: + struct Node { + Node *prev = nullptr; + Node *next = nullptr; + std::shared_ptr data = std::make_shared(); + }; + + uint32_t capability_; + uint32_t min_; + uint32_t current_ = 0; + Node *idle_ = nullptr; + Node *busy_ = nullptr; + std::mutex mutex_; +}; +} // namespace OHOS + +#endif // OHOS_DISTRIBUTED_DATA_KV_STORE_FRAMEWORKS_COMMON_POOL_H diff --git a/kv_store/frameworks/common/priority_queue.h b/kv_store/frameworks/common/priority_queue.h new file mode 100644 index 0000000000000000000000000000000000000000..e1afc5f76d229ab5d7865cf24c5dd0bb9a382f38 --- /dev/null +++ b/kv_store/frameworks/common/priority_queue.h @@ -0,0 +1,122 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DISTRIBUTED_DATA_FRAMEWORKS_COMMON_PRIORITY_QUEUE_H +#define OHOS_DISTRIBUTED_DATA_FRAMEWORKS_COMMON_PRIORITY_QUEUE_H +#include +#include +#include +#include +#include +#include +namespace OHOS { +template +class PriorityQueue { +public: + struct PQMatrix { + _Tsk task_; + _Tid id_; + PQMatrix(_Tsk task, _Tid id) : task_(task), id_(id) {} + }; + using TskIndex = typename std::map<_Tme, PQMatrix>::iterator; + + PriorityQueue(const _Tsk &task) : INVALID_TSK(std::move(task)) {} + _Tsk Pop() + { + std::unique_lock lock(pqMtx_); + while (!tasks_.empty()) { + if (tasks_.begin()->first > std::chrono::steady_clock::now()) { + popCv_.wait_until(lock, tasks_.begin()->first); + continue; + } + auto temp = tasks_.begin(); + auto id = temp->second.id_; + running.emplace(id); + auto res = std::move(temp->second.task_); + tasks_.erase(temp); + indexes_.erase(id); + return res; + } + return INVALID_TSK; + } + + bool Push(_Tsk tsk, _Tid id, _Tme tme) + { + std::unique_lock lock(pqMtx_); + if (!tsk.Valid()) { + return false; + } + auto temp = tasks_.emplace(tme, PQMatrix(std::move(tsk), id)); + indexes_.emplace(id, temp); + popCv_.notify_all(); + return true; + } + + size_t Size() + { + std::lock_guard lock(pqMtx_); + return tasks_.size(); + } + + _Tsk Find(_Tid id) + { + std::unique_lock lock(pqMtx_); + if (indexes_.find(id) != indexes_.end()) { + return indexes_[id]->second.task_; + } + return INVALID_TSK; + } + + bool Remove(_Tid id, bool wait) + { + std::unique_lock lock(pqMtx_); + removeCv_.wait(lock, [this, id, wait] { + return !wait || running.find(id) == running.end(); + }); + auto index = indexes_.find(id); + if (index == indexes_.end()) { + return false; + } + tasks_.erase(index->second); + indexes_.erase(index); + popCv_.notify_all(); + return true; + } + + void Clean() + { + std::unique_lock lock(pqMtx_); + indexes_.clear(); + tasks_.clear(); + } + + void Finish(_Tid id) + { + std::unique_lock lock(pqMtx_); + running.erase(id); + removeCv_.notify_all(); + } + +private: + const _Tsk INVALID_TSK; + std::mutex pqMtx_; + std::condition_variable popCv_; + std::condition_variable removeCv_; + std::multimap<_Tme, PQMatrix> tasks_; + std::set<_Tid> running; + std::map<_Tid, TskIndex> indexes_; +}; +} // namespace OHOS +#endif //OHOS_DISTRIBUTED_DATA_FRAMEWORKS_COMMON_PRIORITY_QUEUE_H diff --git a/kv_store/frameworks/innerkitsimpl/kvdb/src/kvdb_service_client.cpp b/kv_store/frameworks/innerkitsimpl/kvdb/src/kvdb_service_client.cpp index 53ea96862eebc05d25dd3fdbd04519f58976496c..3dcfa4e941a2d35c13421d30e664fdbf7ba1dd93 100644 --- a/kv_store/frameworks/innerkitsimpl/kvdb/src/kvdb_service_client.cpp +++ b/kv_store/frameworks/innerkitsimpl/kvdb/src/kvdb_service_client.cpp @@ -74,10 +74,15 @@ std::shared_ptr KVDBServiceClient::GetInstance() return nullptr; } - sptr client = iface_cast(service); + sptr client = nullptr; + if (service->IsProxyObject()) { + client = iface_cast(service); + } + if (client == nullptr) { client = new (std::nothrow) KVDBServiceClient(service); } + if (client == nullptr) { return nullptr; } diff --git a/kv_store/frameworks/libs/distributeddb/syncer/src/remote_executor.cpp b/kv_store/frameworks/libs/distributeddb/syncer/src/remote_executor.cpp index aedf9d19f3160cfb459173b77c213634c31dc3e0..5a72a11d934fcee46432d4848c37a780eb3aee19 100644 --- a/kv_store/frameworks/libs/distributeddb/syncer/src/remote_executor.cpp +++ b/kv_store/frameworks/libs/distributeddb/syncer/src/remote_executor.cpp @@ -204,12 +204,12 @@ void RemoteExecutor::ParseOneRequestMessage(const std::string &device, Message * } int errCode = CheckPermissions(device); if (errCode != E_OK) { - ResponseFailed(errCode, inMsg->GetSessionId(), inMsg->GetSequenceId(), device); + (void)ResponseFailed(errCode, inMsg->GetSessionId(), inMsg->GetSequenceId(), device); return; } errCode = SendRemoteExecutorData(device, inMsg); if (errCode != E_OK) { - ResponseFailed(errCode, inMsg->GetSessionId(), inMsg->GetSequenceId(), device); + (void)ResponseFailed(errCode, inMsg->GetSessionId(), inMsg->GetSequenceId(), device); } } @@ -507,17 +507,17 @@ int RemoteExecutor::RequestStart(uint32_t sessionId) return errCode; } -void RemoteExecutor::ResponseFailed(int errCode, uint32_t sessionId, uint32_t sequenceId, +int RemoteExecutor::ResponseFailed(int errCode, uint32_t sessionId, uint32_t sequenceId, const std::string &device) { RemoteExecutorAckPacket *packet = new (std::nothrow) RemoteExecutorAckPacket(); if (packet == nullptr) { LOGE("[RemoteExecutor][ResponseFailed] new RemoteExecutorAckPacket error"); - return; + return -E_OUT_OF_MEMORY; } packet->SetAckCode(errCode); packet->SetLastAck(); - (void)ResponseStart(packet, sessionId, sequenceId, device); + return ResponseStart(packet, sessionId, sequenceId, device); } int RemoteExecutor::ResponseData(RelationalRowDataSet &&dataSet, const SendMessage &sendMessage, diff --git a/kv_store/frameworks/libs/distributeddb/syncer/src/remote_executor.h b/kv_store/frameworks/libs/distributeddb/syncer/src/remote_executor.h index 68a878d5c7b2331fe1c9d3925d777377e75b4654..f7c1fdd8ee64a6158781b899bc4ad4bb1f891113 100644 --- a/kv_store/frameworks/libs/distributeddb/syncer/src/remote_executor.h +++ b/kv_store/frameworks/libs/distributeddb/syncer/src/remote_executor.h @@ -77,7 +77,7 @@ protected: virtual bool IsPacketValid(uint32_t sessionId); - void ResponseFailed(int errCode, uint32_t sessionId, uint32_t sequenceId, const std::string &device); + int ResponseFailed(int errCode, uint32_t sessionId, uint32_t sequenceId, const std::string &device); private: struct SendMessage { diff --git a/kv_store/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_database_test.cpp b/kv_store/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_database_test.cpp index 625c4e4b5c44e147989ff32169d50e8af1db1ba2..62b665f3528151e2bcd9b5201999dcabaf5f8cc3 100644 --- a/kv_store/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_database_test.cpp +++ b/kv_store/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_database_test.cpp @@ -1324,7 +1324,9 @@ namespace { std::thread t1(OpenCloseDatabase, storeId); std::thread t2([&]() { for (int i = 0; i < 10000; i++) { // loop 10000 times - g_mgr.DeleteKvStore(storeId); + DBStatus status = g_mgr.DeleteKvStore(storeId); + LOGI("delete res %d", status); + EXPECT_TRUE(status == OK || status == BUSY || status == NOT_FOUND); } }); t1.join(); diff --git a/kv_store/frameworks/libs/distributeddb/test/unittest/common/interfaces/runtime_context_process_system_api_adapter_impl_test.cpp b/kv_store/frameworks/libs/distributeddb/test/unittest/common/interfaces/runtime_context_process_system_api_adapter_impl_test.cpp index 5c280f774a85bd7ff2d6d3a83a753deb35022bfd..92b14a3333605c64f8d2c065e6941275ae561553 100644 --- a/kv_store/frameworks/libs/distributeddb/test/unittest/common/interfaces/runtime_context_process_system_api_adapter_impl_test.cpp +++ b/kv_store/frameworks/libs/distributeddb/test/unittest/common/interfaces/runtime_context_process_system_api_adapter_impl_test.cpp @@ -245,9 +245,9 @@ void FuncCheckDeviceSecurityAbility() void CheckDeviceSecurityAbility002() { g_config.dataDir = g_testDir; - g_mgr.SetKvStoreConfig(g_config); + EXPECT_EQ(g_mgr.SetKvStoreConfig(g_config), OK); - RuntimeContext::GetInstance()->SetProcessSystemApiAdapter(g_adapter); + EXPECT_EQ(RuntimeContext::GetInstance()->SetProcessSystemApiAdapter(g_adapter), E_OK); g_adapter->SetNeedCreateDb(true); const std::string storeId = "CheckDeviceSecurityAbility002"; @@ -257,7 +257,7 @@ void CheckDeviceSecurityAbility002() LOGI("open store!!"); KvStoreNbDelegate::Option option1 = {true, false, false}; g_mgr.GetKvStore(storeId, option1, g_kvNbDelegateCallback); - g_mgr.CloseKvStore(g_kvNbDelegatePtr); + EXPECT_EQ(g_mgr.CloseKvStore(g_kvNbDelegatePtr), OK); } }); diff --git a/kv_store/frameworks/libs/distributeddb/test/unittest/common/storage/distributeddb_relational_get_data_test.cpp b/kv_store/frameworks/libs/distributeddb/test/unittest/common/storage/distributeddb_relational_get_data_test.cpp index 47a2e1524813a7fa5d7a3e5a8c468e0d3db132cd..96c3498d1f2ceb523678ef5cf33a896f8906a83a 100644 --- a/kv_store/frameworks/libs/distributeddb/test/unittest/common/storage/distributeddb_relational_get_data_test.cpp +++ b/kv_store/frameworks/libs/distributeddb/test/unittest/common/storage/distributeddb_relational_get_data_test.cpp @@ -275,6 +275,7 @@ void SetNextBeginTime001() dataItem.flag = DataItem::DELETE_FLAG; token->FinishGetData(); + EXPECT_EQ(token->IsGetAllDataFinished(), false); token->SetNextBeginTime(dataItem); } } diff --git a/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/distributeddb_mock_sync_module_test.cpp b/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/distributeddb_mock_sync_module_test.cpp index d5f3f91a70f289ec1ec5c18ab46559f784167d6c..5ab5ce608d8967ef472610657055ba4a72db9eb5 100644 --- a/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/distributeddb_mock_sync_module_test.cpp +++ b/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/distributeddb_mock_sync_module_test.cpp @@ -62,9 +62,9 @@ public: { syncer_.LocalDataChanged(static_cast(SQLiteGeneralNSNotificationEventType::SQLITE_GENERAL_NS_PUT_EVENT)); } - void Close() + int Close() { - syncer_.Close(true); + return syncer_.Close(true); } private: SyncerProxy syncer_; @@ -181,7 +181,10 @@ void StateMachineCheck013() } MockCommunicator communicator; Init(stateMachine, syncTaskContext, communicator, dbSyncInterface); - EXPECT_CALL(*syncTaskContext, Clear()).WillRepeatedly(Return()); + int count = 0; + EXPECT_CALL(*syncTaskContext, Clear()).WillRepeatedly([&count]() { + count++; + }); syncTaskContext->RegForkGetDeviceIdFunc([]() { std::this_thread::sleep_for(std::chrono::seconds(2)); // sleep 2s }); @@ -190,6 +193,7 @@ void StateMachineCheck013() RefObject::KillAndDecObjRef(syncTaskContext); delete dbSyncInterface; std::this_thread::sleep_for(std::chrono::seconds(5)); // sleep 5s and wait for task exist + EXPECT_EQ(count, 1); } void AutoLaunchCheck001() @@ -253,6 +257,7 @@ void AbilitySync004() t.detach(); } cv.wait(lock, [&]() { return finishCount == loopCount; }); + EXPECT_EQ(context->GetRemoteCompressAlgoStr(), "none"); RefObject::KillAndDecObjRef(context); } @@ -260,13 +265,16 @@ void SyncLifeTest001() { std::shared_ptr syncer = std::make_shared(); VirtualCommunicatorAggregator *virtualCommunicatorAggregator = new VirtualCommunicatorAggregator(); + ASSERT_NE(virtualCommunicatorAggregator, nullptr); RuntimeContext::GetInstance()->SetCommunicatorAggregator(virtualCommunicatorAggregator); VirtualSingleVerSyncDBInterface *syncDBInterface = new VirtualSingleVerSyncDBInterface(); - syncer->Initialize(syncDBInterface, true); + ASSERT_NE(syncDBInterface, nullptr); + EXPECT_EQ(syncer->Initialize(syncDBInterface, true), -E_INVALID_ARGS); syncer->EnableAutoSync(true); for (int i = 0; i < 1000; i++) { // trigger 1000 times auto sync check syncer->LocalDataChanged(static_cast(SQLiteGeneralNSNotificationEventType::SQLITE_GENERAL_NS_PUT_EVENT)); } + EXPECT_EQ(virtualCommunicatorAggregator->GetOnlineDevices().size(), 0u); syncer = nullptr; RuntimeContext::GetInstance()->SetCommunicatorAggregator(nullptr); delete syncDBInterface; @@ -276,9 +284,11 @@ void SyncLifeTest002() { std::shared_ptr syncer = std::make_shared(); VirtualCommunicatorAggregator *virtualCommunicatorAggregator = new VirtualCommunicatorAggregator(); + ASSERT_NE(virtualCommunicatorAggregator, nullptr); RuntimeContext::GetInstance()->SetCommunicatorAggregator(virtualCommunicatorAggregator); const std::string DEVICE_B = "deviceB"; VirtualSingleVerSyncDBInterface *syncDBInterface = new VirtualSingleVerSyncDBInterface(); + ASSERT_NE(syncDBInterface, nullptr); std::string userId = "userid_0"; std::string storeId = "storeId_0"; std::string appId = "appid_0"; @@ -286,7 +296,7 @@ void SyncLifeTest002() std::vector identifierVec(identifier.begin(), identifier.end()); syncDBInterface->SetIdentifier(identifierVec); for (int i = 0; i < 100; i++) { // run 100 times - syncer->Initialize(syncDBInterface, true); + EXPECT_EQ(syncer->Initialize(syncDBInterface, true), E_OK); syncer->EnableAutoSync(true); virtualCommunicatorAggregator->OnlineDevice(DEVICE_B); std::thread writeThread([syncer]() { @@ -295,7 +305,7 @@ void SyncLifeTest002() }); std::thread closeThread([syncer, &syncDBInterface]() { std::this_thread::sleep_for(std::chrono::milliseconds(1)); - syncer->Close(true); + EXPECT_EQ(syncer->Close(true), E_OK); }); closeThread.join(); writeThread.join(); @@ -309,8 +319,10 @@ void SyncLifeTest002() void SyncLifeTest003() { VirtualCommunicatorAggregator *virtualCommunicatorAggregator = new VirtualCommunicatorAggregator(); + ASSERT_NE(virtualCommunicatorAggregator, nullptr); RuntimeContext::GetInstance()->SetCommunicatorAggregator(virtualCommunicatorAggregator); TestInterface *syncDBInterface = new TestInterface(); + ASSERT_NE(syncDBInterface, nullptr); const std::string DEVICE_B = "deviceB"; std::string userId = "userId_0"; std::string storeId = "storeId_0"; @@ -322,7 +334,7 @@ void SyncLifeTest003() virtualCommunicatorAggregator->OnlineDevice(DEVICE_B); syncDBInterface->TestLocalChange(); virtualCommunicatorAggregator->OfflineDevice(DEVICE_B); - syncDBInterface->Close(); + EXPECT_EQ(syncDBInterface->Close(), E_OK); RefObject::KillAndDecObjRef(syncDBInterface); RuntimeContext::GetInstance()->StopTaskPool(); std::this_thread::sleep_for(std::chrono::seconds(1)); @@ -333,14 +345,14 @@ void MockRemoteQuery002() { MockRemoteExecutor *executor = new (std::nothrow) MockRemoteExecutor(); ASSERT_NE(executor, nullptr); - executor->CallResponseFailed(0, 0, 0, "DEVICE"); + EXPECT_EQ(executor->CallResponseFailed(0, 0, 0, "DEVICE"), -E_BUSY); RefObject::KillAndDecObjRef(executor); } void SyncerCheck001() { std::shared_ptr syncer = std::make_shared(); - syncer->SetSyncRetry(true); + EXPECT_EQ(syncer->SetSyncRetry(true), -E_NOT_INIT); syncer = nullptr; } @@ -357,7 +369,7 @@ void TimeSync001() const int timeDriverMs = 100; for (int i = 0; i < loopCount; ++i) { MockTimeSync timeSync; - timeSync.Initialize(communicator, metadata, storage, "DEVICES_A"); + EXPECT_EQ(timeSync.Initialize(communicator, metadata, storage, "DEVICES_A"), E_OK); timeSync.ModifyTimer(timeDriverMs); std::this_thread::sleep_for(std::chrono::milliseconds(timeDriverMs)); timeSync.Close(); diff --git a/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/distributeddb_single_ver_p2p_complex_sync_test.cpp b/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/distributeddb_single_ver_p2p_complex_sync_test.cpp index 3159e96e474664c4acc197af0595244b9a040adb..e8887801c435d5081b76ab700245aebfbee7bac5 100644 --- a/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/distributeddb_single_ver_p2p_complex_sync_test.cpp +++ b/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/distributeddb_single_ver_p2p_complex_sync_test.cpp @@ -23,6 +23,7 @@ #include "distributeddb_tools_unit_test.h" #include "kv_store_nb_delegate.h" #include "kv_virtual_device.h" +#include "mock_sync_task_context.h" #include "platform_specific.h" #include "single_ver_data_sync.h" #include "single_ver_kv_sync_task_context.h" @@ -128,9 +129,11 @@ namespace { void DataSync005() { + ASSERT_NE(g_communicatorAggregator, nullptr); SingleVerDataSync *dataSync = new (std::nothrow) SingleVerDataSync(); ASSERT_TRUE(dataSync != nullptr); dataSync->SendSaveDataNotifyPacket(nullptr, 0, 0, 0, TIME_SYNC_MESSAGE); + EXPECT_EQ(g_communicatorAggregator->GetOnlineDevices().size(), 3u); // 3 online dev delete dataSync; } @@ -138,8 +141,15 @@ namespace { { SingleVerDataSync *dataSync = new (std::nothrow) SingleVerDataSync(); ASSERT_TRUE(dataSync != nullptr); + auto context = new (std::nothrow) MockSyncTaskContext(); dataSync->PutDataMsg(nullptr); + bool isNeedHandle = false; + bool isContinue = false; + EXPECT_EQ(dataSync->MoveNextDataMsg(context, isNeedHandle, isContinue), nullptr); + EXPECT_EQ(isNeedHandle, false); + EXPECT_EQ(isContinue, false); delete dataSync; + delete context; } void ReSetWaterDogTest001() @@ -164,7 +174,7 @@ namespace { * @tc.steps: step3. deviceA,deviceB sync to each other at same time * @tc.expected: step3. sync should return OK. */ - g_deviceB->Sync(DistributedDB::SYNC_MODE_PULL_ONLY, true); + EXPECT_EQ(g_deviceB->Sync(DistributedDB::SYNC_MODE_PULL_ONLY, true), E_OK); g_communicatorAggregator->SetDeviceMtuSize(DEVICE_A, 5 * 1024u * 1024u); // 5 * 1024u * 1024u = 5m g_communicatorAggregator->SetDeviceMtuSize(DEVICE_B, 5 * 1024u * 1024u); // 5 * 1024u * 1024u = 5m } diff --git a/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/mock_remote_executor.h b/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/mock_remote_executor.h index bfab8c9d88781061611c0805aad7e3fdc5f705ec..d8c230bd39b6e5b915e29ced54c63e8d32598fd8 100644 --- a/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/mock_remote_executor.h +++ b/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/mock_remote_executor.h @@ -25,9 +25,9 @@ public: MOCK_METHOD1(IsPacketValid, bool(uint32_t)); - void CallResponseFailed(int errCode, uint32_t sessionId, uint32_t sequenceId, const std::string &device) + int CallResponseFailed(int errCode, uint32_t sessionId, uint32_t sequenceId, const std::string &device) { - RemoteExecutor::ResponseFailed(errCode, sessionId, sequenceId, device); + return RemoteExecutor::ResponseFailed(errCode, sessionId, sequenceId, device); } }; } // namespace DistributedDB diff --git a/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/virtual_communicator_aggregator.cpp b/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/virtual_communicator_aggregator.cpp index d3836d1a247cf0a5d522d7c293e28620a60603b3..31c89841ca4f9c93f37a09936bc3916112ab9b4f 100644 --- a/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/virtual_communicator_aggregator.cpp +++ b/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/virtual_communicator_aggregator.cpp @@ -313,4 +313,14 @@ void VirtualCommunicatorAggregator::DelayTimeHandle(uint32_t messageId, const st skipTimes_--; } } + +std::set VirtualCommunicatorAggregator::GetOnlineDevices() +{ + std::lock_guard lock(communicatorsLock_); + std::set onlineDevices; + for (const auto &item: communicators_) { + onlineDevices.insert(item.first); + } + return onlineDevices; +} } // namespace DistributedDB diff --git a/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/virtual_communicator_aggregator.h b/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/virtual_communicator_aggregator.h index 1c97716c8e2d67243a02d13eb264d2b657b11cbd..1f77ed02845a6af7013d5b96108d974b14028b57 100644 --- a/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/virtual_communicator_aggregator.h +++ b/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/virtual_communicator_aggregator.h @@ -81,6 +81,8 @@ public: std::set &delayDevices); void ResetSendDelayInfo(); + std::set GetOnlineDevices(); + ~VirtualCommunicatorAggregator() {}; VirtualCommunicatorAggregator() {}; diff --git a/kv_store/interfaces/innerkits/distributeddata/BUILD.gn b/kv_store/interfaces/innerkits/distributeddata/BUILD.gn index b78a26d2ab000fda1b0e4dbdd7638872dd0e1323..a0ee3aa5794253d4086c3561ee24fe1dd3461d0e 100644 --- a/kv_store/interfaces/innerkits/distributeddata/BUILD.gn +++ b/kv_store/interfaces/innerkits/distributeddata/BUILD.gn @@ -42,7 +42,7 @@ config("distributeddatafwk_config") { } config("distributeddatafwk_public_config") { - visibility = [ "//foundation/distributeddatamgr/kv_store:*" ] + visibility = [ ":*" ] include_dirs = [ "include", diff --git a/preferences/frameworks/js/napi/preferences/src/napi_preferences.cpp b/preferences/frameworks/js/napi/preferences/src/napi_preferences.cpp index fe2d082b05e9592169c320a86f09c17082fac749..9da824be09e5103fcecffbf2feec9045f495ee5b 100644 --- a/preferences/frameworks/js/napi/preferences/src/napi_preferences.cpp +++ b/preferences/frameworks/js/napi/preferences/src/napi_preferences.cpp @@ -115,7 +115,7 @@ napi_status PreferencesProxy::NewInstance( LOG_ERROR("PreferencesProxy::NewInstance unwarp native preferences is null"); return napi_generic_failure; } - proxy->value_ = std::move(value); + proxy->value_ = value; return napi_ok; } @@ -304,6 +304,9 @@ int ParseDefValue(const napi_env &env, const napi_value &jsVal, std::shared_ptr< } else if (valueType == napi_object) { if (ParseDefObject(env, jsVal, context) != E_OK) { LOG_ERROR("ParseDefValue::ParseDefObject failed"); + std::shared_ptr paramError = std::make_shared("value", "a ValueType."); + context->SetError(paramError); + return ERR; } } else { LOG_ERROR("ParseDefValue Wrong second parameter type"); diff --git a/preferences/interfaces/inner_api/BUILD.gn b/preferences/interfaces/inner_api/BUILD.gn index e0210d6b7ef3f5bf519cce611df8255b48cf3ecd..1133cb2933c4b1bb644f97157ce078b319418216 100644 --- a/preferences/interfaces/inner_api/BUILD.gn +++ b/preferences/interfaces/inner_api/BUILD.gn @@ -21,7 +21,7 @@ config("native_preferences_config") { } config("native_preferences_public_config") { - visibility = [ "//foundation/distributeddatamgr/preferences:*" ] + visibility = [ ":*" ] include_dirs = [ "include" ] } diff --git a/relational_store/bundle.json b/relational_store/bundle.json index baeb0a2ee5d7e3af38b22508758582fc5964c214..1e2b3fdaddc5ff9488ff851c6b09d8960b72dc31 100644 --- a/relational_store/bundle.json +++ b/relational_store/bundle.json @@ -140,8 +140,9 @@ ], "test": [ "//foundation/distributeddatamgr/relational_store/test/js/dataability:unittest", - "//foundation/distributeddatamgr/relational_store/test/js/relationalstore/performance:performancetest", + "//foundation/distributeddatamgr/relational_store/test/js/rdb:performancetest", "//foundation/distributeddatamgr/relational_store/test/js/rdb:unittest", + "//foundation/distributeddatamgr/relational_store/test/js/relationalstore:performancetest", "//foundation/distributeddatamgr/relational_store/test/js/relationalstore:unittest", "//foundation/distributeddatamgr/relational_store/test/native/dataability:unittest", "//foundation/distributeddatamgr/relational_store/test/native/rdb:unittest", diff --git a/relational_store/frameworks/js/napi/common/include/js_utils.h b/relational_store/frameworks/js/napi/common/include/js_utils.h index 67aef256db93af21c51042b08457e48c0beaa161..758add1171744163009cb7a0d8a9c455cd5cc853 100644 --- a/relational_store/frameworks/js/napi/common/include/js_utils.h +++ b/relational_store/frameworks/js/napi/common/include/js_utils.h @@ -19,6 +19,7 @@ #include #include #include +#include #include #include "napi/native_api.h" @@ -27,46 +28,71 @@ namespace OHOS { namespace AppDataMgrJsKit { -class JSUtils final { -public: - static constexpr int OK = 0; - static constexpr int ERR = -1; - static constexpr int32_t DEFAULT_BUF_SIZE = 1024; +namespace JSUtils { + constexpr int OK = 0; + constexpr int ERR = -1; + constexpr int32_t DEFAULT_BUF_SIZE = 1024; // 1 is the margin - static constexpr int32_t BUF_CACHE_MARGIN = 4 + 1; - static constexpr int32_t ASYNC_RST_SIZE = 2; - static constexpr int32_t MAX_VALUE_LENGTH = 8 * 1024; - static constexpr int32_t SYNC_RESULT_ELEMNT_NUM = 2; + constexpr int32_t BUF_CACHE_MARGIN = 4 + 1; + constexpr int32_t ASYNC_RST_SIZE = 2; + constexpr int32_t MAX_VALUE_LENGTH = 8 * 1024; + constexpr int32_t SYNC_RESULT_ELEMNT_NUM = 2; - static std::string Convert2String(napi_env env, napi_value jsStr, bool useDefaultBufSize = true); - static int32_t Convert2Bool(napi_env env, napi_value jsBool, bool &output); - static int32_t Convert2Double(napi_env env, napi_value jsNum, double &output); - static int32_t Convert2String(napi_env env, napi_value jsStr, std::string &output); - static int32_t Convert2U8Vector(napi_env env, napi_value jsValue, std::vector &output); - static std::vector Convert2StrVector(napi_env env, napi_value value); - static std::vector Convert2U8Vector(napi_env env, napi_value jsValue); - static std::string ConvertAny2String(napi_env env, const napi_value jsValue); + std::string Convert2String(napi_env env, napi_value jsStr, bool useDefaultBufSize = true); + int32_t Convert2Bool(napi_env env, napi_value jsBool, bool &output); + int32_t Convert2Double(napi_env env, napi_value jsNum, double &output); + int32_t Convert2String(napi_env env, napi_value jsStr, std::string &output); + int32_t Convert2U8Vector(napi_env env, napi_value jsValue, std::vector &output); + std::vector Convert2StrVector(napi_env env, napi_value value); + std::vector Convert2U8Vector(napi_env env, napi_value jsValue); + std::string ConvertAny2String(napi_env env, const napi_value jsValue); - static int32_t Convert2StrVector(napi_env env, napi_value value, std::vector &output); - static int32_t Convert2BoolVector(napi_env env, napi_value value, std::vector &output); - static int32_t Convert2DoubleVector(napi_env env, napi_value value, std::vector &output); + int32_t Convert2StrVector(napi_env env, napi_value value, std::vector &output); + int32_t Convert2BoolVector(napi_env env, napi_value value, std::vector &output); + int32_t Convert2DoubleVector(napi_env env, napi_value value, std::vector &output); - static napi_value Convert2JSValue(napi_env env, const std::vector &value); - static napi_value Convert2JSValue(napi_env env, const std::string &value); - static napi_value Convert2JSValue(napi_env env, const std::vector &value); - static napi_value Convert2JSValue(napi_env env, int32_t value); - static napi_value Convert2JSValue(napi_env env, int64_t value); - static napi_value Convert2JSValue(napi_env env, double value); - static napi_value Convert2JSValue(napi_env env, bool value); - static napi_value Convert2JSValue(napi_env env, const std::map &value); + napi_value Convert2JSValue(napi_env env, const std::vector &value); + napi_value Convert2JSValue(napi_env env, const std::string &value); + napi_value Convert2JSValue(napi_env env, const std::vector &value); + napi_value Convert2JSValue(napi_env env, int32_t value); + napi_value Convert2JSValue(napi_env env, int64_t value); + napi_value Convert2JSValue(napi_env env, double value); + napi_value Convert2JSValue(napi_env env, bool value); + napi_value Convert2JSValue(napi_env env, const std::map &value); + napi_value Convert2JSValue(napi_env env, const std::monostate &value); - static int32_t Convert2JSValue(napi_env env, std::string value, napi_value &output); - static int32_t Convert2JSValue(napi_env env, bool value, napi_value &output); - static int32_t Convert2JSValue(napi_env env, double value, napi_value &output); - static int32_t Convert2JSStringArr(napi_env env, std::vector value, napi_value &output); - static int32_t Convert2JSBoolArr(napi_env env, std::vector value, napi_value &output); - static int32_t Convert2JSDoubleArr(napi_env env, std::vector value, napi_value &output); -}; + int32_t Convert2JSValue(napi_env env, std::string value, napi_value &output); + int32_t Convert2JSValue(napi_env env, bool value, napi_value &output); + int32_t Convert2JSValue(napi_env env, double value, napi_value &output); + int32_t Convert2JSStringArr(napi_env env, std::vector value, napi_value &output); + int32_t Convert2JSBoolArr(napi_env env, std::vector value, napi_value &output); + int32_t Convert2JSDoubleArr(napi_env env, std::vector value, napi_value &output); + + template + napi_value Convert2JSValue(napi_env env, const T &value); + + template + napi_value GetJSValue(napi_env env, const _T &value) + { + return nullptr; + } + + template + napi_value GetJSValue(napi_env env, const _T &value) + { + auto *val = std::get_if<_First>(&value); + if (val != nullptr) { + return Convert2JSValue(env, *val); + } + return GetJSValue<_T, _Types...>(env, value); + } + + template + napi_value Convert2JSValue(napi_env env, const std::variant<_Types...> &value) + { + return GetJSValue(env, value); + } +} // namespace JSUtils } // namespace AppDataMgrJsKit } // namespace OHOS diff --git a/relational_store/frameworks/js/napi/common/src/js_utils.cpp b/relational_store/frameworks/js/napi/common/src/js_utils.cpp index 61585203d8204043616cd937e2eb8008abb55e65..2be25a4a33976d344a84bd9b79247282a8004b03 100644 --- a/relational_store/frameworks/js/napi/common/src/js_utils.cpp +++ b/relational_store/frameworks/js/napi/common/src/js_utils.cpp @@ -351,6 +351,13 @@ napi_value JSUtils::Convert2JSValue(napi_env env, const std::map +#include #include "js_logger.h" #include "js_utils.h" #include "napi_rdb_error.h" #include "napi_rdb_trace.h" #include "rdb_errno.h" +#include "value_object.h" #if !defined(WINDOWS_PLATFORM) && !defined(MAC_PLATFORM) #include "rdb_result_set_bridge.h" @@ -32,6 +34,25 @@ using namespace OHOS::NativeRdb; using namespace OHOS::AppDataMgrJsKit; namespace OHOS { +namespace AppDataMgrJsKit { +namespace JSUtils { +template<> +napi_value Convert2JSValue(napi_env env, const RowEntity &rowEntity) +{ + napi_value ret; + NAPI_CALL(env, napi_create_object(env, &ret)); + std::map values; + rowEntity.Get(values); + napi_value value = nullptr; + for (auto const &it : values) { + value = JSUtils::Convert2JSValue(env, static_cast(it.second)); + NAPI_CALL(env, napi_set_named_property(env, ret, it.first.c_str(), value)); + } + return ret; +} +} +} + namespace RelationalStoreJsKit { static napi_ref __thread ctorRef_ = nullptr; static const int E_OK = 0; @@ -93,6 +114,7 @@ napi_value ResultSetProxy::GetConstructor(napi_env env) DECLARE_NAPI_FUNCTION("getString", GetString), DECLARE_NAPI_FUNCTION("getDouble", GetDouble), DECLARE_NAPI_FUNCTION("isColumnNull", IsColumnNull), + DECLARE_NAPI_FUNCTION("getRow", GetRow), DECLARE_NAPI_GETTER("columnNames", GetAllColumnNames), DECLARE_NAPI_GETTER("columnCount", GetColumnCount), @@ -512,6 +534,17 @@ napi_value ResultSetProxy::IsColumnNull(napi_env env, napi_callback_info info) return JSUtils::Convert2JSValue(env, result); } +napi_value ResultSetProxy::GetRow(napi_env env, napi_callback_info info) +{ + ResultSetProxy *resultSetProxy = GetInnerResultSet(env, info); + CHECK_RETURN_NULL(resultSetProxy && resultSetProxy->resultSet_); + + RowEntity rowEntity; + int errCode = resultSetProxy->resultSet_->GetRow(rowEntity); + RDB_NAPI_ASSERT(env, errCode == E_OK, std::make_shared(errCode)); + return JSUtils::Convert2JSValue(env, rowEntity); +} + napi_value ResultSetProxy::IsClosed(napi_env env, napi_callback_info info) { ResultSetProxy *resultSetProxy = GetInnerResultSet(env, info); diff --git a/relational_store/frameworks/native/rdb/include/result_set_proxy.h b/relational_store/frameworks/native/rdb/include/result_set_proxy.h index fe57d8d2f67482c37988651073c044a10a493d2d..60240ab1eddcd6c6caf8162dcccdf0d113c1ddc1 100644 --- a/relational_store/frameworks/native/rdb/include/result_set_proxy.h +++ b/relational_store/frameworks/native/rdb/include/result_set_proxy.h @@ -47,6 +47,7 @@ public: int GetLong(int columnIndex, int64_t &value) override; int GetDouble(int columnIndex, double &value) override; int IsColumnNull(int columnIndex, bool &isNull) override; + int GetRow(RowEntity &rowEntity) override; bool IsClosed() const override; int Close() override; diff --git a/relational_store/frameworks/native/rdb/include/sqlite_global_config.h b/relational_store/frameworks/native/rdb/include/sqlite_global_config.h index 21edf315c1a19fd1da96f8f8eda19891b05784b9..4138ea18551bc8565ba4d8f92a1bbe4f16746473 100644 --- a/relational_store/frameworks/native/rdb/include/sqlite_global_config.h +++ b/relational_store/frameworks/native/rdb/include/sqlite_global_config.h @@ -31,6 +31,7 @@ public: static constexpr int DB_WAL_SIZE_LIMIT = 200 * 1024 * 1024; /* default wal file maximum size : 200M */ static constexpr int WAL_AUTO_CHECKPOINT = 100; /* 100 pages */ static constexpr int APP_DEFAULT_UMASK = 0002; + static constexpr int SQLITE_MAX_COLUMN = 2000; static constexpr char ATTACH_BACKUP_SQL[] = "ATTACH ? AS backup KEY ?"; static constexpr char ATTACH_SQL[] = "ATTACH ? AS ? KEY ?"; static constexpr char EXPORT_SQL[] = "SELECT export_database('backup')"; diff --git a/relational_store/frameworks/native/rdb/mock/include/sqlite_global_config.h b/relational_store/frameworks/native/rdb/mock/include/sqlite_global_config.h index a8b1cf24e44a379abfac9693e3a9082ce8e8d4c6..08900d5510b0fbb070c3588b4b7916e2ddae5ae6 100644 --- a/relational_store/frameworks/native/rdb/mock/include/sqlite_global_config.h +++ b/relational_store/frameworks/native/rdb/mock/include/sqlite_global_config.h @@ -32,6 +32,7 @@ public: static constexpr int DB_WAL_SIZE_LIMIT = 200 * 1024 * 1024; /* default wal file maximum size : 200M */ static constexpr int WAL_AUTO_CHECKPOINT = 100; /* 100 pages */ static constexpr int APP_DEFAULT_UMASK = 0002; + static constexpr int SQLITE_MAX_COLUMN = 2000; static constexpr char ATTACH_BACKUP_SQL[] = "ATTACH ? AS backup KEY ?"; static constexpr char ATTACH_SQL[] = "ATTACH ? AS ? KEY ?"; static constexpr char EXPORT_SQL[] = "SELECT export_database('backup')"; diff --git a/relational_store/frameworks/native/rdb/src/abs_result_set.cpp b/relational_store/frameworks/native/rdb/src/abs_result_set.cpp index b7c7fc1a1612b5a2164f633ddd0b7790d9a2a53d..1840a7a36a9a1729fccbcc87894300cad1fe6247 100644 --- a/relational_store/frameworks/native/rdb/src/abs_result_set.cpp +++ b/relational_store/frameworks/native/rdb/src/abs_result_set.cpp @@ -24,6 +24,40 @@ namespace OHOS { namespace NativeRdb { +void RowEntity::Put(const std::string &name, const ValueObject &value) +{ + auto it = values_.emplace(name, std::move(value)); + indexs_.push_back(it.first); +} + +ValueObject RowEntity::Get(const std::string &name) const +{ + auto it = values_.find(name); + if (it == values_.end()) { + return ValueObject(); + } + return it->second; +} + +ValueObject RowEntity::Get(int index) const +{ + if (index < 0 || index >= indexs_.size()) { + return ValueObject(); + } + return indexs_[index]->second; +} + +void RowEntity::Get(std::map &outValues) const +{ + outValues = values_; +} + +void RowEntity::Clear() +{ + values_.clear(); + indexs_.clear(); +} + AbsResultSet::AbsResultSet() : rowPos_(INIT_POS), isClosed(false) { } @@ -70,6 +104,61 @@ int AbsResultSet::IsColumnNull(int columnIndex, bool &isNull) return E_OK; } +int AbsResultSet::GetRow(RowEntity &rowEntity) +{ + rowEntity.Clear(); + std::vector columnNames; + int ret = GetAllColumnNames(columnNames); + if (ret != E_OK) { + LOG_ERROR("GetAllColumnNames::ret is %{public}d", ret); + return ret; + } + int columnCount = static_cast(columnNames.size()); + + ColumnType columnType; + for (int columnIndex = 0; columnIndex < columnCount; ++columnIndex) { + ret = GetColumnType(columnIndex, columnType); + if (ret != E_OK) { + LOG_ERROR("GetColumnType::ret is %{public}d", ret); + return ret; + } + switch (columnType) { + case ColumnType::TYPE_NULL: { + rowEntity.Put(columnNames[columnIndex], ValueObject()); + break; + } + case ColumnType::TYPE_INTEGER: { + int64_t value; + GetLong(columnIndex, value); + rowEntity.Put(columnNames[columnIndex], ValueObject(value)); + break; + } + case ColumnType::TYPE_FLOAT: { + double value; + GetDouble(columnIndex, value); + rowEntity.Put(columnNames[columnIndex], ValueObject(value)); + break; + } + case ColumnType::TYPE_STRING: { + std::string value; + GetString(columnIndex, value); + rowEntity.Put(columnNames[columnIndex], ValueObject(value)); + break; + } + case ColumnType::TYPE_BLOB: { + std::vector value; + GetBlob(columnIndex, value); + rowEntity.Put(columnNames[columnIndex], ValueObject(value)); + break; + } + default: { + return E_ERROR; + } + } + } + return E_OK; +} + int AbsResultSet::GoToRow(int position) { return E_OK; diff --git a/relational_store/frameworks/native/rdb/src/rdb_security_manager.cpp b/relational_store/frameworks/native/rdb/src/rdb_security_manager.cpp index 18bdc14e8b405384823b7268819c5d2a41866a05..fd212bf95cf919f58f86b4ebf4c6cfabe1c638a0 100644 --- a/relational_store/frameworks/native/rdb/src/rdb_security_manager.cpp +++ b/relational_store/frameworks/native/rdb/src/rdb_security_manager.cpp @@ -414,7 +414,7 @@ bool RdbSecurityManager::DecryptWorkKey(std::vector &source, std::vecto return false; } - key.assign(plainKeyBlob.data, plainKeyBlob.data + 32); + key.assign(plainKeyBlob.data, plainKeyBlob.data + plainKeyBlob.size); (void)memset_s(plainBuf, sizeof(plainBuf), 0, sizeof(plainBuf)); return true; } diff --git a/relational_store/frameworks/native/rdb/src/result_set_proxy.cpp b/relational_store/frameworks/native/rdb/src/result_set_proxy.cpp index 91558f05167cadccbf4872b6043bd1c8320c4f76..1dfdb58028878e8ff4e9c892249e705d85a5169c 100644 --- a/relational_store/frameworks/native/rdb/src/result_set_proxy.cpp +++ b/relational_store/frameworks/native/rdb/src/result_set_proxy.cpp @@ -239,6 +239,11 @@ int ResultSetProxy::IsColumnNull(int columnIndex, bool &isNull) return E_OK; } +int ResultSetProxy::GetRow(RowEntity &rowEntity) +{ + return E_NOT_SUPPORT; +} + bool ResultSetProxy::IsClosed() const { MessageParcel data, reply; diff --git a/relational_store/frameworks/native/rdb/src/value_object.cpp b/relational_store/frameworks/native/rdb/src/value_object.cpp index d6d39579cf107caa9295c8cc18bbd898fd51ad45..85776670ab1f75d9106415bad375f382b9f4ed07 100644 --- a/relational_store/frameworks/native/rdb/src/value_object.cpp +++ b/relational_store/frameworks/native/rdb/src/value_object.cpp @@ -73,6 +73,10 @@ ValueObject::ValueObject(const std::string &val) : type(ValueObjectType::TYPE_ST { value = val; } +ValueObject::ValueObject(const char *val) : type(ValueObjectType::TYPE_STRING) +{ + value = std::string(val); +} ValueObject::ValueObject(const std::vector &val) : type(ValueObjectType::TYPE_BLOB) { std::vector blob = val; diff --git a/relational_store/frameworks/native/rdb/src/values_bucket.cpp b/relational_store/frameworks/native/rdb/src/values_bucket.cpp index eee1d9626a0b0727b4e2d74f93602e8471a24f74..053c66d09c89c920d9f1cf7245988c7c136c5827 100644 --- a/relational_store/frameworks/native/rdb/src/values_bucket.cpp +++ b/relational_store/frameworks/native/rdb/src/values_bucket.cpp @@ -14,6 +14,8 @@ */ #include "values_bucket.h" +#include "sqlite_global_config.h" +#include "logger.h" namespace OHOS { namespace NativeRdb { @@ -124,6 +126,10 @@ ValuesBucket *ValuesBucket::Unmarshalling(Parcel &parcel) int mapSize = parcel.ReadInt32(); std::map valuesMap; ValueObject *value = nullptr; + if (mapSize > GlobalExpr::SQLITE_MAX_COLUMN) { + LOG_ERROR("The mapSize is %{public}d ", mapSize); + return new ValuesBucket(valuesMap); + } for (int i = 0; i < mapSize; i++) { std::string key = parcel.ReadString(); value = parcel.ReadParcelable(); diff --git a/relational_store/interfaces/inner_api/dataability/BUILD.gn b/relational_store/interfaces/inner_api/dataability/BUILD.gn index 03fb71be4d50f83304d1af5fa55189e4e880da1a..85ec5c6ca65a86f987270eefa8667e9b8dcb1728 100644 --- a/relational_store/interfaces/inner_api/dataability/BUILD.gn +++ b/relational_store/interfaces/inner_api/dataability/BUILD.gn @@ -30,7 +30,7 @@ config("native_dataability_config") { } config("native_dataability_public_config") { - visibility = [ "//foundation/distributeddatamgr/relational_store:*" ] + visibility = [ ":*" ] include_dirs = [ "include" ] } diff --git a/relational_store/interfaces/inner_api/rdb/BUILD.gn b/relational_store/interfaces/inner_api/rdb/BUILD.gn index 39b20a8b5c2c54e2f62c46f304dac7c977d07a46..48c79dcded762decafe48c0f93cb1af3ff4ddfcd 100644 --- a/relational_store/interfaces/inner_api/rdb/BUILD.gn +++ b/relational_store/interfaces/inner_api/rdb/BUILD.gn @@ -70,7 +70,7 @@ config("native_rdb_config") { } config("native_rdb_public_config") { - visibility = [ "//foundation/distributeddatamgr/relational_store:*" ] + visibility = [ ":*" ] if (is_mingw || is_mac) { include_dirs = [ diff --git a/relational_store/interfaces/inner_api/rdb/include/abs_result_set.h b/relational_store/interfaces/inner_api/rdb/include/abs_result_set.h index 708337ffdc8bd163b0670baf5ed778c4833c9a81..9f0011fef886599720a6a248c70f708969611521 100644 --- a/relational_store/interfaces/inner_api/rdb/include/abs_result_set.h +++ b/relational_store/interfaces/inner_api/rdb/include/abs_result_set.h @@ -22,6 +22,7 @@ #include #include "result_set.h" +#include "value_object.h" namespace OHOS { namespace NativeRdb { @@ -121,6 +122,11 @@ public: */ RDB_API_EXPORT int IsColumnNull(int columnIndex, bool &isNull) override; + /** + * @brief Gets the entire row of data for the current row from the result set. + */ + RDB_API_EXPORT int GetRow(RowEntity &rowEntity) override; + /** * @brief Move the cursor to an absolute position. * diff --git a/relational_store/interfaces/inner_api/rdb/include/remote_result_set.h b/relational_store/interfaces/inner_api/rdb/include/remote_result_set.h new file mode 100644 index 0000000000000000000000000000000000000000..e32ac243ddbf1a61ec3b15a77693404cea35ecc2 --- /dev/null +++ b/relational_store/interfaces/inner_api/rdb/include/remote_result_set.h @@ -0,0 +1,304 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NATIVE_RDB_REMOTE_RESULT_SET_H +#define NATIVE_RDB_REMOTE_RESULT_SET_H + +#include +#include +#include "rdb_visibility.h" + +namespace OHOS { +namespace NativeRdb { + +/** + * @brief Indicates the column type. + * + * Value returned by getColumnType(int) + */ +enum class ColumnType { + /** Indicates the column type is NULL.*/ + TYPE_NULL = 0, + /** Indicates the column type is INTEGER.*/ + TYPE_INTEGER, + /** Indicates the column type is FLOAT.*/ + TYPE_FLOAT, + /** Indicates the column type is STRING.*/ + TYPE_STRING, + /** Indicates the column type is BLOB.*/ + TYPE_BLOB, +}; + +/** + * The RemoteResultSet class of RDB. + * Provides methods for accessing a database result set generated by remote query the database. + */ +class RDB_API_EXPORT RemoteResultSet { +public: + /** + * @brief The error CMD in the correct case. + */ + enum { + /** Indicates the current CMD is CMD_GET_ALL_COLUMN_NAMES.*/ + CMD_GET_ALL_COLUMN_NAMES, + /** Indicates the current CMD is CMD_GET_COLUMN_COUNT.*/ + CMD_GET_COLUMN_COUNT, + /** Indicates the current CMD is CMD_GET_COLUMN_TYPE.*/ + CMD_GET_COLUMN_TYPE, + /** Indicates the current CMD is CMD_GET_COLUMN_INDEX.*/ + CMD_GET_COLUMN_INDEX, + /** Indicates the current CMD is CMD_GET_COLUMN_NAME.*/ + CMD_GET_COLUMN_NAME, + /** Indicates the current CMD is CMD_GET_ROW_COUNT.*/ + CMD_GET_ROW_COUNT, + /** Indicates the current CMD is CMD_GET_ROW_INDEX.*/ + CMD_GET_ROW_INDEX, + /** Indicates the current CMD is CMD_GO_TO.*/ + CMD_GO_TO, + /** Indicates the current CMD is CMD_GO_TO_ROW.*/ + CMD_GO_TO_ROW, + /** Indicates the current CMD is CMD_GO_TO_FIRST_ROW.*/ + CMD_GO_TO_FIRST_ROW, + /** Indicates the current CMD is CMD_GO_TO_LAST_ROW.*/ + CMD_GO_TO_LAST_ROW, + /** Indicates the current CMD is CMD_GO_TO_NEXT_ROW.*/ + CMD_GO_TO_NEXT_ROW, + /** Indicates the current CMD is CMD_GO_TO_PREV_ROW.*/ + CMD_GO_TO_PREV_ROW, + /** Indicates the current CMD is CMD_IS_ENDED_ROW.*/ + CMD_IS_ENDED_ROW, + /** Indicates the current CMD is CMD_IS_STARTED_ROW.*/ + CMD_IS_STARTED_ROW, + /** Indicates the current CMD is CMD_IS_AT_FIRST_ROW.*/ + CMD_IS_AT_FIRST_ROW, + /** Indicates the current CMD is CMD_IS_AT_LAST_ROW.*/ + CMD_IS_AT_LAST_ROW, + /** Indicates the current CMD is CMD_GET_BLOB.*/ + CMD_GET_BLOB, + /** Indicates the current CMD is CMD_GET_STRING.*/ + CMD_GET_STRING, + /** Indicates the current CMD is CMD_GET_INT.*/ + CMD_GET_INT, + /** Indicates the current CMD is CMD_GET_LONG.*/ + CMD_GET_LONG, + /** Indicates the current CMD is CMD_GET_DOUBLE.*/ + CMD_GET_DOUBLE, + /** Indicates the current CMD is CMD_IS_COLUMN_NULL.*/ + CMD_IS_COLUMN_NULL, + /** Indicates the current CMD is CMD_IS_CLOSED.*/ + CMD_IS_CLOSED, + /** Indicates the current CMD is CMD_CLOSE.*/ + CMD_CLOSE, + /** Indicates the current CMD is CMD_MAX.*/ + CMD_MAX + }; + + /** + * @brief Destructor. + */ + virtual ~RemoteResultSet() {} + + /** + * @brief Obtains a string array holding the names of all of the columns in the result set. + * + * @return Returns the names of the columns contains in this query result. + */ + virtual int GetAllColumnNames(std::vector &columnNames) = 0; + + /** + * @brief Obtains the total number of columns. + * + * @return Returns the number of columns + */ + virtual int GetColumnCount(int &count) = 0; + + /** + * @brief Obtains data type of the given column's value. + * + * @param columnIndex Indicates the zero-based index of the target column. + * @return Returns column value type. + */ + virtual int GetColumnType(int columnIndex, ColumnType &columnType) = 0; + + /** + * @brief Obtains the zero-based index for the given column name. + * + * @param columnName Indicates the name of the column. + * @return Returns the column index for the given column, or -1 if the column does not exist. + */ + virtual int GetColumnIndex(const std::string &columnName, int &columnIndex) = 0; + + /** + * @brief Obtains the column name at the given column index. + * + * @param columnIndex Indicates the zero-based index. + * @return Returns the column name for the given index. + */ + virtual int GetColumnName(int columnIndex, std::string &columnName) = 0; + + /** + * @brief Obtains the numbers of rows in the result set. + */ + virtual int GetRowCount(int &count) = 0; + + /** + * @brief Obtains the current position of the cursor in the result set. + * + * The value is zero-based. When the result set is first returned the cursor + * will be at position -1, which is before the first row. + * After the last row is returned another call to next() will leave the cursor past + * the last entry, at a position of count(). + * + * @return Returns the current cursor position. + */ + virtual int GetRowIndex(int &position) const = 0; + + /** + * @brief Move the cursor a relative amount from current position. Positive offset move forward, + * negative offset move backward. + * + * @param offset Indicates the offset to be applied from the current position. + * @return Returns whether the requested move succeeded. + */ + virtual int GoTo(int offset) = 0; + + /** + * @brief Move the cursor to an absolute position. + * + * @param position Indicates the zero-based position to move to. + * @return Returns whether the requested move succeeded. + */ + virtual int GoToRow(int position) = 0; + + /** + * @brief Move the cursor to the first row. + * + * @return Returns whether the requested move succeeded. + */ + virtual int GoToFirstRow() = 0; + + /** + * @brief Move the cursor to the last row. + * + * @return Returns whether the requested move succeeded. + */ + virtual int GoToLastRow() = 0; + + /** + * @brief Move the cursor to the next row. + * + * @return Returns whether the requested move succeeded. + */ + virtual int GoToNextRow() = 0; + + /** + * @brief Move the cursor to the previous row. + * + * @return Returns whether the requested move succeeded. + */ + virtual int GoToPreviousRow() = 0; + + /** + * @brief Obtains whether the cursor is pointing to the position after the last row. + * + * @return Returns whether the cursor is after the last row. + */ + virtual int IsEnded(bool &result) = 0; + + /** + * @brief Obtains whether the cursor is pointing to the position before the first row. + * + * @return Returns whether the cursor is before the first row. + */ + virtual int IsStarted(bool &result) const = 0; + + /** + * @brief Obtains whether the cursor is pointing to the first row. + * + * @return Returns whether the cursor is pointing at the first entry. + */ + virtual int IsAtFirstRow(bool &result) const = 0; + + /** + * @brief Obtains whether the cursor is pointing to the last row. + * + * @return Returns whether the cursor is pointing at the last entry. + */ + virtual int IsAtLastRow(bool &result) = 0; + + /** + * @brief Obtains the value of the requested column as a byte array. + * + * @param columnIndex Indicates the zero-based index of the target column. + * @return Returns the value of the requested column as a byte array. + */ + virtual int GetBlob(int columnIndex, std::vector &blob) = 0; + + /** + * @brief Obtains the value of the requested column as a String. + * + * @param columnIndex Indicates the zero-based index of the target column. + * @return Returns the value of the requested column as a String. + */ + virtual int GetString(int columnIndex, std::string &value) = 0; + + /** + * @brief Obtains the value of the requested column as a int. + * + * @param columnIndex Indicates the zero-based index of the target column. + * @return Returns the value of the requested column as a int. + */ + virtual int GetInt(int columnIndex, int &value) = 0; + + /** + * @brief Obtains the value of the requested column as a long. + * + * @param columnIndex Indicates the zero-based index of the target column. + * @return Returns the value of the requested column as a long. + */ + virtual int GetLong(int columnIndex, int64_t &value) = 0; + + /** + * @brief Obtains the value of the requested column as a double. + * + * @param columnIndex Indicates the zero-based index of the target column. + * @return Returns the value of the requested column as a double. + */ + virtual int GetDouble(int columnIndex, double &value) = 0; + + /** + * @brief Obtains Whether the value of the requested column is null. + * + * @param columnIndex Indicates the zero-based index of the target column. + * @return Returns whether the column value is null. + */ + virtual int IsColumnNull(int columnIndex, bool &isNull) = 0; + + /** + * @brief Obtains Return true if the result set is closed. + * + * @return Returns true if the result set is closed. + */ + virtual bool IsClosed() const = 0; + + /** + * @brief Closes the result set, releasing all of its resources and making it completely invalid. + */ + virtual int Close() = 0; +}; + +} // namespace NativeRdb +} // namespace OHOS +#endif diff --git a/relational_store/interfaces/inner_api/rdb/include/result_set.h b/relational_store/interfaces/inner_api/rdb/include/result_set.h index 2a7f02a7f3f6bfa98cb9f73cf95b066f922b0254..ff08b21f3d85a4369d8a60d5755d64860b672446 100644 --- a/relational_store/interfaces/inner_api/rdb/include/result_set.h +++ b/relational_store/interfaces/inner_api/rdb/include/result_set.h @@ -18,284 +18,39 @@ #include #include -#include "rdb_visibility.h" +#include +#include "remote_result_set.h" +#include "value_object.h" + namespace OHOS { namespace NativeRdb { - -/** - * @brief Indicates the column type. - * - * Value returned by getColumnType(int) - */ -enum class ColumnType { - /** Indicates the column type is NULL.*/ - TYPE_NULL = 0, - /** Indicates the column type is INTEGER.*/ - TYPE_INTEGER, - /** Indicates the column type is FLOAT.*/ - TYPE_FLOAT, - /** Indicates the column type is STRING.*/ - TYPE_STRING, - /** Indicates the column type is BLOB.*/ - TYPE_BLOB, +struct RDB_API_EXPORT RowEntity { +public: + RDB_API_EXPORT void Put(const std::string &name, const ValueObject &value); + RDB_API_EXPORT ValueObject Get(const std::string &name) const; + RDB_API_EXPORT ValueObject Get(const int index) const; + RDB_API_EXPORT void Get(std::map &outValues) const; + RDB_API_EXPORT void Clear(); +private: + std::map values_; + std::vector indexs_; }; /** * The ResultSet class of RDB. * Provides methods for accessing a database result set generated by querying the database. */ -class RDB_API_EXPORT ResultSet { +class RDB_API_EXPORT ResultSet : public RemoteResultSet { public: - /** - * @brief The error CMD in the correct case. - */ - enum { - /** Indicates the current error CMD is CMD_GET_ALL_COLUMN_NAMES.*/ - CMD_GET_ALL_COLUMN_NAMES, - /** Indicates the current error CMD is CMD_GET_COLUMN_COUNT.*/ - CMD_GET_COLUMN_COUNT, - /** Indicates the current error CMD is CMD_GET_COLUMN_TYPE.*/ - CMD_GET_COLUMN_TYPE, - /** Indicates the current error CMD is CMD_GET_COLUMN_INDEX.*/ - CMD_GET_COLUMN_INDEX, - /** Indicates the current error CMD is CMD_GET_COLUMN_NAME.*/ - CMD_GET_COLUMN_NAME, - /** Indicates the current error CMD is CMD_GET_ROW_COUNT.*/ - CMD_GET_ROW_COUNT, - /** Indicates the current error CMD is CMD_GET_ROW_INDEX.*/ - CMD_GET_ROW_INDEX, - /** Indicates the current error CMD is CMD_GO_TO.*/ - CMD_GO_TO, - /** Indicates the current error CMD is CMD_GO_TO_ROW.*/ - CMD_GO_TO_ROW, - /** Indicates the current error CMD is CMD_GO_TO_FIRST_ROW.*/ - CMD_GO_TO_FIRST_ROW, - /** Indicates the current error CMD is CMD_GO_TO_LAST_ROW.*/ - CMD_GO_TO_LAST_ROW, - /** Indicates the current error CMD is CMD_GO_TO_NEXT_ROW.*/ - CMD_GO_TO_NEXT_ROW, - /** Indicates the current error CMD is CMD_GO_TO_PREV_ROW.*/ - CMD_GO_TO_PREV_ROW, - /** Indicates the current error CMD is CMD_IS_ENDED_ROW.*/ - CMD_IS_ENDED_ROW, - /** Indicates the current error CMD is CMD_IS_STARTED_ROW.*/ - CMD_IS_STARTED_ROW, - /** Indicates the current error CMD is CMD_IS_AT_FIRST_ROW.*/ - CMD_IS_AT_FIRST_ROW, - /** Indicates the current error CMD is CMD_IS_AT_LAST_ROW.*/ - CMD_IS_AT_LAST_ROW, - /** Indicates the current error CMD is CMD_GET_BLOB.*/ - CMD_GET_BLOB, - /** Indicates the current error CMD is CMD_GET_STRING.*/ - CMD_GET_STRING, - /** Indicates the current error CMD is CMD_GET_INT.*/ - CMD_GET_INT, - /** Indicates the current error CMD is CMD_GET_LONG.*/ - CMD_GET_LONG, - /** Indicates the current error CMD is CMD_GET_DOUBLE.*/ - CMD_GET_DOUBLE, - /** Indicates the current error CMD is CMD_IS_COLUMN_NULL.*/ - CMD_IS_COLUMN_NULL, - /** Indicates the current error CMD is CMD_IS_CLOSED.*/ - CMD_IS_CLOSED, - /** Indicates the current error CMD is CMD_CLOSE.*/ - CMD_CLOSE, - /** Indicates the current error CMD is CMD_MAX.*/ - CMD_MAX - }; - /** * @brief Destructor. */ virtual ~ResultSet() {} /** - * @brief Obtains a string array holding the names of all of the columns in the result set. - * - * @return Returns the names of the columns contains in this query result. - */ - virtual int GetAllColumnNames(std::vector &columnNames) = 0; - - /** - * @brief Obtains the total number of columns. - * - * @return Returns the number of columns - */ - virtual int GetColumnCount(int &count) = 0; - - /** - * @brief Obtains data type of the given column's value. - * - * @param columnIndex Indicates the zero-based index of the target column. - * @return Returns column value type. - */ - virtual int GetColumnType(int columnIndex, ColumnType &columnType) = 0; - - /** - * @brief Obtains the zero-based index for the given column name. - * - * @param columnName Indicates the name of the column. - * @return Returns the column index for the given column, or -1 if the column does not exist. - */ - virtual int GetColumnIndex(const std::string &columnName, int &columnIndex) = 0; - - /** - * @brief Obtains the column name at the given column index. - * - * @param columnIndex Indicates the zero-based index. - * @return Returns the column name for the given index. - */ - virtual int GetColumnName(int columnIndex, std::string &columnName) = 0; - - /** - * @brief Obtains the numbers of rows in the result set. - */ - virtual int GetRowCount(int &count) = 0; - - /** - * @brief Obtains the current position of the cursor in the result set. - * - * The value is zero-based. When the result set is first returned the cursor - * will be at position -1, which is before the first row. - * After the last row is returned another call to next() will leave the cursor past - * the last entry, at a position of count(). - * - * @return Returns the current cursor position. - */ - virtual int GetRowIndex(int &position) const = 0; - - /** - * @brief Move the cursor a relative amount from current position. Positive offset move forward, - * negative offset move backward. - * - * @param offset Indicates the offset to be applied from the current position. - * @return Returns whether the requested move succeeded. - */ - virtual int GoTo(int offset) = 0; - - /** - * @brief Move the cursor to an absolute position. - * - * @param position Indicates the zero-based position to move to. - * @return Returns whether the requested move succeeded. - */ - virtual int GoToRow(int position) = 0; - - /** - * @brief Move the cursor to the first row. - * - * @return Returns whether the requested move succeeded. - */ - virtual int GoToFirstRow() = 0; - - /** - * @brief Move the cursor to the last row. - * - * @return Returns whether the requested move succeeded. - */ - virtual int GoToLastRow() = 0; - - /** - * @brief Move the cursor to the next row. - * - * @return Returns whether the requested move succeeded. - */ - virtual int GoToNextRow() = 0; - - /** - * @brief Move the cursor to the previous row. - * - * @return Returns whether the requested move succeeded. - */ - virtual int GoToPreviousRow() = 0; - - /** - * @brief Obtains whether the cursor is pointing to the position after the last row. - * - * @return Returns whether the cursor is after the last row. - */ - virtual int IsEnded(bool &result) = 0; - - /** - * @brief Obtains whether the cursor is pointing to the position before the first row. - * - * @return Returns whether the cursor is before the first row. - */ - virtual int IsStarted(bool &result) const = 0; - - /** - * @brief Obtains whether the cursor is pointing to the first row. - * - * @return Returns whether the cursor is pointing at the first entry. - */ - virtual int IsAtFirstRow(bool &result) const = 0; - - /** - * @brief Obtains whether the cursor is pointing to the last row. - * - * @return Returns whether the cursor is pointing at the last entry. - */ - virtual int IsAtLastRow(bool &result) = 0; - - /** - * @brief Obtains the value of the requested column as a byte array. - * - * @param columnIndex Indicates the zero-based index of the target column. - * @return Returns the value of the requested column as a byte array. - */ - virtual int GetBlob(int columnIndex, std::vector &blob) = 0; - - /** - * @brief Obtains the value of the requested column as a String. - * - * @param columnIndex Indicates the zero-based index of the target column. - * @return Returns the value of the requested column as a String. - */ - virtual int GetString(int columnIndex, std::string &value) = 0; - - /** - * @brief Obtains the value of the requested column as a int. - * - * @param columnIndex Indicates the zero-based index of the target column. - * @return Returns the value of the requested column as a int. - */ - virtual int GetInt(int columnIndex, int &value) = 0; - - /** - * @brief Obtains the value of the requested column as a long. - * - * @param columnIndex Indicates the zero-based index of the target column. - * @return Returns the value of the requested column as a long. - */ - virtual int GetLong(int columnIndex, int64_t &value) = 0; - - /** - * @brief Obtains the value of the requested column as a double. - * - * @param columnIndex Indicates the zero-based index of the target column. - * @return Returns the value of the requested column as a double. - */ - virtual int GetDouble(int columnIndex, double &value) = 0; - - /** - * @brief Obtains Whether the value of the requested column is null. - * - * @param columnIndex Indicates the zero-based index of the target column. - * @return Returns whether the column value is null. - */ - virtual int IsColumnNull(int columnIndex, bool &isNull) = 0; - - /** - * @brief Obtains Return true if the result set is closed. - * - * @return Returns true if the result set is closed. - */ - virtual bool IsClosed() const = 0; - - /** - * @brief Closes the result set, releasing all of its resources and making it completely invalid. + * @brief Gets the entire row of data for the current row from the result set. */ - virtual int Close() = 0; + RDB_API_EXPORT virtual int GetRow(RowEntity &rowEntity) = 0; }; } // namespace NativeRdb diff --git a/relational_store/interfaces/inner_api/rdb/include/value_object.h b/relational_store/interfaces/inner_api/rdb/include/value_object.h index ce6e83d4f9d4b7d7792ab5a7ee3404d71f9ec13e..b2ecea7266b60d4a595874b63f582b7cb783c201 100644 --- a/relational_store/interfaces/inner_api/rdb/include/value_object.h +++ b/relational_store/interfaces/inner_api/rdb/include/value_object.h @@ -86,7 +86,7 @@ public: * * @param val Indicates an int input parameter. */ - RDB_API_EXPORT explicit ValueObject(int val); + RDB_API_EXPORT ValueObject(int val); /** * @brief Constructor. @@ -95,7 +95,7 @@ public: * * @param val Indicates an int64_t input parameter. */ - RDB_API_EXPORT explicit ValueObject(int64_t val); + RDB_API_EXPORT ValueObject(int64_t val); /** * @brief Constructor. @@ -104,7 +104,7 @@ public: * * @param val Indicates an double input parameter. */ - RDB_API_EXPORT explicit ValueObject(double val); + RDB_API_EXPORT ValueObject(double val); /** * @brief Constructor. @@ -113,7 +113,7 @@ public: * * @param val Indicates an bool input parameter. */ - RDB_API_EXPORT explicit ValueObject(bool val); + RDB_API_EXPORT ValueObject(bool val); /** * @brief Constructor. @@ -122,7 +122,16 @@ public: * * @param val Indicates an string input parameter. */ - RDB_API_EXPORT explicit ValueObject(const std::string &val); + RDB_API_EXPORT ValueObject(const std::string &val); + + /** + * @brief Constructor. + * + * This constructor is used to convert the const chars input parameter to a value of type ValueObject. + * + * @param val Indicates a const chars input parameter. + */ + RDB_API_EXPORT ValueObject(const char *val); /** * @brief Constructor. @@ -131,7 +140,7 @@ public: * * @param val Indicates an vector input parameter. */ - RDB_API_EXPORT explicit ValueObject(const std::vector &blob); + RDB_API_EXPORT ValueObject(const std::vector &blob); /** * @brief Move assignment operator overloaded function. diff --git a/relational_store/interfaces/inner_api/rdb/mock/include/abs_result_set.h b/relational_store/interfaces/inner_api/rdb/mock/include/abs_result_set.h new file mode 100644 index 0000000000000000000000000000000000000000..5bb0b3e2cbdb0ee67ca8e0959b65110f7091c805 --- /dev/null +++ b/relational_store/interfaces/inner_api/rdb/mock/include/abs_result_set.h @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NATIVE_RDB_ABS_RESULT_SET_H +#define NATIVE_RDB_ABS_RESULT_SET_H + +#include +#include +#include +#include + +#include "result_set.h" +#include "value_object.h" + +namespace OHOS { +namespace NativeRdb { +class AbsResultSet : public ResultSet { +public: + AbsResultSet(); + virtual ~AbsResultSet(); + int GetRowCount(int &count) override; + int GetAllColumnNames(std::vector &columnNames) override; + int GetBlob(int columnIndex, std::vector &blob) override; + int GetString(int columnIndex, std::string &value) override; + int GetInt(int columnIndex, int &value) override; + int GetLong(int columnIndex, int64_t &value) override; + int GetDouble(int columnIndex, double &value) override; + int IsColumnNull(int columnIndex, bool &isNull) override; + int GetRow(RowEntity &rowEntity) override; + int GoToRow(int position) override; + int GetColumnType(int columnIndex, ColumnType &columnType) override; + int GetRowIndex(int &position) const override; + int GoTo(int offset) override; + int GoToFirstRow() override; + int GoToLastRow() override; + int GoToNextRow() override; + int GoToPreviousRow() override; + int IsAtFirstRow(bool &result) const override; + int IsAtLastRow(bool &result) override; + int IsStarted(bool &result) const override; + int IsEnded(bool &result) override; + int GetColumnCount(int &count) override; + int GetColumnIndex(const std::string &columnName, int &columnIndex) override; + int GetColumnName(int columnIndex, std::string &columnName) override; + bool IsClosed() const override; + int Close() override; + +protected: + std::map columnMap_; + int columnCount_ = -1; + // The default position of the result set + static const int INIT_POS = -1; + /* + * The value can be in the range [-1 ~ n], where -1 represents the start flag position and N represents the data end + * flag position, and [0, n-1] represents the real data index. + */ + int rowPos_; + + // Indicates whether the result set is closed + bool isClosed; +}; +} // namespace NativeRdb +} // namespace OHOS + +#endif \ No newline at end of file diff --git a/relational_store/interfaces/inner_api/rdb/mock/include/result_set.h b/relational_store/interfaces/inner_api/rdb/mock/include/result_set.h new file mode 100644 index 0000000000000000000000000000000000000000..824bab2d35508d03107a321c34b469febc7ff925 --- /dev/null +++ b/relational_store/interfaces/inner_api/rdb/mock/include/result_set.h @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NATIVE_RDB_RESULT_SET_H +#define NATIVE_RDB_RESULT_SET_H + +#include +#include +#include +#include "remote_result_set.h" +#include "value_object.h" + +namespace OHOS { +namespace NativeRdb { +struct RowEntity { +public: + void Put(const std::string &name, const ValueObject &value); + ValueObject Get(const std::string &name) const; + ValueObject Get(const int index) const; + void Get(std::map &outValues) const; + void Clear(); +private: + std::map values_; + std::vector indexs_; +}; + +class ResultSet : public RemoteResultSet { +public: + virtual ~ResultSet() {} + virtual int GetRow(RowEntity &rowEntity) = 0; +}; + +} // namespace NativeRdb +} // namespace OHOS +#endif diff --git a/relational_store/interfaces/inner_api/rdb/mock/include/value_object.h b/relational_store/interfaces/inner_api/rdb/mock/include/value_object.h index 099f81b99567413a8f2bcbdf7538387872f64099..1733b2fe4d9aeb4b19393eb2708dcf103fc486c6 100644 --- a/relational_store/interfaces/inner_api/rdb/mock/include/value_object.h +++ b/relational_store/interfaces/inner_api/rdb/mock/include/value_object.h @@ -38,12 +38,13 @@ public: ValueObject(Type valueObject) noexcept; ValueObject(ValueObject &&valueObject) noexcept; ValueObject(const ValueObject &valueObject); - explicit ValueObject(int val); - explicit ValueObject(int64_t val); - explicit ValueObject(double val); - explicit ValueObject(bool val); - explicit ValueObject(const std::string &val); - explicit ValueObject(const std::vector &blob); + ValueObject(int val); + ValueObject(int64_t val); + ValueObject(double val); + ValueObject(bool val); + ValueObject(const std::string &val); + ValueObject(const char *val); + ValueObject(const std::vector &blob); ValueObject &operator=(ValueObject &&valueObject) noexcept; ValueObject &operator=(const ValueObject &valueObject); diff --git a/relational_store/test/js/rdb/BUILD.gn b/relational_store/test/js/rdb/BUILD.gn index 0d59022302a62e7687bc0af0ef0d2e8f677c02e9..a3b5ca97e1191c26838a311c263eca579d4bdea1 100644 --- a/relational_store/test/js/rdb/BUILD.gn +++ b/relational_store/test/js/rdb/BUILD.gn @@ -20,4 +20,11 @@ group("unittest") { deps += [ "unittest/src:unittest" ] } + +group("performancetest") { + testonly = true + deps = [] + + deps += [ "performance/src:RdbPerfJsTest" ] +} ############################################################################### diff --git a/relational_store/test/js/rdb/performance/config.json b/relational_store/test/js/rdb/performance/config.json new file mode 100644 index 0000000000000000000000000000000000000000..e1b1bc28e5922882acd683bf6b3b0a439786fbcb --- /dev/null +++ b/relational_store/test/js/rdb/performance/config.json @@ -0,0 +1,62 @@ +{ + "app": { + "bundleName": "com.example.myapplication", + "vendor": "example", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 4, + "target": 5 + } + }, + "deviceConfig": {}, + "module": { + "package": "com.example.myapplication", + "name": ".MyApplication", + "deviceType": [ + "tablet", + "default", + "phone" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "entry", + "moduleType": "entry" + }, + "abilities": [ + { + "visible": true, + "skills": [ + { + "entities": [ + "entity.system.home" + ], + "actions": [ + "action.system.home" + ] + } + ], + "name": "com.example.myapplication.MainAbility", + "icon": "$media:icon", + "description": "$string:mainability_description", + "label": "MyApplication", + "type": "page", + "launchType": "standard" + } + ], + "js": [ + { + "pages": [ + "pages/index/index" + ], + "name": "default", + "window": { + "designWidth": 720, + "autoDesignWidth": false + } + } + ] + } +} diff --git a/relational_store/test/js/rdb/performance/openharmony_sx.p7b b/relational_store/test/js/rdb/performance/openharmony_sx.p7b new file mode 100644 index 0000000000000000000000000000000000000000..9be1e98fa4c0c28ca997ed660112fa16b194f0f5 Binary files /dev/null and b/relational_store/test/js/rdb/performance/openharmony_sx.p7b differ diff --git a/relational_store/test/js/rdb/performance/src/BUILD.gn b/relational_store/test/js/rdb/performance/src/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..e7b7cdd254742bd5338519b094992fc6c355f6f2 --- /dev/null +++ b/relational_store/test/js/rdb/performance/src/BUILD.gn @@ -0,0 +1,24 @@ +# Copyright (C) 2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") + +module_output_path = "relational_store/performance" + +ohos_js_unittest("RdbPerfJsTest") { + module_out_path = module_output_path + + hap_profile = "../config.json" + + certificate_profile = "../openharmony_sx.p7b" +} diff --git a/relational_store/test/js/rdb/performance/src/PredicatestPerf.js b/relational_store/test/js/rdb/performance/src/PredicatestPerf.js new file mode 100644 index 0000000000000000000000000000000000000000..30057c9904b0ec791e650f158dff0746b1df1f60 --- /dev/null +++ b/relational_store/test/js/rdb/performance/src/PredicatestPerf.js @@ -0,0 +1,506 @@ +/* + * Copyright (C) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, Assert} from 'deccjsunit/index'; +import dataRdb from '@ohos.data.rdb'; +import deviceInfo from '@ohos.deviceInfo'; + +const TAG = "[RDB_PREDICATES_PERF]"; + +const BASE_COUNT = 2000; // loop times +const BASE_COUNT_FIRST = 200; +const BASE_COUNT_SECOND = 10; +const BASE_LINE_TABLE = 500; // callback tablet base line +const BASE_LINE_PHONE = 1000; // callback phone base line +const BASE_LINE = (deviceInfo.deviceType == "tablet") ? BASE_LINE_TABLE : BASE_LINE_PHONE; + +describe('predicatesPerf', function () { + beforeAll(async function () { + console.info(TAG + 'beforeAll'); + }) + beforeEach(async function () { + console.info(TAG + 'beforeEach'); + }) + afterEach(async function () { + console.info(TAG + 'afterEach'); + }) + afterAll(async function () { + console.info(TAG + 'afterAll'); + }) + + console.log(TAG + "*************Unit Test Begin*************"); + + it('SUB_DDM_PERF_RDB_Predicates_inDevices_001', 0, async function (done) { + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT_FIRST; i++) { + let predicates = new dataRdb.RdbPredicates("test"); + for (let j = 0; j < BASE_COUNT_SECOND; j++) { + predicates.inDevices(['123']); + } + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the Predicates_inDevices average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_Predicates_inAllDevices_001', 0, async function (done) { + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT_FIRST; i++) { + let predicates = new dataRdb.RdbPredicates("test"); + for (let j = 0; j < BASE_COUNT_SECOND; j++) { + predicates.inAllDevices(); + } + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the Predicates_inAllDevices average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_Predicates_equalTo_001', 0, async function (done) { + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT_FIRST; i++) { + let predicates = new dataRdb.RdbPredicates("test"); + for (let j = 0; j < BASE_COUNT_SECOND; j++) { + predicates.equalTo("name", "lisi"); + } + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the Predicates_equalTo average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_Predicates_notEqualTo_001', 0, async function (done) { + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT_FIRST; i++) { + let predicates = new dataRdb.RdbPredicates("test"); + for (let j = 0; j < BASE_COUNT_SECOND; j++) { + predicates.notEqualTo("name", "lisi"); + } + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the Predicates_notEqualTo average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_Predicates_beginWrap_001', 0, async function (done) { + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT_FIRST; i++) { + let predicates = new dataRdb.RdbPredicates("test"); + for (let j = 0; j < BASE_COUNT_SECOND; j++) { + predicates.beginWrap(); + } + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the Predicates_beginWrap average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_Predicates_endWrap_001', 0, async function (done) { + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT_FIRST; i++) { + let predicates = new dataRdb.RdbPredicates("test"); + for (let j = 0; j < BASE_COUNT_SECOND; j++) { + predicates.equalTo("name", "lisi"); + predicates.endWrap(); + } + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the Predicates_endWrap average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_Predicates_or_001', 0, async function (done) { + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT_FIRST; i++) { + let predicates = new dataRdb.RdbPredicates("test"); + for (let j = 0; j < BASE_COUNT_SECOND; j++) { + predicates.equalTo("name", "lisi"); + predicates.or(); + predicates.equalTo("age", 18); + } + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the Predicates_or average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_Predicates_and_001', 1, async function (done) { + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT_FIRST; i++) { + let predicates = new dataRdb.RdbPredicates("test"); + for (let j = 0; j < BASE_COUNT_SECOND; j++) { + predicates.equalTo("name", "lisi"); + predicates.and(); + predicates.equalTo("name", "zs"); + } + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the Predicates_and average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_Predicates_contains_001', 0, async function (done) { + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT_FIRST; i++) { + let predicates = new dataRdb.RdbPredicates("test"); + for (let j = 0; j < BASE_COUNT_SECOND; j++) { + predicates.contains("name", "lisi"); + } + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the Predicates_contains average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_Predicates_beginsWith_001', 0, async function (done) { + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT_FIRST; i++) { + let predicates = new dataRdb.RdbPredicates("test"); + for (let j = 0; j < BASE_COUNT_SECOND; j++) { + predicates.beginsWith("name", "lisi"); + } + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the Predicates_beginsWith average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_Predicates_endWith_001', 0, async function (done) { + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT_FIRST; i++) { + let predicates = new dataRdb.RdbPredicates("test"); + for (let j = 0; j < BASE_COUNT_SECOND; j++) { + predicates.endsWith("name", "lisi"); + } + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the Predicates_endWith average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_Predicates_isNull_001', 0, async function (done) { + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT_FIRST; i++) { + let predicates = new dataRdb.RdbPredicates("test"); + for (let j = 0; j < BASE_COUNT_SECOND; j++) { + predicates.isNull("name"); + } + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the Predicates_isNull average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_Predicates_isNotNull_001', 0, async function (done) { + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT_FIRST; i++) { + let predicates = new dataRdb.RdbPredicates("test"); + for (let j = 0; j < BASE_COUNT_SECOND; j++) { + predicates.isNotNull("name"); + } + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the Predicates_isNotNull average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_Predicates_like_001', 0, async function (done) { + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT_FIRST; i++) { + let predicates = new dataRdb.RdbPredicates("test"); + for (let j = 0; j < BASE_COUNT_SECOND; j++) { + predicates.like("name", "li"); + } + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the Predicates_like average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_Predicates_glob_001', 0, async function (done) { + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT_FIRST; i++) { + let predicates = new dataRdb.RdbPredicates("test"); + for (let j = 0; j < BASE_COUNT_SECOND; j++) { + predicates.glob("name", "li"); + } + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the Predicates_glob average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_Predicates_between_001', 0, async function (done) { + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT_FIRST; i++) { + let predicates = new dataRdb.RdbPredicates("test"); + for (let j = 0; j < BASE_COUNT_SECOND; j++) { + predicates.between("age", 1, 100); + } + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the Predicates_between average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_Predicates_notBetween_001', 0, async function (done) { + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT_FIRST; i++) { + let predicates = new dataRdb.RdbPredicates("test"); + for (let j = 0; j < BASE_COUNT_SECOND; j++) { + predicates.notBetween("age", 1, 100); + } + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the Predicates_notBetween average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_Predicates_greaterThan_001', 0, async function (done) { + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT_FIRST; i++) { + let predicates = new dataRdb.RdbPredicates("test"); + for (let j = 0; j < BASE_COUNT_SECOND; j++) { + predicates.greaterThan("age", 1); + } + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the Predicates_greaterThan average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_Predicates_lessThan_001', 0, async function (done) { + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT_FIRST; i++) { + let predicates = new dataRdb.RdbPredicates("test"); + for (let j = 0; j < BASE_COUNT_SECOND; j++) { + predicates.lessThan("age", 1000); + } + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the Predicates_lessThan average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_Predicates_greaterThanOrEqualTo_001', 0, async function (done) { + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT_FIRST; i++) { + let predicates = new dataRdb.RdbPredicates("test"); + for (let j = 0; j < BASE_COUNT_SECOND; j++) { + predicates.greaterThanOrEqualTo("age", 1000); + } + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the Predicates_greaterThanOrEqualTo average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_Predicates_lessThanOrEqualTo_001', 0, async function (done) { + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT_FIRST; i++) { + let predicates = new dataRdb.RdbPredicates("test"); + for (let j = 0; j < BASE_COUNT_SECOND; j++) { + predicates.lessThanOrEqualTo("age", 1000); + } + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the Predicates_lessThanOrEqualTo average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_Predicates_orderByAsc_001', 0, async function (done) { + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT_FIRST; i++) { + let predicates = new dataRdb.RdbPredicates("test"); + for (let j = 0; j < BASE_COUNT_SECOND; j++) { + predicates.orderByAsc("name"); + } + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the Predicates_orderByAsc average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_Predicates_orderByDesc_001', 0, async function (done) { + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT_FIRST; i++) { + let predicates = new dataRdb.RdbPredicates("test"); + for (let j = 0; j < BASE_COUNT_SECOND; j++) { + predicates.orderByDesc("name"); + } + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the Predicates_orderByDesc average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_Predicates_distinct_001', 0, async function (done) { + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT_FIRST; i++) { + let predicates = new dataRdb.RdbPredicates("test"); + for (let j = 0; j < BASE_COUNT_SECOND; j++) { + predicates.distinct(); + } + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the Predicates_distinct average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_Predicates_limitAs_001', 0, async function (done) { + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT; i++) { + let predicates = new dataRdb.RdbPredicates("test"); + predicates.limitAs(6); + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the Predicates_limitAs average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_Predicates_offsetAs_001', 0, async function (done) { + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT; i++) { + let predicates = new dataRdb.RdbPredicates("test"); + predicates.offsetAs(6); + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the Predicates_offsetAs average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_Predicates_groupBy_001', 0, async function (done) { + let nameArr = new Array(); + nameArr.push("id"); + nameArr.push("name"); + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT_FIRST; i++) { + let predicates = new dataRdb.RdbPredicates("test"); + for (let j = 0; j < BASE_COUNT_SECOND; j++) { + predicates.groupBy(nameArr); + } + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the Predicates_groupBy average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_Predicates_indexedBy_001', 0, async function (done) { + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT_FIRST; i++) { + let predicates = new dataRdb.RdbPredicates("test"); + for (let j = 0; j < BASE_COUNT_SECOND; j++) { + predicates.indexedBy("name"); + } + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the Predicates_indexedBy average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_Predicates_in_001', 0, async function (done) { + let nameArr = new Array(); + nameArr.push("id"); + nameArr.push("name"); + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT_FIRST; i++) { + let predicates = new dataRdb.RdbPredicates("test"); + for (let j = 0; j < BASE_COUNT_SECOND; j++) { + predicates.in("name", nameArr); + } + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the Predicates_in average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_Predicates_notIn(_001', 0, async function (done) { + let nameArr = new Array(); + nameArr.push("zhangsan"); + nameArr.push("lisi"); + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT_FIRST; i++) { + let predicates = new dataRdb.RdbPredicates("test"); + for (let j = 0; j < BASE_COUNT_SECOND; j++) { + predicates.notIn("name", nameArr); + } + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the Predicates_notIn average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + console.info(TAG + "*************Unit Test End*************") +}) \ No newline at end of file diff --git a/relational_store/test/js/rdb/performance/src/RdbHelperCallbackPerf.js b/relational_store/test/js/rdb/performance/src/RdbHelperCallbackPerf.js new file mode 100644 index 0000000000000000000000000000000000000000..14d02c2acc812e52a02a4f6ea79148096ed5c447 --- /dev/null +++ b/relational_store/test/js/rdb/performance/src/RdbHelperCallbackPerf.js @@ -0,0 +1,93 @@ +/* + * Copyright (C) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, Assert } from 'deccjsunit/index'; +import dataRdb from '@ohos.data.rdb'; +import featureAbility from '@ohos.ability.featureAbility'; +import deviceInfo from '@ohos.deviceInfo'; + +const TAG = "[RDBHELPER_CALLBACK]"; + +const DB_NAME = "rdbCallback.db"; +const STORE_CONFIG = { + name: DB_NAME, +} +let context = featureAbility.getContext(); +var rdbStore = undefined; +const BASE_COUNT = 2000; // loop times +const BASE_LINE_TABLE = 2500; // callback tablet base line +const BASE_LINE_PHONE = 3000; // callback phone base line +const BASE_LINE = (deviceInfo.deviceType == "tablet") ? BASE_LINE_TABLE : BASE_LINE_PHONE; + +describe('rdbHelperCallbackPerf', function () { + beforeAll(async function () { + console.info(TAG + 'beforeAll'); + }) + beforeEach(async function () { + console.info(TAG + 'beforeEach'); + }) + afterEach(async function () { + console.info(TAG + 'afterEach'); + }) + afterAll(async function () { + console.info(TAG + 'afterAll'); + rdbStore = null + await dataRdb.deleteRdbStore(context, DB_NAME); + }) + + console.log(TAG + "*************Unit Test Begin*************"); + + it('SUB_DDM_PERF_RDB_getRdbStore_Callback_001', 0, async function (done) { + let averageTime = 0; + + async function getRdbStoreCallBackPerf(index) { + dataRdb.getRdbStore(context, STORE_CONFIG, 1, function (err, rdbStore) { + if (index < BASE_COUNT) { + getRdbStoreCallBackPerf(index + 1); + } else { + let endTime = new Date().getTime(); + averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the getRdbStore_Callback average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + } + }) + } + + let startTime = new Date().getTime(); + await getRdbStoreCallBackPerf(0); + }) + + it('SUB_DDM_PERF_RDB_deleteRdbStore_Callback_001', 0, async function (done) { + let averageTime = 0; + + async function deleteRdbStoreCallBackPerf(index) { + dataRdb.deleteRdbStore(context, DB_NAME, function (err, data) { + if (index < BASE_COUNT) { + deleteRdbStoreCallBackPerf(index + 1); + } else { + let endTime = new Date().getTime(); + averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the deleteRdbStore_Callback average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + } + }) + } + + let startTime = new Date().getTime(); + await deleteRdbStoreCallBackPerf(0); + }) +}) \ No newline at end of file diff --git a/relational_store/test/js/rdb/performance/src/RdbHelperPromisePerf.js b/relational_store/test/js/rdb/performance/src/RdbHelperPromisePerf.js new file mode 100644 index 0000000000000000000000000000000000000000..330ffcd228d5341e45a11492f195bcaa50585933 --- /dev/null +++ b/relational_store/test/js/rdb/performance/src/RdbHelperPromisePerf.js @@ -0,0 +1,78 @@ +/* + * Copyright (C) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, Assert} from 'deccjsunit/index'; +import dataRdb from '@ohos.data.rdb'; +import featureAbility from '@ohos.ability.featureAbility'; +import deviceInfo from '@ohos.deviceInfo'; + +const TAG = "[RDBHELPER_PROMISE]"; + +const DB_NAME = "rdbPromise.db"; +const STORE_CONFIG = { + name: DB_NAME, +} +let context = featureAbility.getContext(); +var rdbStore = undefined; +const BASE_COUNT = 2000; // loop times +const BASE_LINE_TABLE = 2500; // callback tablet base line +const BASE_LINE_PHONE = 3000; // callback phone base line +const BASE_LINE = (deviceInfo.deviceType == "tablet") ? BASE_LINE_TABLE : BASE_LINE_PHONE; + +describe('rdbHelperPromisePerf', function () { + beforeAll(async function () { + console.info(TAG + 'beforeAll'); + }) + beforeEach(async function () { + console.info(TAG + 'beforeEach'); + }) + afterEach(async function () { + console.info(TAG + 'afterEach'); + }) + afterAll(async function () { + console.info(TAG + 'afterAll'); + rdbStore = null; + await dataRdb.deleteRdbStore(context, DB_NAME); + }) + + console.log(TAG + "*************Unit Test Begin*************"); + + it('SUB_DDM_PERF_RDB_getRdbStore_Promise_001', 0, async function (done) { + let averageTime = 0; + let startTime = new Date().getTime(); + for (var i = 0; i < BASE_COUNT; i++) { + await dataRdb.getRdbStore(context, STORE_CONFIG, 1); + } + let endTime = new Date().getTime(); + averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the getRdbStore_Promise average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_deleteRdbStore_Promise_001', 0, async function (done) { + let averageTime = 0; + let startTime = new Date().getTime(); + for (var i = 0; i < BASE_COUNT; i++) { + await dataRdb.deleteRdbStore(context, DB_NAME, 1); + } + let endTime = new Date().getTime(); + averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the deleteRdbStore_Promise average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + console.info(TAG + "*************Unit Test End*************") + }) +}) \ No newline at end of file diff --git a/relational_store/test/js/rdb/performance/src/RdbStoreCallbackPerf.js b/relational_store/test/js/rdb/performance/src/RdbStoreCallbackPerf.js new file mode 100644 index 0000000000000000000000000000000000000000..52b39810f54d96507b831d210a18d45abcf77b80 --- /dev/null +++ b/relational_store/test/js/rdb/performance/src/RdbStoreCallbackPerf.js @@ -0,0 +1,125 @@ +/* + * Copyright (C) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, Assert} from 'deccjsunit/index'; +import dataRdb from '@ohos.data.rdb'; +import featureAbility from '@ohos.ability.featureAbility'; +import deviceInfo from '@ohos.deviceInfo'; + +const TAG = "[RDBSTORE_CALLBACK]"; +const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (id INTEGER PRIMARY KEY AUTOINCREMENT, " + + "name TEXT, age INTEGER, salary REAL, blobType BLOB)"; + +const DB_NAME = "rdbStoreCallback.db"; +const STORE_CONFIG = { + name: DB_NAME, +} +let context = featureAbility.getContext(); +var rdbStore = undefined; +const BASE_COUNT = 1000; // loop times +const INSERT_BASE_COUNT = 300; +const BASE_LINE_TABLE = 1800; // callback tablet base line +const BASE_LINE_PHONE = 7000; // callback phone base line +const BASE_LINE = (deviceInfo.deviceType == "tablet") ? BASE_LINE_TABLE : BASE_LINE_PHONE; + +describe('rdbStoreCallbackPerf', function () { + beforeAll(async function () { + console.info(TAG + 'beforeAll'); + rdbStore = await dataRdb.getRdbStore(context, STORE_CONFIG, 1); + }) + beforeEach(async function () { + console.info(TAG + 'beforeEach'); + await rdbStore.executeSql(CREATE_TABLE_TEST, null); + await prepareTestData(); + }) + afterEach(async function () { + console.info(TAG + 'afterEach'); + await rdbStore.executeSql("drop table test"); + }) + afterAll(async function () { + console.info(TAG + 'afterAll'); + rdbStore = null; + await dataRdb.deleteRdbStore(context, DB_NAME); + }) + + async function prepareTestData() { + console.info(TAG + "prepare for query performance test"); + var u8 = new Uint8Array([1, 2, 3]); + var valueBucket = { + "name": "zhangsan", + "age": 18, + "salary": 100.5, + "blobType": u8, + } + await rdbStore.insert("test", valueBucket); + } + + console.log(TAG + "*************Unit Test Begin*************"); + + it('SUB_DDM_PERF_RDB_query_Callback_001', 0, async function (done) { + let averageTime = 0; + let predicates = new dataRdb.RdbPredicates("test"); + predicates.equalTo("age", 10); + + async function queryCallbackPerf(index) { + rdbStore.query(predicates, [], function (err, resultSet) { + resultSet.close(); + if (index < BASE_COUNT) { + queryCallbackPerf(index + 1); + } else { + let endTime = new Date().getTime(); + averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the query_Callback average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + console.info(TAG + "*************Unit Test End*************"); + done(); + } + }) + } + + let startTime = new Date().getTime(); + queryCallbackPerf(0); + }) + + it('SUB_DDM_PERF_RDB_insert_Callback_001', 0, async function (done) { + let averageTime = 0; + var uBlob = new Uint8Array([1, 2, 3]); + var insertValueBucket = { + "name": "zhangsan", + "age": 18, + "salary": 100.5, + "blobType": uBlob, + } + let predicates = new dataRdb.RdbPredicates("test"); + predicates.equalTo("age", 10); + + async function InsertCallbackPerf(index) { + rdbStore.insert("test", insertValueBucket, function (err, data) { + if (index < INSERT_BASE_COUNT) { + InsertCallbackPerf(index + 1); + } else { + let endTime = new Date().getTime(); + averageTime = ((endTime - startTime) * 1000) / INSERT_BASE_COUNT; + console.info(TAG + " the insert_Callback average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + } + }) + } + + let startTime = new Date().getTime(); + InsertCallbackPerf(0); + }) +}) \ No newline at end of file diff --git a/relational_store/test/js/rdb/performance/src/RdbStoreOthersCallbackPerf.js b/relational_store/test/js/rdb/performance/src/RdbStoreOthersCallbackPerf.js new file mode 100644 index 0000000000000000000000000000000000000000..03ced63506a094061d2010d1d6e20439fc363a85 --- /dev/null +++ b/relational_store/test/js/rdb/performance/src/RdbStoreOthersCallbackPerf.js @@ -0,0 +1,165 @@ +/* + * Copyright (C) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, Assert} from 'deccjsunit/index'; +import dataRdb from '@ohos.data.rdb'; +import featureAbility from '@ohos.ability.featureAbility'; +import deviceInfo from '@ohos.deviceInfo'; + +const TAG = "[RDBSTORE_OTHERS_CALLBACK]"; +const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (id INTEGER PRIMARY KEY AUTOINCREMENT, " + + "name TEXT, age INTEGER, salary REAL, blobType BLOB)"; + +const DB_NAME = "rdbUpdateCallback.db"; +const STORE_CONFIG = { + name: DB_NAME, +} +let context = featureAbility.getContext(); +var rdbStore = undefined; +const BASE_COUNT = 1000; // loop times +const SPECIAL_BASE_COUNT = 300; +const BASE_LINE_TABLE = 1800; // callback tablet base line +const BASE_LINE_PHONE = 15000; // callback phone base line +const BASE_LINE = (deviceInfo.deviceType == "tablet") ? BASE_LINE_TABLE : BASE_LINE_PHONE; + +describe('rdbStoreOthersCallbackPerf', function () { + beforeAll(async function () { + console.info(TAG + 'beforeAll'); + rdbStore = await dataRdb.getRdbStore(context, STORE_CONFIG, 1); + }) + beforeEach(async function () { + console.info(TAG + 'beforeEach'); + await rdbStore.executeSql(CREATE_TABLE_TEST, null); + await prepareTestData(); + }) + afterEach(async function () { + console.info(TAG + 'afterEach'); + await rdbStore.executeSql("drop table test"); + }) + afterAll(async function () { + console.info(TAG + 'afterAll'); + rdbStore = null; + await dataRdb.deleteRdbStore(context, DB_NAME); + }) + + async function prepareTestData() { + console.info(TAG + "prepare for query performance test"); + var u8 = new Uint8Array([1, 2, 3]); + var valueBucket = { + "name": "zhangsan", + "age": 18, + "salary": 100.5, + "blobType": u8, + } + await rdbStore.insert("test", valueBucket); + } + + console.log(TAG + "*************Unit Test Begin*************"); + + it('SUB_DDM_PERF_RDB_update_Callback_001', 0, async function (done) { + let averageTime = 0; + var uBlob = new Uint8Array([1, 2, 3]) + var updateVB = { + "name": "zhangsan", + "age": 18, + "salary": 100.5, + "blobType": uBlob, + } + let predicates = new dataRdb.RdbPredicates("test"); + + async function updateCallbackPerf(index) { + predicates.equalTo("age", 18); + rdbStore.update(updateVB, predicates, function (err, data) { + if (index < SPECIAL_BASE_COUNT) { + updateCallbackPerf(index + 1); + } else { + let endTime = new Date().getTime(); + averageTime = ((endTime - startTime) * 1000) / SPECIAL_BASE_COUNT; + console.info(TAG + " the update_Callback average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + } + }) + } + + let startTime = new Date().getTime(); + updateCallbackPerf(0); + }) + + it('SUB_DDM_PERF_RDB_delete_Callback_001', 0, async function (done) { + let averageTime = 0; + let predicates = new dataRdb.RdbPredicates("test"); + predicates.equalTo("age", 0); + + async function deleteCallbackPerf(index) { + rdbStore.delete(predicates, function (err, data) { + if (index < BASE_COUNT) { + deleteCallbackPerf(index + 1) + } else { + let endTime = new Date().getTime(); + averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the delete_Callback average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + } + }) + } + + let startTime = new Date().getTime(); + deleteCallbackPerf(0); + }) + + it('SUB_DDM_PERF_RDB_querySql_Callback_001', 0, async function (done) { + let averageTime = 0; + + async function querySqlCallbackPerf(index) { + rdbStore.querySql("select * from test", [], function (err, data) { + if (index < BASE_COUNT) { + querySqlCallbackPerf(index + 1); + } else { + let endTime = new Date().getTime(); + averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the querySql_Callback average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + } + }) + } + + let startTime = new Date().getTime(); + querySqlCallbackPerf(0); + }) + + it('SUB_DDM_PERF_RDB_executeSql_Callback_001', 0, async function (done) { + let averageTime = 0; + + async function executeSqlCallbackPerf(index) { + rdbStore.executeSql("insert into test (name, age) values ('tom', 22)", function (err, data) { + if (index < SPECIAL_BASE_COUNT) { + executeSqlCallbackPerf(index + 1); + } else { + let endTime = new Date().getTime(); + averageTime = ((endTime - startTime) * 1000) / SPECIAL_BASE_COUNT; + console.info(TAG + " the executeSql_Callback average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + } + }) + } + + let startTime = new Date().getTime(); + executeSqlCallbackPerf(0); + }) +}) diff --git a/relational_store/test/js/rdb/performance/src/RdbStorePromisePerf.js b/relational_store/test/js/rdb/performance/src/RdbStorePromisePerf.js new file mode 100644 index 0000000000000000000000000000000000000000..0034a9a870db09cb7b241d67200afa58da2aa828 --- /dev/null +++ b/relational_store/test/js/rdb/performance/src/RdbStorePromisePerf.js @@ -0,0 +1,86 @@ +/* + * Copyright (C) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, Assert} from 'deccjsunit/index'; +import dataRdb from '@ohos.data.rdb'; +import featureAbility from '@ohos.ability.featureAbility'; +import deviceInfo from '@ohos.deviceInfo'; + +const TAG = "[RDBSTORE_PROMISE]"; +const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (id INTEGER PRIMARY KEY AUTOINCREMENT, " + + "name TEXT, age INTEGER, salary REAL, blobType BLOB)"; + +const DB_NAME = "rdbStorePromise.db"; +const STORE_CONFIG = { + name: DB_NAME, +} +let context = featureAbility.getContext(); +var rdbStore = undefined; +const BASE_COUNT = 1000; // loop times +const BASE_LINE_TABLE = 1800; // callback tablet base line +const BASE_LINE_PHONE = 3000; // callback phone base line +const BASE_LINE = (deviceInfo.deviceType == "tablet") ? BASE_LINE_TABLE : BASE_LINE_PHONE; + +describe('rdbStorePromisePerf', function () { + beforeAll(async function () { + console.info(TAG + 'beforeAll'); + rdbStore = await dataRdb.getRdbStore(context, STORE_CONFIG, 1); + }) + beforeEach(async function () { + console.info(TAG + 'beforeEach'); + await rdbStore.executeSql(CREATE_TABLE_TEST, null); + await prepareTestData(); + }) + afterEach(async function () { + console.info(TAG + 'afterEach'); + await rdbStore.executeSql("drop table test"); + }) + afterAll(async function () { + console.info(TAG + 'afterAll'); + rdbStore = null; + await dataRdb.deleteRdbStore(context, DB_NAME); + }) + + async function prepareTestData() { + console.info(TAG + "prepare for query performance test") + var u8 = new Uint8Array([1, 2, 3]) + var valueBucket = { + "name": "zhangsan", + "age": 18, + "salary": 100.5, + "blobType": u8, + } + await dataRdb.insert("test", valueBucket); + } + + console.log(TAG + "*************Unit Test Begin*************"); + + it('SUB_DDM_PERF_RDB_query_Promise_001', 0, async function (done) { + let averageTime = 0; + let predicates = new dataRdb.RdbPredicates("test"); + predicates.equalTo("age", 10); + let startTime = new Date().getTime(); + for (var i = 0; i < BASE_COUNT; i++) { + let resultSet = await rdbStore.query(predicates, []); + resultSet.close(); + } + let endTime = new Date().getTime(); + averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the query_Promise average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + console.info(TAG + "*************Unit Test End*************"); + done(); + }) +}) diff --git a/relational_store/test/js/rdb/performance/src/RdbStoreSyncPerf.js b/relational_store/test/js/rdb/performance/src/RdbStoreSyncPerf.js new file mode 100644 index 0000000000000000000000000000000000000000..df364d0c0cdb4b9d14a4a50961550917e14c7d88 --- /dev/null +++ b/relational_store/test/js/rdb/performance/src/RdbStoreSyncPerf.js @@ -0,0 +1,98 @@ +/* + * Copyright (C) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, Assert} from 'deccjsunit/index'; +import dataRdb from '@ohos.data.rdb'; +import featureAbility from '@ohos.ability.featureAbility'; +import deviceInfo from '@ohos.deviceInfo'; + +const TAG = "[RDB_SYNC_PROMISE]"; +const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (id INTEGER PRIMARY KEY AUTOINCREMENT, " + + "name TEXT, age INTEGER, salary REAL, blobType BLOB)"; + +const DB_NAME = "rdbSync.db"; +const STORE_CONFIG = { + name: DB_NAME, +} +let context = featureAbility.getContext(); +var rdbStore = undefined; +const BASE_COUNT = 1000; // loop times +const BASE_LINE_TABLE = 2500; // callback tablet base line +const BASE_LINE_PHONE = 3000; // callback phone base line +const BASE_LINE = (deviceInfo.deviceType == "tablet") ? BASE_LINE_TABLE : BASE_LINE_PHONE; + + +describe('rdbStoreSyncPerf', function () { + beforeAll(async function () { + console.info(TAG + 'beforeAll'); + rdbStore = await dataRdb.getRdbStore(context, STORE_CONFIG, 1); + }) + beforeEach(async function () { + console.info(TAG + 'beforeEach'); + }) + afterEach(async function () { + console.info(TAG + 'afterEach'); + }) + afterAll(async function () { + console.info(TAG + 'afterAll'); + rdbStore = null + await dataRdb.deleteRdbStore(context, DB_NAME); + }) + + console.log(TAG + "*************Unit Test Begin*************"); + + it('SUB_DDM_PERF_RDB_version_001', 0, async function (done) { + let averageTime = 0; + let dbVersion = 1; + let startTime = new Date().getTime(); + for (var i = 0; i < BASE_COUNT; i++) { + dbVersion = rdbStore.version; + } + let endTime = new Date().getTime(); + averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the version average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_transaction_commit_001', 0, async function (done) { + let averageTime = 0; + let startTime = new Date().getTime(); + for (var i = 0; i < BASE_COUNT; i++) { + rdbStore.beginTransaction(); + rdbStore.commit(); + } + let endTime = new Date().getTime(); + averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the transaction_commit average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_transaction_rollback_001', 0, async function (done) { + let averageTime = 0; + let startTime = new Date().getTime(); + for (var i = 0; i < BASE_COUNT; i++) { + rdbStore.beginTransaction(); + rdbStore.rollBack(); + } + let endTime = new Date().getTime(); + averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the transaction_rollback average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + console.info(TAG + "*************Unit Test End*************"); + }) +}) diff --git a/relational_store/test/js/rdb/performance/src/ResultSetPerf.js b/relational_store/test/js/rdb/performance/src/ResultSetPerf.js new file mode 100644 index 0000000000000000000000000000000000000000..797d16047dae3972c7219cace8c6399c1bf289f0 --- /dev/null +++ b/relational_store/test/js/rdb/performance/src/ResultSetPerf.js @@ -0,0 +1,288 @@ +/* + * Copyright (C) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, Assert} from 'deccjsunit/index'; +import dataRdb from '@ohos.data.rdb'; +import featureAbility from '@ohos.ability.featureAbility'; +import deviceInfo from '@ohos.deviceInfo'; + +const TAG = "[RDB_RESULTSET_PERF]"; +const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (id INTEGER PRIMARY KEY AUTOINCREMENT, " + + "name TEXT, age INTEGER, salary REAL, blobType BLOB)"; + +const DB_NAME = "resultSetPerf.db"; +const STORE_CONFIG = { + name: DB_NAME, +} +let context = featureAbility.getContext(); +var rdbStore = undefined; +const BASE_COUNT = 2000; // loop times +const SPECIAL_BASE_COUNT = 12000; +const BASE_LINE_TABLE = 500; // callback tablet base line +const BASE_LINE_PHONE = 1000; // callback phone base line +const BASE_LINE = (deviceInfo.deviceType == "tablet") ? BASE_LINE_TABLE : BASE_LINE_PHONE; + +describe('resultSetPerf', function () { + beforeAll(async function () { + console.info(TAG + 'beforeAll'); + rdbStore = await dataRdb.getRdbStore(context, STORE_CONFIG, 1); + }) + beforeEach(async function () { + console.info(TAG + 'beforeEach'); + await rdbStore.executeSql(CREATE_TABLE_TEST, null); + await prepareTestData(); + }) + afterEach(async function () { + console.info(TAG + 'afterEach'); + await rdbStore.executeSql("drop table test"); + }) + afterAll(async function () { + console.info(TAG + 'afterAll'); + rdbStore = null; + await dataRdb.deleteRdbStore(context, DB_NAME); + }) + + async function prepareTestData() { + console.info(TAG + "prepare for query performance test"); + var valueBuckets = []; + var u8 = new Uint8Array([1, 2, 3]) + var valueBucket = { + "name": "zhangsan", + "age": 18, + "salary": 100.5, + "blobType": u8, + } + for (let i = 0; i < BASE_COUNT; i++) { + valueBucket.age += i; + valueBuckets.push(valueBucket); + } + await rdbStore.batchInsert("test", valueBuckets) + } + + console.log(TAG + "*************Unit Test Begin*************"); + + it('SUB_DDM_PERF_RDB_ResultSet_GetColumnIndex_001', 0, async function (done) { + let predicates = new dataRdb.RdbPredicates("test"); + let resultSet = await rdbStore.query(predicates); + resultSet.goToFirstRow(); + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_LINE; i++) { + resultSet.getColumnIndex("id"); + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the ResultSet_GetColumnIndex average time is: " + averageTime + " μs"); + resultSet.close(); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_ResultSet_GetColumnName_001', 0, async function (done) { + let predicates = new dataRdb.RdbPredicates("test"); + let resultSet = await rdbStore.query(predicates); + resultSet.goToFirstRow(); + let startTime = new Date().getTime() + for (let i = 0; i < BASE_COUNT; i++) { + resultSet.getColumnName(0); + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the ResultSet_GetColumnName average time is: " + averageTime + " μs") + resultSet.close(); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_ResultSet_GoTo_001', 0, async function (done) { + let predicates = new dataRdb.RdbPredicates("test"); + let resultSet = await rdbStore.query(predicates); + resultSet.goToFirstRow(); + let startTime = new Date().getTime() + for (let i = 0; i < BASE_COUNT; i++) { + resultSet.goTo(i % 2); + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the ResultSet_GoTo average time is: " + averageTime + " μs") + resultSet.close(); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_ResultSet_GoToRow_001', 0, async function (done) { + let predicates = new dataRdb.RdbPredicates("test"); + let resultSet = await rdbStore.query(predicates); + resultSet.goToFirstRow(); + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT; i++) { + resultSet.goToRow(1); + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the ResultSet_GoToRow average time is: " + averageTime + " μs"); + resultSet.close(); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_ResultSet_GoToFirstRow_001', 0, async function (done) { + let predicates = new dataRdb.RdbPredicates("test"); + let resultSet = await rdbStore.query(predicates); + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT; i++) { + resultSet.goToFirstRow(); + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the ResultSet_GoToFirstRow average time is: " + averageTime + " μs"); + resultSet.close(); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_ResultSet_GoToLastRow_001', 0, async function (done) { + let predicates = new dataRdb.RdbPredicates("test"); + let resultSet = await rdbStore.query(predicates); + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT; i++) { + resultSet.goToLastRow(); + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the ResultSet_GoToLastRow average time is: " + averageTime + " μs"); + resultSet.close(); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_ResultSet_GoToNextRow_001', 0, async function (done) { + let predicates = new dataRdb.RdbPredicates("test"); + let resultSet = await rdbStore.query(predicates); + resultSet.goToFirstRow(); + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT; i++) { + resultSet.goToNextRow(); + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the ResultSet_GoToNextRow average time is: " + averageTime + " μs") + resultSet.close(); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_ResultSet_GoToPreviousRow_001', 0, async function (done) { + let predicates = new dataRdb.RdbPredicates("test"); + let resultSet = await rdbStore.query(predicates); + resultSet.goToLastRow(); + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT; i++) { + resultSet.goToPreviousRow(); + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the ResultSet_GoToPreviousRow average time is: " + averageTime + " μs"); + resultSet.close(); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_ResultSet_GetBlob_001', 0, async function (done) { + let predicates = new dataRdb.RdbPredicates("test"); + let resultSet = await rdbStore.query(predicates); + let columnIndex = resultSet.getColumnIndex("blobType"); + resultSet.goToFirstRow(); + let startTime = new Date().getTime() + for (let i = 0; i < BASE_COUNT; i++) { + resultSet.getBlob(columnIndex); + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the ResultSet_GetBlob average time is: " + averageTime + " μs"); + resultSet.close(); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_ResultSet_GetString_001', 0, async function (done) { + let predicates = new dataRdb.RdbPredicates("test"); + let resultSet = await rdbStore.query(predicates); + let columnIndex = resultSet.getColumnIndex("name"); + let flag = resultSet.goToFirstRow(); + let startTime = new Date().getTime(); + for (var i = 0; i < SPECIAL_BASE_COUNT; i++) { + resultSet.getString(columnIndex); + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / SPECIAL_BASE_COUNT; + console.info(TAG + " the ResultSet_GetString average time is: " + averageTime + " μs"); + resultSet.close(); + expect(averageTime < BASE_LINE).assertTrue(); + done() + }) + + it('SUB_DDM_PERF_RDB_ResultSet_GetLong_001', 0, async function (done) { + let predicates = new dataRdb.RdbPredicates("test"); + let resultSet = await rdbStore.query(predicates); + let columnIndex = resultSet.getColumnIndex("age"); + resultSet.goToFirstRow(); + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT; i++) { + resultSet.getLong(columnIndex); + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the ResultSet_GetLong average time is: " + averageTime + " μs") + resultSet.close(); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_ResultSet_GetDouble_001', 0, async function (done) { + let predicates = new dataRdb.RdbPredicates("test"); + let resultSet = await rdbStore.query(predicates); + let columnIndex = resultSet.getColumnIndex("salary"); + resultSet.goToFirstRow(); + let startTime = new Date().getTime() + for (let i = 0; i < BASE_COUNT; i++) { + resultSet.getDouble(columnIndex); + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the ResultSet_GetDouble average time is: " + averageTime + " μs") + resultSet.close(); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_ResultSet_IsColumnNull_001', 0, async function (done) { + let predicates = new dataRdb.RdbPredicates("test"); + let resultSet = await rdbStore.query(predicates); + let columnIndex = resultSet.getColumnIndex("salary"); + resultSet.goToFirstRow(); + let startTime = new Date().getTime() + for (let i = 0; i < BASE_COUNT; i++) { + resultSet.isColumnNull(columnIndex); + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the ResultSet_IsColumnNull average time is: " + averageTime + " μs"); + resultSet.close(); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + console.info(TAG + "*************Unit Test End*************"); +}) \ No newline at end of file diff --git a/relational_store/test/js/relationalstore/BUILD.gn b/relational_store/test/js/relationalstore/BUILD.gn index 0d59022302a62e7687bc0af0ef0d2e8f677c02e9..27abd8a16ba9e6c5cf8d4beec894cb73555eea4f 100644 --- a/relational_store/test/js/relationalstore/BUILD.gn +++ b/relational_store/test/js/relationalstore/BUILD.gn @@ -20,4 +20,11 @@ group("unittest") { deps += [ "unittest/src:unittest" ] } + +group("performancetest") { + testonly = true + deps = [] + + deps += [ "performance/src:RelationalStorePerfJsTest" ] +} ############################################################################### diff --git a/relational_store/test/js/relationalstore/performance/src/BUILD.gn b/relational_store/test/js/relationalstore/performance/src/BUILD.gn index d13758d24b7418eba934347960dcf8e207c2bd3b..d0814abe7c9eed8aa87ae4d6f14fb7aefa0345dc 100644 --- a/relational_store/test/js/relationalstore/performance/src/BUILD.gn +++ b/relational_store/test/js/relationalstore/performance/src/BUILD.gn @@ -13,9 +13,9 @@ import("//build/test.gni") -module_output_path = "relational_store/oh_perf" +module_output_path = "relational_store/performance" -ohos_js_unittest("OHRdbPerfJsTest") { +ohos_js_unittest("RelationalStorePerfJsTest") { module_out_path = module_output_path hap_profile = "../config.json" diff --git a/relational_store/test/js/relationalstore/performance/src/PredicatestPerf.js b/relational_store/test/js/relationalstore/performance/src/PredicatestPerf.js index 47c0f77b68b63019ddff476174c5ff37452ad1b5..da7fd55667909073b7898bb0c25dff127201fa25 100644 --- a/relational_store/test/js/relationalstore/performance/src/PredicatestPerf.js +++ b/relational_store/test/js/relationalstore/performance/src/PredicatestPerf.js @@ -13,21 +13,12 @@ * limitations under the License. */ -import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, Assert } from 'deccjsunit/index'; -import dataRdb from '@ohos.data.rdb'; -import featureAbility from '@ohos.ability.featureAbility'; +import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, Assert} from 'deccjsunit/index'; +import dataRdb from '@ohos.data.relationalStore'; import deviceInfo from '@ohos.deviceInfo'; const TAG = "[RDB_PREDICATES_PERF]"; -const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (id INTEGER PRIMARY KEY AUTOINCREMENT, " -+ "name TEXT, age INTEGER, salary REAL, blobType BLOB)"; - -const DB_NAME = "predicatesPerf.db"; -const STORE_CONFIG = { - name: DB_NAME, -} -let context = featureAbility.getContext(); -var rdbStore = undefined; + const BASE_COUNT = 2000; // loop times const BASE_COUNT_FIRST = 200; const BASE_COUNT_SECOND = 10; @@ -36,480 +27,480 @@ const BASE_LINE_PHONE = 1000; // callback phone base line const BASE_LINE = (deviceInfo.deviceType == "tablet") ? BASE_LINE_TABLE : BASE_LINE_PHONE; describe('predicatesPerf', function () { - beforeAll(async function () { - console.info(TAG + 'beforeAll'); - }) - beforeEach(async function () { - console.info(TAG + 'beforeEach'); - }) - afterEach(async function () { - console.info(TAG + 'afterEach'); - }) - afterAll(async function () { - console.info(TAG + 'afterAll'); - }) - - console.log(TAG + "*************Unit Test Begin*************"); - - it('SUB_DDM_PERF_RDB_Predicates_inDevices_001', 0, async function (done) { - let startTime = new Date().getTime(); - for (let i = 0; i < BASE_COUNT_FIRST; i++) { - let predicates = new dataRdb.RdbPredicates("test"); - for (let j = 0; j < BASE_COUNT_SECOND; j++) { - predicates.inDevices(['123']); - } - } - let endTime = new Date().getTime(); - let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; - console.info(TAG + " the Predicates_inDevices average time is: " + averageTime + " μs"); - expect(averageTime < BASE_LINE).assertTrue(); - done(); - }) - - it('SUB_DDM_PERF_RDB_Predicates_inAllDevices_001', 0, async function (done) { - let startTime = new Date().getTime(); - for (let i = 0; i < BASE_COUNT_FIRST; i++) { - let predicates = new dataRdb.RdbPredicates("test"); - for (let j = 0; j < BASE_COUNT_SECOND; j++) { - predicates.inAllDevices(); - } - } - let endTime = new Date().getTime(); - let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; - console.info(TAG + " the Predicates_inAllDevices average time is: " + averageTime + " μs"); - expect(averageTime < BASE_LINE).assertTrue(); - done(); - }) - - it('SUB_DDM_PERF_RDB_Predicates_equalTo_001', 0, async function (done) { - let startTime = new Date().getTime(); - for (let i = 0; i < BASE_COUNT_FIRST; i++) { - let predicates = new dataRdb.RdbPredicates("test"); - for (let j = 0; j < BASE_COUNT_SECOND; j++) { - predicates.equalTo("name", "lisi"); - } - } - let endTime = new Date().getTime(); - let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; - console.info(TAG + " the Predicates_equalTo average time is: " + averageTime + " μs"); - expect(averageTime < BASE_LINE).assertTrue(); - done(); - }) - - it('SUB_DDM_PERF_RDB_Predicates_notEqualTo_001', 0, async function (done) { - let startTime = new Date().getTime(); - for (let i = 0; i < BASE_COUNT_FIRST; i++) { - let predicates = new dataRdb.RdbPredicates("test"); - for (let j = 0; j < BASE_COUNT_SECOND; j++) { - predicates.notEqualTo("name", "lisi"); - } - } - let endTime = new Date().getTime(); - let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; - console.info(TAG + " the Predicates_notEqualTo average time is: " + averageTime + " μs"); - expect(averageTime < BASE_LINE).assertTrue(); - done(); - }) - - it('SUB_DDM_PERF_RDB_Predicates_beginWrap_001', 0, async function (done) { - let startTime = new Date().getTime(); - for (let i = 0; i < BASE_COUNT_FIRST; i++) { - let predicates = new dataRdb.RdbPredicates("test"); - for (let j = 0; j < BASE_COUNT_SECOND; j++) { - predicates.beginWrap(); - } - } - let endTime = new Date().getTime(); - let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; - console.info(TAG + " the Predicates_beginWrap average time is: " + averageTime + " μs"); - expect(averageTime < BASE_LINE).assertTrue(); - done(); - }) - - it('SUB_DDM_PERF_RDB_Predicates_endWrap_001', 0, async function (done) { - let startTime = new Date().getTime(); - for (let i = 0; i < BASE_COUNT_FIRST; i++) { - let predicates = new dataRdb.RdbPredicates("test"); - for (let j = 0; j < BASE_COUNT_SECOND; j++) { - predicates.equalTo("name", "lisi"); - predicates.endWrap(); - } - } - let endTime = new Date().getTime(); - let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; - console.info(TAG + " the Predicates_endWrap average time is: " + averageTime + " μs"); - expect(averageTime < BASE_LINE).assertTrue(); - done(); - }) - - it('SUB_DDM_PERF_RDB_Predicates_or_001', 0, async function (done) { - let startTime = new Date().getTime(); - for (let i = 0; i < BASE_COUNT_FIRST; i++) { - let predicates = new dataRdb.RdbPredicates("test"); - for (let j = 0; j < BASE_COUNT_SECOND; j++) { - predicates.equalTo("name", "lisi"); - predicates.or(); - predicates.equalTo("age", 18); - } - } - let endTime = new Date().getTime(); - let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; - console.info(TAG + " the Predicates_or average time is: " + averageTime + " μs"); - expect(averageTime < BASE_LINE).assertTrue(); - done(); - }) - - it('SUB_DDM_PERF_RDB_Predicates_and_001', 1, async function (done) { - let startTime = new Date().getTime(); - for (let i = 0; i < BASE_COUNT_FIRST; i++) { - let predicates = new dataRdb.RdbPredicates("test"); - for (let j = 0; j < BASE_COUNT_SECOND; j++) { - predicates.equalTo("name", "lisi"); - predicates.and(); - predicates.equalTo("name", "zs"); - } - } - let endTime = new Date().getTime(); - let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; - console.info(TAG + " the Predicates_and average time is: " + averageTime + " μs"); - expect(averageTime < BASE_LINE).assertTrue(); - done(); - }) - - it('SUB_DDM_PERF_RDB_Predicates_contains_001', 0, async function (done) { - let startTime = new Date().getTime(); - for (let i = 0; i < BASE_COUNT_FIRST; i++) { - let predicates = new dataRdb.RdbPredicates("test"); - for (let j = 0; j < BASE_COUNT_SECOND; j++) { - predicates.contains("name", "lisi"); - } - } - let endTime = new Date().getTime(); - let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; - console.info(TAG + " the Predicates_contains average time is: " + averageTime + " μs"); - expect(averageTime < BASE_LINE).assertTrue(); - done(); - }) - - it('SUB_DDM_PERF_RDB_Predicates_beginsWith_001', 0, async function (done) { - let startTime = new Date().getTime(); - for (let i = 0; i < BASE_COUNT_FIRST; i++) { - let predicates = new dataRdb.RdbPredicates("test"); - for (let j = 0; j < BASE_COUNT_SECOND; j++) { - predicates.beginsWith("name", "lisi"); - } - } - let endTime = new Date().getTime(); - let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; - console.info(TAG + " the Predicates_beginsWith average time is: " + averageTime + " μs"); - expect(averageTime < BASE_LINE).assertTrue(); - done(); - }) - - it('SUB_DDM_PERF_RDB_Predicates_endWith_001', 0, async function (done) { - let startTime = new Date().getTime(); - for (let i = 0; i < BASE_COUNT_FIRST; i++) { - let predicates = new dataRdb.RdbPredicates("test"); - for (let j = 0; j < BASE_COUNT_SECOND; j++) { - predicates.endsWith("name", "lisi"); - } - } - let endTime = new Date().getTime(); - let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; - console.info(TAG + " the Predicates_endWith average time is: " + averageTime + " μs"); - expect(averageTime < BASE_LINE).assertTrue(); - done(); - }) - - it('SUB_DDM_PERF_RDB_Predicates_isNull_001', 0, async function (done) { - let startTime = new Date().getTime(); - for (let i = 0; i < BASE_COUNT_FIRST; i++) { - let predicates = new dataRdb.RdbPredicates("test"); - for (let j = 0; j < BASE_COUNT_SECOND; j++) { - predicates.isNull("name"); - } - } - let endTime = new Date().getTime(); - let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; - console.info(TAG + " the Predicates_isNull average time is: " + averageTime + " μs"); - expect(averageTime < BASE_LINE).assertTrue(); - done(); - }) - - it('SUB_DDM_PERF_RDB_Predicates_isNotNull_001', 0, async function (done) { - let startTime = new Date().getTime(); - for (let i = 0; i < BASE_COUNT_FIRST; i++) { - let predicates = new dataRdb.RdbPredicates("test"); - for (let j = 0; j < BASE_COUNT_SECOND; j++) { - predicates.isNotNull("name"); - } - } - let endTime = new Date().getTime(); - let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; - console.info(TAG + " the Predicates_isNotNull average time is: " + averageTime + " μs"); - expect(averageTime < BASE_LINE).assertTrue(); - done(); - }) - - it('SUB_DDM_PERF_RDB_Predicates_like_001', 0, async function (done) { - let startTime = new Date().getTime(); - for (let i = 0; i < BASE_COUNT_FIRST; i++) { - let predicates = new dataRdb.RdbPredicates("test"); - for (let j = 0; j < BASE_COUNT_SECOND; j++) { - predicates.like("name", "li"); - } - } - let endTime = new Date().getTime(); - let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; - console.info(TAG + " the Predicates_like average time is: " + averageTime + " μs"); - expect(averageTime < BASE_LINE).assertTrue(); - done(); - }) - - it('SUB_DDM_PERF_RDB_Predicates_glob_001', 0, async function (done) { - let startTime = new Date().getTime(); - for (let i = 0; i < BASE_COUNT_FIRST; i++) { - let predicates = new dataRdb.RdbPredicates("test"); - for (let j = 0; j < BASE_COUNT_SECOND; j++) { - predicates.glob("name", "li"); - } - } - let endTime = new Date().getTime(); - let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; - console.info(TAG + " the Predicates_glob average time is: " + averageTime + " μs"); - expect(averageTime < BASE_LINE).assertTrue(); - done(); - }) - - it('SUB_DDM_PERF_RDB_Predicates_between_001', 0, async function (done) { - let startTime = new Date().getTime(); - for (let i = 0; i < BASE_COUNT_FIRST; i++) { - let predicates = new dataRdb.RdbPredicates("test"); - for (let j = 0; j < BASE_COUNT_SECOND; j++) { - predicates.between("age", 1, 100); - } - } - let endTime = new Date().getTime(); - let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; - console.info(TAG + " the Predicates_between average time is: " + averageTime + " μs"); - expect(averageTime < BASE_LINE).assertTrue(); - done(); - }) - - it('SUB_DDM_PERF_RDB_Predicates_notBetween_001', 0, async function (done) { - let startTime = new Date().getTime(); - for (let i = 0; i < BASE_COUNT_FIRST; i++) { - let predicates = new dataRdb.RdbPredicates("test"); - for (let j = 0; j < BASE_COUNT_SECOND; j++) { - predicates.notBetween("age", 1, 100); - } - } - let endTime = new Date().getTime(); - let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; - console.info(TAG + " the Predicates_notBetween average time is: " + averageTime + " μs"); - expect(averageTime < BASE_LINE).assertTrue(); - done(); - }) - - it('SUB_DDM_PERF_RDB_Predicates_greaterThan_001', 0, async function (done) { - let startTime = new Date().getTime(); - for (let i = 0; i < BASE_COUNT_FIRST; i++) { - let predicates = new dataRdb.RdbPredicates("test"); - for (let j = 0; j < BASE_COUNT_SECOND; j++) { - predicates.greaterThan("age", 1); - } - } - let endTime = new Date().getTime(); - let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; - console.info(TAG + " the Predicates_greaterThan average time is: " + averageTime + " μs"); - expect(averageTime < BASE_LINE).assertTrue(); - done(); - }) - - it('SUB_DDM_PERF_RDB_Predicates_lessThan_001', 0, async function (done) { - let startTime = new Date().getTime(); - for (let i = 0; i < BASE_COUNT_FIRST; i++) { - let predicates = new dataRdb.RdbPredicates("test"); - for (let j = 0; j < BASE_COUNT_SECOND; j++) { - predicates.lessThan("age", 1000); - } - } - let endTime = new Date().getTime(); - let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; - console.info(TAG + " the Predicates_lessThan average time is: " + averageTime + " μs"); - expect(averageTime < BASE_LINE).assertTrue(); - done(); - }) - - it('SUB_DDM_PERF_RDB_Predicates_greaterThanOrEqualTo_001', 0, async function (done) { - let startTime = new Date().getTime(); - for (let i = 0; i < BASE_COUNT_FIRST; i++) { - let predicates = new dataRdb.RdbPredicates("test"); - for (let j = 0; j < BASE_COUNT_SECOND; j++) { - predicates.greaterThanOrEqualTo("age", 1000); - } - } - let endTime = new Date().getTime(); - let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; - console.info(TAG + " the Predicates_greaterThanOrEqualTo average time is: " + averageTime + " μs"); - expect(averageTime < BASE_LINE).assertTrue(); - done(); - }) - - it('SUB_DDM_PERF_RDB_Predicates_lessThanOrEqualTo_001', 0, async function (done) { - let startTime = new Date().getTime(); - for (let i = 0; i < BASE_COUNT_FIRST; i++) { - let predicates = new dataRdb.RdbPredicates("test"); - for (let j = 0; j < BASE_COUNT_SECOND; j++) { - predicates.lessThanOrEqualTo("age", 1000); - } - } - let endTime = new Date().getTime(); - let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; - console.info(TAG + " the Predicates_lessThanOrEqualTo average time is: " + averageTime + " μs"); - expect(averageTime < BASE_LINE).assertTrue(); - done(); - }) - - it('SUB_DDM_PERF_RDB_Predicates_orderByAsc_001', 0, async function (done) { - let startTime = new Date().getTime(); - for (let i = 0; i < BASE_COUNT_FIRST; i++) { - let predicates = new dataRdb.RdbPredicates("test"); - for (let j = 0; j < BASE_COUNT_SECOND; j++) { - predicates.orderByAsc("name"); - } - } - let endTime = new Date().getTime(); - let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; - console.info(TAG + " the Predicates_orderByAsc average time is: " + averageTime + " μs"); - expect(averageTime < BASE_LINE).assertTrue(); - done(); - }) - - it('SUB_DDM_PERF_RDB_Predicates_orderByDesc_001', 0, async function (done) { - let startTime = new Date().getTime(); - for (let i = 0; i < BASE_COUNT_FIRST; i++) { - let predicates = new dataRdb.RdbPredicates("test"); - for (let j = 0; j < BASE_COUNT_SECOND; j++) { - predicates.orderByDesc("name"); - } - } - let endTime = new Date().getTime(); - let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; - console.info(TAG + " the Predicates_orderByDesc average time is: " + averageTime + " μs"); - expect(averageTime < BASE_LINE).assertTrue(); - done(); - }) - - it('SUB_DDM_PERF_RDB_Predicates_distinct_001', 0, async function (done) { - let startTime = new Date().getTime(); - for (let i = 0; i < BASE_COUNT_FIRST; i++) { - let predicates = new dataRdb.RdbPredicates("test"); - for (let j = 0; j < BASE_COUNT_SECOND; j++) { - predicates.distinct(); - } - } - let endTime = new Date().getTime(); - let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; - console.info(TAG + " the Predicates_distinct average time is: " + averageTime + " μs"); - expect(averageTime < BASE_LINE).assertTrue(); - done(); - }) - - it('SUB_DDM_PERF_RDB_Predicates_limitAs_001', 0, async function (done) { - let startTime = new Date().getTime(); - for (let i = 0; i < BASE_COUNT; i++) { - let predicates = new dataRdb.RdbPredicates("test"); - predicates.limitAs(6); - } - let endTime = new Date().getTime(); - let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; - console.info(TAG + " the Predicates_limitAs average time is: " + averageTime + " μs"); - expect(averageTime < BASE_LINE).assertTrue(); - done(); - }) - - it('SUB_DDM_PERF_RDB_Predicates_offsetAs_001', 0, async function (done) { - let startTime = new Date().getTime(); - for (let i = 0; i < BASE_COUNT; i++) { - let predicates = new dataRdb.RdbPredicates("test"); - predicates.offsetAs(6); - } - let endTime = new Date().getTime(); - let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; - console.info(TAG + " the Predicates_offsetAs average time is: " + averageTime + " μs"); - expect(averageTime < BASE_LINE).assertTrue(); - done(); - }) - - it('SUB_DDM_PERF_RDB_Predicates_groupBy_001', 0, async function (done) { - let nameArr = new Array(); - nameArr.push("id"); - nameArr.push("name"); - let startTime = new Date().getTime(); - for (let i = 0; i < BASE_COUNT_FIRST; i++) { - let predicates = new dataRdb.RdbPredicates("test"); - for (let j = 0; j < BASE_COUNT_SECOND; j++) { - predicates.groupBy(nameArr); - } - } - let endTime = new Date().getTime(); - let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; - console.info(TAG + " the Predicates_groupBy average time is: " + averageTime + " μs"); - expect(averageTime < BASE_LINE).assertTrue(); - done(); - }) - - it('SUB_DDM_PERF_RDB_Predicates_indexedBy_001', 0, async function (done) { - let startTime = new Date().getTime(); - for (let i = 0; i < BASE_COUNT_FIRST; i++) { - let predicates = new dataRdb.RdbPredicates("test"); - for (let j = 0; j < BASE_COUNT_SECOND; j++) { - predicates.indexedBy("name"); - } - } - let endTime = new Date().getTime(); - let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; - console.info(TAG + " the Predicates_indexedBy average time is: " + averageTime + " μs"); - expect(averageTime < BASE_LINE).assertTrue(); - done(); - }) - - it('SUB_DDM_PERF_RDB_Predicates_in_001', 0, async function (done) { - let nameArr = new Array(); - nameArr.push("id"); - nameArr.push("name"); - let startTime = new Date().getTime(); - for (let i = 0; i < BASE_COUNT_FIRST; i++) { - let predicates = new dataRdb.RdbPredicates("test"); - for (let j = 0; j < BASE_COUNT_SECOND; j++) { - predicates.in("name", nameArr); - } - } - let endTime = new Date().getTime(); - let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; - console.info(TAG + " the Predicates_in average time is: " + averageTime + " μs"); - expect(averageTime < BASE_LINE).assertTrue(); - done(); - }) - - it('SUB_DDM_PERF_RDB_Predicates_notIn(_001', 0, async function (done) { - let nameArr = new Array(); - nameArr.push("zhangsan"); - nameArr.push("lisi"); - let startTime = new Date().getTime(); - for (let i = 0; i < BASE_COUNT_FIRST; i++) { - let predicates = new dataRdb.RdbPredicates("test"); - for (let j = 0; j < BASE_COUNT_SECOND; j++) { - predicates.notIn("name", nameArr); - } - } - let endTime = new Date().getTime(); - let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; - console.info(TAG + " the Predicates_notIn average time is: " + averageTime + " μs"); - expect(averageTime < BASE_LINE).assertTrue(); - done(); - }) - - console.info(TAG + "*************Unit Test End*************") + beforeAll(async function () { + console.info(TAG + 'beforeAll'); + }) + beforeEach(async function () { + console.info(TAG + 'beforeEach'); + }) + afterEach(async function () { + console.info(TAG + 'afterEach'); + }) + afterAll(async function () { + console.info(TAG + 'afterAll'); + }) + + console.log(TAG + "*************Unit Test Begin*************"); + + it('SUB_DDM_PERF_RDB_Predicates_inDevices_001', 0, async function (done) { + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT_FIRST; i++) { + let predicates = new dataRdb.RdbPredicates("test"); + for (let j = 0; j < BASE_COUNT_SECOND; j++) { + predicates.inDevices(['123']); + } + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the Predicates_inDevices average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_Predicates_inAllDevices_001', 0, async function (done) { + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT_FIRST; i++) { + let predicates = new dataRdb.RdbPredicates("test"); + for (let j = 0; j < BASE_COUNT_SECOND; j++) { + predicates.inAllDevices(); + } + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the Predicates_inAllDevices average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_Predicates_equalTo_001', 0, async function (done) { + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT_FIRST; i++) { + let predicates = new dataRdb.RdbPredicates("test"); + for (let j = 0; j < BASE_COUNT_SECOND; j++) { + predicates.equalTo("name", "lisi"); + } + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the Predicates_equalTo average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_Predicates_notEqualTo_001', 0, async function (done) { + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT_FIRST; i++) { + let predicates = new dataRdb.RdbPredicates("test"); + for (let j = 0; j < BASE_COUNT_SECOND; j++) { + predicates.notEqualTo("name", "lisi"); + } + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the Predicates_notEqualTo average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_Predicates_beginWrap_001', 0, async function (done) { + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT_FIRST; i++) { + let predicates = new dataRdb.RdbPredicates("test"); + for (let j = 0; j < BASE_COUNT_SECOND; j++) { + predicates.beginWrap(); + } + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the Predicates_beginWrap average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_Predicates_endWrap_001', 0, async function (done) { + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT_FIRST; i++) { + let predicates = new dataRdb.RdbPredicates("test"); + for (let j = 0; j < BASE_COUNT_SECOND; j++) { + predicates.equalTo("name", "lisi"); + predicates.endWrap(); + } + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the Predicates_endWrap average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_Predicates_or_001', 0, async function (done) { + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT_FIRST; i++) { + let predicates = new dataRdb.RdbPredicates("test"); + for (let j = 0; j < BASE_COUNT_SECOND; j++) { + predicates.equalTo("name", "lisi"); + predicates.or(); + predicates.equalTo("age", 18); + } + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the Predicates_or average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_Predicates_and_001', 1, async function (done) { + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT_FIRST; i++) { + let predicates = new dataRdb.RdbPredicates("test"); + for (let j = 0; j < BASE_COUNT_SECOND; j++) { + predicates.equalTo("name", "lisi"); + predicates.and(); + predicates.equalTo("name", "zs"); + } + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the Predicates_and average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_Predicates_contains_001', 0, async function (done) { + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT_FIRST; i++) { + let predicates = new dataRdb.RdbPredicates("test"); + for (let j = 0; j < BASE_COUNT_SECOND; j++) { + predicates.contains("name", "lisi"); + } + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the Predicates_contains average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_Predicates_beginsWith_001', 0, async function (done) { + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT_FIRST; i++) { + let predicates = new dataRdb.RdbPredicates("test"); + for (let j = 0; j < BASE_COUNT_SECOND; j++) { + predicates.beginsWith("name", "lisi"); + } + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the Predicates_beginsWith average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_Predicates_endWith_001', 0, async function (done) { + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT_FIRST; i++) { + let predicates = new dataRdb.RdbPredicates("test"); + for (let j = 0; j < BASE_COUNT_SECOND; j++) { + predicates.endsWith("name", "lisi"); + } + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the Predicates_endWith average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_Predicates_isNull_001', 0, async function (done) { + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT_FIRST; i++) { + let predicates = new dataRdb.RdbPredicates("test"); + for (let j = 0; j < BASE_COUNT_SECOND; j++) { + predicates.isNull("name"); + } + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the Predicates_isNull average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_Predicates_isNotNull_001', 0, async function (done) { + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT_FIRST; i++) { + let predicates = new dataRdb.RdbPredicates("test"); + for (let j = 0; j < BASE_COUNT_SECOND; j++) { + predicates.isNotNull("name"); + } + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the Predicates_isNotNull average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_Predicates_like_001', 0, async function (done) { + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT_FIRST; i++) { + let predicates = new dataRdb.RdbPredicates("test"); + for (let j = 0; j < BASE_COUNT_SECOND; j++) { + predicates.like("name", "li"); + } + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the Predicates_like average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_Predicates_glob_001', 0, async function (done) { + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT_FIRST; i++) { + let predicates = new dataRdb.RdbPredicates("test"); + for (let j = 0; j < BASE_COUNT_SECOND; j++) { + predicates.glob("name", "li"); + } + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the Predicates_glob average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_Predicates_between_001', 0, async function (done) { + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT_FIRST; i++) { + let predicates = new dataRdb.RdbPredicates("test"); + for (let j = 0; j < BASE_COUNT_SECOND; j++) { + predicates.between("age", 1, 100); + } + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the Predicates_between average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_Predicates_notBetween_001', 0, async function (done) { + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT_FIRST; i++) { + let predicates = new dataRdb.RdbPredicates("test"); + for (let j = 0; j < BASE_COUNT_SECOND; j++) { + predicates.notBetween("age", 1, 100); + } + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the Predicates_notBetween average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_Predicates_greaterThan_001', 0, async function (done) { + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT_FIRST; i++) { + let predicates = new dataRdb.RdbPredicates("test"); + for (let j = 0; j < BASE_COUNT_SECOND; j++) { + predicates.greaterThan("age", 1); + } + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the Predicates_greaterThan average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_Predicates_lessThan_001', 0, async function (done) { + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT_FIRST; i++) { + let predicates = new dataRdb.RdbPredicates("test"); + for (let j = 0; j < BASE_COUNT_SECOND; j++) { + predicates.lessThan("age", 1000); + } + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the Predicates_lessThan average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_Predicates_greaterThanOrEqualTo_001', 0, async function (done) { + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT_FIRST; i++) { + let predicates = new dataRdb.RdbPredicates("test"); + for (let j = 0; j < BASE_COUNT_SECOND; j++) { + predicates.greaterThanOrEqualTo("age", 1000); + } + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the Predicates_greaterThanOrEqualTo average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_Predicates_lessThanOrEqualTo_001', 0, async function (done) { + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT_FIRST; i++) { + let predicates = new dataRdb.RdbPredicates("test"); + for (let j = 0; j < BASE_COUNT_SECOND; j++) { + predicates.lessThanOrEqualTo("age", 1000); + } + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the Predicates_lessThanOrEqualTo average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_Predicates_orderByAsc_001', 0, async function (done) { + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT_FIRST; i++) { + let predicates = new dataRdb.RdbPredicates("test"); + for (let j = 0; j < BASE_COUNT_SECOND; j++) { + predicates.orderByAsc("name"); + } + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the Predicates_orderByAsc average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_Predicates_orderByDesc_001', 0, async function (done) { + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT_FIRST; i++) { + let predicates = new dataRdb.RdbPredicates("test"); + for (let j = 0; j < BASE_COUNT_SECOND; j++) { + predicates.orderByDesc("name"); + } + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the Predicates_orderByDesc average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_Predicates_distinct_001', 0, async function (done) { + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT_FIRST; i++) { + let predicates = new dataRdb.RdbPredicates("test"); + for (let j = 0; j < BASE_COUNT_SECOND; j++) { + predicates.distinct(); + } + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the Predicates_distinct average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_Predicates_limitAs_001', 0, async function (done) { + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT; i++) { + let predicates = new dataRdb.RdbPredicates("test"); + predicates.limitAs(6); + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the Predicates_limitAs average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_Predicates_offsetAs_001', 0, async function (done) { + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT; i++) { + let predicates = new dataRdb.RdbPredicates("test"); + predicates.offsetAs(6); + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the Predicates_offsetAs average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_Predicates_groupBy_001', 0, async function (done) { + let nameArr = new Array(); + nameArr.push("id"); + nameArr.push("name"); + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT_FIRST; i++) { + let predicates = new dataRdb.RdbPredicates("test"); + for (let j = 0; j < BASE_COUNT_SECOND; j++) { + predicates.groupBy(nameArr); + } + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the Predicates_groupBy average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_Predicates_indexedBy_001', 0, async function (done) { + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT_FIRST; i++) { + let predicates = new dataRdb.RdbPredicates("test"); + for (let j = 0; j < BASE_COUNT_SECOND; j++) { + predicates.indexedBy("name"); + } + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the Predicates_indexedBy average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_Predicates_in_001', 0, async function (done) { + let nameArr = new Array(); + nameArr.push("id"); + nameArr.push("name"); + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT_FIRST; i++) { + let predicates = new dataRdb.RdbPredicates("test"); + for (let j = 0; j < BASE_COUNT_SECOND; j++) { + predicates.in("name", nameArr); + } + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the Predicates_in average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + it('SUB_DDM_PERF_RDB_Predicates_notIn(_001', 0, async function (done) { + let nameArr = new Array(); + nameArr.push("zhangsan"); + nameArr.push("lisi"); + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT_FIRST; i++) { + let predicates = new dataRdb.RdbPredicates("test"); + for (let j = 0; j < BASE_COUNT_SECOND; j++) { + predicates.notIn("name", nameArr); + } + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the Predicates_notIn average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) + + console.info(TAG + "*************Unit Test End*************") }) \ No newline at end of file diff --git a/relational_store/test/js/relationalstore/performance/src/RdbHelperCallbackPerf.js b/relational_store/test/js/relationalstore/performance/src/RdbHelperCallbackPerf.js index ffb0ce800aab9528d8b8251f71562c3a7adffe22..7781c9dddb136adffddac2251d5f6e3d2f8596da 100644 --- a/relational_store/test/js/relationalstore/performance/src/RdbHelperCallbackPerf.js +++ b/relational_store/test/js/relationalstore/performance/src/RdbHelperCallbackPerf.js @@ -13,18 +13,16 @@ * limitations under the License. */ -import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, Assert } from 'deccjsunit/index'; -import dataRdb from '@ohos.data.rdb'; +import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, Assert} from 'deccjsunit/index'; +import dataRdb from '@ohos.data.relationalStore'; import featureAbility from '@ohos.ability.featureAbility'; import deviceInfo from '@ohos.deviceInfo'; const TAG = "[RDBHELPER_CALLBACK]"; -const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (id INTEGER PRIMARY KEY AUTOINCREMENT, " -+ "name TEXT, age INTEGER, salary REAL, blobType BLOB)"; - const DB_NAME = "rdbCallback.db"; const STORE_CONFIG = { - name: DB_NAME, + name: DB_NAME, + securityLevel: dataRdb.SecurityLevel.S1 } let context = featureAbility.getContext(); var rdbStore = undefined; @@ -34,62 +32,62 @@ const BASE_LINE_PHONE = 3000; // callback phone base line const BASE_LINE = (deviceInfo.deviceType == "tablet") ? BASE_LINE_TABLE : BASE_LINE_PHONE; describe('rdbHelperCallbackPerf', function () { - beforeAll(async function () { - console.info(TAG + 'beforeAll'); - }) - beforeEach(async function () { - console.info(TAG + 'beforeEach'); - }) - afterEach(async function () { - console.info(TAG + 'afterEach'); - }) - afterAll(async function () { - console.info(TAG + 'afterAll'); - rdbStore = null - await dataRdb.deleteRdbStore(context, DB_NAME); - }) + beforeAll(async function () { + console.info(TAG + 'beforeAll'); + }) + beforeEach(async function () { + console.info(TAG + 'beforeEach'); + }) + afterEach(async function () { + console.info(TAG + 'afterEach'); + }) + afterAll(async function () { + console.info(TAG + 'afterAll'); + rdbStore = null + await dataRdb.deleteRdbStore(context, DB_NAME); + }) - console.log(TAG + "*************Unit Test Begin*************"); + console.log(TAG + "*************Unit Test Begin*************"); - it('SUB_DDM_PERF_RDB_getRdbStore_Callback_001', 0, async function (done) { - let averageTime = 0; + it('SUB_DDM_PERF_RDB_getRdbStore_Callback_001', 0, async function (done) { + let averageTime = 0; - async function getRdbStoreCallBackPerf(index) { - dataRdb.getRdbStore(context, STORE_CONFIG, 1, function (err, rdbStore) { - if (index < BASE_COUNT) { - getRdbStoreCallBackPerf(index + 1); - } else { - let endTime = new Date().getTime(); - averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; - console.info(TAG + " the getRdbStore_Callback average time is: " + averageTime + " μs"); - expect(averageTime < BASE_LINE).assertTrue(); - done(); - } - }) + async function getRdbStoreCallBackPerf(index) { + dataRdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) { + if (index < BASE_COUNT) { + getRdbStoreCallBackPerf(index + 1); + } else { + let endTime = new Date().getTime(); + averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the getRdbStore_Callback average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); } + }) + } - let startTime = new Date().getTime(); - await getRdbStoreCallBackPerf(0); - }) + let startTime = new Date().getTime(); + await getRdbStoreCallBackPerf(0); + }) - it('SUB_DDM_PERF_RDB_deleteRdbStore_Callback_001', 0, async function (done) { - let averageTime = 0; + it('SUB_DDM_PERF_RDB_deleteRdbStore_Callback_001', 0, async function (done) { + let averageTime = 0; - async function deleteRdbStoreCallBackPerf(index) { - dataRdb.deleteRdbStore(context, DB_NAME, function (err, data) { - if (index < BASE_COUNT) { - deleteRdbStoreCallBackPerf(index + 1); - } else { - let endTime = new Date().getTime(); - averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; - console.info(TAG + " the deleteRdbStore_Callback average time is: " + averageTime + " μs"); - expect(averageTime < BASE_LINE).assertTrue(); - done(); - } - }) + async function deleteRdbStoreCallBackPerf(index) { + dataRdb.deleteRdbStore(context, DB_NAME, function (err, data) { + if (index < BASE_COUNT) { + deleteRdbStoreCallBackPerf(index + 1); + } else { + let endTime = new Date().getTime(); + averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the deleteRdbStore_Callback average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); } + }) + } - let startTime = new Date().getTime(); - await deleteRdbStoreCallBackPerf(0); - }) + let startTime = new Date().getTime(); + await deleteRdbStoreCallBackPerf(0); + }) }) \ No newline at end of file diff --git a/relational_store/test/js/relationalstore/performance/src/RdbHelperPromisePerf.js b/relational_store/test/js/relationalstore/performance/src/RdbHelperPromisePerf.js index fad1e09ee2b72ecf6158bf965b2ac00bd746fd01..d507666d560a2435f055f3101c262d43c6484fbe 100644 --- a/relational_store/test/js/relationalstore/performance/src/RdbHelperPromisePerf.js +++ b/relational_store/test/js/relationalstore/performance/src/RdbHelperPromisePerf.js @@ -13,18 +13,16 @@ * limitations under the License. */ -import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, Assert } from 'deccjsunit/index'; -import dataRdb from '@ohos.data.rdb'; +import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, Assert} from 'deccjsunit/index'; +import dataRdb from '@ohos.data.relationalStore'; import featureAbility from '@ohos.ability.featureAbility'; import deviceInfo from '@ohos.deviceInfo'; const TAG = "[RDBHELPER_PROMISE]"; -const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (id INTEGER PRIMARY KEY AUTOINCREMENT, " -+ "name TEXT, age INTEGER, salary REAL, blobType BLOB)"; - const DB_NAME = "rdbPromise.db"; const STORE_CONFIG = { - name: DB_NAME, + name: DB_NAME, + securityLevel: dataRdb.SecurityLevel.S1 } let context = featureAbility.getContext(); var rdbStore = undefined; @@ -34,47 +32,47 @@ const BASE_LINE_PHONE = 3000; // callback phone base line const BASE_LINE = (deviceInfo.deviceType == "tablet") ? BASE_LINE_TABLE : BASE_LINE_PHONE; describe('rdbHelperPromisePerf', function () { - beforeAll(async function () { - console.info(TAG + 'beforeAll'); - }) - beforeEach(async function () { - console.info(TAG + 'beforeEach'); - }) - afterEach(async function () { - console.info(TAG + 'afterEach'); - }) - afterAll(async function () { - console.info(TAG + 'afterAll'); - rdbStore = null; - await dataRdb.deleteRdbStore(context, DB_NAME); - }) + beforeAll(async function () { + console.info(TAG + 'beforeAll'); + }) + beforeEach(async function () { + console.info(TAG + 'beforeEach'); + }) + afterEach(async function () { + console.info(TAG + 'afterEach'); + }) + afterAll(async function () { + console.info(TAG + 'afterAll'); + rdbStore = null; + await dataRdb.deleteRdbStore(context, DB_NAME); + }) - console.log(TAG + "*************Unit Test Begin*************"); + console.log(TAG + "*************Unit Test Begin*************"); - it('SUB_DDM_PERF_RDB_getRdbStore_Promise_001', 0, async function (done) { - let averageTime = 0; - let startTime = new Date().getTime(); - for (var i = 0; i < BASE_COUNT; i++) { - await dataRdb.getRdbStore(context, STORE_CONFIG, 1); - } - let endTime = new Date().getTime(); - averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; - console.info(TAG + " the getRdbStore_Promise average time is: " + averageTime + " μs"); - expect(averageTime < BASE_LINE).assertTrue(); - done(); - }) + it('SUB_DDM_PERF_RDB_getRdbStore_Promise_001', 0, async function (done) { + let averageTime = 0; + let startTime = new Date().getTime(); + for (var i = 0; i < BASE_COUNT; i++) { + await dataRdb.getRdbStore(context, STORE_CONFIG); + } + let endTime = new Date().getTime(); + averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the getRdbStore_Promise average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) - it('SUB_DDM_PERF_RDB_deleteRdbStore_Promise_001', 0, async function (done) { - let averageTime = 0; - let startTime = new Date().getTime(); - for (var i = 0; i < BASE_COUNT; i++) { - await dataRdb.deleteRdbStore(context, DB_NAME, 1); - } - let endTime = new Date().getTime(); - averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; - console.info(TAG + " the deleteRdbStore_Promise average time is: " + averageTime + " μs"); - expect(averageTime < BASE_LINE).assertTrue(); - done(); - console.info(TAG + "*************Unit Test End*************") - }) + it('SUB_DDM_PERF_RDB_deleteRdbStore_Promise_001', 0, async function (done) { + let averageTime = 0; + let startTime = new Date().getTime(); + for (var i = 0; i < BASE_COUNT; i++) { + await dataRdb.deleteRdbStore(context, DB_NAME, 1); + } + let endTime = new Date().getTime(); + averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the deleteRdbStore_Promise average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + console.info(TAG + "*************Unit Test End*************") + }) }) \ No newline at end of file diff --git a/relational_store/test/js/relationalstore/performance/src/RdbStoreCallbackPerf.js b/relational_store/test/js/relationalstore/performance/src/RdbStoreCallbackPerf.js index 0c4fc81fe220c2850db9e41febecb26d5e520d80..72aed689349e5844eba2c1bd25937790d34327d3 100644 --- a/relational_store/test/js/relationalstore/performance/src/RdbStoreCallbackPerf.js +++ b/relational_store/test/js/relationalstore/performance/src/RdbStoreCallbackPerf.js @@ -13,18 +13,19 @@ * limitations under the License. */ -import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, Assert } from 'deccjsunit/index'; -import dataRdb from '@ohos.data.rdb'; +import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, Assert} from 'deccjsunit/index'; +import dataRdb from '@ohos.data.relationalStore'; import featureAbility from '@ohos.ability.featureAbility'; import deviceInfo from '@ohos.deviceInfo'; const TAG = "[RDBSTORE_CALLBACK]"; const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (id INTEGER PRIMARY KEY AUTOINCREMENT, " -+ "name TEXT, age INTEGER, salary REAL, blobType BLOB)"; + + "name TEXT, age INTEGER, salary REAL, blobType BLOB)"; const DB_NAME = "rdbStoreCallback.db"; const STORE_CONFIG = { - name: DB_NAME, + name: DB_NAME, + securityLevel: dataRdb.SecurityLevel.S1 } let context = featureAbility.getContext(); var rdbStore = undefined; @@ -35,91 +36,91 @@ const BASE_LINE_PHONE = 7000; // callback phone base line const BASE_LINE = (deviceInfo.deviceType == "tablet") ? BASE_LINE_TABLE : BASE_LINE_PHONE; describe('rdbStoreCallbackPerf', function () { - beforeAll(async function () { - console.info(TAG + 'beforeAll'); - rdbStore = await dataRdb.getRdbStore(context, STORE_CONFIG, 1); - }) - beforeEach(async function () { - console.info(TAG + 'beforeEach'); - await rdbStore.executeSql(CREATE_TABLE_TEST, null); - await prepareTestData(); - }) - afterEach(async function () { - console.info(TAG + 'afterEach'); - await rdbStore.executeSql("drop table test"); - }) - afterAll(async function () { - console.info(TAG + 'afterAll'); - rdbStore = null; - await dataRdb.deleteRdbStore(context, DB_NAME); - }) + beforeAll(async function () { + console.info(TAG + 'beforeAll'); + rdbStore = await dataRdb.getRdbStore(context, STORE_CONFIG); + }) + beforeEach(async function () { + console.info(TAG + 'beforeEach'); + await rdbStore.executeSql(CREATE_TABLE_TEST, null); + await prepareTestData(); + }) + afterEach(async function () { + console.info(TAG + 'afterEach'); + await rdbStore.executeSql("drop table test"); + }) + afterAll(async function () { + console.info(TAG + 'afterAll'); + rdbStore = null; + await dataRdb.deleteRdbStore(context, DB_NAME); + }) - async function prepareTestData() { - console.info(TAG + "prepare for query performance test"); - var u8 = new Uint8Array([1, 2, 3]); - var valueBucket = { - "name": "zhangsan", - "age": 18, - "salary": 100.5, - "blobType": u8, - } - await rdbStore.insert("test", valueBucket); + async function prepareTestData() { + console.info(TAG + "prepare for query performance test"); + var u8 = new Uint8Array([1, 2, 3]); + var valueBucket = { + "name": "zhangsan", + "age": 18, + "salary": 100.5, + "blobType": u8, } + await rdbStore.insert("test", valueBucket); + } - console.log(TAG + "*************Unit Test Begin*************"); + console.log(TAG + "*************Unit Test Begin*************"); - it('SUB_DDM_PERF_RDB_query_Callback_001', 0, async function (done) { - let averageTime = 0; - let predicates = new dataRdb.RdbPredicates("test"); - predicates.equalTo("age", 10); + it('SUB_DDM_PERF_RDB_query_Callback_001', 0, async function (done) { + let averageTime = 0; + let predicates = new dataRdb.RdbPredicates("test"); + predicates.equalTo("age", 10); - async function queryCallbackPerf(index) { - rdbStore.query(predicates, [], function (err, resultSet) { - resultSet.close(); - if (index < BASE_COUNT) { - queryCallbackPerf(index + 1); - } else { - let endTime = new Date().getTime(); - averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; - console.info(TAG + " the query_Callback average time is: " + averageTime + " μs"); - expect(averageTime < BASE_LINE).assertTrue(); - console.info(TAG + "*************Unit Test End*************"); - done(); - } - }) + async function queryCallbackPerf(index) { + rdbStore.query(predicates, [], function (err, resultSet) { + resultSet.close(); + if (index < BASE_COUNT) { + queryCallbackPerf(index + 1); + } else { + let endTime = new Date().getTime(); + averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the query_Callback average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + console.info(TAG + "*************Unit Test End*************"); + done(); } + }) + } - let startTime = new Date().getTime(); - queryCallbackPerf(0); - }) + let startTime = new Date().getTime(); + queryCallbackPerf(0); + }) - it('SUB_DDM_PERF_RDB_insert_Callback_001', 0, async function (done) { - let averageTime = 0; - var uBlob = new Uint8Array([1, 2, 3]); - var insertValueBucket = { - "name": "zhangsan", - "age": 18, - "salary": 100.5, - "blobType": uBlob, - } - let predicates = new dataRdb.RdbPredicates("test"); - predicates.equalTo("age", 10); + it('SUB_DDM_PERF_RDB_insert_Callback_001', 0, async function (done) { + let averageTime = 0; + var uBlob = new Uint8Array([1, 2, 3]); + var insertValueBucket = { + "name": "zhangsan", + "age": 18, + "salary": 100.5, + "blobType": uBlob, + } + let predicates = new dataRdb.RdbPredicates("test"); + predicates.equalTo("age", 10); - async function InsertCallbackPerf(index) { - rdbStore.insert("test", insertValueBucket, function (err, data) { - if (index < INSERT_BASE_COUNT) { - InsertCallbackPerf(index + 1); - } else { - let endTime = new Date().getTime(); - averageTime = ((endTime - startTime) * 1000) / INSERT_BASE_COUNT; - console.info(TAG + " the insert_Callback average time is: " + averageTime + " μs"); - expect(averageTime < BASE_LINE).assertTrue(); - done(); - } - }) + async function InsertCallbackPerf(index) { + rdbStore.insert("test", insertValueBucket, function (err, data) { + if (index < INSERT_BASE_COUNT) { + InsertCallbackPerf(index + 1); + } else { + let endTime = new Date().getTime(); + averageTime = ((endTime - startTime) * 1000) / INSERT_BASE_COUNT; + console.info(TAG + " the insert_Callback average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); } + }) + } - let startTime = new Date().getTime(); - InsertCallbackPerf(0); - }) + let startTime = new Date().getTime(); + InsertCallbackPerf(0); + }) }) \ No newline at end of file diff --git a/relational_store/test/js/relationalstore/performance/src/RdbStoreOthersCallbackPerf.js b/relational_store/test/js/relationalstore/performance/src/RdbStoreOthersCallbackPerf.js index 77e7cb07d46a44d6530882b8811a4f1240f4e4a9..1bce013b5c1b5e7961c915fc990a3617776490e9 100644 --- a/relational_store/test/js/relationalstore/performance/src/RdbStoreOthersCallbackPerf.js +++ b/relational_store/test/js/relationalstore/performance/src/RdbStoreOthersCallbackPerf.js @@ -13,18 +13,19 @@ * limitations under the License. */ -import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, Assert } from 'deccjsunit/index'; -import dataRdb from '@ohos.data.rdb'; +import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, Assert} from 'deccjsunit/index'; +import dataRdb from '@ohos.data.relationalStore'; import featureAbility from '@ohos.ability.featureAbility'; import deviceInfo from '@ohos.deviceInfo'; const TAG = "[RDBSTORE_OTHERS_CALLBACK]"; const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (id INTEGER PRIMARY KEY AUTOINCREMENT, " -+ "name TEXT, age INTEGER, salary REAL, blobType BLOB)"; + + "name TEXT, age INTEGER, salary REAL, blobType BLOB)"; const DB_NAME = "rdbUpdateCallback.db"; const STORE_CONFIG = { - name: DB_NAME, + name: DB_NAME, + securityLevel: dataRdb.SecurityLevel.S1 } let context = featureAbility.getContext(); var rdbStore = undefined; @@ -35,131 +36,131 @@ const BASE_LINE_PHONE = 15000; // callback phone base line const BASE_LINE = (deviceInfo.deviceType == "tablet") ? BASE_LINE_TABLE : BASE_LINE_PHONE; describe('rdbStoreOthersCallbackPerf', function () { - beforeAll(async function () { - console.info(TAG + 'beforeAll'); - rdbStore = await dataRdb.getRdbStore(context, STORE_CONFIG, 1); - }) - beforeEach(async function () { - console.info(TAG + 'beforeEach'); - await rdbStore.executeSql(CREATE_TABLE_TEST, null); - await prepareTestData(); - }) - afterEach(async function () { - console.info(TAG + 'afterEach'); - await rdbStore.executeSql("drop table test"); - }) - afterAll(async function () { - console.info(TAG + 'afterAll'); - rdbStore = null; - await dataRdb.deleteRdbStore(context, DB_NAME); - }) - - async function prepareTestData() { - console.info(TAG + "prepare for query performance test"); - var u8 = new Uint8Array([1, 2, 3]); - var valueBucket = { - "name": "zhangsan", - "age": 18, - "salary": 100.5, - "blobType": u8, - } - await rdbStore.insert("test", valueBucket); + beforeAll(async function () { + console.info(TAG + 'beforeAll'); + rdbStore = await dataRdb.getRdbStore(context, STORE_CONFIG); + }) + beforeEach(async function () { + console.info(TAG + 'beforeEach'); + await rdbStore.executeSql(CREATE_TABLE_TEST, null); + await prepareTestData(); + }) + afterEach(async function () { + console.info(TAG + 'afterEach'); + await rdbStore.executeSql("drop table test"); + }) + afterAll(async function () { + console.info(TAG + 'afterAll'); + rdbStore = null; + await dataRdb.deleteRdbStore(context, DB_NAME); + }) + + async function prepareTestData() { + console.info(TAG + "prepare for query performance test"); + var u8 = new Uint8Array([1, 2, 3]); + var valueBucket = { + "name": "zhangsan", + "age": 18, + "salary": 100.5, + "blobType": u8, } - - console.log(TAG + "*************Unit Test Begin*************"); - - it('SUB_DDM_PERF_RDB_update_Callback_001', 0, async function (done) { - let averageTime = 0; - var uBlob = new Uint8Array([1, 2, 3]) - var updateVB = { - "name": "zhangsan", - "age": 18, - "salary": 100.5, - "blobType": uBlob, - } - let predicates = new dataRdb.RdbPredicates("test"); - - async function updateCallbackPerf(index) { - predicates.equalTo("age", 18); - rdbStore.update(updateVB, predicates, function (err, data) { - if (index < SPECIAL_BASE_COUNT) { - updateCallbackPerf(index + 1); - } else { - let endTime = new Date().getTime(); - averageTime = ((endTime - startTime) * 1000) / SPECIAL_BASE_COUNT; - console.info(TAG + " the update_Callback average time is: " + averageTime + " μs"); - expect(averageTime < BASE_LINE).assertTrue(); - done(); - } - }) + await rdbStore.insert("test", valueBucket); + } + + console.log(TAG + "*************Unit Test Begin*************"); + + it('SUB_DDM_PERF_RDB_update_Callback_001', 0, async function (done) { + let averageTime = 0; + var uBlob = new Uint8Array([1, 2, 3]) + var updateVB = { + "name": "zhangsan", + "age": 18, + "salary": 100.5, + "blobType": uBlob, + } + let predicates = new dataRdb.RdbPredicates("test"); + + async function updateCallbackPerf(index) { + predicates.equalTo("age", 18); + rdbStore.update(updateVB, predicates, function (err, data) { + if (index < SPECIAL_BASE_COUNT) { + updateCallbackPerf(index + 1); + } else { + let endTime = new Date().getTime(); + averageTime = ((endTime - startTime) * 1000) / SPECIAL_BASE_COUNT; + console.info(TAG + " the update_Callback average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); } + }) + } - let startTime = new Date().getTime(); - updateCallbackPerf(0); - }) - - it('SUB_DDM_PERF_RDB_delete_Callback_001', 0, async function (done) { - let averageTime = 0; - let predicates = new dataRdb.RdbPredicates("test"); - predicates.equalTo("age", 0); - - async function deleteCallbackPerf(index) { - rdbStore.delete(predicates, function (err, data) { - if (index < BASE_COUNT) { - deleteCallbackPerf(index + 1) - } else { - let endTime = new Date().getTime(); - averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; - console.info(TAG + " the delete_Callback average time is: " + averageTime + " μs"); - expect(averageTime < BASE_LINE).assertTrue(); - done(); - } - }) + let startTime = new Date().getTime(); + updateCallbackPerf(0); + }) + + it('SUB_DDM_PERF_RDB_delete_Callback_001', 0, async function (done) { + let averageTime = 0; + let predicates = new dataRdb.RdbPredicates("test"); + predicates.equalTo("age", 0); + + async function deleteCallbackPerf(index) { + rdbStore.delete(predicates, function (err, data) { + if (index < BASE_COUNT) { + deleteCallbackPerf(index + 1) + } else { + let endTime = new Date().getTime(); + averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the delete_Callback average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); } + }) + } - let startTime = new Date().getTime(); - deleteCallbackPerf(0); - }) - - it('SUB_DDM_PERF_RDB_querySql_Callback_001', 0, async function (done) { - let averageTime = 0; - - async function querySqlCallbackPerf(index) { - rdbStore.querySql("select * from test", [], function (err, data) { - if (index < BASE_COUNT) { - querySqlCallbackPerf(index + 1); - } else { - let endTime = new Date().getTime(); - averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; - console.info(TAG + " the querySql_Callback average time is: " + averageTime + " μs"); - expect(averageTime < BASE_LINE).assertTrue(); - done(); - } - }) + let startTime = new Date().getTime(); + deleteCallbackPerf(0); + }) + + it('SUB_DDM_PERF_RDB_querySql_Callback_001', 0, async function (done) { + let averageTime = 0; + + async function querySqlCallbackPerf(index) { + rdbStore.querySql("select * from test", [], function (err, data) { + if (index < BASE_COUNT) { + querySqlCallbackPerf(index + 1); + } else { + let endTime = new Date().getTime(); + averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the querySql_Callback average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); } + }) + } - let startTime = new Date().getTime(); - querySqlCallbackPerf(0); - }) - - it('SUB_DDM_PERF_RDB_executeSql_Callback_001', 0, async function (done) { - let averageTime = 0; - - async function executeSqlCallbackPerf(index) { - rdbStore.executeSql("insert into test (name, age) values ('tom', 22)", function (err, data) { - if (index < SPECIAL_BASE_COUNT) { - executeSqlCallbackPerf(index + 1); - } else { - let endTime = new Date().getTime(); - averageTime = ((endTime - startTime) * 1000) / SPECIAL_BASE_COUNT; - console.info(TAG + " the executeSql_Callback average time is: " + averageTime + " μs"); - expect(averageTime < BASE_LINE).assertTrue(); - done(); - } - }) + let startTime = new Date().getTime(); + querySqlCallbackPerf(0); + }) + + it('SUB_DDM_PERF_RDB_executeSql_Callback_001', 0, async function (done) { + let averageTime = 0; + + async function executeSqlCallbackPerf(index) { + rdbStore.executeSql("insert into test (name, age) values ('tom', 22)", function (err, data) { + if (index < SPECIAL_BASE_COUNT) { + executeSqlCallbackPerf(index + 1); + } else { + let endTime = new Date().getTime(); + averageTime = ((endTime - startTime) * 1000) / SPECIAL_BASE_COUNT; + console.info(TAG + " the executeSql_Callback average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); } + }) + } - let startTime = new Date().getTime(); - executeSqlCallbackPerf(0); - }) + let startTime = new Date().getTime(); + executeSqlCallbackPerf(0); + }) }) diff --git a/relational_store/test/js/relationalstore/performance/src/RdbStorePromisePerf.js b/relational_store/test/js/relationalstore/performance/src/RdbStorePromisePerf.js index 87c157e0f08544a47a4f1014037a885f8d921796..a2209b6f2eda796749646b0fea46becdeb63d94d 100644 --- a/relational_store/test/js/relationalstore/performance/src/RdbStorePromisePerf.js +++ b/relational_store/test/js/relationalstore/performance/src/RdbStorePromisePerf.js @@ -13,18 +13,19 @@ * limitations under the License. */ -import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, Assert } from 'deccjsunit/index'; -import dataRdb from '@ohos.data.rdb'; +import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, Assert} from 'deccjsunit/index'; +import dataRdb from '@ohos.data.relationalStore'; import featureAbility from '@ohos.ability.featureAbility'; import deviceInfo from '@ohos.deviceInfo'; const TAG = "[RDBSTORE_PROMISE]"; const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (id INTEGER PRIMARY KEY AUTOINCREMENT, " -+ "name TEXT, age INTEGER, salary REAL, blobType BLOB)"; + + "name TEXT, age INTEGER, salary REAL, blobType BLOB)"; const DB_NAME = "rdbStorePromise.db"; const STORE_CONFIG = { - name: DB_NAME, + name: DB_NAME, + securityLevel: dataRdb.SecurityLevel.S1 } let context = featureAbility.getContext(); var rdbStore = undefined; @@ -34,53 +35,53 @@ const BASE_LINE_PHONE = 3000; // callback phone base line const BASE_LINE = (deviceInfo.deviceType == "tablet") ? BASE_LINE_TABLE : BASE_LINE_PHONE; describe('rdbStorePromisePerf', function () { - beforeAll(async function () { - console.info(TAG + 'beforeAll'); - rdbStore = await dataRdb.getRdbStore(context, STORE_CONFIG, 1); - }) - beforeEach(async function () { - console.info(TAG + 'beforeEach'); - await rdbStore.executeSql(CREATE_TABLE_TEST, null); - await prepareTestData(); - }) - afterEach(async function () { - console.info(TAG + 'afterEach'); - await rdbStore.executeSql("drop table test"); - }) - afterAll(async function () { - console.info(TAG + 'afterAll'); - rdbStore = null; - await dataRdb.deleteRdbStore(context, DB_NAME); - }) + beforeAll(async function () { + console.info(TAG + 'beforeAll'); + rdbStore = await dataRdb.getRdbStore(context, STORE_CONFIG); + }) + beforeEach(async function () { + console.info(TAG + 'beforeEach'); + await rdbStore.executeSql(CREATE_TABLE_TEST, null); + await prepareTestData(); + }) + afterEach(async function () { + console.info(TAG + 'afterEach'); + await rdbStore.executeSql("drop table test"); + }) + afterAll(async function () { + console.info(TAG + 'afterAll'); + rdbStore = null; + await dataRdb.deleteRdbStore(context, DB_NAME); + }) - async function prepareTestData() { - console.info(TAG + "prepare for query performance test") - var u8 = new Uint8Array([1, 2, 3]) - var valueBucket = { - "name": "zhangsan", - "age": 18, - "salary": 100.5, - "blobType": u8, - } - await dataRdb.insert("test", valueBucket); + async function prepareTestData() { + console.info(TAG + "prepare for query performance test") + var u8 = new Uint8Array([1, 2, 3]) + var valueBucket = { + "name": "zhangsan", + "age": 18, + "salary": 100.5, + "blobType": u8, } + await dataRdb.insert("test", valueBucket); + } - console.log(TAG + "*************Unit Test Begin*************"); + console.log(TAG + "*************Unit Test Begin*************"); - it('SUB_DDM_PERF_RDB_query_Promise_001', 0, async function (done) { - let averageTime = 0; - let predicates = new dataRdb.RdbPredicates("test"); - predicates.equalTo("age", 10); - let startTime = new Date().getTime(); - for (var i = 0; i < BASE_COUNT; i++) { - let resultSet = await rdbStore.query(predicates, []); - resultSet.close(); - } - let endTime = new Date().getTime(); - averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; - console.info(TAG + " the query_Promise average time is: " + averageTime + " μs"); - expect(averageTime < BASE_LINE).assertTrue(); - console.info(TAG + "*************Unit Test End*************"); - done(); - }) + it('SUB_DDM_PERF_RDB_query_Promise_001', 0, async function (done) { + let averageTime = 0; + let predicates = new dataRdb.RdbPredicates("test"); + predicates.equalTo("age", 10); + let startTime = new Date().getTime(); + for (var i = 0; i < BASE_COUNT; i++) { + let resultSet = await rdbStore.query(predicates, []); + resultSet.close(); + } + let endTime = new Date().getTime(); + averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the query_Promise average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + console.info(TAG + "*************Unit Test End*************"); + done(); + }) }) diff --git a/relational_store/test/js/relationalstore/performance/src/RdbStoreSyncPerf.js b/relational_store/test/js/relationalstore/performance/src/RdbStoreSyncPerf.js index b8b922b93348e7b6c97d2faf96107dc1452aa6c5..3a3b90f288a0868846bcb18e68cc56f6b0419a3f 100644 --- a/relational_store/test/js/relationalstore/performance/src/RdbStoreSyncPerf.js +++ b/relational_store/test/js/relationalstore/performance/src/RdbStoreSyncPerf.js @@ -13,18 +13,16 @@ * limitations under the License. */ -import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, Assert } from 'deccjsunit/index'; -import dataRdb from '@ohos.data.rdb'; +import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, Assert} from 'deccjsunit/index'; +import dataRdb from '@ohos.data.relationalStore'; import featureAbility from '@ohos.ability.featureAbility'; import deviceInfo from '@ohos.deviceInfo'; const TAG = "[RDB_SYNC_PROMISE]"; -const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (id INTEGER PRIMARY KEY AUTOINCREMENT, " -+ "name TEXT, age INTEGER, salary REAL, blobType BLOB)"; - const DB_NAME = "rdbSync.db"; const STORE_CONFIG = { - name: DB_NAME, + name: DB_NAME, + securityLevel: dataRdb.SecurityLevel.S1 } let context = featureAbility.getContext(); var rdbStore = undefined; @@ -35,64 +33,64 @@ const BASE_LINE = (deviceInfo.deviceType == "tablet") ? BASE_LINE_TABLE : BASE_L describe('rdbStoreSyncPerf', function () { - beforeAll(async function () { - console.info(TAG + 'beforeAll'); - rdbStore = await dataRdb.getRdbStore(context, STORE_CONFIG, 1); - }) - beforeEach(async function () { - console.info(TAG + 'beforeEach'); - }) - afterEach(async function () { - console.info(TAG + 'afterEach'); - }) - afterAll(async function () { - console.info(TAG + 'afterAll'); - rdbStore = null - await dataRdb.deleteRdbStore(context, DB_NAME); - }) + beforeAll(async function () { + console.info(TAG + 'beforeAll'); + rdbStore = await dataRdb.getRdbStore(context, STORE_CONFIG); + }) + beforeEach(async function () { + console.info(TAG + 'beforeEach'); + }) + afterEach(async function () { + console.info(TAG + 'afterEach'); + }) + afterAll(async function () { + console.info(TAG + 'afterAll'); + rdbStore = null + await dataRdb.deleteRdbStore(context, DB_NAME); + }) - console.log(TAG + "*************Unit Test Begin*************"); + console.log(TAG + "*************Unit Test Begin*************"); - it('SUB_DDM_PERF_RDB_version_001', 0, async function (done) { - let averageTime = 0; - let dbVersion = 1; - let startTime = new Date().getTime(); - for (var i = 0; i < BASE_COUNT; i++) { - dbVersion = rdbStore.version; - } - let endTime = new Date().getTime(); - averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; - console.info(TAG + " the version average time is: " + averageTime + " μs"); - expect(averageTime < BASE_LINE).assertTrue(); - done(); - }) + it('SUB_DDM_PERF_RDB_version_001', 0, async function (done) { + let averageTime = 0; + let dbVersion = 1; + let startTime = new Date().getTime(); + for (var i = 0; i < BASE_COUNT; i++) { + dbVersion = rdbStore.version; + } + let endTime = new Date().getTime(); + averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the version average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) - it('SUB_DDM_PERF_RDB_transaction_commit_001', 0, async function (done) { - let averageTime = 0; - let startTime = new Date().getTime(); - for (var i = 0; i < BASE_COUNT; i++) { - rdbStore.beginTransaction(); - rdbStore.commit(); - } - let endTime = new Date().getTime(); - averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; - console.info(TAG + " the transaction_commit average time is: " + averageTime + " μs"); - expect(averageTime < BASE_LINE).assertTrue(); - done(); - }) + it('SUB_DDM_PERF_RDB_transaction_commit_001', 0, async function (done) { + let averageTime = 0; + let startTime = new Date().getTime(); + for (var i = 0; i < BASE_COUNT; i++) { + rdbStore.beginTransaction(); + rdbStore.commit(); + } + let endTime = new Date().getTime(); + averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the transaction_commit average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) - it('SUB_DDM_PERF_RDB_transaction_rollback_001', 0, async function (done) { - let averageTime = 0; - let startTime = new Date().getTime(); - for (var i = 0; i < BASE_COUNT; i++) { - rdbStore.beginTransaction(); - rdbStore.rollBack(); - } - let endTime = new Date().getTime(); - averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; - console.info(TAG + " the transaction_rollback average time is: " + averageTime + " μs"); - expect(averageTime < BASE_LINE).assertTrue(); - done(); - console.info(TAG + "*************Unit Test End*************"); - }) + it('SUB_DDM_PERF_RDB_transaction_rollback_001', 0, async function (done) { + let averageTime = 0; + let startTime = new Date().getTime(); + for (var i = 0; i < BASE_COUNT; i++) { + rdbStore.beginTransaction(); + rdbStore.rollBack(); + } + let endTime = new Date().getTime(); + averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the transaction_rollback average time is: " + averageTime + " μs"); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + console.info(TAG + "*************Unit Test End*************"); + }) }) diff --git a/relational_store/test/js/relationalstore/performance/src/ResultSetPerf.js b/relational_store/test/js/relationalstore/performance/src/ResultSetPerf.js index 15ea1d0d8f7475f7bd1e4abe6245f772c02ab325..797a790627bb38dec55fd72460786ce1547d67d6 100644 --- a/relational_store/test/js/relationalstore/performance/src/ResultSetPerf.js +++ b/relational_store/test/js/relationalstore/performance/src/ResultSetPerf.js @@ -13,18 +13,19 @@ * limitations under the License. */ -import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, Assert } from 'deccjsunit/index'; -import dataRdb from '@ohos.data.rdb'; +import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, Assert} from 'deccjsunit/index'; +import dataRdb from '@ohos.data.relationalStore'; import featureAbility from '@ohos.ability.featureAbility'; import deviceInfo from '@ohos.deviceInfo'; const TAG = "[RDB_RESULTSET_PERF]"; const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (id INTEGER PRIMARY KEY AUTOINCREMENT, " -+ "name TEXT, age INTEGER, salary REAL, blobType BLOB)"; + + "name TEXT, age INTEGER, salary REAL, blobType BLOB)"; const DB_NAME = "resultSetPerf.db"; const STORE_CONFIG = { - name: DB_NAME, + name: DB_NAME, + securityLevel: dataRdb.SecurityLevel.S1 } let context = featureAbility.getContext(); var rdbStore = undefined; @@ -35,260 +36,254 @@ const BASE_LINE_PHONE = 1000; // callback phone base line const BASE_LINE = (deviceInfo.deviceType == "tablet") ? BASE_LINE_TABLE : BASE_LINE_PHONE; describe('resultSetPerf', function () { - beforeAll(async function () { - console.info(TAG + 'beforeAll'); - rdbStore = await dataRdb.getRdbStore(context, STORE_CONFIG, 1); - }) - beforeEach(async function () { - console.info(TAG + 'beforeEach'); - await rdbStore.executeSql(CREATE_TABLE_TEST, null); - await prepareTestData(); - }) - afterEach(async function () { - console.info(TAG + 'afterEach'); - await rdbStore.executeSql("drop table test"); - }) - afterAll(async function () { - console.info(TAG + 'afterAll'); - rdbStore = null; - await dataRdb.deleteRdbStore(context, DB_NAME); - }) + beforeAll(async function () { + console.info(TAG + 'beforeAll'); + rdbStore = await dataRdb.getRdbStore(context, STORE_CONFIG); + }) + beforeEach(async function () { + console.info(TAG + 'beforeEach'); + await rdbStore.executeSql(CREATE_TABLE_TEST, null); + await prepareTestData(); + }) + afterEach(async function () { + console.info(TAG + 'afterEach'); + await rdbStore.executeSql("drop table test"); + }) + afterAll(async function () { + console.info(TAG + 'afterAll'); + rdbStore = null; + await dataRdb.deleteRdbStore(context, DB_NAME); + }) - async function prepareTestData() { - console.info(TAG + "prepare for query performance test"); - var valueBuckets = []; - var u8 = new Uint8Array([1, 2, 3]) - var valueBucket = { - "name": "zhangsan", - "age": 18, - "salary": 100.5, - "blobType": u8, - } - for (let i = 0; i < BASE_COUNT; i++) { - valueBucket.age += i; - valueBuckets.push(valueBucket); - } - rdbStore.batchInsert("test", valueBuckets, function (err, insertNum) { - if (err) { - console.error(`batchInsert is failed, err: ${err}`); - return; - } - console.info(`batchInsert is successful, the number of values that were inserted = ${insertNum}`); - }) + async function prepareTestData() { + console.info(TAG + "prepare for query performance test"); + var valueBuckets = []; + var u8 = new Uint8Array([1, 2, 3]) + var valueBucket = { + "name": "zhangsan", + "age": 18, + "salary": 100.5, + "blobType": u8, } + for (let i = 0; i < BASE_COUNT; i++) { + valueBucket.age += i; + valueBuckets.push(valueBucket); + } + await rdbStore.batchInsert("test", valueBuckets); + } - console.log(TAG + "*************Unit Test Begin*************"); + console.log(TAG + "*************Unit Test Begin*************"); - it('SUB_DDM_PERF_RDB_ResultSet_GetColumnIndex_001', 0, async function (done) { - let predicates = new dataRdb.RdbPredicates("test"); - let resultSet = await rdbStore.query(predicates); - resultSet.goToFirstRow(); - let startTime = new Date().getTime(); - for (let i = 0; i < BASE_LINE; i++) { - resultSet.getColumnIndex("id"); - } - let endTime = new Date().getTime(); - let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; - console.info(TAG + " the ResultSet_GetColumnIndex average time is: " + averageTime + " μs"); - resultSet.close(); - expect(averageTime < BASE_LINE).assertTrue(); - done(); - }) + it('SUB_DDM_PERF_RDB_ResultSet_GetColumnIndex_001', 0, async function (done) { + let predicates = new dataRdb.RdbPredicates("test"); + let resultSet = await rdbStore.query(predicates); + resultSet.goToFirstRow(); + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_LINE; i++) { + resultSet.getColumnIndex("id"); + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the ResultSet_GetColumnIndex average time is: " + averageTime + " μs"); + resultSet.close(); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) - it('SUB_DDM_PERF_RDB_ResultSet_GetColumnName_001', 0, async function (done) { - let predicates = new dataRdb.RdbPredicates("test"); - let resultSet = await rdbStore.query(predicates); - resultSet.goToFirstRow(); - let startTime = new Date().getTime() - for (let i = 0; i < BASE_COUNT; i++) { - resultSet.getColumnName(0); - } - let endTime = new Date().getTime(); - let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; - console.info(TAG + " the ResultSet_GetColumnName average time is: " + averageTime + " μs") - resultSet.close(); - expect(averageTime < BASE_LINE).assertTrue(); - done(); - }) + it('SUB_DDM_PERF_RDB_ResultSet_GetColumnName_001', 0, async function (done) { + let predicates = new dataRdb.RdbPredicates("test"); + let resultSet = await rdbStore.query(predicates); + resultSet.goToFirstRow(); + let startTime = new Date().getTime() + for (let i = 0; i < BASE_COUNT; i++) { + resultSet.getColumnName(0); + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the ResultSet_GetColumnName average time is: " + averageTime + " μs") + resultSet.close(); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) - it('SUB_DDM_PERF_RDB_ResultSet_GoTo_001', 0, async function (done) { - let predicates = new dataRdb.RdbPredicates("test"); - let resultSet = await rdbStore.query(predicates); - resultSet.goToFirstRow(); - let startTime = new Date().getTime() - for (let i = 0; i < BASE_COUNT; i++) { - resultSet.goTo(i % 2); - } - let endTime = new Date().getTime(); - let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; - console.info(TAG + " the ResultSet_GoTo average time is: " + averageTime + " μs") - resultSet.close(); - expect(averageTime < BASE_LINE).assertTrue(); - done(); - }) + it('SUB_DDM_PERF_RDB_ResultSet_GoTo_001', 0, async function (done) { + let predicates = new dataRdb.RdbPredicates("test"); + let resultSet = await rdbStore.query(predicates); + resultSet.goToFirstRow(); + let startTime = new Date().getTime() + for (let i = 0; i < BASE_COUNT; i++) { + resultSet.goTo(i % 2); + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the ResultSet_GoTo average time is: " + averageTime + " μs") + resultSet.close(); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) - it('SUB_DDM_PERF_RDB_ResultSet_GoToRow_001', 0, async function (done) { - let predicates = new dataRdb.RdbPredicates("test"); - let resultSet = await rdbStore.query(predicates); - resultSet.goToFirstRow(); - let startTime = new Date().getTime(); - for (let i = 0; i < BASE_COUNT; i++) { - resultSet.goToRow(1); - } - let endTime = new Date().getTime(); - let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; - console.info(TAG + " the ResultSet_GoToRow average time is: " + averageTime + " μs"); - resultSet.close(); - expect(averageTime < BASE_LINE).assertTrue(); - done(); - }) + it('SUB_DDM_PERF_RDB_ResultSet_GoToRow_001', 0, async function (done) { + let predicates = new dataRdb.RdbPredicates("test"); + let resultSet = await rdbStore.query(predicates); + resultSet.goToFirstRow(); + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT; i++) { + resultSet.goToRow(1); + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the ResultSet_GoToRow average time is: " + averageTime + " μs"); + resultSet.close(); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) - it('SUB_DDM_PERF_RDB_ResultSet_GoToFirstRow_001', 0, async function (done) { - let predicates = new dataRdb.RdbPredicates("test"); - let resultSet = await rdbStore.query(predicates); - let startTime = new Date().getTime(); - for (let i = 0; i < BASE_COUNT; i++) { - resultSet.goToFirstRow(); - } - let endTime = new Date().getTime(); - let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; - console.info(TAG + " the ResultSet_GoToFirstRow average time is: " + averageTime + " μs"); - resultSet.close(); - expect(averageTime < BASE_LINE).assertTrue(); - done(); - }) + it('SUB_DDM_PERF_RDB_ResultSet_GoToFirstRow_001', 0, async function (done) { + let predicates = new dataRdb.RdbPredicates("test"); + let resultSet = await rdbStore.query(predicates); + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT; i++) { + resultSet.goToFirstRow(); + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the ResultSet_GoToFirstRow average time is: " + averageTime + " μs"); + resultSet.close(); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) - it('SUB_DDM_PERF_RDB_ResultSet_GoToLastRow_001', 0, async function (done) { - let predicates = new dataRdb.RdbPredicates("test"); - let resultSet = await rdbStore.query(predicates); - let startTime = new Date().getTime(); - for (let i = 0; i < BASE_COUNT; i++) { - resultSet.goToLastRow(); - } - let endTime = new Date().getTime(); - let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; - console.info(TAG + " the ResultSet_GoToLastRow average time is: " + averageTime + " μs"); - resultSet.close(); - expect(averageTime < BASE_LINE).assertTrue(); - done(); - }) + it('SUB_DDM_PERF_RDB_ResultSet_GoToLastRow_001', 0, async function (done) { + let predicates = new dataRdb.RdbPredicates("test"); + let resultSet = await rdbStore.query(predicates); + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT; i++) { + resultSet.goToLastRow(); + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the ResultSet_GoToLastRow average time is: " + averageTime + " μs"); + resultSet.close(); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) - it('SUB_DDM_PERF_RDB_ResultSet_GoToNextRow_001', 0, async function (done) { - let predicates = new dataRdb.RdbPredicates("test"); - let resultSet = await rdbStore.query(predicates); - resultSet.goToFirstRow(); - let startTime = new Date().getTime(); - for (let i = 0; i < BASE_COUNT; i++) { - resultSet.goToNextRow(); - } - let endTime = new Date().getTime(); - let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; - console.info(TAG + " the ResultSet_GoToNextRow average time is: " + averageTime + " μs") - resultSet.close(); - expect(averageTime < BASE_LINE).assertTrue(); - done(); - }) + it('SUB_DDM_PERF_RDB_ResultSet_GoToNextRow_001', 0, async function (done) { + let predicates = new dataRdb.RdbPredicates("test"); + let resultSet = await rdbStore.query(predicates); + resultSet.goToFirstRow(); + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT; i++) { + resultSet.goToNextRow(); + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the ResultSet_GoToNextRow average time is: " + averageTime + " μs") + resultSet.close(); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) - it('SUB_DDM_PERF_RDB_ResultSet_GoToPreviousRow_001', 0, async function (done) { - let predicates = new dataRdb.RdbPredicates("test"); - let resultSet = await rdbStore.query(predicates); - resultSet.goToLastRow(); - let startTime = new Date().getTime(); - for (let i = 0; i < BASE_COUNT; i++) { - resultSet.goToPreviousRow(); - } - let endTime = new Date().getTime(); - let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; - console.info(TAG + " the ResultSet_GoToPreviousRow average time is: " + averageTime + " μs"); - resultSet.close(); - expect(averageTime < BASE_LINE).assertTrue(); - done(); - }) + it('SUB_DDM_PERF_RDB_ResultSet_GoToPreviousRow_001', 0, async function (done) { + let predicates = new dataRdb.RdbPredicates("test"); + let resultSet = await rdbStore.query(predicates); + resultSet.goToLastRow(); + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT; i++) { + resultSet.goToPreviousRow(); + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the ResultSet_GoToPreviousRow average time is: " + averageTime + " μs"); + resultSet.close(); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) - it('SUB_DDM_PERF_RDB_ResultSet_GetBlob_001', 0, async function (done) { - let predicates = new dataRdb.RdbPredicates("test"); - let resultSet = await rdbStore.query(predicates); - let columnIndex = resultSet.getColumnIndex("blobType"); - resultSet.goToFirstRow(); - let startTime = new Date().getTime() - for (let i = 0; i < BASE_COUNT; i++) { - resultSet.getBlob(columnIndex); - } - let endTime = new Date().getTime(); - let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; - console.info(TAG + " the ResultSet_GetBlob average time is: " + averageTime + " μs"); - resultSet.close(); - expect(averageTime < BASE_LINE).assertTrue(); - done(); - }) + it('SUB_DDM_PERF_RDB_ResultSet_GetBlob_001', 0, async function (done) { + let predicates = new dataRdb.RdbPredicates("test"); + let resultSet = await rdbStore.query(predicates); + let columnIndex = resultSet.getColumnIndex("blobType"); + resultSet.goToFirstRow(); + let startTime = new Date().getTime() + for (let i = 0; i < BASE_COUNT; i++) { + resultSet.getBlob(columnIndex); + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the ResultSet_GetBlob average time is: " + averageTime + " μs"); + resultSet.close(); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) - it('SUB_DDM_PERF_RDB_ResultSet_GetString_001', 0, async function (done) { - let predicates = new dataRdb.RdbPredicates("test"); - let resultSet = await rdbStore.query(predicates); - let columnIndex = resultSet.getColumnIndex("name"); - let flag = resultSet.goToFirstRow(); - let startTime = new Date().getTime(); - for (var i = 0; i < SPECIAL_BASE_COUNT; i++) { - resultSet.getString(columnIndex); - } - let endTime = new Date().getTime(); - let averageTime = ((endTime - startTime) * 1000) / SPECIAL_BASE_COUNT; - console.info(TAG + " the ResultSet_GetString average time is: " + averageTime + " μs"); - resultSet.close(); - expect(averageTime < BASE_LINE).assertTrue(); - done() - }) + it('SUB_DDM_PERF_RDB_ResultSet_GetString_001', 0, async function (done) { + let predicates = new dataRdb.RdbPredicates("test"); + let resultSet = await rdbStore.query(predicates); + let columnIndex = resultSet.getColumnIndex("name"); + let flag = resultSet.goToFirstRow(); + let startTime = new Date().getTime(); + for (var i = 0; i < SPECIAL_BASE_COUNT; i++) { + resultSet.getString(columnIndex); + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / SPECIAL_BASE_COUNT; + console.info(TAG + " the ResultSet_GetString average time is: " + averageTime + " μs"); + resultSet.close(); + expect(averageTime < BASE_LINE).assertTrue(); + done() + }) - it('SUB_DDM_PERF_RDB_ResultSet_GetLong_001', 0, async function (done) { - let predicates = new dataRdb.RdbPredicates("test"); - let resultSet = await rdbStore.query(predicates); - let columnIndex = resultSet.getColumnIndex("age"); - resultSet.goToFirstRow(); - let startTime = new Date().getTime(); - for (let i = 0; i < BASE_COUNT; i++) { - resultSet.getLong(columnIndex); - } - let endTime = new Date().getTime(); - let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; - console.info(TAG + " the ResultSet_GetLong average time is: " + averageTime + " μs") - resultSet.close(); - expect(averageTime < BASE_LINE).assertTrue(); - done(); - }) + it('SUB_DDM_PERF_RDB_ResultSet_GetLong_001', 0, async function (done) { + let predicates = new dataRdb.RdbPredicates("test"); + let resultSet = await rdbStore.query(predicates); + let columnIndex = resultSet.getColumnIndex("age"); + resultSet.goToFirstRow(); + let startTime = new Date().getTime(); + for (let i = 0; i < BASE_COUNT; i++) { + resultSet.getLong(columnIndex); + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the ResultSet_GetLong average time is: " + averageTime + " μs") + resultSet.close(); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) - it('SUB_DDM_PERF_RDB_ResultSet_GetDouble_001', 0, async function (done) { - let predicates = new dataRdb.RdbPredicates("test"); - let resultSet = await rdbStore.query(predicates); - let columnIndex = resultSet.getColumnIndex("salary"); - resultSet.goToFirstRow(); - let startTime = new Date().getTime() - for (let i = 0; i < BASE_COUNT; i++) { - resultSet.getDouble(columnIndex); - } - let endTime = new Date().getTime(); - let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; - console.info(TAG + " the ResultSet_GetDouble average time is: " + averageTime + " μs") - resultSet.close(); - expect(averageTime < BASE_LINE).assertTrue(); - done(); - }) + it('SUB_DDM_PERF_RDB_ResultSet_GetDouble_001', 0, async function (done) { + let predicates = new dataRdb.RdbPredicates("test"); + let resultSet = await rdbStore.query(predicates); + let columnIndex = resultSet.getColumnIndex("salary"); + resultSet.goToFirstRow(); + let startTime = new Date().getTime() + for (let i = 0; i < BASE_COUNT; i++) { + resultSet.getDouble(columnIndex); + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the ResultSet_GetDouble average time is: " + averageTime + " μs") + resultSet.close(); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) - it('SUB_DDM_PERF_RDB_ResultSet_IsColumnNull_001', 0, async function (done) { - let predicates = new dataRdb.RdbPredicates("test"); - let resultSet = await rdbStore.query(predicates); - let columnIndex = resultSet.getColumnIndex("salary"); - resultSet.goToFirstRow(); - let startTime = new Date().getTime() - for (let i = 0; i < BASE_COUNT; i++) { - resultSet.isColumnNull(columnIndex); - } - let endTime = new Date().getTime(); - let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; - console.info(TAG + " the ResultSet_IsColumnNull average time is: " + averageTime + " μs"); - resultSet.close(); - expect(averageTime < BASE_LINE).assertTrue(); - done(); - }) + it('SUB_DDM_PERF_RDB_ResultSet_IsColumnNull_001', 0, async function (done) { + let predicates = new dataRdb.RdbPredicates("test"); + let resultSet = await rdbStore.query(predicates); + let columnIndex = resultSet.getColumnIndex("salary"); + resultSet.goToFirstRow(); + let startTime = new Date().getTime() + for (let i = 0; i < BASE_COUNT; i++) { + resultSet.isColumnNull(columnIndex); + } + let endTime = new Date().getTime(); + let averageTime = ((endTime - startTime) * 1000) / BASE_COUNT; + console.info(TAG + " the ResultSet_IsColumnNull average time is: " + averageTime + " μs"); + resultSet.close(); + expect(averageTime < BASE_LINE).assertTrue(); + done(); + }) - console.info(TAG + "*************Unit Test End*************"); + console.info(TAG + "*************Unit Test End*************"); }) \ No newline at end of file diff --git a/relational_store/test/js/relationalstore/performance/src/SceneGetValuesBucketPerf.js b/relational_store/test/js/relationalstore/performance/src/SceneGetValuesBucketPerf.js new file mode 100644 index 0000000000000000000000000000000000000000..33aa0de7e28f031f35f63c49fbeec18c2ed48faa --- /dev/null +++ b/relational_store/test/js/relationalstore/performance/src/SceneGetValuesBucketPerf.js @@ -0,0 +1,197 @@ +/* + * Copyright (C) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, Assert} from 'deccjsunit/index'; +import dataRdb from '@ohos.data.relationalStore'; +import featureAbility from '@ohos.ability.featureAbility'; + +const TAG = "[RDB_RESULTSET_PERF]"; +const CREATE_TABLE_TEST = "CREATE TABLE test (" + + "data01 TEXT, data02 INTEGER, data03 FLOAT, data04 BLOB, data05 BOOLEAN, " + + "data06 TEXT, data07 INTEGER, data08 FLOAT, data09 BLOB, data10 BOOLEAN, " + + "data11 TEXT, data12 INTEGER, data13 FLOAT, data14 BLOB, data15 BOOLEAN, " + + "data16 TEXT, data17 INTEGER, data18 FLOAT, data19 BLOB, data20 BOOLEAN" + + ");"; + +const FIELDS = ["data01", "data02", "data03", "data04", "data05", "data06", "data07", "data08", "data09", "data10", + "data11", "data12", "data13", "data14", "data15", "data16", "data17", "data18", "data19", "data20"] + +function CREATE_STRING(len) { + let result = ''; + for (let i = 0; i < len; i++) { + result += 'a'; + } + return result; +} + +const CONST_STRING_VALUE = CREATE_STRING(127); + +function CREATE_UINT8_ARRAY(len) { + let result = new Uint8Array(len); + for (let i = 0; i < len; i++) { + result[i] = 1; + } + return result; +} + +const CONST_UINT8_ARRAY = CREATE_UINT8_ARRAY(127); + +const DB_NAME = "resultSetPerf.db"; +const STORE_CONFIG = { + name: DB_NAME, + securityLevel: dataRdb.SecurityLevel.S3 +} + +let context = featureAbility.getContext(); +let rdbStore = undefined; +const BASE_COUNT = 2000; // loop times + +describe('SceneGetValuesBucketPerf', function () { + beforeAll(async function () { + console.info(TAG + 'beforeAll'); + rdbStore = await dataRdb.getRdbStore(context, STORE_CONFIG); + await rdbStore.executeSql(CREATE_TABLE_TEST); + await prepareTestData(); + }) + + beforeEach(async function () { + console.info(TAG + 'beforeEach'); + }) + + afterEach(async function () { + console.info(TAG + 'afterEach'); + }) + + afterAll(async function () { + console.info(TAG + 'afterAll'); + await rdbStore.executeSql("drop table test"); + rdbStore = null; + await dataRdb.deleteRdbStore(context, DB_NAME); + }) + + async function prepareTestData() { + console.info(TAG + "prepare for query performance test"); + let valueBuckets = []; + let valueBucket = { + data01: CONST_STRING_VALUE, + data02: 10001, + data03: 101.5, + data04: CONST_UINT8_ARRAY, + data05: false, + data06: CONST_STRING_VALUE, + data07: 10002, + data08: 102.5, + data09: CONST_UINT8_ARRAY, + data10: true, + data11: CONST_STRING_VALUE, + data12: 10003, + data13: 103.5, + data14: CONST_UINT8_ARRAY, + data15: false, + data16: CONST_STRING_VALUE, + data17: 10004, + data18: 104.5, + data19: CONST_UINT8_ARRAY, + data20: true + } + for (let i = 0; i < BASE_COUNT; i++) { + valueBuckets.push(valueBucket); + } + await rdbStore.batchInsert("test", valueBuckets) + } + + it('Scene_GetValuesBucket_0001', 0, async function (done) { + console.log(TAG + "************* Scene_GetValuesBucket_0001 start *************"); + let predicates = await new dataRdb.RdbPredicates("test") + let resultSet = await rdbStore.query(predicates) + expect(2000).assertEqual(resultSet.rowCount); + + let startTime = new Date().getTime(); + let allValues = new Array(); + let i = 0; + while (resultSet.goToNextRow()) { + let values = resultSet.getRow(); + allValues[i++] = values; + } + resultSet.close(); + let endTime = new Date().getTime(); + let averageTime = (endTime - startTime); + console.info(TAG + " the Scene_GetValuesBucket_0001 average time is: " + averageTime + " ms"); + expect(2000).assertEqual(allValues.length); + expect(averageTime).assertLess(600); + + expect(CONST_STRING_VALUE).assertEqual(allValues[0]["data01"]); + done(); + console.log(TAG + "************* Scene_GetValuesBucket_0001 end *************"); + }) + + /** + * @tc.name RDB Backup Restore test + * @tc.number SUB_DDM_RDB_JS_RdbBackupRestoreTest_0010 + * @tc.desc RDB backup and restore function test + */ + it('Scene_GetValuesBucket_0002', 0, async function (done) { + console.log(TAG + "************* Scene_GetValuesBucket_0002 start *************"); + let predicates = await new dataRdb.RdbPredicates("test") + let resultSet = await rdbStore.query(predicates) + expect(2000).assertEqual(resultSet.rowCount); + + let startTime = new Date().getTime(); + let allValues = new Array(2000); + + let i = 0; + let indexes = new Array(20); + while (resultSet.goToNextRow()) { + let values = new Array(); + + if (i == 0) { + for (let i = 0; i < 20; i++) { + indexes[i] = resultSet.getColumnIndex(FIELDS[i]); + } + } + + for (let i = 0; i < 20; i++) { + switch (resultSet.getColumnType(indexes[i])) { + case 0: // TYPE_NULL + values[FIELDS[i]] = null; + break; + case 1: // TYPE_INTEGER + values[FIELDS[i]] = resultSet.getInt(indexes[i]); + break; + case 2: // TYPE_FLOAT + values[FIELDS[i]] = resultSet.getDouble(indexes[i]); + break; + case 3: // TYPE_STRING + values[FIELDS[i]] = resultSet.getString(indexes[i]); + break; + case 4: // TYPE_BLOB + values[FIELDS[i]] = resultSet.getBlob(indexes[i]); + break; + } + } + allValues[i++] = values; + } + resultSet.close(); + let endTime = new Date().getTime(); + let averageTime = (endTime - startTime); + console.info(TAG + " the Scene_GetValuesBucket_0002 average time is: " + averageTime + " ms"); + expect(2000).assertEqual(allValues.length); + expect(averageTime).assertLess(1500); + + expect(CONST_STRING_VALUE).assertEqual(allValues[0]["data01"]); + done(); + console.log(TAG + "************* Scene_GetValuesBucket_0002 end *************"); + }) +}) \ No newline at end of file diff --git a/relational_store/test/js/relationalstore/unittest/src/RdbStoreResultSetGetRow.test.js b/relational_store/test/js/relationalstore/unittest/src/RdbStoreResultSetGetRow.test.js new file mode 100644 index 0000000000000000000000000000000000000000..76d4c1672882fa942ccc30d71f4b2667580baff2 --- /dev/null +++ b/relational_store/test/js/relationalstore/unittest/src/RdbStoreResultSetGetRow.test.js @@ -0,0 +1,182 @@ +/* + * Copyright (C) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' +import data_relationalStore from '@ohos.data.relationalStore'; +import ability_featureAbility from '@ohos.ability.featureAbility' + +var context = ability_featureAbility.getContext() + +const TAG = "[RELATIONAL_STORE_JSKITS_TEST]" + +const STORE_CONFIG = { + name: "stepResultSet_getRow_test.db", + securityLevel: data_relationalStore.SecurityLevel.S1, +} +let rdbStore +describe('rdbStoreResultSetGetRowTest', function () { + beforeAll(async function () { + console.info(TAG + 'beforeAll') + await data_relationalStore.deleteRdbStore(context, "stepResultSet_getRow_test.db"); + rdbStore = await data_relationalStore.getRdbStore(context, STORE_CONFIG); + }) + + beforeEach(async function () { + console.info(TAG + 'beforeEach') + await rdbStore.executeSql("CREATE TABLE test (id INTEGER PRIMARY KEY AUTOINCREMENT, data1 TEXT, " + + "data2 INTEGER, data3 FLOAT, data4 BLOB, data5 BOOLEAN);"); + }) + + afterEach(async function () { + console.info(TAG + 'afterEach') + await rdbStore.executeSql("DROP TABLE IF EXISTS test"); + }) + + afterAll(async function () { + console.info(TAG + 'afterAll') + await data_relationalStore.deleteRdbStore(context, "stepResultSet_getRow_test.db"); + }) + + console.log(TAG + "*************Unit Test Begin*************"); + + /** + * @tc.name rdb store resultSet getRow test + * @tc.number rdbStoreResultSetGetRowTest0001 + * @tc.desc resultSet getRow test + */ + it('rdbStoreResultSetGetRowTest0001', 0, async function (done) { + console.log(TAG + "************* rdbStoreResultSetGetRowTest0001 start *************"); + let valueBucket = { + id: 1 + }; + let rowId = await rdbStore.insert("test", valueBucket); + expect(1).assertEqual(rowId); + + let predicates = await new data_relationalStore.RdbPredicates("test") + let resultSet = await rdbStore.query(predicates) + expect(true).assertEqual(resultSet.goToFirstRow()); + + let valueBucket_ret = resultSet.getRow(); + + expect(1).assertEqual(valueBucket_ret["id"]); + expect(null).assertEqual(valueBucket_ret["data1"]); + expect(null).assertEqual(valueBucket_ret["data2"]); + expect(null).assertEqual(valueBucket_ret["data3"]); + expect(null).assertEqual(valueBucket_ret["data4"]); + expect(null).assertEqual(valueBucket_ret["data5"]); + + done(); + console.log(TAG + "************* rdbStoreResultSetGetRowTest0001 end *************"); + }) + + /** + * @tc.name rdb store resultSet getRow test + * @tc.number rdbStoreResultSetGetRowTest0002 + * @tc.desc resultSet getRow test + */ + it('rdbStoreResultSetGetRowTest0002', 0, async function (done) { + console.log(TAG + "************* rdbStoreResultSetGetRowTest0002 start *************"); + let valueBucket = { + data1: null, + data2: undefined, + data4: undefined, + data5: null + }; + let rowId = await rdbStore.insert("test", valueBucket); + expect(1).assertEqual(rowId); + + let predicates = await new data_relationalStore.RdbPredicates("test") + let resultSet = await rdbStore.query(predicates) + expect(true).assertEqual(resultSet.goToFirstRow()); + + let valueBucket_ret = resultSet.getRow(); + + expect(1).assertEqual(valueBucket_ret["id"]); + expect(null).assertEqual(valueBucket_ret["data1"]); + expect(null).assertEqual(valueBucket_ret["data2"]); + expect(null).assertEqual(valueBucket_ret["data3"]); + expect(null).assertEqual(valueBucket_ret["data4"]); + expect(null).assertEqual(valueBucket_ret["data5"]); + + done(); + console.log(TAG + "************* rdbStoreResultSetGetRowTest0002 end *************"); + }) + + /** + * @tc.name rdb store resultSet getRow test + * @tc.number rdbStoreResultSetGetRowTest0003 + * @tc.desc resultSet getRow test + */ + it('rdbStoreResultSetGetRowTest0003', 0, async function (done) { + console.log(TAG + "************* rdbStoreResultSetGetRowTest0003 start *************"); + let valueBucket = { + data1: "hello", + data2: 10, + data3: 1.0, + data4: new Uint8Array([1, 2, 3, 4]), + data5: true, + }; + let rowId = await rdbStore.insert("test", valueBucket); + expect(1).assertEqual(rowId); + + let predicates = await new data_relationalStore.RdbPredicates("test") + let resultSet = await rdbStore.query(predicates) + expect(true).assertEqual(resultSet.goToFirstRow()); + + let valueBucket_ret = resultSet.getRow(); + + expect(1).assertEqual(valueBucket_ret.id); + expect("hello").assertEqual(valueBucket_ret.data1); + expect(10).assertEqual(valueBucket_ret.data2); + expect(1.0).assertEqual(valueBucket_ret.data3); + expect(4).assertEqual(valueBucket_ret.data4[3]); + expect(1).assertEqual(valueBucket_ret.data5); + + done(); + console.log(TAG + "************* rdbStoreResultSetGetRowTest0003 end *************"); + }) + + /** + * @tc.name rdb store resultSet getRow test + * @tc.number rdbStoreResultSetGetRowTest0004 + * @tc.desc resultSet getRow test + */ + it('rdbStoreResultSetGetRowTest0004', 0, async function (done) { + console.log(TAG + "************* rdbStoreResultSetGetRowTest0004 start *************"); + let valueBucket = { + "data1": "", + "data2": 10, + "data3": 1.0, + "data4": new Uint8Array([1, 2, 3, 4]), + "data5": true, + }; + let rowId = await rdbStore.insert("test", valueBucket); + expect(1).assertEqual(rowId); + + let predicates = await new data_relationalStore.RdbPredicates("test") + let resultSet = await rdbStore.query(predicates, ["data1", "data2"]) + expect(true).assertEqual(resultSet.goToFirstRow()); + + let valueBucket_ret = resultSet.getRow(); + + expect("").assertEqual(valueBucket_ret.data1); + expect(undefined).assertEqual(valueBucket_ret.data3); + expect(undefined).assertEqual(valueBucket_ret.data4); + + done(); + console.log(TAG + "************* rdbStoreResultSetGetRowTest0004 end *************"); + }) + console.log(TAG + "*************Unit Test End*************"); +}) \ No newline at end of file diff --git a/relational_store/test/js/relationalstore/unittest/src/RdbStoreResultSetJsunit.test.js b/relational_store/test/js/relationalstore/unittest/src/RdbStoreResultSetJsunit.test.js index 271bd11f555ac76d5eaf399b18c4b62845bf114c..fb02dbec7cf1a6c60c8aa291023706002f7127ba 100644 --- a/relational_store/test/js/relationalstore/unittest/src/RdbStoreResultSetJsunit.test.js +++ b/relational_store/test/js/relationalstore/unittest/src/RdbStoreResultSetJsunit.test.js @@ -2274,43 +2274,5 @@ describe('rdbResultSetTest', function () { console.log(TAG + "************* testBigData0014 end *************"); }) - - /** - * @tc.name resultSet Maximum read connections normal test - * @tc.number Maximum_Read_Connections_0001 - * @tc.desc resultSet getBlob normal test - */ - it('testMaximumReadConnections0001', 0, async function (done) { - console.log(TAG + "************* testMaximumReadConnections0002 start *************"); - - try{ - let resultSet1 = await rdbStore.queryByStep("SELECT ?, ? FROM test", ["id", "data1"]) - expect(true).assertEqual(resultSet1.goToFirstRow()) - - let resultSet2 = await rdbStore.queryByStep("SELECT ?, ? FROM test", ["id", "data1"]) - expect(true).assertEqual(resultSet2.goToFirstRow()) - - let resultSet3 = await rdbStore.queryByStep("SELECT ?, ? FROM test", ["id", "data1"]) - expect(true).assertEqual(resultSet3.goToFirstRow()) - - let resultSet4 = await rdbStore.queryByStep("SELECT ?, ? FROM test", ["id", "data1"]) - expect(true).assertEqual(resultSet4.goToFirstRow()) - - resultSet1.close(); - resultSet2.close(); - resultSet3.close(); - resultSet4.close(); - - resultSet1 = null; - resultSet2 = null; - resultSet3 = null; - resultSet4 = null; - } catch (e) { - expect(null).assertFail(); - } - done(); - console.log(TAG + "************* testMaximumReadConnections0001 end *************"); - }) - console.log(TAG + "*************Unit Test End*************"); }) \ No newline at end of file diff --git a/relational_store/test/native/rdb/BUILD.gn b/relational_store/test/native/rdb/BUILD.gn index 3bed308b4d83a2bbd260228d6b748f9381854aad..f6d223dac1dad1624c9918a599dbbdb1c66891fe 100644 --- a/relational_store/test/native/rdb/BUILD.gn +++ b/relational_store/test/native/rdb/BUILD.gn @@ -52,6 +52,7 @@ ohos_unittest("NativeRdbTest") { "unittest/rdb_predicates_join_test.cpp", "unittest/rdb_predicates_test.cpp", "unittest/rdb_sqlite_shared_result_set_test.cpp", + "unittest/rdb_step_result_get_row_test.cpp", "unittest/rdb_step_result_set_test.cpp", "unittest/rdb_store_concurrent_test.cpp", "unittest/rdb_store_config_test.cpp", diff --git a/relational_store/test/native/rdb/unittest/rdb_execute_test.cpp b/relational_store/test/native/rdb/unittest/rdb_execute_test.cpp index cec0a0d9ab3741e978bd08e5e94703d53131c267..9b486e439cc3feaafda774019eef8f217a60aa5f 100644 --- a/relational_store/test/native/rdb/unittest/rdb_execute_test.cpp +++ b/relational_store/test/native/rdb/unittest/rdb_execute_test.cpp @@ -35,12 +35,10 @@ public: static const std::string DATABASE_NAME; static std::shared_ptr store; - static const int E_SQLITE_ERROR; // errno SQLITE_ERROR }; const std::string RdbExecuteTest::DATABASE_NAME = RDB_TEST_PATH + "execute_test.db"; std::shared_ptr RdbExecuteTest::store = nullptr; -const int RdbExecuteTest::E_SQLITE_ERROR = -1; // errno SQLITE_ERROR class ExecuteTestOpenCallback : public RdbOpenCallback { public: diff --git a/relational_store/test/native/rdb/unittest/rdb_sqlite_shared_result_set_test.cpp b/relational_store/test/native/rdb/unittest/rdb_sqlite_shared_result_set_test.cpp index 8b3853db6efca9bc187065ffddfe4a760b022caf..f3c28b3300af0ba0a60d069ccd4413bcc470c466 100644 --- a/relational_store/test/native/rdb/unittest/rdb_sqlite_shared_result_set_test.cpp +++ b/relational_store/test/native/rdb/unittest/rdb_sqlite_shared_result_set_test.cpp @@ -36,12 +36,10 @@ public: static const std::string DATABASE_NAME; static std::shared_ptr store; - static const int E_SQLITE_ERROR; }; const std::string RdbSqliteSharedResultSetTest::DATABASE_NAME = RDB_TEST_PATH + "shared_test.db"; std::shared_ptr RdbSqliteSharedResultSetTest::store = nullptr; -const int RdbSqliteSharedResultSetTest::E_SQLITE_ERROR = -1; class SqliteSharedOpenCallback : public RdbOpenCallback { public: @@ -943,4 +941,76 @@ HWTEST_F(RdbSqliteSharedResultSetTest, Sqlite_Shared_Result_Set_018, TestSize.Le resultSet->Close(); bool closeFlag = resultSet->IsClosed(); EXPECT_EQ(closeFlag, true); +} + +/* * + * @tc.name: Sqlite_Shared_Result_Set_019 + * @tc.desc: normal testcase of SqliteSharedResultSet for GetRow + * @tc.type: FUNC + * @tc.require: AR000FKD4F + */ +HWTEST_F(RdbSqliteSharedResultSetTest, Sqlite_Shared_Result_Set_019, TestSize.Level1) +{ + GenerateDefaultTable(); + std::vector selectionArgs; + std::unique_ptr resultSet = + RdbSqliteSharedResultSetTest::store->QuerySql("SELECT * FROM test", selectionArgs); + EXPECT_NE(resultSet, nullptr); + + EXPECT_EQ(E_OK, resultSet->GoToFirstRow()); + + int iRet = E_ERROR; + RowEntity rowEntity; + iRet = resultSet->GetRow(rowEntity); + EXPECT_EQ(E_OK, iRet); + + int idValue = rowEntity.Get("id"); + std::string data1Value = rowEntity.Get("data1"); + int data2Value = rowEntity.Get("data2"); + double data3Value = rowEntity.Get("data3"); + std::vector data4Value = rowEntity.Get("data4"); + EXPECT_EQ(1, idValue); + EXPECT_EQ("hello", data1Value); + EXPECT_EQ(10, data2Value); + EXPECT_EQ(1.0, data3Value); + EXPECT_EQ(66, data4Value[0]); + + int idValueByIndex = rowEntity.Get(0); + std::string data1ValueByIndex = rowEntity.Get(1); + int data2ValueByIndex = rowEntity.Get(2); + double data3ValueByIndex = rowEntity.Get(3); + std::vector data4ValueByIndex = rowEntity.Get(4); + EXPECT_EQ(1, idValueByIndex); + EXPECT_EQ("hello", data1ValueByIndex); + EXPECT_EQ(10, data2ValueByIndex); + EXPECT_EQ(1.0, data3ValueByIndex); + EXPECT_EQ(66, data4ValueByIndex[0]); +} + +/* * + * @tc.name: Sqlite_Shared_Result_Set_020 + * @tc.desc: normal testcase of SqliteSharedResultSet for GetRow + * @tc.type: FUNC + * @tc.require: AR000FKD4F + */ +HWTEST_F(RdbSqliteSharedResultSetTest, Sqlite_Shared_Result_Set_020, TestSize.Level1) +{ + GenerateDefaultTable(); + std::vector selectionArgs; + std::unique_ptr resultSet = + RdbSqliteSharedResultSetTest::store->QuerySql("SELECT data1, data2 FROM test", selectionArgs); + EXPECT_NE(resultSet, nullptr); + + EXPECT_EQ(E_OK, resultSet->GoToFirstRow()); + + int iRet = E_ERROR; + RowEntity rowEntity; + iRet = resultSet->GetRow(rowEntity); + EXPECT_EQ(E_OK, iRet); + + std::string data1Value = rowEntity.Get("data1"); + EXPECT_EQ("hello", data1Value); + + std::string data1ValueByIndex = rowEntity.Get(0); + EXPECT_EQ("hello", data1ValueByIndex); } \ No newline at end of file diff --git a/relational_store/test/native/rdb/unittest/rdb_step_result_get_row_test.cpp b/relational_store/test/native/rdb/unittest/rdb_step_result_get_row_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6b564e018f37c08a91a57175c6e63d4180db3353 --- /dev/null +++ b/relational_store/test/native/rdb/unittest/rdb_step_result_get_row_test.cpp @@ -0,0 +1,254 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include + +#include "common.h" +#include "logger.h" +#include "rdb_errno.h" +#include "rdb_helper.h" +#include "rdb_open_callback.h" + +using namespace testing::ext; +using namespace OHOS::NativeRdb; + +class RdbStepResultSetGetRowTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + + static const std::string DATABASE_NAME; + static std::shared_ptr store; +}; + +const std::string RdbStepResultSetGetRowTest::DATABASE_NAME = RDB_TEST_PATH + "stepResultSet_getRow_test.db"; +std::shared_ptr RdbStepResultSetGetRowTest::store = nullptr; + +class RdbStepResultSetGetOpenCallback : public RdbOpenCallback { +public: + int OnCreate(RdbStore &rdbStore) override; + int OnUpgrade(RdbStore &rdbStore, int oldVersion, int newVersion) override; +}; + +int RdbStepResultSetGetOpenCallback::OnCreate(RdbStore &store) +{ + return E_OK; +} + +int RdbStepResultSetGetOpenCallback::OnUpgrade(RdbStore &store, int oldVersion, int newVersion) +{ + return E_OK; +} + +void RdbStepResultSetGetRowTest::SetUpTestCase(void) +{ + int errCode = E_OK; + RdbHelper::DeleteRdbStore(DATABASE_NAME); + RdbStoreConfig config(RdbStepResultSetGetRowTest::DATABASE_NAME); + RdbStepResultSetGetOpenCallback helper; + RdbStepResultSetGetRowTest::store = RdbHelper::GetRdbStore(config, 1, helper, errCode); + EXPECT_NE(RdbStepResultSetGetRowTest::store, nullptr); + EXPECT_EQ(errCode, E_OK); +} + +void RdbStepResultSetGetRowTest::TearDownTestCase(void) +{ + RdbHelper::ClearCache(); + RdbHelper::DeleteRdbStore(RdbStepResultSetGetRowTest::DATABASE_NAME); +} + +void RdbStepResultSetGetRowTest::SetUp(void) +{ + store->ExecuteSql("CREATE TABLE test (id INTEGER PRIMARY KEY AUTOINCREMENT, data1 TEXT, " + "data2 INTEGER, data3 FLOAT, data4 BLOB, data5 BOOLEAN);"); +} + +void RdbStepResultSetGetRowTest::TearDown(void) +{ + store->ExecuteSql("DROP TABLE IF EXISTS test"); +} + +/* * + * @tc.name: RdbStore_StepResultSet_GetRow_001 + * @tc.desc: test StepResultSet GetRow + * @tc.type: FUNC + * @tc.require: AR000FKD4F + */ +HWTEST_F(RdbStepResultSetGetRowTest, RdbStore_StepResultSet_GetRow_001, TestSize.Level1) +{ + int64_t rowId; + ValuesBucket valuesBucket; + valuesBucket.PutInt("id", ValueObject(1)); + int errorCode = RdbStepResultSetGetRowTest::store->Insert(rowId, "test", valuesBucket); + EXPECT_EQ(E_OK, errorCode); + EXPECT_EQ(1, rowId); + + std::unique_ptr resultSet = RdbStepResultSetGetRowTest::store->QueryByStep("SELECT * FROM test"); + EXPECT_NE(resultSet, nullptr); + + EXPECT_EQ(E_OK, resultSet->GoToFirstRow()); + + int iRet = E_ERROR; + RowEntity rowEntity; + iRet = resultSet->GetRow(rowEntity); + EXPECT_EQ(E_OK, iRet); + + int idValue = rowEntity.Get("id"); + EXPECT_EQ(1, idValue); + + int idValueByIndex = rowEntity.Get(0); + EXPECT_EQ(1, idValueByIndex); + + resultSet->Close(); +} + +/* * + * @tc.name: RdbStore_StepResultSet_GetRow_002 + * @tc.desc: test StepResultSet GetRow + * @tc.type: FUNC + * @tc.require: AR000FKD4F + */ +HWTEST_F(RdbStepResultSetGetRowTest, RdbStore_StepResultSet_GetRow_002, TestSize.Level1) +{ + ValuesBucket valuesBucket; + valuesBucket.PutNull("data1"); + valuesBucket.PutNull("data2"); + valuesBucket.PutNull("data3"); + valuesBucket.PutNull("data4"); + valuesBucket.PutNull("data5"); + int64_t rowId; + int errorCode = RdbStepResultSetGetRowTest::store->Insert(rowId, "test", valuesBucket); + EXPECT_EQ(E_OK, errorCode); + EXPECT_EQ(1, rowId); + + std::unique_ptr resultSet = RdbStepResultSetGetRowTest::store->QueryByStep("SELECT * FROM test"); + EXPECT_NE(resultSet, nullptr); + + EXPECT_EQ(E_OK, resultSet->GoToFirstRow()); + + int iRet = E_ERROR; + RowEntity rowEntity; + iRet = resultSet->GetRow(rowEntity); + EXPECT_EQ(E_OK, iRet); + + int idValue = rowEntity.Get("id"); + EXPECT_EQ(1, idValue); + + int idValueByIndex = rowEntity.Get(0); + EXPECT_EQ(1, idValueByIndex); + + resultSet->Close(); +} + +/* * + * @tc.name: RdbStore_StepResultSet_GetRow_003 + * @tc.desc: test StepResultSet GetRow + * @tc.type: FUNC + * @tc.require: AR000FKD4F + */ +HWTEST_F(RdbStepResultSetGetRowTest, RdbStore_StepResultSet_GetRow_003, TestSize.Level1) +{ + ValuesBucket valuesBucket; + valuesBucket.PutString("data1", "olleh"); + valuesBucket.PutInt("data2", 20); + valuesBucket.PutDouble("data3", 2.0); + valuesBucket.PutBlob("data4", { 4, 3, 2, 1 }); + valuesBucket.PutBool("data5", true); + int64_t rowId; + int errorCode = RdbStepResultSetGetRowTest::store->Insert(rowId, "test", valuesBucket); + EXPECT_EQ(E_OK, errorCode); + EXPECT_EQ(1, rowId); + + std::unique_ptr resultSet = RdbStepResultSetGetRowTest::store->QueryByStep("SELECT * FROM test"); + EXPECT_NE(resultSet, nullptr); + + EXPECT_EQ(E_OK, resultSet->GoToFirstRow()); + + int iRet = E_ERROR; + RowEntity rowEntity; + iRet = resultSet->GetRow(rowEntity); + EXPECT_EQ(E_OK, iRet); + + int idValue = rowEntity.Get("id"); + std::string data1Value = rowEntity.Get("data1"); + int data2Value = rowEntity.Get("data2"); + double data3Value = rowEntity.Get("data3"); + std::vector data4Value = rowEntity.Get("data4"); + int data5Value = rowEntity.Get("data5"); + EXPECT_EQ(1, idValue); + EXPECT_EQ("olleh", data1Value); + EXPECT_EQ(20, data2Value); + EXPECT_EQ(2.0, data3Value); + EXPECT_EQ(1, data4Value[3]); + EXPECT_EQ(1, data5Value); + + int idValueByIndex = rowEntity.Get(0); + std::string data1ValueByIndex = rowEntity.Get(1); + int data2ValueByIndex = rowEntity.Get(2); + double data3ValueByIndex = rowEntity.Get(3); + std::vector data4ValueByIndex = rowEntity.Get(4); + int data5ValueByIndex = rowEntity.Get(5); + EXPECT_EQ(1, idValueByIndex); + EXPECT_EQ("olleh", data1ValueByIndex); + EXPECT_EQ(20, data2ValueByIndex); + EXPECT_EQ(2.0, data3ValueByIndex); + EXPECT_EQ(1, data4ValueByIndex[3]); + EXPECT_EQ(1, data5ValueByIndex); + + resultSet->Close(); +} + +/* * + * @tc.name: RdbStore_StepResultSet_GetRow_004 + * @tc.desc: test StepResultSet GetRow + * @tc.type: FUNC + * @tc.require: AR000FKD4F + */ +HWTEST_F(RdbStepResultSetGetRowTest, RdbStore_StepResultSet_GetRow_004, TestSize.Level1) +{ + ValuesBucket valuesBucket; + valuesBucket.PutString("data1", ""); + valuesBucket.PutInt("data2", 10); + valuesBucket.PutDouble("data3", 1.0); + valuesBucket.PutBlob("data4", { 1, 2, 3, 4 }); + valuesBucket.PutBool("data5", true); + int64_t rowId; + int errorCode = RdbStepResultSetGetRowTest::store->Insert(rowId, "test", valuesBucket); + EXPECT_EQ(E_OK, errorCode); + EXPECT_EQ(1, rowId); + + std::unique_ptr resultSet = + RdbStepResultSetGetRowTest::store->QueryByStep("SELECT data1, data2 FROM test"); + EXPECT_NE(resultSet, nullptr); + + EXPECT_EQ(E_OK, resultSet->GoToFirstRow()); + + int iRet = E_ERROR; + RowEntity rowEntity; + iRet = resultSet->GetRow(rowEntity); + EXPECT_EQ(E_OK, iRet); + + std::string data1Value = rowEntity.Get("data1"); + EXPECT_EQ("", data1Value); + + std::string data1ValueByIndex = rowEntity.Get(0); + EXPECT_EQ("", data1ValueByIndex); + + resultSet->Close(); +} \ No newline at end of file diff --git a/relational_store/test/native/rdb/unittest/rdb_step_result_set_test.cpp b/relational_store/test/native/rdb/unittest/rdb_step_result_set_test.cpp index 22ee3381459a8332ebb47ba69cf27a57fe95fa3e..3cd6e7b00169dbc469d02a090c58b6bc92896f3e 100644 --- a/relational_store/test/native/rdb/unittest/rdb_step_result_set_test.cpp +++ b/relational_store/test/native/rdb/unittest/rdb_step_result_set_test.cpp @@ -13,8 +13,10 @@ * limitations under the License. */ +#include #include #include + #include "common.h" #include "logger.h" #include "rdb_errno.h" @@ -35,14 +37,10 @@ public: static const std::string DATABASE_NAME; static std::shared_ptr store; - static const int E_SQLITE_ERROR; - static const int E_INVALID_COLUMN_TYPE; }; const std::string RdbStepResultSetTest::DATABASE_NAME = RDB_TEST_PATH + "stepResultSet_test.db"; std::shared_ptr RdbStepResultSetTest::store = nullptr; -const int RdbStepResultSetTest::E_SQLITE_ERROR = -1; // errno SQLITE_ERROR -const int RdbStepResultSetTest::E_INVALID_COLUMN_TYPE = 1009; // errno SQLITE_NULL class RdbStepResultSetOpenCallback : public RdbOpenCallback { public: @@ -137,12 +135,13 @@ HWTEST_F(RdbStepResultSetTest, RdbStore_StepResultSet_001, TestSize.Level1) std::unique_ptr resultSet = store->QueryByStep("SELECT * FROM test"); EXPECT_NE(resultSet, nullptr); - bool bResultSet = false; + bool bResultSet = true; int iRet = resultSet->IsStarted(bResultSet); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(bResultSet, false); EXPECT_EQ(resultSet->GoTo(1), E_OK); + bResultSet = false; iRet = resultSet->IsAtFirstRow(bResultSet); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(bResultSet, true); @@ -216,17 +215,18 @@ HWTEST_F(RdbStepResultSetTest, RdbStore_StepResultSet_002, TestSize.Level1) resultSet->GetRowCount(count); EXPECT_EQ(3, count); - int position = -1; + int position = INT_MIN; int iRet = resultSet->GetRowIndex(position); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(-1, position); - bool bResultSet = false; + bool bResultSet = true; resultSet->IsAtFirstRow(bResultSet); EXPECT_EQ(bResultSet, false); EXPECT_EQ(E_OK, resultSet->GoToRow(2)); + bResultSet = false; iRet = resultSet->IsAtLastRow(bResultSet); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(true, bResultSet); @@ -239,14 +239,17 @@ HWTEST_F(RdbStepResultSetTest, RdbStore_StepResultSet_002, TestSize.Level1) EXPECT_EQ(E_OK, resultSet->GoToLastRow()); + bResultSet = false; iRet = resultSet->IsAtLastRow(bResultSet); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(true, bResultSet); + bResultSet = false; iRet = resultSet->IsStarted(bResultSet); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(bResultSet, true); + bResultSet = true; iRet = resultSet->IsEnded(bResultSet); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(bResultSet, false); @@ -264,8 +267,8 @@ HWTEST_F(RdbStepResultSetTest, RdbStore_StepResultSet_003, TestSize.Level1) std::unique_ptr resultSet = store->QueryByStep("SELECT * FROM test"); EXPECT_NE(resultSet, nullptr); - int position = -1; - bool bResultSet = false; + int position = INT_MIN; + bool bResultSet = true; int iRet = resultSet->GetRowIndex(position); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(-1, position); @@ -274,10 +277,12 @@ HWTEST_F(RdbStepResultSetTest, RdbStore_StepResultSet_003, TestSize.Level1) EXPECT_EQ(E_OK, iRet); EXPECT_EQ(bResultSet, false); + bResultSet = true; iRet = resultSet->IsAtFirstRow(bResultSet); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(bResultSet, false); + bResultSet = true; iRet = resultSet->IsEnded(bResultSet); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(bResultSet, false); @@ -290,14 +295,17 @@ HWTEST_F(RdbStepResultSetTest, RdbStore_StepResultSet_003, TestSize.Level1) EXPECT_EQ(E_OK, iRet); EXPECT_EQ(0, position); + bResultSet = false; iRet = resultSet->IsStarted(bResultSet); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(bResultSet, true); + bResultSet = false; iRet = resultSet->IsAtFirstRow(bResultSet); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(bResultSet, true); + bResultSet = true; iRet = resultSet->IsEnded(bResultSet); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(bResultSet, false); @@ -314,14 +322,17 @@ HWTEST_F(RdbStepResultSetTest, RdbStore_StepResultSet_003, TestSize.Level1) EXPECT_EQ(E_OK, iRet); EXPECT_EQ(-1, position); + bResultSet = true; iRet = resultSet->IsStarted(bResultSet); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(bResultSet, false); + bResultSet = true; iRet = resultSet->IsAtFirstRow(bResultSet); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(bResultSet, false); + bResultSet = false; iRet = resultSet->IsEnded(bResultSet); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(bResultSet, true); @@ -339,8 +350,8 @@ HWTEST_F(RdbStepResultSetTest, RdbStore_StepResultSet_004, TestSize.Level1) std::unique_ptr resultSet = store->QueryByStep("SELECT data1, data2, data3, data4 FROM test"); EXPECT_NE(resultSet, nullptr); - int position = -1; - bool bResultSet = false; + int position = INT_MIN; + bool bResultSet = true; int iRet = resultSet->GetRowIndex(position); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(-1, position); @@ -349,6 +360,7 @@ HWTEST_F(RdbStepResultSetTest, RdbStore_StepResultSet_004, TestSize.Level1) EXPECT_EQ(E_OK, iRet); EXPECT_EQ(bResultSet, false); + bResultSet = true; iRet = resultSet->IsAtFirstRow(bResultSet); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(bResultSet, false); @@ -359,10 +371,12 @@ HWTEST_F(RdbStepResultSetTest, RdbStore_StepResultSet_004, TestSize.Level1) EXPECT_EQ(E_OK, iRet); EXPECT_EQ(-1, position); + bResultSet = true; iRet = resultSet->IsStarted(bResultSet); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(bResultSet, false); + bResultSet = true; iRet = resultSet->IsAtFirstRow(bResultSet); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(bResultSet, false); @@ -382,7 +396,7 @@ HWTEST_F(RdbStepResultSetTest, RdbStore_StepResultSet_005, TestSize.Level1) EXPECT_EQ(E_OK, resultSet->GoToFirstRow()); - int position = -1; + int position = INT_MIN; bool bResultSet = false; int iRet = resultSet->GetRowIndex(position); EXPECT_EQ(E_OK, iRet); @@ -392,6 +406,7 @@ HWTEST_F(RdbStepResultSetTest, RdbStore_StepResultSet_005, TestSize.Level1) EXPECT_EQ(E_OK, iRet); EXPECT_EQ(bResultSet, true); + bResultSet = false; iRet = resultSet->IsStarted(bResultSet); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(bResultSet, true); @@ -401,10 +416,12 @@ HWTEST_F(RdbStepResultSetTest, RdbStore_StepResultSet_005, TestSize.Level1) EXPECT_EQ(E_OK, iRet); EXPECT_EQ(0, position); + bResultSet = false; iRet = resultSet->IsAtFirstRow(bResultSet); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(bResultSet, true); + bResultSet = false; iRet = resultSet->IsStarted(bResultSet); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(bResultSet, true); @@ -412,10 +429,12 @@ HWTEST_F(RdbStepResultSetTest, RdbStore_StepResultSet_005, TestSize.Level1) EXPECT_EQ(E_OK, resultSet->GoToNextRow()); EXPECT_EQ(E_OK, resultSet->GoToFirstRow()); + bResultSet = false; iRet = resultSet->IsAtFirstRow(bResultSet); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(bResultSet, true); + bResultSet = false; iRet = resultSet->IsStarted(bResultSet); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(bResultSet, true); @@ -435,8 +454,8 @@ HWTEST_F(RdbStepResultSetTest, RdbStore_StepResultSet_006, TestSize.Level1) EXPECT_NE(E_OK, resultSet->GoToFirstRow()); - int position = -1; - bool bResultSet = false; + int position = INT_MIN; + bool bResultSet = true; int iRet = resultSet->GetRowIndex(position); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(-1, position); @@ -445,6 +464,7 @@ HWTEST_F(RdbStepResultSetTest, RdbStore_StepResultSet_006, TestSize.Level1) EXPECT_EQ(E_OK, iRet); EXPECT_EQ(bResultSet, false); + bResultSet = true; iRet = resultSet->IsStarted(bResultSet); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(bResultSet, false); @@ -452,10 +472,12 @@ HWTEST_F(RdbStepResultSetTest, RdbStore_StepResultSet_006, TestSize.Level1) EXPECT_NE(E_OK, resultSet->GoToNextRow()); EXPECT_NE(E_OK, resultSet->GoToFirstRow()); + bResultSet = true; iRet = resultSet->IsAtFirstRow(bResultSet); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(bResultSet, false); + bResultSet = true; iRet = resultSet->IsStarted(bResultSet); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(bResultSet, false); @@ -476,8 +498,8 @@ HWTEST_F(RdbStepResultSetTest, RdbStore_StepResultSet_007, TestSize.Level1) int moveTimes = 0; EXPECT_EQ(E_OK, resultSet->GoToFirstRow()); moveTimes++; - int position = -1; - bool bResultSet = false; + int position = INT_MIN; + bool bResultSet = true; int iRet = resultSet->GetRowIndex(position); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(0, position); @@ -493,6 +515,7 @@ HWTEST_F(RdbStepResultSetTest, RdbStore_StepResultSet_007, TestSize.Level1) EXPECT_EQ(E_OK, iRet); EXPECT_EQ(-1, position); + bResultSet = false; iRet = resultSet->IsEnded(bResultSet); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(bResultSet, true); @@ -513,7 +536,7 @@ HWTEST_F(RdbStepResultSetTest, RdbStore_StepResultSet_008, TestSize.Level1) EXPECT_NE(E_OK, resultSet->GoToFirstRow()); moveTimes++; - int position = -1; + int position = INT_MIN; bool bResultSet = false; int iRet = resultSet->GetRowIndex(position); EXPECT_EQ(E_OK, iRet); @@ -530,6 +553,7 @@ HWTEST_F(RdbStepResultSetTest, RdbStore_StepResultSet_008, TestSize.Level1) EXPECT_EQ(E_OK, iRet); EXPECT_EQ(-1, position); + bResultSet = false; iRet = resultSet->IsEnded(bResultSet); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(bResultSet, true); @@ -888,6 +912,7 @@ HWTEST_F(RdbStepResultSetTest, RdbStore_StepResultSet_016, TestSize.Level1) EXPECT_EQ(E_OK, iRet); EXPECT_EQ(bResultSet, true); + bResultSet = false; iRet = resultSet->IsStarted(bResultSet); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(bResultSet, true); @@ -915,7 +940,7 @@ HWTEST_F(RdbStepResultSetTest, testGetRowCount003, TestSize.Level1) std::unique_ptr resultSet = store->QueryByStep("SELECT * FROM test"); EXPECT_NE(resultSet, nullptr); - bool bResultSet = false; + bool bResultSet = true; int iRet = resultSet->IsStarted(bResultSet); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(bResultSet, false); @@ -926,6 +951,7 @@ HWTEST_F(RdbStepResultSetTest, testGetRowCount003, TestSize.Level1) EXPECT_EQ(3, count); EXPECT_EQ(E_OK, resultSet->GoToNextRow()); + bResultSet = false; iRet = resultSet->IsAtFirstRow(bResultSet); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(bResultSet, true); @@ -963,7 +989,7 @@ HWTEST_F(RdbStepResultSetTest, testGetRowCount003, TestSize.Level1) EXPECT_EQ(3, count); EXPECT_EQ(E_OK, resultSet->GoToNextRow()); - int position = -1; + int position = INT_MIN; iRet = resultSet->GetRowIndex(position); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(1, position); @@ -1005,12 +1031,13 @@ HWTEST_F(RdbStepResultSetTest, testGetRowCount004, TestSize.Level1) std::unique_ptr resultSet = store->QueryByStep("SELECT data1, data2, data3, data4 FROM test"); EXPECT_NE(resultSet, nullptr); - bool bResultSet = false; + bool bResultSet = true; int iRet = resultSet->IsStarted(bResultSet); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(bResultSet, false); EXPECT_EQ(E_OK, resultSet->GoToNextRow()); + bResultSet = false; iRet = resultSet->IsAtFirstRow(bResultSet); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(bResultSet, true); @@ -1050,7 +1077,7 @@ HWTEST_F(RdbStepResultSetTest, testGetRowCount004, TestSize.Level1) EXPECT_EQ(E_OK, resultSet->GoToNextRow()); - int position = -1; + int position = INT_MIN; iRet = resultSet->GetRowIndex(position); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(1, position); @@ -1093,17 +1120,18 @@ HWTEST_F(RdbStepResultSetTest, testGoToRow005, TestSize.Level1) std::unique_ptr resultSet = store->QueryByStep("SELECT data1, data2, data3, data4 FROM test"); EXPECT_NE(resultSet, nullptr); - bool bResultSet = false; + bool bResultSet = true; int iRet = resultSet->IsStarted(bResultSet); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(bResultSet, false); EXPECT_EQ(E_OK, resultSet->GoToNextRow()); + bResultSet = false; iRet = resultSet->IsAtFirstRow(bResultSet); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(bResultSet, true); - int position = -1; + int position = INT_MIN; iRet = resultSet->GetRowIndex(position); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(0, position); @@ -1167,7 +1195,7 @@ HWTEST_F(RdbStepResultSetTest, testGo006, TestSize.Level1) GenerateDefaultTable(); std::unique_ptr resultSet = store->QueryByStep("SELECT * FROM test"); EXPECT_NE(resultSet, nullptr); - int position = -1; + int position = INT_MIN; int iRet = resultSet->GetRowIndex(position); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(-1, position); @@ -1252,13 +1280,14 @@ HWTEST_F(RdbStepResultSetTest, testGoToPrevious007, TestSize.Level1) EXPECT_EQ(E_OK, iRet); EXPECT_EQ(3, count); - bool bResultSet = false; + bool bResultSet = true; iRet = resultSet->IsStarted(bResultSet); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(bResultSet, false); EXPECT_EQ(E_OK, resultSet->GoToFirstRow()); + bResultSet = false; iRet = resultSet->IsAtFirstRow(bResultSet); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(bResultSet, true); @@ -1295,11 +1324,12 @@ HWTEST_F(RdbStepResultSetTest, testGoToPrevious007, TestSize.Level1) int ret = resultSet->GoToPreviousRow(); EXPECT_NE(E_OK, ret); - int position = -1; + int position = INT_MIN; iRet = resultSet->GetRowIndex(position); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(-1, position); + bResultSet = true; iRet = resultSet->IsStarted(bResultSet); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(bResultSet, false); @@ -1323,6 +1353,7 @@ HWTEST_F(RdbStepResultSetTest, testGoToPrevious007, TestSize.Level1) EXPECT_EQ(E_OK, resultSet->GoToLastRow()); + bResultSet = false; iRet = resultSet->IsAtLastRow(bResultSet); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(true, bResultSet); @@ -1339,6 +1370,7 @@ HWTEST_F(RdbStepResultSetTest, testGoToPrevious007, TestSize.Level1) EXPECT_EQ(E_OK, iRet); EXPECT_EQ(-1, position); + bResultSet = false; iRet = resultSet->IsEnded(bResultSet); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(bResultSet, true); @@ -1356,13 +1388,14 @@ HWTEST_F(RdbStepResultSetTest, testSqlStep008, TestSize.Level1) std::unique_ptr resultSet = store->QueryByStep("SELECT data1, data2, data3, data4 FROM test"); EXPECT_NE(resultSet, nullptr); - bool bResultSet = false; + bool bResultSet = true; int iRet = resultSet->IsStarted(bResultSet); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(bResultSet, false); EXPECT_EQ(E_OK, resultSet->GoTo(1)); + bResultSet = false; iRet = resultSet->IsAtFirstRow(bResultSet); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(bResultSet, true); @@ -1387,7 +1420,7 @@ HWTEST_F(RdbStepResultSetTest, testSqlStep008, TestSize.Level1) EXPECT_EQ(E_OK, resultSet->GoToFirstRow()); EXPECT_EQ(E_OK, resultSet->GoToNextRow()); - int position = -1; + int position = INT_MIN; iRet = resultSet->GetRowIndex(position); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(1, position); @@ -1435,18 +1468,19 @@ HWTEST_F(RdbStepResultSetTest, testSqlStep009, TestSize.Level1) EXPECT_EQ(E_OK, iRet); EXPECT_EQ(3, count); - int position = -1; + int position = INT_MIN; iRet = resultSet->GetRowIndex(position); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(-1, position); - bool bResultSet = false; + bool bResultSet = true; iRet = resultSet->IsAtFirstRow(bResultSet); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(bResultSet, false); EXPECT_EQ(E_OK, resultSet->GoToRow(2)); + bResultSet = false; iRet = resultSet->IsAtLastRow(bResultSet); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(true, bResultSet); @@ -1459,18 +1493,22 @@ HWTEST_F(RdbStepResultSetTest, testSqlStep009, TestSize.Level1) EXPECT_EQ(E_OK, resultSet->GoToLastRow()); + bResultSet = false; iRet = resultSet->IsAtLastRow(bResultSet); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(true, bResultSet); + bResultSet = false; iRet = resultSet->IsAtLastRow(bResultSet); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(true, bResultSet); + bResultSet = false; iRet = resultSet->IsStarted(bResultSet); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(bResultSet, true); + bResultSet = true; iRet = resultSet->IsEnded(bResultSet); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(bResultSet, false); @@ -1488,19 +1526,21 @@ HWTEST_F(RdbStepResultSetTest, testSqlStep010, TestSize.Level1) std::unique_ptr resultSet = store->QueryByStep("SELECT data1, data2, data3, data4 FROM test"); EXPECT_NE(resultSet, nullptr); - int position = -1; + int position = INT_MIN; int iRet = resultSet->GetRowIndex(position); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(-1, position); - bool bResultSet = false; + bool bResultSet = true; iRet = resultSet->IsStarted(bResultSet); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(bResultSet, false); + bResultSet = true; iRet = resultSet->IsAtFirstRow(bResultSet); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(bResultSet, false); + bResultSet = true; iRet = resultSet->IsEnded(bResultSet); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(bResultSet, false); @@ -1513,14 +1553,17 @@ HWTEST_F(RdbStepResultSetTest, testSqlStep010, TestSize.Level1) EXPECT_EQ(E_OK, iRet); EXPECT_EQ(0, position); + bResultSet = false; iRet = resultSet->IsStarted(bResultSet); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(bResultSet, true); + bResultSet = false; iRet = resultSet->IsAtFirstRow(bResultSet); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(bResultSet, true); + bResultSet = true; iRet = resultSet->IsEnded(bResultSet); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(bResultSet, false); @@ -1533,14 +1576,17 @@ HWTEST_F(RdbStepResultSetTest, testSqlStep010, TestSize.Level1) EXPECT_EQ(E_OK, iRet); EXPECT_EQ(-1, position); + bResultSet = true; iRet = resultSet->IsStarted(bResultSet); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(bResultSet, false); + bResultSet = true; iRet = resultSet->IsAtFirstRow(bResultSet); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(bResultSet, false); + bResultSet = false; iRet = resultSet->IsEnded(bResultSet); EXPECT_EQ(E_OK, iRet); EXPECT_EQ(bResultSet, true); diff --git a/relational_store/test/native/rdb/unittest/rdb_store_rekey_test.cpp b/relational_store/test/native/rdb/unittest/rdb_store_rekey_test.cpp index 596e0156dd42674b32c7fc2d2c748469ed105ed6..ab96934f7b2c9d831ca6830c0dcfaf4921ba7537 100644 --- a/relational_store/test/native/rdb/unittest/rdb_store_rekey_test.cpp +++ b/relational_store/test/native/rdb/unittest/rdb_store_rekey_test.cpp @@ -63,12 +63,12 @@ public: static const std::string createTableTest; }; -std::string const RekeyTestOpenCallback::createTableTest = std::string("CREATE TABLE IF NOT EXISTS test ") - + std::string("(id INTEGER PRIMARY KEY " - "AUTOINCREMENT, " - "name TEXT NOT NULL, age INTEGER, " - "salary " - "REAL, blobType BLOB)"); +std::string const RekeyTestOpenCallback::createTableTest = "CREATE TABLE IF NOT EXISTS test " + "(id INTEGER PRIMARY KEY " + "AUTOINCREMENT, " + "name TEXT NOT NULL, age INTEGER, " + "salary " + "REAL, blobType BLOB)"; int RekeyTestOpenCallback::OnCreate(RdbStore &store) { @@ -80,24 +80,20 @@ int RekeyTestOpenCallback::OnUpgrade(RdbStore &store, int oldVersion, int newVer return E_OK; } -void RdbRekeyTest::SetUpTestCase() { - -} +void RdbRekeyTest::SetUpTestCase() {} void RdbRekeyTest::TearDownTestCase() {} void RdbRekeyTest::SetUp() { - RdbHelper::ClearCache(); - RdbHelper::DeleteRdbStore(encryptedDatabasePath); RdbStoreConfig config = GetRdbConfig(encryptedDatabasePath); - int errCode = E_OK; RekeyTestOpenCallback helper; + int errCode; std::shared_ptr store = RdbHelper::GetRdbStore(config, 1, helper, errCode); EXPECT_NE(store, nullptr); - EXPECT_EQ(errCode, E_OK); InsertData(store); store.reset(); + RdbHelper::ClearCache(); } void RdbRekeyTest::TearDown() diff --git a/relational_store/test/native/rdb/unittest/rdb_transaction_test.cpp b/relational_store/test/native/rdb/unittest/rdb_transaction_test.cpp index 665328fa7494da44d8ce7df2300a383ed11b32b1..bda1219aa99a75f816c62c1d798460ede22a705d 100644 --- a/relational_store/test/native/rdb/unittest/rdb_transaction_test.cpp +++ b/relational_store/test/native/rdb/unittest/rdb_transaction_test.cpp @@ -15,6 +15,7 @@ #include +#include #include #include "common.h" @@ -35,12 +36,10 @@ public: static const std::string DATABASE_NAME; static std::shared_ptr store; - static const int E_SQLITE_ERROR; // errno SQLITE_ERROR }; const std::string RdbTransactionTest::DATABASE_NAME = RDB_TEST_PATH + "transaction_test.db"; std::shared_ptr RdbTransactionTest::store = nullptr; -const int RdbTransactionTest::E_SQLITE_ERROR = -1; // errno SQLITE_ERROR class TransactionTestOpenCallback : public RdbOpenCallback { public: @@ -675,7 +674,7 @@ HWTEST_F(RdbTransactionTest, RdbStore_BatchInsert_003, TestSize.Level1) valuesBuckets.push_back(std::move(values)); } - number = -1; + number = INT_MIN; error = store->BatchInsert(number, "test", valuesBuckets); EXPECT_EQ(E_OK, error); EXPECT_EQ(-1, number); diff --git a/relational_store/test/native/rdb/unittest/rdb_value_bucket_test.cpp b/relational_store/test/native/rdb/unittest/rdb_value_bucket_test.cpp index 0fa37582d8147eedd92eab56b856a298a36d47db..3ba9821ed2051537d575a8d603399ace53e242e4 100644 --- a/relational_store/test/native/rdb/unittest/rdb_value_bucket_test.cpp +++ b/relational_store/test/native/rdb/unittest/rdb_value_bucket_test.cpp @@ -22,6 +22,7 @@ #include "parcel.h" #include "value_object.h" #include "values_bucket.h" +#include "sqlite_global_config.h" using namespace testing::ext; using namespace OHOS; @@ -209,6 +210,24 @@ HWTEST_F(ValuesBucketTest, Values_Bucket_004, TestSize.Level1) EXPECT_EQ(true, valuesBucket->IsEmpty()); } +/** + * @tc.name: Values_Bucket_005 + * @tc.desc: test Values Bucket Unmarshalling + * @tc.type: FUNC + */ +HWTEST_F(ValuesBucketTest, Values_Bucket_005, TestSize.Level1) +{ + Parcel parcel; + ValuesBucket values; + for (int i = 0; i < GlobalExpr::SQLITE_MAX_COLUMN + 1; i++) { + values.PutInt("id" + std::to_string(i), i); + } + + EXPECT_EQ(true, values.Marshalling(parcel)); + auto valuesBucket = std::shared_ptr(ValuesBucket::Unmarshalling(parcel)); + EXPECT_EQ(true, valuesBucket->IsEmpty()); +} + /** * @tc.name: Values_Object_001 * @tc.desc: test ValuesObject operator diff --git a/relational_store/test/native/rdb/unittest/rdb_wal_limit_test.cpp b/relational_store/test/native/rdb/unittest/rdb_wal_limit_test.cpp index a0d0761eff2149a4a8b9a2dab2a760b908984578..8efaffe2443ca67263734ed58680f24348ec0337 100644 --- a/relational_store/test/native/rdb/unittest/rdb_wal_limit_test.cpp +++ b/relational_store/test/native/rdb/unittest/rdb_wal_limit_test.cpp @@ -86,7 +86,6 @@ void RdbWalLimitTest::SetUp(void) { int errCode = E_OK; RdbHelper::DeleteRdbStore(DATABASE_NAME); - RdbStoreConfig config(DATABASE_NAME); RdbWalLimitCallback helper; store = RdbHelper::GetRdbStore(config, 1, helper, errCode); diff --git a/relational_store/test/native/rdb_data_share_adapter/unittest/rdb_data_share_adapter_test.cpp b/relational_store/test/native/rdb_data_share_adapter/unittest/rdb_data_share_adapter_test.cpp index fdb348b1238fd8fbcd076be9b05544e22a622010..96fda84dd6f11cf3c0478e1b9ccc6d295ce7a00c 100644 --- a/relational_store/test/native/rdb_data_share_adapter/unittest/rdb_data_share_adapter_test.cpp +++ b/relational_store/test/native/rdb_data_share_adapter/unittest/rdb_data_share_adapter_test.cpp @@ -44,17 +44,11 @@ public: static const std::string DATABASE_NAME; static std::shared_ptr store; - static const int E_SQLITE_ERROR; - static const int E_INVALID_COLUMN_TYPE; - static const size_t DEFAULT_BLOCK_SIZE; static const std::string RDB_ADAPTER_TEST_PATH; }; const std::string RdbDataShareAdapterTest::RDB_ADAPTER_TEST_PATH = "/data/test/"; const std::string RdbDataShareAdapterTest::DATABASE_NAME = RDB_ADAPTER_TEST_PATH + "rdbDataShareAdapter_test.db"; -const int RdbDataShareAdapterTest::E_SQLITE_ERROR = -1; // errno SQLITE_ERROR -const int RdbDataShareAdapterTest::E_INVALID_COLUMN_TYPE = 1009; // errno SQLITE_NULL -const size_t RdbDataShareAdapterTest::DEFAULT_BLOCK_SIZE = 2 * 1024 * 1024; std::shared_ptr RdbDataShareAdapterTest::store = nullptr; class RdbStepSharedResultSetOpenCallback : public RdbOpenCallback { @@ -88,7 +82,6 @@ void RdbDataShareAdapterTest::SetUpTestCase(void) void RdbDataShareAdapterTest::TearDownTestCase(void) { - store = nullptr; RdbHelper::DeleteRdbStore(RdbDataShareAdapterTest::DATABASE_NAME); }