From 925bd4559e2b318cb83bb05102ffad6fdeadd4fb Mon Sep 17 00:00:00 2001 From: Stephen York Date: Mon, 4 Jan 2021 12:53:56 +1100 Subject: [PATCH] Update main.lua Replace recursive call to saveData with CreateThread and a timer. Loop now builds when and where clauses for a set operation update against multiple records with a single mysql execute rather than a single update PER player. --- server/main.lua | 45 ++++++++++++++++++++++++++++++++++++++------- 1 file changed, 38 insertions(+), 7 deletions(-) diff --git a/server/main.lua b/server/main.lua index 246800dc..c1252f0f 100644 --- a/server/main.lua +++ b/server/main.lua @@ -70,20 +70,51 @@ AddEventHandler('esx_status:update', function(status) end end) +Citizen.CreateThread(function() + while(true) do + Citizen.Wait(10 * 60 * 1000) + + SaveData() + + end + +end) + function SaveData() local xPlayers = ESX.GetPlayers() + -- Example of a bulk update statement that we are building below + --[[ + UPDATE users + SET status = (case when identifier = 'license:123' then '{hunger:45, thirst:23}' + when identifier = 'license:456' then '{hunger:1000, thirst:1000}' + when identifier = 'license:789' then '{hunger:1000, thirst:1000}' + end) + WHERE identifier in ('license:123', 'license:456', 'license:789') + + ]] + local updateStatement = 'UPDATE users SET status = (case %s end) where identifier in (%s)' + local whenList = '' + local whereList = '' + local firstItem = true + for i=1, #xPlayers, 1 do local xPlayer = ESX.GetPlayerFromId(xPlayers[i]) local status = xPlayer.get('status') - MySQL.Async.execute('UPDATE users SET status = @status WHERE identifier = @identifier', { - ['@status'] = json.encode(status), - ['@identifier'] = xPlayer.identifier - }) + whenList = whenList .. string.format('when identifier = \'%s\' then \'%s\' ', xPlayer.identifier, json.encode(status)) + + if firstItem == false then + whereList = whereList .. ', ' + end + whereList = whereList .. string.format('\'%s\'', xPlayer.identifier) + + firstItem = false + end - SetTimeout(10 * 60 * 1000, SaveData) -end + local sql = string.format(updateStatement, whenList, whereList) -SaveData() + MySQL.Async.execute(sql) + +end