-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathTableClient.ts
939 lines (890 loc) · 33.4 KB
/
TableClient.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import type {
CreateTableEntityResponse,
DeleteTableEntityOptions,
GetAccessPolicyResponse,
GetTableEntityOptions,
GetTableEntityResponse,
ListTableEntitiesOptions,
SignedIdentifier,
TableServiceClientOptions as TableClientOptions,
TableEntity,
TableEntityQueryOptions,
TableEntityResult,
TableEntityResultPage,
TableTransactionResponse,
TransactionAction,
UpdateMode,
UpdateTableEntityOptions,
} from "./models";
import type {
DeleteTableEntityResponse,
SetAccessPolicyResponse,
UpdateEntityResponse,
UpsertEntityResponse,
} from "./generatedModels";
import type {
FullOperationResponse,
InternalClientPipelineOptions,
OperationOptions,
ServiceClient,
ServiceClientOptions,
} from "@azure/core-client";
import type { TableDeleteEntityOptionalParams } from "./generated";
import { GeneratedClient } from "./generated";
import type { NamedKeyCredential, SASCredential, TokenCredential } from "@azure/core-auth";
import { isNamedKeyCredential, isSASCredential, isTokenCredential } from "@azure/core-auth";
import { COSMOS_SCOPE, STORAGE_SCOPE, TablesLoggingAllowedHeaderNames } from "./utils/constants";
import { decodeContinuationToken, encodeContinuationToken } from "./utils/continuationToken";
import {
deserialize,
deserializeObjectsArray,
deserializeSignedIdentifier,
serialize,
serializeQueryOptions,
serializeSignedIdentifiers,
} from "./serialization";
import { parseXML, stringifyXML } from "@azure/core-xml";
import { InternalTableTransaction } from "./TableTransaction";
import type { ListEntitiesResponse } from "./utils/internalModels";
import type { PagedAsyncIterableIterator } from "@azure/core-paging";
import type { Pipeline } from "@azure/core-rest-pipeline";
import type { Table } from "./generated/operationsInterfaces";
import type { TableQueryEntitiesOptionalParams } from "./generated/models";
import { Uuid } from "./utils/uuid";
import { apiVersionPolicy } from "./utils/apiVersionPolicy";
import { cosmosPatchPolicy } from "./cosmosPathPolicy";
import { escapeQuotes } from "./odata";
import { getClientParamsFromConnectionString } from "./utils/connectionString";
import { handleTableAlreadyExists } from "./utils/errorHelpers";
import { isCosmosEndpoint } from "./utils/isCosmosEndpoint";
import { isCredential } from "./utils/isCredential";
import { logger } from "./logger";
import { setTokenChallengeAuthenticationPolicy } from "./utils/challengeAuthenticationUtils";
import { tablesNamedKeyCredentialPolicy } from "./tablesNamedCredentialPolicy";
import { tablesSASTokenPolicy } from "./tablesSASTokenPolicy";
import { tracingClient } from "./utils/tracing";
/**
* A TableClient represents a Client to the Azure Tables service allowing you
* to perform operations on a single table.
*/
export class TableClient {
/**
* Table Account URL
*/
public url: string;
/**
* Represents a pipeline for making a HTTP request to a URL.
* Pipelines can have multiple policies to manage manipulating each request before and after it is made to the server.
*/
public pipeline: Pipeline;
private table: Table;
private generatedClient: ServiceClient;
private credential?: NamedKeyCredential | SASCredential | TokenCredential;
private clientOptions: TableClientOptions;
private readonly allowInsecureConnection: boolean;
/**
* Name of the table to perform operations on.
*/
public readonly tableName: string;
/**
* Creates a new instance of the TableClient class.
*
* @param url - The URL of the service account that is the target of the desired operation, such as "https://myaccount.table.core.windows.net".
* @param tableName - the name of the table
* @param credential - NamedKeyCredential used to authenticate requests. Only Supported for Node
* @param options - Optional. Options to configure the HTTP pipeline.
*
*
* ### Example using an account name/key:
*
* ```js
* const { AzureNamedKeyCredential, TableClient } = require("@azure/data-tables");
* const account = "<storage account name>";
* const accountKey = "<account key>"
* const tableName = "<table name>";
* const sharedKeyCredential = new AzureNamedKeyCredential(account, accountKey);
*
* const client = new TableClient(
* `https://${account}.table.core.windows.net`,
* tableName,
* sharedKeyCredential
* );
* ```
*/
constructor(
url: string,
tableName: string,
credential: NamedKeyCredential,
options?: TableClientOptions,
);
/**
* Creates a new instance of the TableClient class.
*
* @param url - The URL of the service account that is the target of the desired operation, such as "https://myaccount.table.core.windows.net".
* @param tableName - the name of the table
* @param credential - SASCredential used to authenticate requests
* @param options - Optional. Options to configure the HTTP pipeline.
*
*
* ### Example using a SAS Token:
*
* ```js
* const { AzureSASCredential, TableClient } = require("@azure/data-tables");
* const account = "<storage account name>";
* const sasToken = "<sas-token>";
* const tableName = "<table name>";
* const sasCredential = new AzureSASCredential(sasToken);
*
* const client = new TableClient(
* `https://${account}.table.core.windows.net`,
* tableName,
* sasCredential
* );
* ```
*/
constructor(
url: string,
tableName: string,
credential: SASCredential,
options?: TableClientOptions,
);
/**
* Creates a new instance of the TableClient class.
*
* @param url - The URL of the service account that is the target of the desired operation, such as "https://myaccount.table.core.windows.net".
* @param tableName - the name of the table
* @param credential - Azure Active Directory credential used to authenticate requests
* @param options - Optional. Options to configure the HTTP pipeline.
*
*
* ### Example using an Azure Active Directory credential:
*
* ```js
* cons { DefaultAzureCredential } = require("@azure/identity");
* const { AzureSASCredential, TableClient } = require("@azure/data-tables");
* const account = "<storage account name>";
* const sasToken = "<sas-token>";
* const tableName = "<table name>";
* const credential = new DefaultAzureCredential();
*
* const client = new TableClient(
* `https://${account}.table.core.windows.net`,
* tableName,
* credential
* );
* ```
*/
constructor(
url: string,
tableName: string,
credential: TokenCredential,
options?: TableClientOptions,
);
/**
* Creates an instance of TableClient.
*
* @param url - A Client string pointing to Azure Storage table service, such as
* "https://myaccount.table.core.windows.net". You can append a SAS,
* such as "https://myaccount.table.core.windows.net?sasString".
* @param tableName - the name of the table
* @param options - Options to configure the HTTP pipeline.
*
* ### Example appending a SAS token:
*
* ```js
* const { TableClient } = require("@azure/data-tables");
* const account = "<storage account name>";
* const sasToken = "<SAS token>";
* const tableName = "<table name>";
*
* const client = new TableClient(
* `https://${account}.table.core.windows.net?${sasToken}`,
* `${tableName}`
* );
* ```
*/
constructor(url: string, tableName: string, options?: TableClientOptions);
constructor(
url: string,
tableName: string,
credentialOrOptions?: NamedKeyCredential | SASCredential | TableClientOptions | TokenCredential,
options: TableClientOptions = {},
) {
this.url = url;
this.tableName = tableName;
const isCosmos = isCosmosEndpoint(this.url);
const credential = isCredential(credentialOrOptions) ? credentialOrOptions : undefined;
this.credential = credential;
this.clientOptions = (!isCredential(credentialOrOptions) ? credentialOrOptions : options) || {};
this.allowInsecureConnection = this.clientOptions.allowInsecureConnection ?? false;
const internalPipelineOptions: ServiceClientOptions & InternalClientPipelineOptions = {
...this.clientOptions,
endpoint: this.clientOptions.endpoint || this.url,
loggingOptions: {
logger: logger.info,
additionalAllowedHeaderNames: [...TablesLoggingAllowedHeaderNames],
},
deserializationOptions: {
parseXML,
},
serializationOptions: {
stringifyXML,
},
};
const generatedClient = new GeneratedClient(this.url, internalPipelineOptions);
if (isNamedKeyCredential(credential)) {
generatedClient.pipeline.addPolicy(tablesNamedKeyCredentialPolicy(credential));
} else if (isSASCredential(credential)) {
generatedClient.pipeline.addPolicy(tablesSASTokenPolicy(credential));
}
if (isTokenCredential(credential)) {
const scope = isCosmos ? COSMOS_SCOPE : STORAGE_SCOPE;
setTokenChallengeAuthenticationPolicy(generatedClient.pipeline, credential, scope);
}
if (isCosmos) {
generatedClient.pipeline.addPolicy(cosmosPatchPolicy());
}
if (options.version) {
generatedClient.pipeline.addPolicy(apiVersionPolicy(options.version));
}
this.generatedClient = generatedClient;
this.table = generatedClient.table;
this.pipeline = generatedClient.pipeline;
}
/**
* Permanently deletes the current table with all of its entities.
* @param options - The options parameters.
*
* ### Example deleting a table
* ```js
* const { AzureNamedKeyCredential, TableClient } = require("@azure/data-tables")
* const account = "<storage account name>";
* const accountKey = "<account key>"
* const tableName = "<table name>";
* const sharedKeyCredential = new AzureNamedKeyCredential(account, accountKey);
*
* const client = new TableClient(
* `https://${account}.table.core.windows.net`,
* `${tableName}`,
* sharedKeyCredential
* );
*
* // calling deleteTable will delete the table used
* // to instantiate the TableClient.
* // Note: If the table doesn't exist this function doesn't fail.
* await client.deleteTable();
* ```
*/
// eslint-disable-next-line @azure/azure-sdk/ts-naming-options
public deleteTable(options: OperationOptions = {}): Promise<void> {
return tracingClient.withSpan("TableClient.deleteTable", options, async (updatedOptions) => {
try {
await this.table.delete(this.tableName, updatedOptions);
} catch (e: any) {
if (e.statusCode === 404) {
logger.info("TableClient.deleteTable: Table doesn't exist");
} else {
throw e;
}
}
});
}
/**
* Creates a table with the tableName passed to the client constructor
* @param options - The options parameters.
*
* ### Example creating a table
* ```js
* const { AzureNamedKeyCredential, TableClient } = require("@azure/data-tables")
* const account = "<storage account name>";
* const accountKey = "<account key>"
* const tableName = "<table name>";
* const sharedKeyCredential = new AzureNamedKeyCredential(account, accountKey);
*
* const client = new TableClient(
* `https://${account}.table.core.windows.net`,
* `${tableName}`,
* sharedKeyCredential
* );
*
* // calling create table will create the table used
* // to instantiate the TableClient.
* // Note: If the table already
* // exists this function doesn't throw.
* await client.createTable();
* ```
*/
// eslint-disable-next-line @azure/azure-sdk/ts-naming-options
public createTable(options: OperationOptions = {}): Promise<void> {
return tracingClient.withSpan("TableClient.createTable", options, async (updatedOptions) => {
try {
await this.table.create({ name: this.tableName }, updatedOptions);
} catch (e: any) {
handleTableAlreadyExists(e, { ...updatedOptions, logger, tableName: this.tableName });
}
});
}
/**
* Returns a single entity in the table.
* @param partitionKey - The partition key of the entity.
* @param rowKey - The row key of the entity.
* @param options - The options parameters.
*
* ### Example getting an entity
* ```js
* const { AzureNamedKeyCredential, TableClient } = require("@azure/data-tables")
* const account = "<storage account name>";
* const accountKey = "<account key>"
* const tableName = "<table name>";
* const sharedKeyCredential = new AzureNamedKeyCredential(account, accountKey);
*
* const client = new TableClient(
* `https://${account}.table.core.windows.net`,
* `${tableName}`,
* sharedKeyCredential
* );
*
* // getEntity will get a single entity stored in the service that
* // matches exactly the partitionKey and rowKey used as parameters
* // to the method.
* const entity = await client.getEntity("<partitionKey>", "<rowKey>");
* console.log(entity);
* ```
*/
public getEntity<T extends object = Record<string, unknown>>(
partitionKey: string,
rowKey: string,
// eslint-disable-next-line @azure/azure-sdk/ts-naming-options
options: GetTableEntityOptions = {},
): Promise<GetTableEntityResponse<TableEntityResult<T>>> {
return tracingClient.withSpan("TableClient.getEntity", options, async (updatedOptions) => {
let parsedBody: any;
function onResponse(rawResponse: FullOperationResponse, flatResponse: unknown): void {
parsedBody = rawResponse.parsedBody;
if (updatedOptions.onResponse) {
updatedOptions.onResponse(rawResponse, flatResponse);
}
}
const { disableTypeConversion, queryOptions, ...getEntityOptions } = updatedOptions;
await this.table.queryEntitiesWithPartitionAndRowKey(
this.tableName,
escapeQuotes(partitionKey),
escapeQuotes(rowKey),
{
...getEntityOptions,
queryOptions: serializeQueryOptions(queryOptions || {}),
onResponse,
},
);
const tableEntity = deserialize<TableEntityResult<T>>(
parsedBody,
disableTypeConversion ?? false,
);
return tableEntity;
});
}
/**
* Queries entities in a table.
* @param options - The options parameters.
*
* Example listing entities
* ```js
* const { AzureNamedKeyCredential, TableClient } = require("@azure/data-tables")
* const account = "<storage account name>";
* const accountKey = "<account key>"
* const tableName = "<table name>";
* const sharedKeyCredential = new AzureNamedKeyCredential(account, accountKey);
*
* const client = new TableClient(
* `https://${account}.table.core.windows.net`,
* `${tableName}`,
* sharedKeyCredential
* );
*
* // list entities returns a AsyncIterableIterator
* // this helps consuming paginated responses by
* // automatically handling getting the next pages
* const entities = client.listEntities();
*
* // this loop will get all the entities from all the pages
* // returned by the service
* for await (const entity of entities) {
* console.log(entity);
* }
* ```
*/
public listEntities<T extends object = Record<string, unknown>>(
// eslint-disable-next-line @azure/azure-sdk/ts-naming-options
options: ListTableEntitiesOptions = {},
): PagedAsyncIterableIterator<TableEntityResult<T>, TableEntityResultPage<T>> {
const tableName = this.tableName;
const iter = this.listEntitiesAll<T>(tableName, options);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: (settings) => {
const pageOptions: InternalListTableEntitiesOptions = {
...options,
queryOptions: { ...options.queryOptions, top: settings?.maxPageSize },
};
if (settings?.continuationToken) {
pageOptions.continuationToken = settings.continuationToken;
}
return this.listEntitiesPage(tableName, pageOptions);
},
};
}
private async *listEntitiesAll<T extends object>(
tableName: string,
options?: InternalListTableEntitiesOptions,
): AsyncIterableIterator<TableEntityResult<T>> {
const firstPage = await this._listEntities<T>(tableName, options);
yield* firstPage;
if (firstPage.continuationToken) {
const optionsWithContinuation: InternalListTableEntitiesOptions = {
...options,
continuationToken: firstPage.continuationToken,
};
for await (const page of this.listEntitiesPage<T>(tableName, optionsWithContinuation)) {
yield* page;
}
}
}
private async *listEntitiesPage<T extends object>(
tableName: string,
options: InternalListTableEntitiesOptions = {},
): AsyncIterableIterator<ListEntitiesResponse<TableEntityResult<T>>> {
let result = await tracingClient.withSpan(
"TableClient.listEntitiesPage",
options,
(updatedOptions) => this._listEntities<T>(tableName, updatedOptions),
);
yield result;
while (result.continuationToken) {
const optionsWithContinuation: InternalListTableEntitiesOptions = {
...options,
continuationToken: result.continuationToken,
};
result = await tracingClient.withSpan(
"TableClient.listEntitiesPage",
optionsWithContinuation,
(updatedOptions, span) => {
span.setAttribute("continuationToken", result.continuationToken);
return this._listEntities<T>(tableName, updatedOptions);
},
);
yield result;
}
}
private async _listEntities<T extends object>(
tableName: string,
options: InternalListTableEntitiesOptions = {},
): Promise<TableEntityResultPage<T>> {
const { disableTypeConversion = false } = options;
const queryOptions = serializeQueryOptions(options.queryOptions || {});
const listEntitiesOptions: TableQueryEntitiesOptionalParams = {
...options,
queryOptions,
};
// If a continuation token is used, decode it and set the next row and partition key
if (options.continuationToken) {
const continuationToken = decodeContinuationToken(options.continuationToken);
listEntitiesOptions.nextRowKey = continuationToken.nextRowKey;
listEntitiesOptions.nextPartitionKey = continuationToken.nextPartitionKey;
}
const {
xMsContinuationNextPartitionKey: nextPartitionKey,
xMsContinuationNextRowKey: nextRowKey,
value,
} = await this.table.queryEntities(tableName, listEntitiesOptions);
const tableEntities = deserializeObjectsArray<TableEntityResult<T>>(
value ?? [],
disableTypeConversion,
);
// Encode nextPartitionKey and nextRowKey as a single continuation token and add it as a
// property to the page.
const continuationToken = encodeContinuationToken(nextPartitionKey, nextRowKey);
const page: TableEntityResultPage<T> = Object.assign([...tableEntities], {
continuationToken,
});
return page;
}
/**
* Insert entity in the table.
* @param entity - The properties for the table entity.
* @param options - The options parameters.
*
* ### Example creating an entity
* ```js
* const { AzureNamedKeyCredential, TableClient } = require("@azure/data-tables")
* const account = "<storage account name>";
* const accountKey = "<account key>"
* const tableName = "<table name>";
* const sharedKeyCredential = new AzureNamedKeyCredential(account, accountKey);
*
* const client = new TableClient(
* `https://${account}.table.core.windows.net`,
* `${tableName}`,
* sharedKeyCredential
* );
*
* // partitionKey and rowKey are required properties of the entity to create
* // and accepts any other properties
* await client.createEntity({partitionKey: "p1", rowKey: "r1", foo: "Hello!"});
* ```
*/
public createEntity<T extends object>(
entity: TableEntity<T>,
// eslint-disable-next-line @azure/azure-sdk/ts-naming-options
options: OperationOptions = {},
): Promise<CreateTableEntityResponse> {
return tracingClient.withSpan("TableClient.createEntity", options, (updatedOptions) => {
const { ...createTableEntity } = updatedOptions || {};
return this.table.insertEntity(this.tableName, {
...createTableEntity,
tableEntityProperties: serialize(entity),
responsePreference: "return-no-content",
});
});
}
/**
* Deletes the specified entity in the table.
* @param partitionKey - The partition key of the entity.
* @param rowKey - The row key of the entity.
* @param options - The options parameters.
*
* ### Example deleting an entity
* ```js
* const { AzureNamedKeyCredential, TableClient } = require("@azure/data-tables")
* const account = "<storage account name>";
* const accountKey = "<account key>"
* const tableName = "<table name>";
* const sharedKeyCredential = new AzureNamedKeyCredential(account, accountKey);
*
* const client = new TableClient(
* `https://${account}.table.core.windows.net`,
* `${tableName}`,
* sharedKeyCredential
* );
*
* // deleteEntity deletes the entity that matches
* // exactly the partitionKey and rowKey passed as parameters
* await client.deleteEntity("<partitionKey>", "<rowKey>")
* ```
*/
public deleteEntity(
partitionKey: string,
rowKey: string,
// eslint-disable-next-line @azure/azure-sdk/ts-naming-options
options: DeleteTableEntityOptions = {},
): Promise<DeleteTableEntityResponse> {
return tracingClient.withSpan("TableClient.deleteEntity", options, (updatedOptions) => {
const { etag = "*", ...rest } = updatedOptions;
const deleteOptions: TableDeleteEntityOptionalParams = {
...rest,
};
return this.table.deleteEntity(
this.tableName,
escapeQuotes(partitionKey),
escapeQuotes(rowKey),
etag,
deleteOptions,
);
});
}
/**
* Update an entity in the table.
* @param entity - The properties of the entity to be updated.
* @param mode - The different modes for updating the entity:
* - Merge: Updates an entity by updating the entity's properties without replacing the existing entity.
* - Replace: Updates an existing entity by replacing the entire entity.
* @param options - The options parameters.
*
* ### Example updating an entity
* ```js
* const { AzureNamedKeyCredential, TableClient } = require("@azure/data-tables")
* const account = "<storage account name>";
* const accountKey = "<account key>"
* const tableName = "<table name>";
* const sharedKeyCredential = new AzureNamedKeyCredential(account, accountKey);
*
* const client = new TableClient(
* `https://${account}.table.core.windows.net`,
* `${tableName}`,
* sharedKeyCredential
* );
*
* const entity = {partitionKey: "p1", rowKey: "r1", bar: "updatedBar"};
*
* // Update uses update mode "Merge" as default
* // merge means that update will match a stored entity
* // that has the same partitionKey and rowKey as the entity
* // passed to the method and then will only update the properties present in it.
* // Any other properties that are not defined in the entity passed to updateEntity
* // will remain as they are in the service
* await client.updateEntity(entity)
*
* // We can also set the update mode to Replace, which will match the entity passed
* // to updateEntity with one stored in the service and replace with the new one.
* // If there are any missing properties in the entity passed to updateEntity, they
* // will be removed from the entity stored in the service
* await client.updateEntity(entity, "Replace")
* ```
*/
public updateEntity<T extends object>(
entity: TableEntity<T>,
mode: UpdateMode = "Merge",
// eslint-disable-next-line @azure/azure-sdk/ts-naming-options
options: UpdateTableEntityOptions = {},
): Promise<UpdateEntityResponse> {
return tracingClient.withSpan(
"TableClient.updateEntity",
options,
async (updatedOptions) => {
const partitionKey = escapeQuotes(entity.partitionKey);
const rowKey = escapeQuotes(entity.rowKey);
const { etag = "*", ...updateEntityOptions } = updatedOptions || {};
if (mode === "Merge") {
return this.table.mergeEntity(this.tableName, partitionKey, rowKey, {
tableEntityProperties: serialize(entity),
ifMatch: etag,
...updateEntityOptions,
});
}
if (mode === "Replace") {
return this.table.updateEntity(this.tableName, partitionKey, rowKey, {
tableEntityProperties: serialize(entity),
ifMatch: etag,
...updateEntityOptions,
});
}
throw new Error(`Unexpected value for update mode: ${mode}`);
},
{
spanAttributes: {
updateEntityMode: mode,
},
},
);
}
/**
* Upsert an entity in the table.
* @param entity - The properties for the table entity.
* @param mode - The different modes for updating the entity:
* - Merge: Updates an entity by updating the entity's properties without replacing the existing entity.
* - Replace: Updates an existing entity by replacing the entire entity.
* @param options - The options parameters.
*
* ### Example upserting an entity
* ```js
* const { AzureNamedKeyCredential, TableClient } = require("@azure/data-tables")
* const account = "<storage account name>";
* const accountKey = "<account key>"
* const tableName = "<table name>";
* const sharedKeyCredential = new AzureNamedKeyCredential(account, accountKey);
*
* const client = new TableClient(
* `https://${account}.table.core.windows.net`,
* `${tableName}`,
* sharedKeyCredential
* );
*
* const entity = {partitionKey: "p1", rowKey: "r1", bar: "updatedBar"};
*
* // Upsert uses update mode "Merge" as default.
* // This behaves similarly to update but creates the entity
* // if it doesn't exist in the service
* await client.upsertEntity(entity)
*
* // We can also set the update mode to Replace.
* // This behaves similarly to update but creates the entity
* // if it doesn't exist in the service
* await client.upsertEntity(entity, "Replace")
* ```
*/
public upsertEntity<T extends object>(
entity: TableEntity<T>,
mode: UpdateMode = "Merge",
// eslint-disable-next-line @azure/azure-sdk/ts-naming-options
options: OperationOptions = {},
): Promise<UpsertEntityResponse> {
return tracingClient.withSpan(
"TableClient.upsertEntity",
options,
async (updatedOptions) => {
const partitionKey = escapeQuotes(entity.partitionKey);
const rowKey = escapeQuotes(entity.rowKey);
if (mode === "Merge") {
return this.table.mergeEntity(this.tableName, partitionKey, rowKey, {
tableEntityProperties: serialize(entity),
...updatedOptions,
});
}
if (mode === "Replace") {
return this.table.updateEntity(this.tableName, partitionKey, rowKey, {
tableEntityProperties: serialize(entity),
...updatedOptions,
});
}
throw new Error(`Unexpected value for update mode: ${mode}`);
},
{
spanAttributes: {
upsertEntityMode: mode,
},
},
);
}
/**
* Retrieves details about any stored access policies specified on the table that may be used with
* Shared Access Signatures.
* @param options - The options parameters.
*/
// eslint-disable-next-line @azure/azure-sdk/ts-naming-options
public getAccessPolicy(options: OperationOptions = {}): Promise<GetAccessPolicyResponse> {
return tracingClient.withSpan(
"TableClient.getAccessPolicy",
options,
async (updatedOptions) => {
const signedIdentifiers = await this.table.getAccessPolicy(this.tableName, updatedOptions);
return deserializeSignedIdentifier(signedIdentifiers);
},
);
}
/**
* Sets stored access policies for the table that may be used with Shared Access Signatures.
* @param tableAcl - The Access Control List for the table.
* @param options - The options parameters.
*/
public setAccessPolicy(
tableAcl: SignedIdentifier[],
// eslint-disable-next-line @azure/azure-sdk/ts-naming-options
options: OperationOptions = {},
): Promise<SetAccessPolicyResponse> {
return tracingClient.withSpan("TableClient.setAccessPolicy", options, (updatedOptions) => {
const serlializedAcl = serializeSignedIdentifiers(tableAcl);
return this.table.setAccessPolicy(this.tableName, {
...updatedOptions,
tableAcl: serlializedAcl,
});
});
}
/**
* Submits a Transaction which is composed of a set of actions. You can provide the actions as a list
* or you can use {@link TableTransaction} to help building the transaction.
*
* Example usage:
* ```typescript
* const { TableClient } = require("@azure/data-tables");
* const connectionString = "<connection-string>"
* const tableName = "<tableName>"
* const client = TableClient.fromConnectionString(connectionString, tableName);
* const actions = [
* ["create", {partitionKey: "p1", rowKey: "1", data: "test1"}],
* ["delete", {partitionKey: "p1", rowKey: "2"}],
* ["update", {partitionKey: "p1", rowKey: "3", data: "newTest"}, "Merge"]
* ]
* const result = await client.submitTransaction(actions);
* ```
*
* Example usage with TableTransaction:
* ```js
* const { TableClient } = require("@azure/data-tables");
* const connectionString = "<connection-string>"
* const tableName = "<tableName>"
* const client = TableClient.fromConnectionString(connectionString, tableName);
* const transaction = new TableTransaction();
* // Call the available action in the TableTransaction object
* transaction.create({partitionKey: "p1", rowKey: "1", data: "test1"});
* transaction.delete("p1", "2");
* transaction.update({partitionKey: "p1", rowKey: "3", data: "newTest"}, "Merge")
* // submitTransaction with the actions list on the transaction.
* const result = await client.submitTransaction(transaction.actions);
* ```
*
* @param actions - tuple that contains the action to perform, and the entity to perform the action with
*/
public async submitTransaction(actions: TransactionAction[]): Promise<TableTransactionResponse> {
const partitionKey = actions[0][1].partitionKey;
const transactionId = Uuid.generateUuid();
const changesetId = Uuid.generateUuid();
// Add pipeline
const transactionClient = new InternalTableTransaction(
this.url,
partitionKey,
transactionId,
changesetId,
this.generatedClient,
new TableClient(this.url, this.tableName),
this.credential,
this.allowInsecureConnection,
);
for (const item of actions) {
const [action, entity, updateMode = "Merge", updateOptions] = item;
switch (action) {
case "create":
transactionClient.createEntity(entity);
break;
case "delete":
transactionClient.deleteEntity(entity.partitionKey, entity.rowKey);
break;
case "update":
transactionClient.updateEntity(entity, updateMode, updateOptions);
break;
case "upsert":
transactionClient.upsertEntity(entity, updateMode);
}
}
return transactionClient.submitTransaction();
}
/**
*
* Creates an instance of TableClient from connection string.
*
* @param connectionString - Account connection string or a SAS connection string of an Azure storage account.
* [ Note - Account connection string can only be used in NODE.JS runtime. ]
* Account connection string example -
* `DefaultEndpointsProtocol=https;AccountName=myaccount;AccountKey=accountKey;EndpointSuffix=core.windows.net`
* SAS connection string example -
* `BlobEndpoint=https://myaccount.table.core.windows.net/;QueueEndpoint=https://myaccount.queue.core.windows.net/;FileEndpoint=https://myaccount.file.core.windows.net/;TableEndpoint=https://myaccount.table.core.windows.net/;SharedAccessSignature=sasString`
* @param options - Options to configure the HTTP pipeline.
* @returns A new TableClient from the given connection string.
*/
public static fromConnectionString(
connectionString: string,
tableName: string,
// eslint-disable-next-line @azure/azure-sdk/ts-naming-options
options?: TableClientOptions,
): TableClient {
const {
url,
options: clientOptions,
credential,
} = getClientParamsFromConnectionString(connectionString, options);
if (credential) {
return new TableClient(url, tableName, credential, clientOptions);
} else {
return new TableClient(url, tableName, clientOptions);
}
}
}
type InternalQueryOptions = TableEntityQueryOptions & { top?: number };
interface InternalListTableEntitiesOptions extends ListTableEntitiesOptions {
queryOptions?: InternalQueryOptions;
/**
* An entity query continuation token from a previous call.
*/
continuationToken?: string;
/**
* If true, automatic type conversion will be disabled and entity properties will
* be represented by full metadata types. For example, an Int32 value will be \{value: "123", type: "Int32"\} instead of 123.
* This option applies for all the properties
*/
disableTypeConversion?: boolean;
}