Created
June 8, 2023 18:18
-
-
Save fukasawah/5d9be035da5b50ce3c1c81fda6600e66 to your computer and use it in GitHub Desktop.
(TypeScript+AWS SDK v3)DynamoDBテーブルから全レコードを削除する関数 (Delete all records from a DynamoDB table)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { | |
DescribeTableCommand, | |
DynamoDBClient, | |
ListTablesCommand, | |
ScanCommand, | |
BatchWriteItemCommand, | |
ScanCommandOutput, | |
AttributeValue, | |
} from '@aws-sdk/client-dynamodb'; | |
/** | |
* 指定したDynamoDBのテーブル名のテーブルから全てのItemを取得するジェネレータ | |
* @param tableName DynamoDBのテーブル名 | |
*/ | |
const createItemGenerator = async function* (dynamoDBClient: DynamoDBClient, tableName: string) { | |
let LastEvaluatedKey; | |
while (true) { | |
const scanRes: ScanCommandOutput = await dynamoDBClient.send( | |
new ScanCommand({ TableName: tableName, ExclusiveStartKey: LastEvaluatedKey }), | |
); | |
for (const item of scanRes.Items ?? []) { | |
yield item; | |
} | |
if (!scanRes.LastEvaluatedKey) { | |
break; | |
} | |
LastEvaluatedKey = scanRes.LastEvaluatedKey; | |
} | |
}; | |
/** | |
* イテレータから決まった要素数だけ切り出すジェネレータを生成します | |
* @param iterable イテレータ | |
* @param batchSize 分割サイズ | |
*/ | |
const batch = async function* batch<T>(iterable: AsyncIterableIterator<T>, batchSize: number) { | |
let items: T[] = []; | |
for await (const item of iterable) { | |
items.push(item); | |
if (items.length >= batchSize) { | |
yield items; | |
items = []; | |
} | |
} | |
if (items.length !== 0) { | |
yield items; | |
} | |
}; | |
/** | |
* テーブルの一覧を取得します。 | |
* メモ化されています。 | |
*/ | |
const getTableMetaData = (function () { | |
let memorize: { | |
[tableName: string]: { | |
/** レコードから一意のキーの値だけを持つレコードに変換する(削除で使用) */ | |
selectPrimaryKey: (record: Record<string, AttributeValue>) => Record<string, AttributeValue>; | |
}; | |
}; | |
return async (dynamoDBClient: DynamoDBClient) => { | |
// テーブルの一覧取得 | |
if (!memorize) { | |
memorize = {}; | |
const res = await dynamoDBClient.send(new ListTablesCommand({ Limit: 100 })); | |
for (const tableName of res.TableNames ?? []) { | |
const describe = await dynamoDBClient.send(new DescribeTableCommand({ TableName: tableName })); | |
const keySchema = describe.Table?.KeySchema; | |
const pk = keySchema?.find((key) => key.KeyType === 'HASH'); // Partition Key | |
const sk = keySchema?.find((key) => key.KeyType === 'RANGE'); // Sort Key | |
if (!pk) { | |
throw new Error(`Undefined partitionKey table. tableName=${tableName}, keySchema=${keySchema}`); | |
} | |
memorize[tableName] = { | |
selectPrimaryKey(record) { | |
return { | |
[pk.AttributeName as string]: record[pk.AttributeName as string], | |
...(sk ? { [sk.AttributeName as string]: record[sk.AttributeName as string] } : {}), | |
}; | |
}, | |
}; | |
} | |
} | |
return memorize; | |
}; | |
})(); | |
/** | |
* 指定したDynamoDBテーブルのレコードをすべて削除します。 | |
* | |
* @param tableName テーブル名 | |
*/ | |
export const clearTable = async (dynamoDBClient: DynamoDBClient, tableName: string) => { | |
const tableInfo = await getTableMetaData(dynamoDBClient); | |
const { selectPrimaryKey: selectKey } = tableInfo[tableName]; | |
for await (const chunk of batch(createItemGenerator(dynamoDBClient, tableName), 25)) { | |
await dynamoDBClient.send( | |
new BatchWriteItemCommand({ | |
RequestItems: { | |
[tableName]: chunk.map((m) => { | |
return { | |
DeleteRequest: { | |
Key: selectKey(m), | |
}, | |
}; | |
}), | |
}, | |
}), | |
); | |
} | |
}; | |
/** | |
* すべてのDynamoDBテーブルのレコードを削除します。 | |
*/ | |
export const clearAllTables = async (dynamoDBClient: DynamoDBClient) => { | |
const tableInfo = await getTableMetaData(dynamoDBClient); | |
await Promise.all(Object.keys(tableInfo).map((t) => clearTable(dynamoDBClient, t))); | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Copyright (c) 2023 fukasawah | |
Permission is hereby granted, free of charge, to any person obtaining a copy | |
of this software and associated documentation files (the "Software"), to deal | |
in the Software without restriction, including without limitation the rights | |
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
copies of the Software, and to permit persons to whom the Software is | |
furnished to do so, subject to the following conditions: | |
The above copyright notice and this permission notice shall be included in all | |
copies or substantial portions of the Software. | |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | |
SOFTWARE. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment