• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.data.sendableRelationalStore (共享关系型数据库)
2<!--Kit: ArkData-->
3<!--Subsystem: DistributedDataManager-->
4<!--Owner: @baijidong-->
5<!--Designer: @widecode; @htt1997-->
6<!--Tester: @yippo; @logic42-->
7<!--Adviser: @ge-yafang-->
8
9该模块针对关系型数据库(Relational Database,RDB)提供了sendable支持。支持从查询结果集中获取sendable类型ValuesBucket用于并发实例间传递。
10
11> **说明:**
12>
13> 本模块首批接口从API version 12开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
14
15## 使用场景
16
17在使用[taskpool](../../arkts-utils/taskpool-introduction.md)进行多线程计算时,因为对跨线程传递的数据类型限制,关系型数据库常规的ValuesBucket、Asset、Assets数据存储容器不能直接用于跨线程传递。
18
19本模块提供了相应的类型转换工具函数,以便在常规数据存储容器和支持跨线程传递的数据存储容器之间进行类型转换,用于跨线程传递。
20
21## 导入模块
22
23```ts
24import { sendableRelationalStore } from '@kit.ArkData';
25```
26
27## sendableRelationalStore.toSendableValuesBucket
28
29toSendableValuesBucket(valuesBucket: NonSendableBucket): ValuesBucket
30
31将不能用于跨线程传递的键值对数据,转换为可用于跨线程传递的键值对数据。
32
33**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
34
35**参数:**
36
37| 参数名       | 类型                                    | 必填 | 说明                               |
38| ------------ | --------------------------------------- | ---- | :--------------------------------- |
39| valuesBucket | [NonSendableBucket](#nonsendablebucket) | 是   | 不可跨线程传递的ValuesBucket数据。 |
40
41**返回值**:
42
43| 类型                          | 说明                                 |
44| ----------------------------- | ------------------------------------ |
45| [ValuesBucket](#valuesbucket) | 可用于跨线程传递的ValuesBucket数据。 |
46
47**错误码:**
48
49以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[关系型数据库错误码](errorcode-data-rdb.md)。
50
51| **错误码ID** | **错误信息**                                                                                                                                    |
52| ------------ | ----------------------------------------------------------------------------------------------------------------------------------------------- |
53| 401          | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
54| 14800000     | Inner error.                                                                                                                                    |
55
56**示例:**
57
58```ts
59const asset1: sendableRelationalStore.NonSendableAsset = {
60  name: 'hangman',
61  uri: '//path/example',
62  path: '//path/example',
63  createTime: 'createTime1',
64  modifyTime: 'modifyTime1',
65  size: 'size1'
66};
67const asset2: sendableRelationalStore.NonSendableAsset = {
68  name: 'hangman',
69  uri: '//path/example',
70  path: '//path/example',
71  createTime: 'createTime1',
72  modifyTime: 'modifyTime1',
73  size: 'size1'
74};
75const u8 = new Uint8Array([1, 2, 3]);
76const valuesBucket: sendableRelationalStore.NonSendableBucket = {
77  age: 18,
78  name: "hangman",
79  salary: 100.5,
80  passed: true,
81  data1: asset1,
82  blobType: u8,
83  bigValue: BigInt("15822401018187971961171"),
84  data2: [asset1, asset2]
85};
86
87const sendableValuesBucket = sendableRelationalStore.toSendableValuesBucket(valuesBucket);
88```
89
90## sendableRelationalStore.fromSendableValuesBucket
91
92fromSendableValuesBucket(valuesBucket: ValuesBucket): NonSendableBucket
93
94将可用于跨线程传递的键值对数据,转换为不能用于跨线程传递的键值对数据。
95
96**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
97
98**参数:**
99
100| 参数名       | 类型                          | 必填 | 说明                                 |
101| ------------ | ----------------------------- | ---- | :----------------------------------- |
102| valuesBucket | [ValuesBucket](#valuesbucket) | 是   | 可用于跨线程传递的ValuesBucket数据。 |
103
104**返回值**:
105
106| 类型                                    | 说明                               |
107| --------------------------------------- | ---------------------------------- |
108| [NonSendableBucket](#nonsendablebucket) | 不可跨线程传递的ValuesBucket数据。 |
109
110**错误码:**
111
112以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[关系型数据库错误码](errorcode-data-rdb.md)。
113
114| **错误码ID** | **错误信息**                                                                                                  |
115| ------------ | ------------------------------------------------------------------------------------------------------------- |
116| 401          | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
117| 14800000     | Inner error.                                                                                                  |
118
119**示例:**
120
121```ts
122const asset1: sendableRelationalStore.NonSendableAsset = {
123  name: 'hangman',
124  uri: '//path/example',
125  path: '//path/example',
126  createTime: 'createTime1',
127  modifyTime: 'modifyTime1',
128  size: 'size1'
129};
130const asset2: sendableRelationalStore.NonSendableAsset = {
131  name: 'hangman',
132  uri: '//path/example',
133  path: '//path/example',
134  createTime: 'createTime1',
135  modifyTime: 'modifyTime1',
136  size: 'size1'
137};
138const u8 = new Uint8Array([1, 2, 3]);
139
140const sendableValuesBucket = sendableRelationalStore.toSendableValuesBucket({
141  age: 18,
142  name: "hangman",
143  salary: 100.5,
144  passed: true,
145  data1: asset1,
146  blobType: u8,
147  bigValue: BigInt("15822401018187971961171"),
148  data2: [asset1, asset2]
149});
150const nonSendableBucket = sendableRelationalStore.fromSendableValuesBucket(sendableValuesBucket);
151```
152
153## sendableRelationalStore.toSendableAsset
154
155toSendableAsset(asset: NonSendableAsset): Asset
156
157将不可跨线程传递的附件数据,转换为可跨线程传递的附件数据。
158
159**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
160
161**参数:**
162
163| 参数名 | 类型                                   | 必填 | 说明                        |
164| ------ | -------------------------------------- | ---- | :-------------------------- |
165| asset  | [NonSendableAsset](#nonsendablebucket) | 是   | 不可跨线程传递的Asset数据。 |
166
167**返回值**:
168
169| 类型            | 说明                      |
170| --------------- | ------------------------- |
171| [Asset](#asset) | 可跨线程传递的Asset数据。 |
172
173**错误码:**
174
175以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[关系型数据库错误码](errorcode-data-rdb.md)。
176
177| **错误码ID** | **错误信息**                                                                                                  |
178| ------------ | ------------------------------------------------------------------------------------------------------------- |
179| 401          | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
180| 14800000     | Inner error.                                                                                                  |
181
182**示例:**
183
184```ts
185const asset1: sendableRelationalStore.NonSendableAsset = {
186  name: 'hangman',
187  uri: '//path/example',
188  path: '//path/example',
189  createTime: 'createTime1',
190  modifyTime: 'modifyTime1',
191  size: 'size1'
192};
193const sendableAsset = sendableRelationalStore.toSendableAsset(asset1);
194```
195
196## sendableRelationalStore.fromSendableAsset
197
198fromSendableAsset(asset: Asset): NonSendableAsset
199
200将可跨线程传递的附件数据,转换为不可跨线程传递的附件数据。
201
202**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
203
204**参数:**
205
206| 参数名 | 类型            | 必填 | 说明                      |
207| ------ | --------------- | ---- | :------------------------ |
208| asset  | [Asset](#asset) | 是   | 可跨线程传递的Asset数据。 |
209
210**返回值**:
211
212| 类型                                   | 说明                        |
213| -------------------------------------- | --------------------------- |
214| [NonSendableAsset](#nonsendablebucket) | 不可跨线程传递的Asset数据。 |
215
216**错误码:**
217
218以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[关系型数据库错误码](errorcode-data-rdb.md)。
219
220| **错误码ID** | **错误信息**                                                                                                  |
221| ------------ | ------------------------------------------------------------------------------------------------------------- |
222| 401          | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
223| 14800000     | Inner error.                                                                                                  |
224
225**示例:**
226
227```ts
228const asset1: sendableRelationalStore.NonSendableAsset = {
229  name: 'hangman',
230  uri: '//path/example',
231  path: '//path/example',
232  createTime: 'createTime1',
233  modifyTime: 'modifyTime1',
234  size: 'size1'
235};
236const sendableAsset = sendableRelationalStore.toSendableAsset(asset1);
237const normalAsset = sendableRelationalStore.fromSendableAsset(sendableAsset);
238```
239
240## sendableRelationalStore.fromSendableValues<sup>20+</sup>
241
242fromSendableValues(values: collections.Array\<ValueType>): NonSendableValues
243
244将可跨线程传递的数组数据,转换为不可跨线程传递的数组数据。
245
246**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
247
248**参数:**
249
250| 参数名 | 类型            | 必填 | 说明                      |
251| ------ | --------------- | ---- | :------------------------ |
252| values  | collections.Array\<[ValueType](arkts-apis-data-relationalStore-t.md#valuetype)> | 是   | 可跨线程传递的数组数据。 |
253
254**返回值**:
255
256| 类型                                   | 说明                        |
257| -------------------------------------- | --------------------------- |
258| [NonSendableValues](#nonsendablevalues20) | 不可跨线程传递的数组数据。 |
259
260**错误码:**
261
262以下错误码的详细介绍请参见[关系型数据库错误码](errorcode-data-rdb.md)。
263
264| **错误码ID** | **错误信息**                                                                                                  |
265| ------------ | ------------------------------------------------------------------------------------------------------------- |
266| 14800000     | Inner error.                                                                                                  |
267
268**示例:**
269
270```ts
271import { sendableRelationalStore } from '@kit.ArkData';
272import { collections } from '@kit.ArkTS';
273const array = new collections.Array<sendableRelationalStore.ValueType>();
274array.push("a");
275array.push("b");
276array.push(1);
277array.push(2);
278const values = sendableRelationalStore.fromSendableValues(array);
279```
280
281## sendableRelationalStore.toSendableValues<sup>20+</sup>
282
283toSendableValues(values: NonSendableValues): collections.Array\<ValueType>
284
285将不可跨线程传递的数组数据,转换为可跨线程传递的数组数据。
286
287**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
288
289**参数:**
290
291| 参数名 | 类型            | 必填 | 说明                      |
292| ------ | --------------- | ---- | :------------------------ |
293| values  | [NonSendableValues](#nonsendablevalues20) | 是   | 不可跨线程传递的数组数据。 |
294
295**返回值**:
296
297| 类型                                   | 说明                        |
298| -------------------------------------- | --------------------------- |
299| collections.Array\<[ValueType](arkts-apis-data-relationalStore-t.md#valuetype)> | 可跨线程传递的数组数据。 |
300
301**错误码:**
302
303以下错误码的详细介绍请参见[关系型数据库错误码](errorcode-data-rdb.md)。
304
305| **错误码ID** | **错误信息**                                                                                                  |
306| ------------ | ------------------------------------------------------------------------------------------------------------- |
307| 14800000     | Inner error.                                                                                                  |
308
309**示例:**
310
311```ts
312import { relationalStore, sendableRelationalStore } from '@kit.ArkData';
313const array: relationalStore.ValueType[] = [];
314array.push(1);
315array.push(2);
316array.push("aaaaaa")
317const values = sendableRelationalStore.toSendableValues(array);
318```
319
320## Asset
321
322记录资产附件(文件、图片、视频等类型文件)的相关信息。用于支持资产数据跨线程传递,继承自[lang.ISendable](../apis-arkts/js-apis-arkts-lang.md#langisendable)。资产类型的相关接口暂不支持Datashare。使用[sendableRelationalStore.toSendableAsset](#sendablerelationalstoretosendableasset)方法创建。
323
324**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
325
326| 名称       | 类型   | 只读 | 可选 | 说明                               |
327| ---------- | ------ | ---  | ---- | ---------------------------------- |
328| name       | string | 否   | 否   | 资产的名称。                       |
329| uri        | string | 否   | 否   | 资产的uri,在系统里的绝对路径。    |
330| path       | string | 否   | 否   | 资产在应用沙箱里的路径。           |
331| createTime | string | 否   | 否   | 资产被创建出来的时间。             |
332| modifyTime | string | 否   | 否   | 资产最后一次被修改的时间。         |
333| size       | string | 否   | 否   | 资产占用空间的大小。               |
334| status     | number | 否   | 是   | 资产的状态,取值与[relationalStore.AssetStatus](arkts-apis-data-relationalStore-e.md#assetstatus10)枚举值保持一致,默认值为relationalStore.AssetStatus.ASSET_NORMAL。|
335
336
337## Assets
338
339type Assets = collections.Array\<Asset>
340
341表示[Asset](#asset)类型数据的集合。用于支持Asset数据集合跨线程传递。
342
343**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
344
345| 类型                                                                                               | 说明                              |
346| -------------------------------------------------------------------------------------------------- | --------------------------------- |
347| [collections.Array](../apis-arkts/arkts-apis-arkts-collections-Array.md)\<[Asset](#asset)> | 用于并发场景的Asset附件数据集合。 |
348
349## ValueType
350
351type ValueType = null | number | string | boolean | collections.Uint8Array | Asset | Assets | collections.Float32Array | bigint
352
353用于表示允许的数据字段类型,接口参数具体类型根据其功能而定。
354
355**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
356
357| 类型    | 说明                 |
358| ------- | -------------------- |
359| null    | 表示值类型为空。     |
360| number  | 表示值类型为数字。   |
361| string  | 表示值类型为字符串。 |
362| boolean | 表示值类型为布尔值。 |
363| [collections.Uint8Array](../apis-arkts/arkts-apis-arkts-collections-Uint8Array.md) | 表示值类型为Uint8类型的数组。|
364| [Asset](#asset)  | 表示值类型为附件Asset。<br/>当字段类型是Asset时,在创建表的sql语句中,类型应当为:ASSET。             |
365| [Assets](#assets) | 表示值类型为附件数据集合Assets。<br/>当字段类型是Assets时,在创建表的sql语句中,类型应当为:ASSETS。 |
366| [collections.Float32Array](../apis-arkts/arkts-apis-arkts-collections-Float32Array.md) | 表示值类型为浮点数组。<br/>当字段类型是collections.Float32Array时,在创建表的sql语句中,类型应当为:floatvector(128)。 |
367| bigint | 表示值类型为任意长度的整数。<br/>当字段类型是bigint时,在创建表的sql语句中,类型应当为:UNLIMITED INT,详见[通过关系型数据库实现数据持久化](../../database/data-persistence-by-rdb-store.md)。<br/>**说明:** <br>bigint类型字段不能比较大小,不适用以下谓词操作:between、notBetween、greaterThan、lessThan、greaterThanOrEqualTo、lessThanOrEqualTo、orderByAsc、orderByDesc。<br/>bigint类型字段的数据写入时,需通过BigInt()方法或在数据尾部添加'n'的方式明确为bigint类型,如'let data = BigInt(1234)'或'let data = 1234n'。<br/>bigint字段如果写入number类型的数据,则查询该数据的返回类型为number,而非bigint。 |
368
369## ValuesBucket
370
371type ValuesBucket = collections.Map<string, ValueType>
372
373表示[ValueType](#valuetype)数据的键值对存储,用于支持ValueType数据跨线程传递。
374
375**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
376
377| 类型                                                                                                          | 说明                                                                    |
378| ------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- |
379| [collections.Map](../apis-arkts/arkts-apis-arkts-collections-Map.md)<string, [ValueType](#valuetype)> | 并发场景的键值对数据存储,其中,键的类型为string,值的类型为ValueType。 |
380
381## NonSendableBucket
382
383type NonSendableBucket = relationalStore.ValuesBucket
384
385用于存储键值对的类型。不支持跨线程传递。
386
387**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
388
389| 类型                                                                           | 说明                         |
390| ------------------------------------------------------------------------------ | ---------------------------- |
391| [relationalStore.ValuesBucket](arkts-apis-data-relationalStore-t.md#valuesbucket) | 非并发场景的键值对数据存储。 |
392
393## NonSendableValues<sup>20+</sup>
394
395type NonSendableValues = Array\<relationalStore.ValueType>
396
397表示[ValueType](arkts-apis-data-relationalStore-t.md#valuetype)数据数组存储。不支持跨线程传递。
398
399**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
400
401| 类型                                                               | 说明                           |
402| ------------------------------------------------------------------ | ------------------------------ |
403| Array\<[relationalStore.ValueType](arkts-apis-data-relationalStore-t.md#valuetype)> | 非并发场景的数组数据存储,值的类型为ValueType。 |
404
405## NonSendableAsset
406
407type NonSendableAsset = relationalStore.Asset
408
409记录资产附件(文件、图片、视频等类型文件)的相关信息。不支持跨线程传递。
410
411**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
412
413| 类型                                                               | 说明                           |
414| ------------------------------------------------------------------ | ------------------------------ |
415| [relationalStore.Asset](arkts-apis-data-relationalStore-i.md#asset10) | 非并发场景的资产附件数据存储。 |
416
417## 跨线程传递使用示例
418
419调用taskpool执行数据插入时,主线程调用toSendableValuesBucket方法将数据转为跨线程传递类型,传入taskpool处理。
420
421调用taskpool执行数据查询时,调用ResultSet的getSendableRow方法,获取可跨线程传递的数据行返回主线程,主线程中调用fromSendableValuesBucket方法,转为常规ValuesBucket执行后续处理。
422
423```ts
424// Index.ets
425import { relationalStore, sendableRelationalStore } from '@kit.ArkData';
426import { taskpool } from '@kit.ArkTS';
427
428@Concurrent
429async function insert(context: Context, dataItem: sendableRelationalStore.ValuesBucket) {
430  const CONFIG: relationalStore.StoreConfig = {
431    name: "Store.db",
432    securityLevel: relationalStore.SecurityLevel.S3,
433  };
434
435  let store = await relationalStore.getRdbStore(context, CONFIG);
436  console.info(`Get store successfully!`);
437
438  const CREATE_TABLE_SQL = "CREATE TABLE IF NOT EXISTS test (" +
439    "id INTEGER PRIMARY KEY AUTOINCREMENT, " +
440    "name TEXT NOT NULL, " +
441    "age INTEGER, " +
442    "salary REAL, " +
443    "blobType BLOB)";
444  await store.executeSql(CREATE_TABLE_SQL);
445  console.info(`Create table test successfully!`);
446
447  // 数据插入
448  const rowId = await store.insertSync("test", dataItem);
449  await store.close();
450  return rowId;
451}
452
453@Concurrent
454async function queryByName(context: Context, name: string) {
455  const CONFIG: relationalStore.StoreConfig = {
456    name: "Store.db",
457    securityLevel: relationalStore.SecurityLevel.S3,
458  };
459
460  let store = await relationalStore.getRdbStore(context, CONFIG);
461  console.info(`Get store successfully!`);
462
463  const predicates = new relationalStore.RdbPredicates("test");
464  predicates.equalTo("name", name);
465
466  const resultSet = await store.query(predicates);
467  if (resultSet.rowCount > 0 && resultSet.goToFirstRow()) {
468    // 获取可用于跨线程传递的ValuesBucket返回查询结果
469    return resultSet.getSendableRow();
470  }
471  return null;
472}
473
474
475@Entry
476@Component
477struct Index {
478  @State message: string = 'Hello World';
479
480  build() {
481    RelativeContainer() {
482      Text(this.message)
483        .id('HelloWorld')
484        .fontSize(50)
485        .fontWeight(FontWeight.Bold)
486        .alignRules({
487          center: { anchor: '__container__', align: VerticalAlign.Center },
488          middle: { anchor: '__container__', align: HorizontalAlign.Center }
489        })
490        .onClick(async () => {
491          let context: Context = this.getUIContext().getHostContext() as Context;
492
493          const item: relationalStore.ValuesBucket = {
494            name: "zhangsan",
495            age: 20,
496            salary: 5000
497          }
498          // 调用toSendableValuesBucket转换数据,用于跨线程传递。
499          const sendableItem = sendableRelationalStore.toSendableValuesBucket(item);
500          const insertRowId = await taskpool.execute(insert, context, sendableItem) as number;
501          console.info(`Insert data success, row id is: ${insertRowId}`);
502
503          const rowData = await taskpool.execute(queryByName, context, "zhangsan");
504          if (rowData) {
505            const row =
506              sendableRelationalStore.fromSendableValuesBucket(rowData as sendableRelationalStore.ValuesBucket);
507            console.info(`Query success, name is ${row['name']}, age is ${row['age']}.`);
508          } else {
509            console.error(`Query failed.`)
510          }
511        })
512    }
513    .height('100%')
514    .width('100%')
515  }
516}
517```