How to delete a whole datastore?

Hello
What is the easiest way to delete a whole datastore (or all items in it)?

Thank you

like players inventory or whole data ???

Depends; what data are you deleting? Player data? Check if the data saved is outdated; and include a version.
Did you accidentally spam the datastores? Well goodluck. :ListKeysAsync()

You mean every row in it as well?

yes, I want to delete all data in a datastore and I wonder whether there is an easier way than to loop through all rows.

Here’s a bruteforce approach:

local DataStoreService = game:GetService("DataStoreService")

local DATASTORE_TO_DELETE = "YOUR DATASTORE NAME HERE"

local function removeKey(datastore: DataStore, key: string): ()
	local success, response = pcall(function()
		return datastore:RemoveAsync(key)
	end)
	if success then
		print("Removed", key)
		return 
	end
	--Silence the rate limit errors
	if not response:find("Too many requests") then warn(response) end
	return removeKey(datastore, key)
end

local function listKeys(datastore: DataStore, cursor: string?, batchSize: number): DataStoreKeyPages
	local success, response = pcall(function()
		return datastore:ListKeysAsync("", batchSize, cursor, true)
	end)
	if success then return response end
	warn(response)
	return listKeys(datastore, cursor, batchSize)
end

local function removeKeys(datastore: DataStore, keys: {string}): ()
	local threads = {}
	--remove the batch of keys in parallel
	for _, key in pairs(keys) do
		table.insert(threads, task.spawn(removeKey, datastore, key))
	end
	--yield until the datastore stops crying and has deleted everything
	while task.wait(0.5) do
		local isFinished = true
		for _, thread in pairs(threads) do
			if coroutine.status(thread) ~= "dead" then
				isFinished = false 
				break
			end
		end
		if isFinished then break end
	end
end

local function getKeys(datastore: DataStore, cursor: string?, amount: number): (string, {string})
	local pages = listKeys(datastore, cursor, amount)
	local cursor, keys = pages.Cursor, {}
	while true do
		for _, key: DataStoreKey in pairs(pages:GetCurrentPage()) do
			table.insert(keys, key.KeyName)
		end
		if pages.IsFinished then break end
		pages = pages:AdvanceToNextPageAsync()
		if not pages then break end
	end
	return cursor, keys
end

local function deleteDatastore(name: string): ()
	local datastore = DataStoreService:GetDataStore(name)
	local batchSize = 200
	local cursor, keys
	while true do
		cursor, keys = getKeys(datastore, cursor, batchSize)
		removeKeys(datastore, keys)
		task.wait(10) --Let the API take a nap
		if cursor == "" then break end
	end
	print("Datastore", name, "has been deleted!")
end

deleteDatastore(DATASTORE_TO_DELETE)

I suggest running the above code again after it says it deleted the datastore, just so you know it really cleared up the entire thing.

1 Like