• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2022 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #ifndef DATASHARE_HELPER_H
17 #define DATASHARE_HELPER_H
18 
19 #include <list>
20 #include <map>
21 #include <memory>
22 #include <mutex>
23 #include <string>
24 
25 #include "data_ability_observer_stub.h"
26 #include "datashare_business_error.h"
27 #include "datashare_errno.h"
28 #include "datashare_observer.h"
29 #include "datashare_operation_statement.h"
30 #include "datashare_option.h"
31 #include "datashare_predicates.h"
32 #include "datashare_result_set.h"
33 #include "datashare_template.h"
34 #include "datashare_values_bucket.h"
35 #include "uri.h"
36 
37 
38 using Uri = OHOS::Uri;
39 
40 namespace OHOS {
41 namespace AppExecFwk {
42 class PacMap;
43 class IDataAbilityObserver;
44 } // namespace AppExecFwk
45 
46 namespace DataShare {
47 using string = std::string;
48 class DataShareHelper : public std::enable_shared_from_this<DataShareHelper> {
49 public:
50     /**
51      * @brief Destructor.
52      */
53     virtual ~DataShareHelper() = default;
54 
55     /**
56      * @brief You can use this method to specify the Uri of the data to operate and set the binding relationship
57      * between the ability using the Data template (data share for short) and the associated client process in
58      * a DataShareHelper instance.
59      *
60      * @param token Indicates the System token.
61      * @param strUri Indicates the database table or disk file to operate.
62      * @param waitTime connect extension waiting time.
63      *
64      * @return Returns the created DataShareHelper instance.
65      */
66     [[deprecated(
67         "Use Create(const sptr<IRemoteObject> &, const std::string &, const std::string &, const int &) instead.")]]
68     static std::shared_ptr<DataShareHelper> Creator(const sptr<IRemoteObject> &token,
69         const std::string &strUri, const std::string &extUri = "", const int waitTime = 2, bool isSystem = false);
70 
71     /**
72      * @brief Creates a DataShareHelper instance with the Uri and {@link #CreateOptions} .
73      *
74      * @param strUri Indicates the database table or disk file to operate.
75      * @param options Indicates the optional config.
76      * @param waitTime connect extension waiting time.
77      *
78      * @return Returns the created DataShareHelper instance with a specified Uri.
79      */
80     [[deprecated(
81         "Use Create(const sptr<IRemoteObject> &, const std::string &,const std::string &, const int &) instead.")]]
82     static std::shared_ptr<DataShareHelper> Creator(const std::string &strUri, const CreateOptions &options,
83         const std::string &bundleName = "", const int waitTime = 2, bool isSystem = false);
84 
85     /**
86      * @brief Creates a DataShareHelper instance, priority silent access, use non-silent access when silent is not
87      * available, at this time, it is necessary to apply for communication permission with the extension.
88      *
89      * @param token Indicates the System token.
90      * @param strUri Indicates the database table or disk file to operate for silent access.
91      * @param extUri Indicates the database table or disk file to operate for non silent access.
92      * @param waitTime connect extension waiting time.
93      *
94      * @return Returns the created DataShareHelper instance with a specified Uri.
95      */
96     static std::pair<int, std::shared_ptr<DataShareHelper>> Create(const sptr<IRemoteObject> &token,
97         const std::string &strUri, const std::string &extUri, const int waitTime = 2);
98 
99     /**
100      * @brief Releases the client resource of the Data share.
101      * You should call this method to releases client resource after the data operations are complete.
102      *
103      * @return Returns true if the resource is successfully released; returns false otherwise.
104      */
105     virtual bool Release() = 0;
106 
107     /**
108      * @brief Obtains the MIME types of files supported.
109      *
110      * @param uri Indicates the path of the files to obtain.
111      * @param mimeTypeFilter Indicates the MIME types of the files to obtain. This parameter cannot be null.
112      *
113      * @return Returns the matched MIME types. If there is no match, null is returned.
114      */
115     virtual std::vector<std::string> GetFileTypes(Uri &uri, const std::string &mimeTypeFilter) = 0;
116 
117     /**
118      * @brief Opens a file in a specified remote path.
119      *
120      * @param uri Indicates the path of the file to open.
121      * @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access
122      * (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file,
123      * "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing data,
124      *  or "rwt" for read and write access that truncates any existing file.
125      *
126      * @return Returns the file descriptor.
127      */
128     virtual int OpenFile(Uri &uri, const std::string &mode) = 0;
129 
130     /**
131      * @brief Opens a file in a specified remote path.
132      *
133      * @param uri Indicates the path of the file to open.
134      * @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access
135      * (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file,
136      * "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing data,
137      *  or "rwt" for read and write access that truncates any existing file.
138      * @param errCode real error code.
139      *
140      * @return Returns the file descriptor.
141      */
142     virtual int OpenFileWithErrCode(Uri &uri, const std::string &mode, int32_t &errCode) = 0;
143 
144     /**
145      * @brief This is like openFile, open a file that need to be able to return sub-sections of files,often assets
146      * inside of their .hap.
147      *
148      * @param uri Indicates the path of the file to open.
149      * @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access
150      * (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file,
151      * "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing
152      * data, or "rwt" for read and write access that truncates any existing file.
153      *
154      * @return Returns the RawFileDescriptor object containing file descriptor.
155      */
156     virtual int OpenRawFile(Uri &uri, const std::string &mode) = 0;
157 
158     /**
159      * @brief Inserts a single data record into the database.
160      *
161      * @param uri Indicates the path of the data to operate.
162      * @param value  Indicates the data record to insert. If this parameter is null, a blank row will be inserted.
163      *
164      * @return Returns the index of the inserted data record.
165      */
166     [[deprecated("Use InsertEx(Uri &, const DataShareValuesBucket &) instead.")]]
167     virtual int Insert(Uri &uri, const DataShareValuesBucket &value) = 0;
168 
169     /**
170      * @brief Inserts a single data record into the database.
171      *
172      * @param uri Indicates the path of the data to operate.
173      * @param value  Indicates the data record to insert. If this parameter is null, a blank row will be inserted.
174      * @param result Indicates the result string of the insert operation.
175      *
176      * @return Returns the index of the inserted data record.
177      */
178     virtual int InsertExt(Uri &uri, const DataShareValuesBucket &value, std::string &result) = 0;
179 
180     /**
181      * @brief Updates data records in the database.
182      *
183      * @param uri Indicates the path of data to update.
184      * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null.
185      * @param value Indicates the data to update. This parameter can be null.
186      *
187      * @return Returns the number of data records updated.
188      */
189     [[deprecated("Use UpdateEx(Uri &, const DataSharePredicates &, const DataShareValuesBucket &) instead.")]]
190     virtual int Update(Uri &uri, const DataSharePredicates &predicates, const DataShareValuesBucket &value) = 0;
191 
192     /**
193      * @brief Batch updates data records in the database.
194      *
195      * @param updateOperations Indicates the param of data to update.
196      * @param results Indicates the number of data records updated.
197      *
198      * @return Return the execution results of batch updates.
199      */
200     virtual int BatchUpdate(const UpdateOperations &operations, std::vector<BatchUpdateResult> &results) = 0;
201 
202     /**
203      * @brief Deletes one or more data records from the database.
204      *
205      * @param uri Indicates the path of the data to operate.
206      * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null.
207      *
208      * @return Returns the number of data records deleted.
209      */
210     [[deprecated("Use DeleteEx(Uri &, const DataSharePredicates &) instead.")]]
211     virtual int Delete(Uri &uri, const DataSharePredicates &predicates) = 0;
212 
213     /**
214      * @brief Query records from the database.
215      *
216      * @param uri Indicates the path of data to query.
217      * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null.
218      * @param columns Indicates the columns to query. If this parameter is null, all columns are queried.
219      * @param businessError Indicates the error by query.
220      *
221      * @return Returns the query result.
222      */
223     virtual std::shared_ptr<DataShareResultSet> Query(Uri &uri, const DataSharePredicates &predicates,
224         std::vector<std::string> &columns, DatashareBusinessError *businessError = nullptr) = 0;
225 
226     /**
227      * @brief Query records from the database with timeout.
228      *
229      * @param uri Indicates the path of data to query.
230      * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null.
231      * @param columns Indicates the columns to query. If this parameter is null, all columns are queried.
232      * @param option Indicates the query options. The option includes a timeout period, in milliseconds.
233      * @param businessError Indicates the error by query.
234      *
235      * @return Returns the query result.
236      */
237     virtual std::shared_ptr<DataShareResultSet> Query(Uri &uri, const DataSharePredicates &predicates,
238         std::vector<std::string> &columns, DataShareOption &option,
239         DatashareBusinessError *businessError = nullptr) { return nullptr; }
240 
241     /**
242      * @brief Obtains the MIME type matching the data specified by the URI of the Data share. This method should be
243      * implemented by a Data share. Data abilities supports general data types, including text, HTML, and JPEG.
244      *
245      * @param uri Indicates the URI of the data.
246      *
247      * @return Returns the MIME type that matches the data specified by uri.
248      */
249     virtual std::string GetType(Uri &uri) = 0;
250 
251     /**
252      * @brief Inserts multiple data records into the database.
253      *
254      * @param uri Indicates the path of the data to operate.
255      * @param values Indicates the data records to insert.
256      *
257      * @return Returns the number of data records inserted.
258      */
259     virtual int BatchInsert(Uri &uri, const std::vector<DataShareValuesBucket> &values) = 0;
260 
261     /**
262      * @brief Performs batch operations on the database.
263      *
264      * @param statements Indicates a list of database operation statement on the database.
265      * @param result Indicates the result of the operation.
266      *
267      * @return Returns the ipc result.
268      */
269     virtual int ExecuteBatch(const std::vector<OperationStatement> &statements, ExecResultSet &result) = 0;
270 
271     /**
272      * @brief Registers an observer to DataObsMgr specified by the given Uri.
273      *
274      * @param uri, Indicates the path of the data to operate.
275      * @param dataObserver, Indicates the IDataAbilityObserver object.
276      *
277      * @return Returns the result. Error codes are listed in DataShare datashare_errno.h and
278      * DataObs dataobs_mgr_errors.h.
279      */
280     virtual int RegisterObserver(const Uri &uri, const sptr<AAFwk::IDataAbilityObserver> &dataObserver) = 0;
281 
282     /**
283      * @brief Deregisters an observer used for DataObsMgr specified by the given Uri.
284      *
285      * @param uri, Indicates the path of the data to operate.
286      * @param dataObserver, Indicates the IDataAbilityObserver object.
287      *
288      * @return Returns the result. Error codes are listed in DataShare datashare_errno.h and
289      * DataObs dataobs_mgr_errors.h.
290      */
291     virtual int UnregisterObserver(const Uri &uri, const sptr<AAFwk::IDataAbilityObserver> &dataObserver) = 0;
292 
293     /**
294      * @brief Notifies the registered observers of a change to the data resource specified by Uri.
295      *
296      * @param uri, Indicates the path of the data to operate.
297      */
298     virtual void NotifyChange(const Uri &uri) = 0;
299 
300     /**
301      * Registers an observer to DataObsMgr specified by the given Uri.
302      *
303      * @param uri, Indicates the path of the data to operate.
304      * @param dataObserver, Indicates the IDataAbilityObserver object.
305      * @param isDescendants, Indicates the Whether to note the change of descendants.
306      */
307     void RegisterObserverExt(const Uri &uri, std::shared_ptr<DataShareObserver> dataObserver,
308         bool isDescendants, bool isSystem = false);
309 
310     /**
311      * Registers an observer specified by the given Uri to the provider. This function is supported only when using
312      * non-silent DataShareHelper, and there is no default implemention in the provider side. It needs to be handled by
313      * the user. Otherwise, the provider side will do nothing but simply return error.
314      *
315      * @param uri, Indicates the path of the data to operate.
316      * @param dataObserver, Indicates the IDataAbilityObserver object.
317      * @param isDescendants, Indicates the Whether to note the change of descendants.
318      */
319     virtual int RegisterObserverExtProvider(const Uri &uri, std::shared_ptr<DataShareObserver> dataObserver,
320         bool isDescendants) = 0;
321 
322     /**
323      * Deregisters an observer used for DataObsMgr specified by the given Uri.
324      *
325      * @param uri, Indicates the path of the data to operate.
326      * @param dataObserver, Indicates the IDataAbilityObserver object
327      */
328     void UnregisterObserverExt(const Uri &uri, std::shared_ptr<DataShareObserver> dataObserver, bool isSystem = false);
329 
330     /**
331      * Deregisters an observer specified by the given Uri to the provider. This function is supported only when using
332      * non-silent DataShareHelper, and there is no default implemention in the provider side. It needs to be handled by
333      * the user. Otherwise, the provider side will do nothing but simply return error.
334      *
335      * @param uri, Indicates the path of the data to operate.
336      * @param dataObserver, Indicates the IDataAbilityObserver object
337      */
338     virtual int UnregisterObserverExtProvider(const Uri &uri, std::shared_ptr<DataShareObserver> dataObserver) = 0;
339 
340     /**
341      * Notifies the registered observers of a change to the data resource specified by Uris.
342      *
343      * @param changeInfo Indicates the info of the data to operate.
344      */
345     void NotifyChangeExt(const DataShareObserver::ChangeInfo &changeInfo, bool isSystem = false);
346 
347     /**
348      * Notifies the registered observers of a change to the data resource specified by Uris. This function is supported
349      * only when using non-silent DataShareHelper, and there is no default implemention in the provider side. It needs
350      * to be handled by the user. Otherwise, the provider side will do nothing but simply return true.
351      *
352      * @param changeInfo Indicates the info of the data to operate.
353      */
354     virtual void NotifyChangeExtProvider(const DataShareObserver::ChangeInfo &changeInfo) = 0;
355 
356     /**
357      * @brief Converts the given uri that refer to the Data share into a normalized URI. A normalized URI can be used
358      * across devices, persisted, backed up, and restored. It can refer to the same item in the Data share even if the
359      * context has changed. If you implement URI normalization for a Data share, you must also implement
360      * denormalizeUri(ohos.utils.net.Uri) to enable URI denormalization. After this feature is enabled, URIs passed to
361      * any method that is called on the Data share must require normalization verification and denormalization. The
362      * default implementation of this method returns null, indicating that this Data share does not support URI
363      * normalization.
364      *
365      * @param uri Indicates the Uri object to normalize.
366      *
367      * @return Returns the normalized Uri object if the Data share supports URI normalization; returns null otherwise.
368      */
369     virtual Uri NormalizeUri(Uri &uri) = 0;
370 
371     /**
372      * @brief Converts the given normalized uri generated by normalizeUri(ohos.utils.net.Uri) into a denormalized one.
373      * The default implementation of this method returns the original URI passed to it.
374      *
375      * @param uri uri Indicates the Uri object to denormalize.
376      *
377      * @return Returns the denormalized Uri object if the denormalization is successful; returns the original Uri passed
378      * to this method if there is nothing to do; returns null if the data identified by the original Uri cannot be found
379      * in the current environment.
380      */
381     virtual Uri DenormalizeUri(Uri &uri) = 0;
382 
383     /**
384      * @brief Adds a template of {@link #SubscribeRdbData}.
385      * @param uri, the uri to add.
386      * @param subscriberId, the subscribe id to add.
387      * @param tpl, the template to add.
388      * @return Returns the error code.
389      */
390     virtual int AddQueryTemplate(const std::string &uri, int64_t subscriberId, Template &tpl) = 0;
391 
392     /**
393      * @brief Deletes a template of {@link #SubscribeRdbData}
394      * @param uri, the uri to delete.
395      * @param subscriberId, the subscribe id to delete.
396      * @return Returns the error code.
397      */
398     virtual int DelQueryTemplate(const std::string &uri, int64_t subscriberId) = 0;
399 
400     /**
401      * @brief Update a single data into host data area.
402      * @param data, the data to publish.
403      * @param bundleName the bundleName of data to publish.
404      * @return Returns the error code.
405      */
406     virtual std::vector<OperationResult> Publish(const Data &data, const std::string &bundleName) = 0;
407 
408     /**
409      * @brief Get published data by bundleName.
410      * @param bundleName, the bundleName of data.
411      * @param resultCode, the errcode returned by function
412      * @return Data {@link #Data}
413      */
414     virtual Data GetPublishedData(const std::string &bundleName, int &resultCode) = 0;
415 
416     /**
417      * @brief Registers observers to observe rdb data specified by the given uris and template.
418      * @param uris, the paths of the data to operate.
419      * @param templateId, the template of observers.
420      * @param callback, the callback function of observers.
421      * @return Returns the error code.
422      */
423     virtual std::vector<OperationResult> SubscribeRdbData(const std::vector<std::string> &uris,
424         const TemplateId &templateId, const std::function<void(const RdbChangeNode &changeNode)> &callback) = 0;
425 
426     /**
427      * @brief Unregisters observers used for monitoring data specified by the given uris and template.
428      * @param uris, the paths of the data to operate, if uris is empty, Unregisters all observers.
429      * @param templateId, the template of observers.
430      * @return Returns the error code.
431      */
432     virtual std::vector<OperationResult> UnsubscribeRdbData(const std::vector<std::string> &uris,
433         const TemplateId &templateId) = 0;
434 
435     /**
436      * @brief Enable observers by the given uris and template.
437      * @param uris, the paths of the data to operate.
438      * @param templateId, the template of observers.
439      * @return Returns the error code.
440      */
441     virtual std::vector<OperationResult> EnableRdbSubs(const std::vector<std::string> &uris,
442         const TemplateId &templateId) = 0;
443 
444     /**
445      * @brief Disable observers by the given uris and template.
446      * @param uris, the paths of the data to operate.
447      * @param templateId, the template of observers.
448      * @return Returns the error code.
449      */
450     virtual std::vector<OperationResult> DisableRdbSubs(const std::vector<std::string> &uris,
451         const TemplateId &templateId) = 0;
452 
453     /**
454      * @brief Registers observers to observe published data specified by the given uris and subscriberId.
455      * @param uris, the uris of the data to operate.
456      * @param subscriberId, the subscriberId of observers.
457      * @param callback, the callback function of observers.
458      * @return Returns the error code.
459      */
460     virtual std::vector<OperationResult> SubscribePublishedData(const std::vector<std::string> &uris,
461         int64_t subscriberId, const std::function<void(const PublishedDataChangeNode &changeNode)> &callback) = 0;
462 
463     /**
464      * @brief Unregisters observers used for monitoring data specified by the given uris and subscriberId.
465      * @param uris, the uris of the data to operate, if uris is empty, Unregisters all observers.
466      * @param subscriberId, the subscriberId of observers.
467      * @return Returns the error code.
468      */
469     virtual std::vector<OperationResult> UnsubscribePublishedData(const std::vector<std::string> &uris,
470         int64_t subscriberId) = 0;
471 
472     /**
473      * @brief Enable observers by the given uris and subscriberId.
474      * @param uris, the paths of the data to operate.
475      * @param subscriberId, the subscriberId of observers.
476      * @return Returns the error code.
477      */
478     virtual std::vector<OperationResult> EnablePubSubs(const std::vector<std::string> &uris, int64_t subscriberId) = 0;
479 
480     /**
481      * @brief Disable observers by the given uris and template.
482      * @param uris, the paths of the data to operate.
483      * @param subscriberId, the subscriberId of observers.
484      * @return Returns the error code.
485      */
486     virtual std::vector<OperationResult> DisablePubSubs(const std::vector<std::string> &uris, int64_t subscriberId) = 0;
487 
488     /**
489      * @brief Set default switch for silent access.
490      * @param uri, the uri to disable/enable.
491      * @param enable, the enable of silent switch.
492      * @param isSystem, is system app or not.
493      * @return Returns the error code.
494      */
495     static int SetSilentSwitch(Uri &uri, bool enable, bool isSystem = false);
496 
497     /**
498      * @brief Inserts a single data record into the database.
499      *
500      * @param uri Indicates the path of the data to operate.
501      * @param value  Indicates the data record to insert. If this parameter is null, a blank row will be inserted.
502      *
503      * @return Returns pair<int32_t errCode, int32_t index>, the errCode and the index of the inserted data record.
504      */
505     virtual std::pair<int32_t, int32_t> InsertEx(Uri &uri, const DataShareValuesBucket &value);
506 
507     /**
508      * @brief Updates data records in the database.
509      *
510      * @param uri Indicates the path of data to update.
511      * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null.
512      * @param value Indicates the data to update. This parameter can be null.
513      *
514      * @return Returns pair<int32_t errCode, int32_t index>, the errCode and the index of data records updated.
515      */
516     virtual std::pair<int32_t, int32_t> UpdateEx(
517         Uri &uri, const DataSharePredicates &predicates, const DataShareValuesBucket &value);
518 
519     /**
520      * @brief Deletes one or more data records from the database.
521      *
522      * @param uri Indicates the path of the data to operate.
523      * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null.
524      *
525      * @return Returns pair<int32_t errCode, int32_t index>, the errCode and the index of data records deleted.
526      */
527     virtual std::pair<int32_t, int32_t> DeleteEx(Uri &uri, const DataSharePredicates &predicates);
528 
529     /**
530      * @brief UserDefineFunc supports user-defined serialization of data and deserialization of reply.
531      * It directly passes IPC parameters without any processing.
532      * Through this interface, users can implement their own business logic.
533      * When implementing user customized logic, it is recommended to not send errCode using return. Instead, use the
534      * reply parameter to carry the errCode to avoid conflicts with IPC error codes. Return is intended to be used
535      * only to return the results of the IPC call.
536      *
537      * @param data Data sent from the consumer to the provider
538      * @param reply Data returned from the provider to the consumer, including errCode
539      * @param option The options of IPC call
540      *
541      * @return Returns int32_t, the errCode returnd by IPC call to provider.
542      */
543     virtual int32_t UserDefineFunc(MessageParcel &data, MessageParcel &reply, MessageOption &option);
544 
545 private:
546     static std::shared_ptr<DataShareHelper> CreateServiceHelper(const std::string &extUri = "",
547         const std::string &bundleName = "", bool isSystem = false);
548 
549     static int GetSilentProxyStatus(const std::string &uri, bool isSystem);
550 
551     static std::shared_ptr<DataShareHelper> CreateExtHelper(Uri &uri, const sptr<IRemoteObject> &token,
552         const int waitTime = 2, bool isSystem = false);
553 
554     static std::string TransferUriPrefix(const std::string &originPrefix, const std::string &replacedPrefix,
555         const std::string &originUriStr);
556 
557     static bool IsProxy(Uri &uri);
558 
559     static std::pair<int, std::shared_ptr<DataShareHelper>> CreateProxyHelper(const std::string &strUri,
560         const std::string &extUri);
561 };
562 } // namespace DataShare
563 } // namespace OHOS
564 #endif // DATASHARE_HELPER_H