This repository has been archived on 2025-01-04. You can view files and clone it, but cannot push or open issues or pull requests.
lwb6/legacyworlds-server-data/db-structure/parts/050-updates/025-empire-debt.sql
Emmanuel BENOîT e50775ec76 Database definition & tests organisation
* The main loader script has been updated to generate the list of files
it needs to load automatically. As a consequence, files that contained
manually-maintained lists of scripts have been removed, and definition
directories have been renamed accordingly.

* PostgreSQL extension loading and configuration has been moved to a
separate script to be loaded automatically in the main transaction.

* Data and function definition scripts that had the -data or -functions
suffix have been renamed (the suffix is unnecessary).

* Unit tests have been reorganised to follow the definition's structure.

* Documentation has been improved
2012-01-06 11:19:19 +01:00

62 lines
No EOL
2 KiB
PL/PgSQL

-- LegacyWorlds Beta 6
-- PostgreSQL database scripts
--
-- Game updates - damage fleets and buildings when an
-- empire is out of cash and has too much upkeep
--
-- Copyright(C) 2004-2010, DeepClone Development
-- --------------------------------------------------------
CREATE OR REPLACE FUNCTION sys.process_empire_debt_updates( c_tick BIGINT )
RETURNS VOID
STRICT VOLATILE
SECURITY INVOKER
AS $$
DECLARE
fleet_dr REAL;
bld_dr REAL;
empire INT;
debt REAL;
upkeep REAL;
BEGIN
fleet_dr := sys.get_constant( 'game.debt.fleet');
bld_dr := sys.get_constant( 'game.debt.buildings');
FOR empire, debt IN SELECT e.name_id AS id , e.debt
FROM sys.updates su
INNER JOIN emp.updates eu ON eu.update_id = su.id
INNER JOIN emp.empires e ON eu.empire_id = e.name_id
WHERE su.last_tick = c_tick AND su.status = 'PROCESSING'
AND su.gu_type = 'EMPIRE_DEBT' AND e.debt > 0
FOR UPDATE
LOOP
PERFORM sys.write_log( 'EmpireDebt' , 'DEBUG'::log_level , 'Handling debt for empire #'
|| empire || ' (at tick: ' || debt || '; daily: ' || ( debt * 1440 ) || ')' );
debt := debt * 1440.0;
-- Does the empire own fleets?
SELECT INTO upkeep sum( d.upkeep * s.amount )
FROM fleets.fleets f
INNER JOIN fleets.ships s ON s.fleet_id = f.id
INNER JOIN tech.buildables d ON d.name_id = s.ship_id
WHERE f.owner_id = empire;
IF upkeep IS NOT NULL
THEN
PERFORM fleets.handle_debt( empire , upkeep , ( CASE WHEN debt > upkeep THEN upkeep ELSE debt END ) , fleet_dr );
debt := debt - upkeep;
CONTINUE WHEN debt <= 0;
END IF;
-- Does the empire have buildings?
SELECT INTO upkeep sum( d.upkeep * b.amount )
FROM emp.planets ep
INNER JOIN verse.planet_buildings b ON b.planet_id = ep.planet_id
INNER JOIN tech.buildables d ON d.name_id = b.building_id
WHERE ep.empire_id = empire;
CONTINUE WHEN NOT FOUND OR upkeep = 0;
PERFORM verse.handle_debt( empire , upkeep , debt , bld_dr );
END LOOP;
END;
$$ LANGUAGE plpgsql;