Repositories | Polyback | Log in to see private repositories


polyback-website / 7e551d223f42aecd154514fc9f0a7f04b918903f / container/db/schema.sql

59,077 bytes | parent directory

-- =====================================================================
-- Project Polygon (polygon-website-foss) - reconstructed MariaDB schema
-- Reconstructed from the inline SQL and row-property accesses in the PHP
-- sources (main branch, with hints from origin/* branches).
--
-- * All timestamps are UNIX epoch integers (the code uses UNIX_TIMESTAMP()
--   and time()/date() on fetched values), stored as BIGINT.
-- * No foreign keys: the application deletes rows freely.
-- * Column-name case matters for PHP (PDO::FETCH_OBJ / FETCH_ASSOC keys
--   use the case declared here), so it follows the case the code reads.
-- * Every NOT NULL column that some INSERT omits has a DEFAULT so the
--   schema works under STRICT_TRANS_TABLES.
-- =====================================================================

SET NAMES utf8mb4;

-- ---------------------------------------------------------------------
-- Users / auth
-- ---------------------------------------------------------------------

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(50) NOT NULL,
  `password` text DEFAULT NULL,
  `lastpwdchange` bigint(20) DEFAULT NULL,
  `email` varchar(255) DEFAULT NULL,
  `keyUsed` varchar(255) DEFAULT NULL,
  `jointime` bigint(20) NOT NULL DEFAULT 0,
  `lastonline` bigint(20) NOT NULL DEFAULT 0,
  `regip` varchar(45) DEFAULT NULL,
  `loginIp` varchar(45) DEFAULT NULL,
  `status` varchar(255) DEFAULT NULL,
  `blurb` text DEFAULT NULL,
  `adminlevel` tinyint(4) NOT NULL DEFAULT 0,
  `currency` int(11) NOT NULL DEFAULT 0,
  `nextCurrencyStipend` bigint(20) NOT NULL DEFAULT 0,
  `PlaceSlots` int(11) NOT NULL DEFAULT 3,
  `twofa` tinyint(1) NOT NULL DEFAULT 0,
  `twofaSecret` varchar(255) DEFAULT NULL,
  `twofaRecoveryCodes` text DEFAULT NULL,
  `discordID` varchar(32) DEFAULT NULL,
  `discordKey` varchar(64) DEFAULT NULL,
  `discordVerifiedTime` bigint(20) DEFAULT NULL,
  `Banned` tinyint(1) NOT NULL DEFAULT 0,
  `ForumThreads` int(11) NOT NULL DEFAULT 0,
  `ForumReplies` int(11) NOT NULL DEFAULT 0,
  `ClientPresenceLocation` int(11) DEFAULT NULL,
  `ClientPresenceType` varchar(50) DEFAULT NULL,
  `ClientPresencePing` bigint(20) NOT NULL DEFAULT 0,
  `Knockouts` int(11) NOT NULL DEFAULT 0,
  `Wipeouts` int(11) NOT NULL DEFAULT 0,
  `PlaceVisits` int(11) NOT NULL DEFAULT 0,
  `CreatableInviteTickets` int(11) NOT NULL DEFAULT 0,
  `LastInviteTicketCheck` bigint(20) DEFAULT NULL,
  `PendingFriendRequests` int(11) NOT NULL DEFAULT 0,
  `theme` varchar(20) NOT NULL DEFAULT 'light',
  `filter` tinyint(1) NOT NULL DEFAULT 1,
  `bodycolors` text NOT NULL DEFAULT '{"Head":24,"Torso":23,"Left Arm":24,"Right Arm":24,"Left Leg":119,"Right Leg":119}',
  PRIMARY KEY (`id`),
  UNIQUE KEY `username` (`username`),
  KEY `email` (`email`),
  KEY `discordID` (`discordID`),
  KEY `discordKey` (`discordKey`),
  KEY `lastonline` (`lastonline`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS `sessions` (
  `sessionKey` varchar(512) NOT NULL,
  `userId` int(11) NOT NULL,
  `userAgent` text DEFAULT NULL,
  `loginIp` varchar(45) DEFAULT NULL,
  `lastIp` varchar(45) DEFAULT NULL,
  `created` bigint(20) NOT NULL DEFAULT 0,
  `lastonline` bigint(20) NOT NULL DEFAULT 0,
  `csrf` varchar(128) DEFAULT NULL,
  `twofaVerified` tinyint(1) NOT NULL DEFAULT 0,
  `IsGameClient` tinyint(1) NOT NULL DEFAULT 0,
  `valid` tinyint(1) NOT NULL DEFAULT 1,
  PRIMARY KEY (`sessionKey`),
  KEY `userId` (`userId`),
  KEY `loginIp` (`loginIp`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS `InviteTickets` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `Ticket` varchar(255) NOT NULL,
  `TimeCreated` bigint(20) NOT NULL DEFAULT 0,
  `CreatedBy` int(11) NOT NULL,
  `UsedBy` int(11) DEFAULT NULL,
  PRIMARY KEY (`ID`),
  UNIQUE KEY `Ticket` (`Ticket`),
  KEY `CreatedBy` (`CreatedBy`),
  KEY `UsedBy` (`UsedBy`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS `namefilter` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) NOT NULL,
  `exact` tinyint(1) NOT NULL DEFAULT 0,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS `bans` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `userId` int(11) NOT NULL,
  `bannerId` int(11) NOT NULL,
  `timeStarted` bigint(20) NOT NULL DEFAULT 0,
  `timeEnds` bigint(20) NOT NULL DEFAULT 0,
  `reason` text NOT NULL,
  `banType` tinyint(4) NOT NULL,
  `note` text DEFAULT NULL,
  `isDismissed` tinyint(1) NOT NULL DEFAULT 0,
  PRIMARY KEY (`id`),
  KEY `userId` (`userId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS `stafflogs` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `time` bigint(20) NOT NULL DEFAULT 0,
  `adminId` int(11) NOT NULL,
  `action` text NOT NULL,
  PRIMARY KEY (`id`),
  KEY `adminId` (`adminId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS `announcements` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `createdBy` int(11) NOT NULL,
  `text` text NOT NULL,
  `bgcolor` varchar(16) NOT NULL,
  `textcolor` varchar(16) NOT NULL,
  `activated` tinyint(1) NOT NULL DEFAULT 1,
  `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ---------------------------------------------------------------------
-- Social
-- ---------------------------------------------------------------------

CREATE TABLE IF NOT EXISTS `friends` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `requesterId` int(11) NOT NULL,
  `receiverId` int(11) NOT NULL,
  `timeSent` bigint(20) NOT NULL DEFAULT 0,
  `status` tinyint(4) NOT NULL DEFAULT 0, -- 0 pending, 1 friends, 2 revoked
  PRIMARY KEY (`id`),
  KEY `requesterId` (`requesterId`),
  KEY `receiverId` (`receiverId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- user status updates (groupId NULL) and group shouts (groupId set)
CREATE TABLE IF NOT EXISTS `feed` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `userId` int(11) NOT NULL,
  `groupId` int(11) DEFAULT NULL,
  `text` text NOT NULL,
  `timestamp` bigint(20) NOT NULL DEFAULT 0,
  PRIMARY KEY (`id`),
  KEY `userId` (`userId`),
  KEY `groupId` (`groupId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS `feed_news` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(255) NOT NULL,
  `body` text NOT NULL,
  `user_id` int(11) NOT NULL,
  `time_created` bigint(20) NOT NULL DEFAULT 0,
  `time_deleted` bigint(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ---------------------------------------------------------------------
-- Catalog / assets
-- ---------------------------------------------------------------------

CREATE TABLE IF NOT EXISTS `assets` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `type` int(11) NOT NULL,
  `creator` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `description` text DEFAULT NULL,
  `created` bigint(20) NOT NULL DEFAULT 0,
  `updated` bigint(20) NOT NULL DEFAULT 0,
  `price` int(11) NOT NULL DEFAULT 0,
  `sale` tinyint(1) NOT NULL DEFAULT 0,
  `Sales` int(11) NOT NULL DEFAULT 0,
  `approved` tinyint(4) NOT NULL DEFAULT 0, -- 0 pending, 1 approved, 2 declined
  `comments` tinyint(1) NOT NULL DEFAULT 1,
  `publicDomain` tinyint(1) NOT NULL DEFAULT 0,
  `imageID` int(11) DEFAULT NULL,
  `audioType` varchar(100) DEFAULT NULL,
  `gear_attributes` text DEFAULT NULL,
  `TemplateOrder` int(11) DEFAULT NULL,
  -- place (type 9) fields
  `Version` int(11) DEFAULT NULL,
  `Access` varchar(20) NOT NULL DEFAULT 'Everyone',
  `ChatType` varchar(20) NOT NULL DEFAULT 'Classic',
  `MaxPlayers` int(11) DEFAULT NULL,
  `Visits` int(11) NOT NULL DEFAULT 0,
  `ActivePlayers` int(11) NOT NULL DEFAULT 0,
  `ServerRunning` tinyint(1) NOT NULL DEFAULT 0,
  `LastServerUpdate` bigint(20) NOT NULL DEFAULT 0,
  PRIMARY KEY (`id`),
  KEY `creator` (`creator`),
  KEY `type` (`type`),
  KEY `TemplateOrder` (`TemplateOrder`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS `ownedAssets` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `assetId` int(11) NOT NULL,
  `userId` int(11) NOT NULL,
  `timestamp` bigint(20) NOT NULL DEFAULT 0,
  `wearing` tinyint(1) NOT NULL DEFAULT 0,
  `TagID` int(11) DEFAULT NULL,
  `last_toggle` bigint(20) NOT NULL DEFAULT 0,
  PRIMARY KEY (`id`),
  KEY `assetId` (`assetId`),
  KEY `userId` (`userId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS `transactions` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `purchaser` int(11) NOT NULL,
  `seller` int(11) NOT NULL,
  `assetId` int(11) NOT NULL,
  `amount` int(11) NOT NULL DEFAULT 0,
  `flagged` tinyint(1) NOT NULL DEFAULT 0,
  `timestamp` bigint(20) NOT NULL DEFAULT 0,
  PRIMARY KEY (`id`),
  KEY `purchaser` (`purchaser`),
  KEY `seller` (`seller`),
  KEY `assetId` (`assetId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS `asset_comments` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `assetID` int(11) NOT NULL,
  `author` int(11) NOT NULL,
  `content` text NOT NULL,
  `time` bigint(20) NOT NULL DEFAULT 0,
  PRIMARY KEY (`id`),
  KEY `assetID` (`assetID`),
  KEY `author` (`author`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- thumbnail/render jobs; jobID is a generateUUID() string
CREATE TABLE IF NOT EXISTS `renderqueue` (
  `jobID` varchar(36) NOT NULL,
  `renderType` varchar(32) NOT NULL,
  `assetID` int(11) NOT NULL,
  `renderStatus` tinyint(4) NOT NULL DEFAULT 0, -- 0 pending, 1 rendering, 2 done, 3 cancelled, 4 failed
  `timestampRequested` bigint(20) NOT NULL DEFAULT 0,
  `timestampAcknowledged` bigint(20) DEFAULT NULL,
  `timestampCompleted` bigint(20) DEFAULT NULL,
  `additionalInfo` text DEFAULT NULL,
  PRIMARY KEY (`jobID`),
  KEY `asset` (`renderType`,`assetID`),
  KEY `renderStatus` (`renderStatus`),
  KEY `timestampRequested` (`timestampRequested`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- render/thumbnail server heartbeat (api/render/ping.php updates id = 2)
CREATE TABLE IF NOT EXISTS `servers` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `ping` bigint(20) NOT NULL DEFAULT 0,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ---------------------------------------------------------------------
-- Games (gameserver/job system)
-- ---------------------------------------------------------------------

CREATE TABLE IF NOT EXISTS `GameServers` (
  `ServerID` int(11) NOT NULL AUTO_INCREMENT,
  `Name` varchar(255) NOT NULL,
  `ServiceAddress` varchar(255) NOT NULL DEFAULT '127.0.0.1',
  `ServicePort` int(11) NOT NULL DEFAULT 0,
  `Priority` int(11) NOT NULL DEFAULT 0,
  `MaximumJobs` int(11) NOT NULL DEFAULT 0,
  `Online` tinyint(1) NOT NULL DEFAULT 0,
  `ActiveJobs` int(11) NOT NULL DEFAULT 0,
  `CpuUsage` int(11) NOT NULL DEFAULT 0,
  `AvailableMemory` int(11) NOT NULL DEFAULT 0,
  `LastUpdated` bigint(20) NOT NULL DEFAULT 0,
  PRIMARY KEY (`ServerID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- JobID is a generateUUID() string supplied by placelauncher.php
CREATE TABLE IF NOT EXISTS `GameJobs` (
  `JobID` varchar(36) NOT NULL,
  `RequestedBy` int(11) NOT NULL,
  `ServerID` int(11) NOT NULL,
  `Version` varchar(50) NOT NULL,
  `PlaceID` int(11) NOT NULL,
  `TimeCreated` bigint(20) NOT NULL DEFAULT 0,
  `LastUpdated` bigint(20) NOT NULL DEFAULT 0,
  `Status` varchar(20) NOT NULL DEFAULT 'Pending', -- Pending, Queued, Loading, Ready, Closed, Crashed
  `PlayerCount` int(11) NOT NULL DEFAULT 0,
  `MachineAddress` varchar(255) DEFAULT NULL,
  `ServerPort` int(11) DEFAULT NULL,
  PRIMARY KEY (`JobID`),
  KEY `RequestedBy` (`RequestedBy`),
  KEY `PlaceID` (`PlaceID`),
  KEY `ServerID` (`ServerID`),
  KEY `Status` (`Status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS `GameJobSessions` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `Ticket` varchar(64) NOT NULL,
  `SecurityTicket` varchar(64) NOT NULL,
  `ReplicatorTicket` varchar(255) DEFAULT NULL,
  `JobID` varchar(36) NOT NULL,
  `IsTeleport` tinyint(1) NOT NULL DEFAULT 0,
  `UserID` int(11) NOT NULL,
  `TimeCreated` bigint(20) NOT NULL DEFAULT 0,
  `Active` tinyint(1) NOT NULL DEFAULT 0,
  `Verified` tinyint(1) NOT NULL DEFAULT 0,
  PRIMARY KEY (`id`),
  KEY `Ticket` (`Ticket`),
  KEY `SecurityTicket` (`SecurityTicket`),
  KEY `JobID` (`JobID`),
  KEY `UserID` (`UserID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- legacy self-hosted servers (still read by Games.php / characterfetch.php)
CREATE TABLE IF NOT EXISTS `selfhosted_servers` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `ticket` varchar(64) NOT NULL,
  `name` varchar(255) NOT NULL,
  `description` text DEFAULT NULL,
  `ip` varchar(255) NOT NULL,
  `port` int(11) NOT NULL,
  `version` int(11) NOT NULL,
  `maxplayers` int(11) NOT NULL DEFAULT 10,
  `pbs` tinyint(1) NOT NULL DEFAULT 0,
  `Privacy` varchar(20) NOT NULL DEFAULT 'Public',
  `PrivacyWhitelist` text DEFAULT NULL, -- JSON array of user ids
  `LastWhitelistEdit` bigint(20) DEFAULT NULL,
  `hoster` int(11) NOT NULL,
  `allowed_gears` text DEFAULT NULL,
  `created` bigint(20) NOT NULL DEFAULT 0,
  `ping` bigint(20) NOT NULL DEFAULT 0,
  PRIMARY KEY (`id`),
  KEY `ticket` (`ticket`),
  KEY `hoster` (`hoster`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS `client_sessions` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `ticket` varchar(64) NOT NULL,
  `securityTicket` varchar(64) NOT NULL,
  `uid` int(11) NOT NULL,
  `sessionType` int(11) NOT NULL DEFAULT 0,
  `serverID` int(11) NOT NULL,
  `created` bigint(20) NOT NULL DEFAULT 0,
  `ping` bigint(20) NOT NULL DEFAULT 0,
  `isTeleport` tinyint(1) NOT NULL DEFAULT 0,
  `RequesterIP` varchar(45) DEFAULT NULL,
  `valid` tinyint(1) NOT NULL DEFAULT 1,
  `verified` tinyint(1) NOT NULL DEFAULT 0,
  `used` tinyint(1) NOT NULL DEFAULT 0,
  PRIMARY KEY (`id`),
  KEY `ticket` (`ticket`),
  KEY `securityTicket` (`securityTicket`),
  KEY `uid` (`uid`),
  KEY `serverID` (`serverID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ---------------------------------------------------------------------
-- Groups
-- ---------------------------------------------------------------------

CREATE TABLE IF NOT EXISTS `groups` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `creator` int(11) NOT NULL,
  `owner` int(11) NOT NULL,
  `emblem` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `description` text NOT NULL,
  `entry` varchar(20) NOT NULL DEFAULT 'Anyone', -- Anyone / Manual
  `created` bigint(20) NOT NULL DEFAULT 0,
  `MemberCount` int(11) NOT NULL DEFAULT 1,
  `deleted` tinyint(1) NOT NULL DEFAULT 0,
  PRIMARY KEY (`id`),
  KEY `creator` (`creator`),
  KEY `owner` (`owner`),
  KEY `name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS `groups_members` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `GroupID` int(11) NOT NULL,
  `UserID` int(11) NOT NULL,
  `Rank` int(11) NOT NULL,
  `Joined` bigint(20) NOT NULL DEFAULT 0,
  `Pending` tinyint(1) NOT NULL DEFAULT 0,
  PRIMARY KEY (`id`),
  KEY `GroupID` (`GroupID`),
  KEY `UserID` (`UserID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS `groups_ranks` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `GroupID` int(11) NOT NULL,
  `Name` varchar(255) NOT NULL,
  `Description` text DEFAULT NULL,
  `Rank` int(11) NOT NULL, -- 0 = guest, 255 = owner
  `Permissions` text NOT NULL, -- JSON object
  `Created` bigint(20) NOT NULL DEFAULT 0,
  PRIMARY KEY (`id`),
  KEY `GroupRank` (`GroupID`,`Rank`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS `groups_relationships` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `Type` varchar(20) NOT NULL, -- Allies / Enemies
  `Declarer` int(11) NOT NULL,
  `Recipient` int(11) NOT NULL,
  `Status` tinyint(4) NOT NULL DEFAULT 0, -- 0 pending, 1 established, 2 broken
  `Declared` bigint(20) NOT NULL DEFAULT 0,
  `Established` bigint(20) DEFAULT NULL,
  `Broken` bigint(20) DEFAULT NULL,
  PRIMARY KEY (`ID`),
  KEY `Declarer` (`Declarer`),
  KEY `Recipient` (`Recipient`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS `groups_wall` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `GroupID` int(11) NOT NULL,
  `PosterID` int(11) NOT NULL,
  `Content` text NOT NULL,
  `TimePosted` bigint(20) NOT NULL DEFAULT 0,
  `Deleted` tinyint(1) NOT NULL DEFAULT 0,
  PRIMARY KEY (`id`),
  KEY `GroupID` (`GroupID`),
  KEY `PosterID` (`PosterID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS `groups_audit` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `GroupID` int(11) NOT NULL,
  `Category` varchar(64) NOT NULL,
  `Time` bigint(20) NOT NULL DEFAULT 0,
  `UserID` int(11) NOT NULL,
  `Rank` varchar(255) DEFAULT NULL, -- rank NAME at time of action
  `Description` text NOT NULL,
  PRIMARY KEY (`id`),
  KEY `GroupID` (`GroupID`),
  KEY `UserID` (`UserID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ---------------------------------------------------------------------
-- Forum
-- ---------------------------------------------------------------------

CREATE TABLE IF NOT EXISTS `forum_forums` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `description` text DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS `forum_subforums` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `forumid` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `description` text DEFAULT NULL,
  `displayposition` int(11) NOT NULL DEFAULT 0,
  `minadminlevel` int(11) NOT NULL DEFAULT 0,
  PRIMARY KEY (`id`),
  KEY `forumid` (`forumid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS `forum_threads` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `subforumid` int(11) NOT NULL,
  `author` int(11) NOT NULL,
  `subject` varchar(255) NOT NULL,
  `body` text NOT NULL,
  `postTime` bigint(20) NOT NULL DEFAULT 0,
  `bumpIndex` bigint(20) NOT NULL DEFAULT 0,
  `pinned` tinyint(1) NOT NULL DEFAULT 0,
  `deleted` tinyint(1) NOT NULL DEFAULT 0,
  PRIMARY KEY (`id`),
  KEY `subforumid` (`subforumid`),
  KEY `author` (`author`),
  KEY `bumpIndex` (`bumpIndex`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS `forum_replies` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `threadId` int(11) NOT NULL,
  `author` int(11) NOT NULL,
  `body` text NOT NULL,
  `postTime` bigint(20) NOT NULL DEFAULT 0,
  `deleted` tinyint(1) NOT NULL DEFAULT 0,
  PRIMARY KEY (`id`),
  KEY `threadId` (`threadId`),
  KEY `author` (`author`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- render server heartbeat row used by api/render/ping.php
INSERT IGNORE INTO `servers` (`id`, `name`, `ping`) VALUES (2, 'Render', 0);


-- =====================================================================
-- MIGRATION SECTION
-- Upgrades a database built from the earlier hand-reconstructed schema
-- (current-schema.sql) to the definitions above, keeping data.
-- Run the whole file: the CREATE TABLE IF NOT EXISTS statements above
-- add the missing tables, and the statements below alter the existing
-- ones. Everything here is safe to re-run, and is a no-op on a database
-- built from the CREATE section alone.
-- =====================================================================

-- 1. drop all foreign keys from the hand-built schema
ALTER TABLE `GameJobSessions` DROP FOREIGN KEY IF EXISTS `GameJobSessions_ibfk_1`;
ALTER TABLE `GameJobSessions` DROP FOREIGN KEY IF EXISTS `GameJobSessions_ibfk_2`;
ALTER TABLE `GameJobs` DROP FOREIGN KEY IF EXISTS `GameJobs_ibfk_1`;
ALTER TABLE `GameJobs` DROP FOREIGN KEY IF EXISTS `GameJobs_ibfk_2`;
ALTER TABLE `GameJobs` DROP FOREIGN KEY IF EXISTS `GameJobs_ibfk_3`;
ALTER TABLE `InviteTickets` DROP FOREIGN KEY IF EXISTS `InviteTickets_ibfk_1`;
ALTER TABLE `InviteTickets` DROP FOREIGN KEY IF EXISTS `InviteTickets_ibfk_2`;
ALTER TABLE `assets` DROP FOREIGN KEY IF EXISTS `assets_ibfk_1`;
ALTER TABLE `bans` DROP FOREIGN KEY IF EXISTS `bans_ibfk_1`;
ALTER TABLE `forum_subforums` DROP FOREIGN KEY IF EXISTS `forum_subforums_ibfk_1`;
ALTER TABLE `forum_threads` DROP FOREIGN KEY IF EXISTS `forum_threads_ibfk_1`;
ALTER TABLE `forum_threads` DROP FOREIGN KEY IF EXISTS `forum_threads_ibfk_2`;
ALTER TABLE `friends` DROP FOREIGN KEY IF EXISTS `friends_ibfk_1`;
ALTER TABLE `friends` DROP FOREIGN KEY IF EXISTS `friends_ibfk_2`;
ALTER TABLE `groups` DROP FOREIGN KEY IF EXISTS `groups_ibfk_1`;
ALTER TABLE `groups` DROP FOREIGN KEY IF EXISTS `groups_ibfk_2`;
ALTER TABLE `groups_members` DROP FOREIGN KEY IF EXISTS `groups_members_ibfk_1`;
ALTER TABLE `groups_members` DROP FOREIGN KEY IF EXISTS `groups_members_ibfk_2`;
ALTER TABLE `ownedAssets` DROP FOREIGN KEY IF EXISTS `ownedAssets_ibfk_1`;
ALTER TABLE `ownedAssets` DROP FOREIGN KEY IF EXISTS `ownedAssets_ibfk_2`;

-- 2. convert existing tables to utf8mb4 (TEXT columns are restored to TEXT by the MODIFYs below)
ALTER TABLE `GameJobSessions` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
ALTER TABLE `GameJobs` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
ALTER TABLE `GameServers` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
ALTER TABLE `InviteTickets` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
ALTER TABLE `announcements` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
ALTER TABLE `assets` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
ALTER TABLE `bans` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
ALTER TABLE `forum_forums` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
ALTER TABLE `forum_subforums` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
ALTER TABLE `forum_threads` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
ALTER TABLE `friends` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
ALTER TABLE `groups` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
ALTER TABLE `groups_members` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
ALTER TABLE `namefilter` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
ALTER TABLE `ownedAssets` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
ALTER TABLE `sessions` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
ALTER TABLE `users` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

-- 3. TIMESTAMP/DATETIME columns that the code fills with UNIX_TIMESTAMP() integers:
--    convert through a temp column so existing datetimes become epoch seconds.
--    Each step only runs while the column is still a TIMESTAMP/DATETIME (re-runnable).
-- InviteTickets.TimeCreated
SET @conv = (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'InviteTickets' AND COLUMN_NAME = 'TimeCreated' AND DATA_TYPE IN ('timestamp','datetime'));
SET @s = IF(@conv > 0, 'ALTER TABLE `InviteTickets` ADD COLUMN IF NOT EXISTS `TimeCreated_unix` bigint(20) NOT NULL DEFAULT 0', 'DO 0'); PREPARE st FROM @s; EXECUTE st; DEALLOCATE PREPARE st;
SET @s = IF(@conv > 0, 'UPDATE `InviteTickets` SET `TimeCreated_unix` = COALESCE(UNIX_TIMESTAMP(`TimeCreated`), 0)', 'DO 0'); PREPARE st FROM @s; EXECUTE st; DEALLOCATE PREPARE st;
SET @s = IF(@conv > 0, 'ALTER TABLE `InviteTickets` DROP COLUMN `TimeCreated`', 'DO 0'); PREPARE st FROM @s; EXECUTE st; DEALLOCATE PREPARE st;
SET @s = IF(@conv > 0, 'ALTER TABLE `InviteTickets` CHANGE COLUMN `TimeCreated_unix` `TimeCreated` bigint(20) NOT NULL DEFAULT 0', 'DO 0'); PREPARE st FROM @s; EXECUTE st; DEALLOCATE PREPARE st;
-- ownedAssets.timestamp
SET @conv = (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'ownedAssets' AND COLUMN_NAME = 'timestamp' AND DATA_TYPE IN ('timestamp','datetime'));
SET @s = IF(@conv > 0, 'ALTER TABLE `ownedAssets` ADD COLUMN IF NOT EXISTS `timestamp_unix` bigint(20) NOT NULL DEFAULT 0', 'DO 0'); PREPARE st FROM @s; EXECUTE st; DEALLOCATE PREPARE st;
SET @s = IF(@conv > 0, 'UPDATE `ownedAssets` SET `timestamp_unix` = COALESCE(UNIX_TIMESTAMP(`timestamp`), 0)', 'DO 0'); PREPARE st FROM @s; EXECUTE st; DEALLOCATE PREPARE st;
SET @s = IF(@conv > 0, 'ALTER TABLE `ownedAssets` DROP COLUMN `timestamp`', 'DO 0'); PREPARE st FROM @s; EXECUTE st; DEALLOCATE PREPARE st;
SET @s = IF(@conv > 0, 'ALTER TABLE `ownedAssets` CHANGE COLUMN `timestamp_unix` `timestamp` bigint(20) NOT NULL DEFAULT 0', 'DO 0'); PREPARE st FROM @s; EXECUTE st; DEALLOCATE PREPARE st;
-- ownedAssets.last_toggle
SET @conv = (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'ownedAssets' AND COLUMN_NAME = 'last_toggle' AND DATA_TYPE IN ('timestamp','datetime'));
SET @s = IF(@conv > 0, 'ALTER TABLE `ownedAssets` ADD COLUMN IF NOT EXISTS `last_toggle_unix` bigint(20) NOT NULL DEFAULT 0', 'DO 0'); PREPARE st FROM @s; EXECUTE st; DEALLOCATE PREPARE st;
SET @s = IF(@conv > 0, 'UPDATE `ownedAssets` SET `last_toggle_unix` = COALESCE(UNIX_TIMESTAMP(`last_toggle`), 0)', 'DO 0'); PREPARE st FROM @s; EXECUTE st; DEALLOCATE PREPARE st;
SET @s = IF(@conv > 0, 'ALTER TABLE `ownedAssets` DROP COLUMN `last_toggle`', 'DO 0'); PREPARE st FROM @s; EXECUTE st; DEALLOCATE PREPARE st;
SET @s = IF(@conv > 0, 'ALTER TABLE `ownedAssets` CHANGE COLUMN `last_toggle_unix` `last_toggle` bigint(20) NOT NULL DEFAULT 0', 'DO 0'); PREPARE st FROM @s; EXECUTE st; DEALLOCATE PREPARE st;
-- assets.created
SET @conv = (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'assets' AND COLUMN_NAME = 'created' AND DATA_TYPE IN ('timestamp','datetime'));
SET @s = IF(@conv > 0, 'ALTER TABLE `assets` ADD COLUMN IF NOT EXISTS `created_unix` bigint(20) NOT NULL DEFAULT 0', 'DO 0'); PREPARE st FROM @s; EXECUTE st; DEALLOCATE PREPARE st;
SET @s = IF(@conv > 0, 'UPDATE `assets` SET `created_unix` = COALESCE(UNIX_TIMESTAMP(`created`), 0)', 'DO 0'); PREPARE st FROM @s; EXECUTE st; DEALLOCATE PREPARE st;
SET @s = IF(@conv > 0, 'ALTER TABLE `assets` DROP COLUMN `created`', 'DO 0'); PREPARE st FROM @s; EXECUTE st; DEALLOCATE PREPARE st;
SET @s = IF(@conv > 0, 'ALTER TABLE `assets` CHANGE COLUMN `created_unix` `created` bigint(20) NOT NULL DEFAULT 0', 'DO 0'); PREPARE st FROM @s; EXECUTE st; DEALLOCATE PREPARE st;
-- assets.updated
SET @conv = (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'assets' AND COLUMN_NAME = 'updated' AND DATA_TYPE IN ('timestamp','datetime'));
SET @s = IF(@conv > 0, 'ALTER TABLE `assets` ADD COLUMN IF NOT EXISTS `updated_unix` bigint(20) NOT NULL DEFAULT 0', 'DO 0'); PREPARE st FROM @s; EXECUTE st; DEALLOCATE PREPARE st;
SET @s = IF(@conv > 0, 'UPDATE `assets` SET `updated_unix` = COALESCE(UNIX_TIMESTAMP(`updated`), 0)', 'DO 0'); PREPARE st FROM @s; EXECUTE st; DEALLOCATE PREPARE st;
SET @s = IF(@conv > 0, 'ALTER TABLE `assets` DROP COLUMN `updated`', 'DO 0'); PREPARE st FROM @s; EXECUTE st; DEALLOCATE PREPARE st;
SET @s = IF(@conv > 0, 'ALTER TABLE `assets` CHANGE COLUMN `updated_unix` `updated` bigint(20) NOT NULL DEFAULT 0', 'DO 0'); PREPARE st FROM @s; EXECUTE st; DEALLOCATE PREPARE st;

-- 4. data clean-ups needed before the type changes below succeed under strict mode
UPDATE `assets` SET `imageID` = NULL WHERE `imageID` IS NOT NULL AND CAST(`imageID` AS CHAR) NOT REGEXP '^[0-9]+$';
-- groups.entry was INT in the hand-built schema; the code stores 'Anyone' / 'Manual'
ALTER TABLE `groups` MODIFY COLUMN `entry` varchar(20) NOT NULL DEFAULT 'Anyone';
UPDATE `groups` SET `entry` = 'Anyone' WHERE `entry` NOT IN ('Anyone', 'Manual');
UPDATE `users` SET `bodycolors` = '{"Head":24,"Torso":23,"Left Arm":24,"Right Arm":24,"Left Leg":119,"Right Leg":119}' WHERE `bodycolors` IS NULL OR `bodycolors` = '';
UPDATE `users` SET `status` = NULL WHERE `status` = 'active';
-- users.email is always 'placeholder' on registration, so it cannot be UNIQUE
ALTER TABLE `users` DROP INDEX IF EXISTS `unique_email`;

-- 5. back-fill NULLs in columns that become NOT NULL
UPDATE `GameJobSessions` SET `Active` = 0 WHERE `Active` IS NULL;
UPDATE `GameJobSessions` SET `Verified` = 0 WHERE `Verified` IS NULL;
UPDATE `GameJobs` SET `PlayerCount` = 0 WHERE `PlayerCount` IS NULL;
UPDATE `GameServers` SET `Online` = 0 WHERE `Online` IS NULL;
UPDATE `GameServers` SET `ActiveJobs` = 0 WHERE `ActiveJobs` IS NULL;
UPDATE `assets` SET `price` = 0 WHERE `price` IS NULL;
UPDATE `assets` SET `Sales` = 0 WHERE `Sales` IS NULL;
UPDATE `assets` SET `approved` = 0 WHERE `approved` IS NULL;
UPDATE `assets` SET `Visits` = 0 WHERE `Visits` IS NULL;
UPDATE `assets` SET `ActivePlayers` = 0 WHERE `ActivePlayers` IS NULL;
UPDATE `assets` SET `ServerRunning` = 0 WHERE `ServerRunning` IS NULL;
UPDATE `bans` SET `isDismissed` = 0 WHERE `isDismissed` IS NULL;
UPDATE `forum_subforums` SET `minadminlevel` = 0 WHERE `minadminlevel` IS NULL;
UPDATE `forum_threads` SET `pinned` = 0 WHERE `pinned` IS NULL;
UPDATE `forum_threads` SET `deleted` = 0 WHERE `deleted` IS NULL;
UPDATE `groups_members` SET `Pending` = 0 WHERE `Pending` IS NULL;
UPDATE `ownedAssets` SET `wearing` = 0 WHERE `wearing` IS NULL;
UPDATE `sessions` SET `created` = 0 WHERE `created` IS NULL;
UPDATE `sessions` SET `lastonline` = 0 WHERE `lastonline` IS NULL;
UPDATE `sessions` SET `twofaVerified` = 0 WHERE `twofaVerified` IS NULL;
UPDATE `sessions` SET `IsGameClient` = 0 WHERE `IsGameClient` IS NULL;
UPDATE `sessions` SET `valid` = 1 WHERE `valid` IS NULL;
UPDATE `users` SET `jointime` = 0 WHERE `jointime` IS NULL;
UPDATE `users` SET `lastonline` = 0 WHERE `lastonline` IS NULL;
UPDATE `users` SET `adminlevel` = 0 WHERE `adminlevel` IS NULL;
UPDATE `users` SET `currency` = 0 WHERE `currency` IS NULL;
UPDATE `users` SET `nextCurrencyStipend` = 0 WHERE `nextCurrencyStipend` IS NULL;
UPDATE `users` SET `twofa` = 0 WHERE `twofa` IS NULL;
UPDATE `users` SET `Banned` = 0 WHERE `Banned` IS NULL;
UPDATE `users` SET `ForumThreads` = 0 WHERE `ForumThreads` IS NULL;
UPDATE `users` SET `ForumReplies` = 0 WHERE `ForumReplies` IS NULL;
UPDATE `users` SET `ClientPresencePing` = 0 WHERE `ClientPresencePing` IS NULL;
UPDATE `users` SET `Knockouts` = 0 WHERE `Knockouts` IS NULL;
UPDATE `users` SET `Wipeouts` = 0 WHERE `Wipeouts` IS NULL;
UPDATE `users` SET `PlaceVisits` = 0 WHERE `PlaceVisits` IS NULL;
UPDATE `users` SET `CreatableInviteTickets` = 0 WHERE `CreatableInviteTickets` IS NULL;
UPDATE `users` SET `PendingFriendRequests` = 0 WHERE `PendingFriendRequests` IS NULL;
UPDATE `users` SET `theme` = 'light' WHERE `theme` IS NULL;
UPDATE `users` SET `filter` = 1 WHERE `filter` IS NULL;
UPDATE `users` SET `bodycolors` = '{"Head":24,"Torso":23,"Left Arm":24,"Right Arm":24,"Left Leg":119,"Right Leg":119}' WHERE `bodycolors` IS NULL;

-- 6. bring every column of the existing tables to its final definition
ALTER TABLE `GameJobSessions`
  MODIFY COLUMN `id` int(11) NOT NULL AUTO_INCREMENT,
  MODIFY COLUMN `Ticket` varchar(64) NOT NULL,
  MODIFY COLUMN `SecurityTicket` varchar(64) NOT NULL,
  MODIFY COLUMN `ReplicatorTicket` varchar(255) DEFAULT NULL,
  MODIFY COLUMN `JobID` varchar(36) NOT NULL,
  MODIFY COLUMN `IsTeleport` tinyint(1) NOT NULL DEFAULT 0,
  MODIFY COLUMN `UserID` int(11) NOT NULL,
  MODIFY COLUMN `TimeCreated` bigint(20) NOT NULL DEFAULT 0,
  MODIFY COLUMN `Active` tinyint(1) NOT NULL DEFAULT 0,
  MODIFY COLUMN `Verified` tinyint(1) NOT NULL DEFAULT 0;
ALTER TABLE `GameJobs`
  MODIFY COLUMN `JobID` varchar(36) NOT NULL,
  MODIFY COLUMN `RequestedBy` int(11) NOT NULL,
  MODIFY COLUMN `ServerID` int(11) NOT NULL,
  MODIFY COLUMN `Version` varchar(50) NOT NULL,
  MODIFY COLUMN `PlaceID` int(11) NOT NULL,
  MODIFY COLUMN `TimeCreated` bigint(20) NOT NULL DEFAULT 0,
  MODIFY COLUMN `LastUpdated` bigint(20) NOT NULL DEFAULT 0,
  MODIFY COLUMN `Status` varchar(20) NOT NULL DEFAULT 'Pending',
  MODIFY COLUMN `PlayerCount` int(11) NOT NULL DEFAULT 0,
  MODIFY COLUMN `MachineAddress` varchar(255) DEFAULT NULL,
  MODIFY COLUMN `ServerPort` int(11) DEFAULT NULL;
ALTER TABLE `GameServers`
  MODIFY COLUMN `ServerID` int(11) NOT NULL AUTO_INCREMENT,
  MODIFY COLUMN `Name` varchar(255) NOT NULL,
  ADD COLUMN IF NOT EXISTS `ServiceAddress` varchar(255) NOT NULL DEFAULT '127.0.0.1',
  ADD COLUMN IF NOT EXISTS `ServicePort` int(11) NOT NULL DEFAULT 0,
  ADD COLUMN IF NOT EXISTS `Priority` int(11) NOT NULL DEFAULT 0,
  ADD COLUMN IF NOT EXISTS `MaximumJobs` int(11) NOT NULL DEFAULT 0,
  MODIFY COLUMN `Online` tinyint(1) NOT NULL DEFAULT 0,
  MODIFY COLUMN `ActiveJobs` int(11) NOT NULL DEFAULT 0,
  ADD COLUMN IF NOT EXISTS `CpuUsage` int(11) NOT NULL DEFAULT 0,
  ADD COLUMN IF NOT EXISTS `AvailableMemory` int(11) NOT NULL DEFAULT 0,
  MODIFY COLUMN `LastUpdated` bigint(20) NOT NULL DEFAULT 0;
ALTER TABLE `InviteTickets`
  MODIFY COLUMN `ID` int(11) NOT NULL AUTO_INCREMENT,
  MODIFY COLUMN `Ticket` varchar(255) NOT NULL,
  MODIFY COLUMN `TimeCreated` bigint(20) NOT NULL DEFAULT 0,
  MODIFY COLUMN `CreatedBy` int(11) NOT NULL,
  MODIFY COLUMN `UsedBy` int(11) DEFAULT NULL;
ALTER TABLE `announcements`
  MODIFY COLUMN `id` int(11) NOT NULL AUTO_INCREMENT,
  MODIFY COLUMN `createdBy` int(11) NOT NULL,
  MODIFY COLUMN `text` text NOT NULL,
  MODIFY COLUMN `bgcolor` varchar(16) NOT NULL,
  MODIFY COLUMN `textcolor` varchar(16) NOT NULL,
  MODIFY COLUMN `activated` tinyint(1) NOT NULL DEFAULT 1,
  MODIFY COLUMN `created_at` timestamp NOT NULL DEFAULT current_timestamp();
ALTER TABLE `assets`
  MODIFY COLUMN `id` int(11) NOT NULL AUTO_INCREMENT,
  MODIFY COLUMN `type` int(11) NOT NULL,
  MODIFY COLUMN `creator` int(11) NOT NULL,
  MODIFY COLUMN `name` varchar(255) NOT NULL,
  MODIFY COLUMN `description` text DEFAULT NULL,
  MODIFY COLUMN `created` bigint(20) NOT NULL DEFAULT 0,
  MODIFY COLUMN `updated` bigint(20) NOT NULL DEFAULT 0,
  MODIFY COLUMN `price` int(11) NOT NULL DEFAULT 0,
  MODIFY COLUMN `sale` tinyint(1) NOT NULL DEFAULT 0,
  MODIFY COLUMN `Sales` int(11) NOT NULL DEFAULT 0,
  MODIFY COLUMN `approved` tinyint(4) NOT NULL DEFAULT 0,
  ADD COLUMN IF NOT EXISTS `comments` tinyint(1) NOT NULL DEFAULT 1,
  ADD COLUMN IF NOT EXISTS `publicDomain` tinyint(1) NOT NULL DEFAULT 0,
  MODIFY COLUMN `imageID` int(11) DEFAULT NULL,
  ADD COLUMN IF NOT EXISTS `audioType` varchar(100) DEFAULT NULL,
  MODIFY COLUMN `gear_attributes` text DEFAULT NULL,
  MODIFY COLUMN `TemplateOrder` int(11) DEFAULT NULL,
  ADD COLUMN IF NOT EXISTS `Version` int(11) DEFAULT NULL,
  ADD COLUMN IF NOT EXISTS `Access` varchar(20) NOT NULL DEFAULT 'Everyone',
  ADD COLUMN IF NOT EXISTS `ChatType` varchar(20) NOT NULL DEFAULT 'Classic',
  MODIFY COLUMN `MaxPlayers` int(11) DEFAULT NULL,
  MODIFY COLUMN `Visits` int(11) NOT NULL DEFAULT 0,
  MODIFY COLUMN `ActivePlayers` int(11) NOT NULL DEFAULT 0,
  MODIFY COLUMN `ServerRunning` tinyint(1) NOT NULL DEFAULT 0,
  ADD COLUMN IF NOT EXISTS `LastServerUpdate` bigint(20) NOT NULL DEFAULT 0;
ALTER TABLE `bans`
  MODIFY COLUMN `id` int(11) NOT NULL AUTO_INCREMENT,
  MODIFY COLUMN `userId` int(11) NOT NULL,
  MODIFY COLUMN `bannerId` int(11) NOT NULL,
  MODIFY COLUMN `timeStarted` bigint(20) NOT NULL DEFAULT 0,
  MODIFY COLUMN `timeEnds` bigint(20) NOT NULL DEFAULT 0,
  MODIFY COLUMN `reason` text NOT NULL,
  MODIFY COLUMN `banType` tinyint(4) NOT NULL,
  MODIFY COLUMN `note` text DEFAULT NULL,
  MODIFY COLUMN `isDismissed` tinyint(1) NOT NULL DEFAULT 0;
ALTER TABLE `forum_forums`
  MODIFY COLUMN `id` int(11) NOT NULL AUTO_INCREMENT,
  MODIFY COLUMN `name` varchar(255) NOT NULL,
  MODIFY COLUMN `description` text DEFAULT NULL;
ALTER TABLE `forum_subforums`
  MODIFY COLUMN `id` int(11) NOT NULL AUTO_INCREMENT,
  MODIFY COLUMN `forumid` int(11) NOT NULL,
  MODIFY COLUMN `name` varchar(255) NOT NULL,
  MODIFY COLUMN `description` text DEFAULT NULL,
  MODIFY COLUMN `displayposition` int(11) NOT NULL DEFAULT 0,
  MODIFY COLUMN `minadminlevel` int(11) NOT NULL DEFAULT 0;
ALTER TABLE `forum_threads`
  MODIFY COLUMN `id` int(11) NOT NULL AUTO_INCREMENT,
  MODIFY COLUMN `subforumid` int(11) NOT NULL,
  MODIFY COLUMN `author` int(11) NOT NULL,
  MODIFY COLUMN `subject` varchar(255) NOT NULL,
  MODIFY COLUMN `body` text NOT NULL,
  MODIFY COLUMN `postTime` bigint(20) NOT NULL DEFAULT 0,
  MODIFY COLUMN `bumpIndex` bigint(20) NOT NULL DEFAULT 0,
  MODIFY COLUMN `pinned` tinyint(1) NOT NULL DEFAULT 0,
  MODIFY COLUMN `deleted` tinyint(1) NOT NULL DEFAULT 0;
ALTER TABLE `friends`
  MODIFY COLUMN `id` int(11) NOT NULL AUTO_INCREMENT,
  MODIFY COLUMN `requesterId` int(11) NOT NULL,
  MODIFY COLUMN `receiverId` int(11) NOT NULL,
  MODIFY COLUMN `timeSent` bigint(20) NOT NULL DEFAULT 0,
  MODIFY COLUMN `status` tinyint(4) NOT NULL DEFAULT 0;
ALTER TABLE `groups`
  MODIFY COLUMN `id` int(11) NOT NULL AUTO_INCREMENT,
  MODIFY COLUMN `creator` int(11) NOT NULL,
  MODIFY COLUMN `owner` int(11) NOT NULL,
  MODIFY COLUMN `emblem` int(11) NOT NULL,
  MODIFY COLUMN `name` varchar(255) NOT NULL,
  MODIFY COLUMN `description` text NOT NULL,
  MODIFY COLUMN `entry` varchar(20) NOT NULL DEFAULT 'Anyone',
  MODIFY COLUMN `created` bigint(20) NOT NULL DEFAULT 0,
  ADD COLUMN IF NOT EXISTS `MemberCount` int(11) NOT NULL DEFAULT 1,
  ADD COLUMN IF NOT EXISTS `deleted` tinyint(1) NOT NULL DEFAULT 0;
ALTER TABLE `groups_members`
  MODIFY COLUMN `id` int(11) NOT NULL AUTO_INCREMENT,
  MODIFY COLUMN `GroupID` int(11) NOT NULL,
  MODIFY COLUMN `UserID` int(11) NOT NULL,
  MODIFY COLUMN `Rank` int(11) NOT NULL,
  MODIFY COLUMN `Joined` bigint(20) NOT NULL DEFAULT 0,
  MODIFY COLUMN `Pending` tinyint(1) NOT NULL DEFAULT 0;
ALTER TABLE `namefilter`
  MODIFY COLUMN `id` int(11) NOT NULL AUTO_INCREMENT,
  MODIFY COLUMN `username` varchar(255) NOT NULL,
  MODIFY COLUMN `exact` tinyint(1) NOT NULL DEFAULT 0;
ALTER TABLE `ownedAssets`
  MODIFY COLUMN `id` int(11) NOT NULL AUTO_INCREMENT,
  MODIFY COLUMN `assetId` int(11) NOT NULL,
  MODIFY COLUMN `userId` int(11) NOT NULL,
  MODIFY COLUMN `timestamp` bigint(20) NOT NULL DEFAULT 0,
  MODIFY COLUMN `wearing` tinyint(1) NOT NULL DEFAULT 0,
  MODIFY COLUMN `TagID` int(11) DEFAULT NULL,
  MODIFY COLUMN `last_toggle` bigint(20) NOT NULL DEFAULT 0;
ALTER TABLE `sessions`
  MODIFY COLUMN `sessionKey` varchar(512) NOT NULL,
  MODIFY COLUMN `userId` int(11) NOT NULL,
  MODIFY COLUMN `userAgent` text DEFAULT NULL,
  MODIFY COLUMN `loginIp` varchar(45) DEFAULT NULL,
  MODIFY COLUMN `lastIp` varchar(45) DEFAULT NULL,
  MODIFY COLUMN `created` bigint(20) NOT NULL DEFAULT 0,
  MODIFY COLUMN `lastonline` bigint(20) NOT NULL DEFAULT 0,
  MODIFY COLUMN `csrf` varchar(128) DEFAULT NULL,
  MODIFY COLUMN `twofaVerified` tinyint(1) NOT NULL DEFAULT 0,
  MODIFY COLUMN `IsGameClient` tinyint(1) NOT NULL DEFAULT 0,
  MODIFY COLUMN `valid` tinyint(1) NOT NULL DEFAULT 1;
ALTER TABLE `users`
  MODIFY COLUMN `id` int(11) NOT NULL AUTO_INCREMENT,
  MODIFY COLUMN `username` varchar(50) NOT NULL,
  MODIFY COLUMN `password` text DEFAULT NULL,
  ADD COLUMN IF NOT EXISTS `lastpwdchange` bigint(20) DEFAULT NULL,
  MODIFY COLUMN `email` varchar(255) DEFAULT NULL,
  MODIFY COLUMN `keyUsed` varchar(255) DEFAULT NULL,
  MODIFY COLUMN `jointime` bigint(20) NOT NULL DEFAULT 0,
  MODIFY COLUMN `lastonline` bigint(20) NOT NULL DEFAULT 0,
  MODIFY COLUMN `regip` varchar(45) DEFAULT NULL,
  MODIFY COLUMN `loginIp` varchar(45) DEFAULT NULL,
  MODIFY COLUMN `status` varchar(255) DEFAULT NULL,
  MODIFY COLUMN `blurb` text DEFAULT NULL,
  MODIFY COLUMN `adminlevel` tinyint(4) NOT NULL DEFAULT 0,
  MODIFY COLUMN `currency` int(11) NOT NULL DEFAULT 0,
  MODIFY COLUMN `nextCurrencyStipend` bigint(20) NOT NULL DEFAULT 0,
  ADD COLUMN IF NOT EXISTS `PlaceSlots` int(11) NOT NULL DEFAULT 3,
  MODIFY COLUMN `twofa` tinyint(1) NOT NULL DEFAULT 0,
  MODIFY COLUMN `twofaSecret` varchar(255) DEFAULT NULL,
  MODIFY COLUMN `twofaRecoveryCodes` text DEFAULT NULL,
  MODIFY COLUMN `discordID` varchar(32) DEFAULT NULL,
  MODIFY COLUMN `discordKey` varchar(64) DEFAULT NULL,
  MODIFY COLUMN `discordVerifiedTime` bigint(20) DEFAULT NULL,
  MODIFY COLUMN `Banned` tinyint(1) NOT NULL DEFAULT 0,
  MODIFY COLUMN `ForumThreads` int(11) NOT NULL DEFAULT 0,
  MODIFY COLUMN `ForumReplies` int(11) NOT NULL DEFAULT 0,
  ADD COLUMN IF NOT EXISTS `ClientPresenceLocation` int(11) DEFAULT NULL,
  ADD COLUMN IF NOT EXISTS `ClientPresenceType` varchar(50) DEFAULT NULL,
  MODIFY COLUMN `ClientPresencePing` bigint(20) NOT NULL DEFAULT 0,
  MODIFY COLUMN `Knockouts` int(11) NOT NULL DEFAULT 0,
  MODIFY COLUMN `Wipeouts` int(11) NOT NULL DEFAULT 0,
  MODIFY COLUMN `PlaceVisits` int(11) NOT NULL DEFAULT 0,
  MODIFY COLUMN `CreatableInviteTickets` int(11) NOT NULL DEFAULT 0,
  MODIFY COLUMN `LastInviteTicketCheck` bigint(20) DEFAULT NULL,
  MODIFY COLUMN `PendingFriendRequests` int(11) NOT NULL DEFAULT 0,
  MODIFY COLUMN `theme` varchar(20) NOT NULL DEFAULT 'light',
  MODIFY COLUMN `filter` tinyint(1) NOT NULL DEFAULT 1,
  MODIFY COLUMN `bodycolors` text NOT NULL DEFAULT '{"Head":24,"Torso":23,"Left Arm":24,"Right Arm":24,"Left Leg":119,"Right Leg":119}';

-- 7. indexes
ALTER TABLE `GameJobSessions` ADD INDEX IF NOT EXISTS `Ticket` (`Ticket`);
ALTER TABLE `GameJobSessions` ADD INDEX IF NOT EXISTS `SecurityTicket` (`SecurityTicket`);
ALTER TABLE `GameJobSessions` ADD INDEX IF NOT EXISTS `JobID` (`JobID`);
ALTER TABLE `GameJobSessions` ADD INDEX IF NOT EXISTS `UserID` (`UserID`);
ALTER TABLE `GameJobs` ADD INDEX IF NOT EXISTS `RequestedBy` (`RequestedBy`);
ALTER TABLE `GameJobs` ADD INDEX IF NOT EXISTS `PlaceID` (`PlaceID`);
ALTER TABLE `GameJobs` ADD INDEX IF NOT EXISTS `ServerID` (`ServerID`);
ALTER TABLE `GameJobs` ADD INDEX IF NOT EXISTS `Status` (`Status`);
ALTER TABLE `InviteTickets` ADD UNIQUE INDEX IF NOT EXISTS `Ticket` (`Ticket`);
ALTER TABLE `InviteTickets` ADD INDEX IF NOT EXISTS `CreatedBy` (`CreatedBy`);
ALTER TABLE `InviteTickets` ADD INDEX IF NOT EXISTS `UsedBy` (`UsedBy`);
ALTER TABLE `assets` ADD INDEX IF NOT EXISTS `creator` (`creator`);
ALTER TABLE `assets` ADD INDEX IF NOT EXISTS `type` (`type`);
ALTER TABLE `assets` ADD INDEX IF NOT EXISTS `TemplateOrder` (`TemplateOrder`);
ALTER TABLE `bans` ADD INDEX IF NOT EXISTS `userId` (`userId`);
ALTER TABLE `forum_subforums` ADD INDEX IF NOT EXISTS `forumid` (`forumid`);
ALTER TABLE `forum_threads` ADD INDEX IF NOT EXISTS `subforumid` (`subforumid`);
ALTER TABLE `forum_threads` ADD INDEX IF NOT EXISTS `author` (`author`);
ALTER TABLE `forum_threads` ADD INDEX IF NOT EXISTS `bumpIndex` (`bumpIndex`);
ALTER TABLE `friends` ADD INDEX IF NOT EXISTS `requesterId` (`requesterId`);
ALTER TABLE `friends` ADD INDEX IF NOT EXISTS `receiverId` (`receiverId`);
ALTER TABLE `groups` ADD INDEX IF NOT EXISTS `creator` (`creator`);
ALTER TABLE `groups` ADD INDEX IF NOT EXISTS `owner` (`owner`);
ALTER TABLE `groups` ADD INDEX IF NOT EXISTS `name` (`name`);
ALTER TABLE `groups_members` ADD INDEX IF NOT EXISTS `GroupID` (`GroupID`);
ALTER TABLE `groups_members` ADD INDEX IF NOT EXISTS `UserID` (`UserID`);
ALTER TABLE `ownedAssets` ADD INDEX IF NOT EXISTS `assetId` (`assetId`);
ALTER TABLE `ownedAssets` ADD INDEX IF NOT EXISTS `userId` (`userId`);
ALTER TABLE `sessions` ADD INDEX IF NOT EXISTS `userId` (`userId`);
ALTER TABLE `sessions` ADD INDEX IF NOT EXISTS `loginIp` (`loginIp`);
ALTER TABLE `users` ADD UNIQUE INDEX IF NOT EXISTS `username` (`username`);
ALTER TABLE `users` ADD INDEX IF NOT EXISTS `email` (`email`);
ALTER TABLE `users` ADD INDEX IF NOT EXISTS `discordID` (`discordID`);
ALTER TABLE `users` ADD INDEX IF NOT EXISTS `discordKey` (`discordKey`);
ALTER TABLE `users` ADD INDEX IF NOT EXISTS `lastonline` (`lastonline`);

-- polygon-engine importer: content-hash index of assets uploaded by the place importer
CREATE TABLE IF NOT EXISTS `import_assets` (
  `sha256` char(64) NOT NULL,
  `assetId` int(11) NOT NULL,
  `source` varchar(255) NOT NULL DEFAULT '',
  `created` bigint(20) NOT NULL DEFAULT 0,
  PRIMARY KEY (`sha256`),
  KEY `assetId` (`assetId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Roblox asset dump (archived Roblox assets, kept apart from Polygon's own `assets`).
-- Served for rbxassetid:// and roblox.com/asset URLs at /asset/?id=<roblox id>; Polygon's
-- own content is polyasset://<id> at /polyasset/?id=<id>. Content lives in the shared assets
-- volume under rbxdump/<first two hex>/<sha256>.
CREATE TABLE IF NOT EXISTS `roblox_assets` (
  `id` bigint(20) unsigned NOT NULL,
  `name` varchar(255) DEFAULT NULL,
  `description` text DEFAULT NULL,
  `asset_type_id` int(11) DEFAULT NULL,
  `type_inferred` tinyint(1) NOT NULL DEFAULT 0,
  `roblox_creator_id` bigint(20) DEFAULT NULL,
  `roblox_creator_name` varchar(100) DEFAULT NULL,
  `roblox_creator_type` varchar(16) DEFAULT NULL,
  `roblox_created` datetime DEFAULT NULL,
  `roblox_updated` datetime DEFAULT NULL,
  `owner_id` int(11) NOT NULL DEFAULT 1,
  `for_sale` tinyint(1) NOT NULL DEFAULT 0,
  `price` int(11) DEFAULT NULL,
  `latest_version` int(11) DEFAULT NULL,
  `sha256` char(64) DEFAULT NULL,
  `size` bigint(20) DEFAULT NULL,
  `kind` varchar(16) DEFAULT NULL,
  `thumbnail_sha256` char(64) DEFAULT NULL,
  `source` varchar(16) NOT NULL,
  `imported` bigint(20) NOT NULL DEFAULT 0,
  PRIMARY KEY (`id`),
  KEY `sha256` (`sha256`),
  KEY `asset_type_id` (`asset_type_id`),
  KEY `owner_id` (`owner_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS `roblox_asset_versions` (
  `asset_id` bigint(20) unsigned NOT NULL,
  `version` int(11) NOT NULL,
  `sha256` char(64) NOT NULL,
  `size` bigint(20) NOT NULL,
  `kind` varchar(16) DEFAULT NULL,
  PRIMARY KEY (`asset_id`, `version`),
  KEY `sha256` (`sha256`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- place client versions are era codes (2010M, 2011M, 2012L, 2014M, 2016M), not bare years
ALTER TABLE `assets` MODIFY COLUMN `Version` varchar(8) DEFAULT NULL;
UPDATE `assets` SET `Version` = CASE `Version` WHEN '2010' THEN '2010M' WHEN '2011' THEN '2011M' WHEN '2012' THEN '2012L' WHEN '2014' THEN '2014M' WHEN '2016' THEN '2016M' ELSE `Version` END WHERE `Version` REGEXP '^[0-9]{4}$';
UPDATE `GameJobs` SET `Version` = CASE `Version` WHEN '2010' THEN '2010M' WHEN '2011' THEN '2011M' WHEN '2012' THEN '2012L' ELSE `Version` END WHERE `Version` REGEXP '^[0-9]{4}$';


-- one-time join tickets the Polygon Player hands to a game server (redeemed by the engine)
CREATE TABLE IF NOT EXISTS `JoinTickets` (
  `Ticket` char(48) NOT NULL,
  `UserID` int(11) NOT NULL,
  `JobID` varchar(36) NOT NULL,
  `Created` bigint(20) NOT NULL,
  `Used` tinyint(1) NOT NULL DEFAULT 0,
  PRIMARY KEY (`Ticket`),
  KEY `UserID` (`UserID`, `Created`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- game servers run one exact engine release; players only join games on the latest one
ALTER TABLE `GameJobs` ADD COLUMN IF NOT EXISTS `EngineVersion` varchar(40) DEFAULT NULL;

-- Polyback Player content downloads: short-lived per-user tokens put in the join link
CREATE TABLE IF NOT EXISTS `ClientContentTokens` (
  `Token` char(64) NOT NULL,
  `UserID` int(11) NOT NULL,
  `Created` bigint(20) NOT NULL,
  `Expires` bigint(20) NOT NULL,
  PRIMARY KEY (`Token`),
  KEY `UserID` (`UserID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- abuse reports from in-game Report Abuse (sent by the game server with recent chat)
CREATE TABLE IF NOT EXISTS `AbuseReports` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `ReporterID` int(11) NOT NULL,
  `TargetID` int(11) DEFAULT NULL,
  `PlaceID` int(11) DEFAULT NULL,
  `JobID` varchar(36) DEFAULT NULL,
  `Reason` varchar(200) NOT NULL,
  `Comment` text NOT NULL,
  `ChatLog` mediumtext NOT NULL,
  `Created` bigint(20) NOT NULL,
  `HandledBy` int(11) DEFAULT NULL,
  `HandledAt` bigint(20) DEFAULT NULL,
  PRIMARY KEY (`ID`),
  KEY `TargetID` (`TargetID`),
  KEY `HandledBy` (`HandledBy`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Polygon Studio sign-ins: long-lived tokens (only their sha256 is stored), revocable
CREATE TABLE IF NOT EXISTS `StudioTokens` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `TokenHash` char(64) NOT NULL,
  `UserID` int(11) NOT NULL,
  `Label` varchar(100) DEFAULT NULL,
  `Created` bigint(20) NOT NULL,
  `LastUsed` bigint(20) NOT NULL DEFAULT 0,
  `Revoked` tinyint(1) NOT NULL DEFAULT 0,
  PRIMARY KEY (`id`),
  UNIQUE KEY `TokenHash` (`TokenHash`),
  KEY `UserID` (`UserID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- failed Studio sign-ins (rate limiting)
CREATE TABLE IF NOT EXISTS `StudioLoginAttempts` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `IP` varchar(64) NOT NULL,
  `Time` bigint(20) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `IP` (`IP`, `Time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- place files published from Studio (each version's file is kept: assets/place-versions/<id>-<n>)
CREATE TABLE IF NOT EXISTS `StudioPlaceVersions` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `PlaceID` int(11) NOT NULL,
  `Version` int(11) NOT NULL,
  `UserID` int(11) NOT NULL,
  `Created` bigint(20) NOT NULL,
  `Size` bigint(20) NOT NULL,
  `Sha256` char(64) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `PlaceVersion` (`PlaceID`, `Version`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- one-time codes from the website's Edit button: the Polyback Player opens Studio with one,
-- and Studio trades it for a Studio token (2 minutes, single use; only the hash is stored)
CREATE TABLE IF NOT EXISTS `StudioLaunchCodes` (
  `CodeHash` char(64) NOT NULL,
  `UserID` int(11) NOT NULL,
  `PlaceID` int(11) NOT NULL,
  `Expires` bigint(20) NOT NULL,
  `Used` tinyint(1) NOT NULL DEFAULT 0,
  PRIMARY KEY (`CodeHash`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Visit (solo) games: a one-player server nobody else is matched into
ALTER TABLE `GameJobs` ADD COLUMN IF NOT EXISTS `Private` tinyint(1) NOT NULL DEFAULT 0;

-- DataStoreService: persistent data per place (game servers read/write it with their key)
CREATE TABLE IF NOT EXISTS `DataStoreEntries` (
  `PlaceID` int(11) NOT NULL,
  `Ordered` tinyint(1) NOT NULL DEFAULT 0,
  `Store` varchar(50) NOT NULL,
  `Scope` varchar(50) NOT NULL,
  `KeyName` varchar(50) NOT NULL,
  `Value` mediumtext NOT NULL,
  `NumValue` bigint(20) DEFAULT NULL,
  `Version` int(11) NOT NULL DEFAULT 1,
  `Updated` bigint(20) NOT NULL,
  PRIMARY KEY (`PlaceID`, `Ordered`, `Store`, `Scope`, `KeyName`),
  KEY `Sorted` (`PlaceID`, `Store`, `Scope`, `NumValue`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;

-- Studio imports by users: who uploaded each imported asset and its size (for the storage
-- cap), and an optional per-user cap in MB set by an admin (NULL: the site default)
ALTER TABLE `import_assets` ADD COLUMN IF NOT EXISTS `uploader` int(11) NOT NULL DEFAULT 0;
ALTER TABLE `import_assets` ADD COLUMN IF NOT EXISTS `size` bigint(20) NOT NULL DEFAULT 0;
ALTER TABLE `import_assets` ADD INDEX IF NOT EXISTS `uploader` (`uploader`);
ALTER TABLE `users` ADD COLUMN IF NOT EXISTS `ImportQuotaMB` int(11) DEFAULT NULL;

-- Private servers: a game started by a player for themselves (PrivateMode 'Solo', the Visit
-- button and "Just me") or for themselves and their friends ('Friends'). Both keep
-- Private = 1, so public matchmaking and the public server list never touch them; OwnerID
-- is who started it. NULL PrivateMode: a public game.
ALTER TABLE `GameJobs` ADD COLUMN IF NOT EXISTS `OwnerID` int(11) DEFAULT NULL;
ALTER TABLE `GameJobs` ADD COLUMN IF NOT EXISTS `PrivateMode` varchar(10) DEFAULT NULL;
ALTER TABLE `GameJobs` ADD INDEX IF NOT EXISTS `OwnerID` (`OwnerID`);

-- who is in each game (Polygon Player servers): added when the game redeems a player's join
-- ticket, cleared when the game reports it emptied, ended, or the player joined elsewhere
CREATE TABLE IF NOT EXISTS `GameJobPlayers` (
  `JobID` varchar(36) NOT NULL,
  `UserID` int(11) NOT NULL,
  `Joined` bigint(20) NOT NULL,
  `Active` tinyint(1) NOT NULL DEFAULT 1,
  PRIMARY KEY (`JobID`, `UserID`),
  KEY `UserID` (`UserID`, `Active`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Visit games started before private servers existed are solo private servers of whoever started them
UPDATE `GameJobs` SET `PrivateMode` = 'Solo', `OwnerID` = `RequestedBy` WHERE `Private` = 1 AND `PrivateMode` IS NULL;

-- Friends chat: 1:1 messages between friends (only friends may send; checked by the site).
-- Conversation: a conversation's messages by id (one range per direction); Unread: per-friend
-- unread counts and marking read; SenderTime: the send rate limit.
CREATE TABLE IF NOT EXISTS `ChatMessages` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `SenderID` int(11) NOT NULL,
  `ReceiverID` int(11) NOT NULL,
  `Message` varchar(500) NOT NULL,
  `TimeSent` bigint(20) NOT NULL,
  `IsRead` tinyint(1) NOT NULL DEFAULT 0,
  PRIMARY KEY (`ID`),
  KEY `Conversation` (`SenderID`, `ReceiverID`, `ID`),
  KEY `Unread` (`ReceiverID`, `IsRead`, `SenderID`),
  KEY `SenderTime` (`SenderID`, `TimeSent`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- chat "is typing" status: when the sender last said they were typing to the receiver
-- (0: stopped); it counts for a few seconds only
CREATE TABLE IF NOT EXISTS `ChatTyping` (
  `SenderID` int(11) NOT NULL,
  `ReceiverID` int(11) NOT NULL,
  `Updated` bigint(20) NOT NULL DEFAULT 0,
  PRIMARY KEY (`SenderID`, `ReceiverID`),
  KEY `Receiver` (`ReceiverID`, `Updated`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Join queue: GameJobs.Status 'Queued' = a new-server request waiting in its game server's
-- queue for a free slot (the varchar(20) Status column needs no change). The site counts
-- queued requests per machine when picking one, and per player (one place each).
CREATE INDEX IF NOT EXISTS `ServerStatus` ON `GameJobs` (`ServerID`, `Status`);
CREATE INDEX IF NOT EXISTS `RequesterStatus` ON `GameJobs` (`RequestedBy`, `Status`);

-- Deploy Updates (/admin/deploy-updates): where each program is built from, its builds
-- (queued by the site, run by the polybuild build runner, which may only read DeploySources and
-- DeployState and update DeployBuilds), deploy/rollback requests (carried out by the root deploy
-- daemon) and what is deployed now. Program: website, engine, gameserver, bootstrapper.
CREATE TABLE IF NOT EXISTS `DeploySources` (
  `Program` varchar(20) NOT NULL,
  `GitURL` varchar(255) NOT NULL,
  `Branch` varchar(100) NOT NULL DEFAULT 'master',
  `UpdatedBy` int(11) DEFAULT NULL,
  `Updated` bigint(20) NOT NULL DEFAULT 0,
  PRIMARY KEY (`Program`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
INSERT IGNORE INTO `DeploySources` (`Program`, `GitURL`, `Branch`) VALUES
 ('website', 'https://polyback.xyz/git/polyback-website.git', 'master'),
 ('engine', 'https://polyback.xyz/git/polyback-engine.git', 'master'),
 ('gameserver', 'https://polyback.xyz/git/polyback-gameserver.git', 'master'),
 ('bootstrapper', 'https://polyback.xyz/git/polyback-bootstrapper.git', 'master');

-- Status: queued, running, success, failed, cancelled. Stage: what a running build is doing.
-- Artifacts: JSON {"<platform>": {"file", "size", "sha256"}, ...} under the runner's artifacts/<ID>/.
CREATE TABLE IF NOT EXISTS `DeployBuilds` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `Program` varchar(20) NOT NULL,
  `Status` varchar(12) NOT NULL DEFAULT 'queued',
  `Stage` varchar(100) DEFAULT NULL,
  `CancelRequested` tinyint(1) NOT NULL DEFAULT 0,
  `RequestedBy` int(11) NOT NULL DEFAULT 0,
  `TimeRequested` bigint(20) NOT NULL DEFAULT 0,
  `TimeStarted` bigint(20) DEFAULT NULL,
  `TimeFinished` bigint(20) DEFAULT NULL,
  `GitURL` varchar(255) NOT NULL,
  `Branch` varchar(100) NOT NULL,
  `CommitHash` varchar(64) DEFAULT NULL,
  `CommitAuthor` varchar(255) DEFAULT NULL,
  `CommitMessage` text DEFAULT NULL,
  `CommitTime` bigint(20) DEFAULT NULL,
  `Version` varchar(40) DEFAULT NULL,
  `Artifacts` text DEFAULT NULL,
  `ArtifactBytes` bigint(20) NOT NULL DEFAULT 0,
  `Log` mediumtext DEFAULT NULL,
  PRIMARY KEY (`ID`),
  KEY `ProgramID` (`Program`, `ID`),
  KEY `Status` (`Status`, `ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Action: deploy (BuildID) or rollback (to the program's previous deployed build).
-- Status: queued, running, success, failed.
CREATE TABLE IF NOT EXISTS `DeployActions` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `Program` varchar(20) NOT NULL,
  `Action` varchar(12) NOT NULL DEFAULT 'deploy',
  `BuildID` int(11) DEFAULT NULL,
  `Status` varchar(12) NOT NULL DEFAULT 'queued',
  `RequestedBy` int(11) NOT NULL DEFAULT 0,
  `TimeRequested` bigint(20) NOT NULL DEFAULT 0,
  `TimeStarted` bigint(20) DEFAULT NULL,
  `TimeFinished` bigint(20) DEFAULT NULL,
  `Log` mediumtext DEFAULT NULL,
  PRIMARY KEY (`ID`),
  KEY `Status` (`Status`, `ID`),
  KEY `ProgramID` (`Program`, `ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS `DeployState` (
  `Program` varchar(20) NOT NULL,
  `CurrentBuildID` int(11) DEFAULT NULL,
  `CurrentVersion` varchar(64) DEFAULT NULL,
  `PreviousBuildID` int(11) DEFAULT NULL,
  `PreviousVersion` varchar(64) DEFAULT NULL,
  `Updated` bigint(20) NOT NULL DEFAULT 0,
  PRIMARY KEY (`Program`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Heartbeats of the build runner and the deploy daemon (the page warns when one isn't running).
CREATE TABLE IF NOT EXISTS `DeployDaemons` (
  `Name` varchar(20) NOT NULL,
  `Heartbeat` bigint(20) NOT NULL DEFAULT 0,
  `Info` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`Name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Which part of each schema file a website deploy has applied (the files only grow: a deploy
-- runs what was appended since, or the whole idempotent file if earlier parts changed).
CREATE TABLE IF NOT EXISTS `SchemaApplied` (
  `File` varchar(100) NOT NULL,
  `Bytes` bigint(20) NOT NULL DEFAULT 0,
  `SHA256` char(64) NOT NULL,
  `Applied` bigint(20) NOT NULL DEFAULT 0,
  PRIMARY KEY (`File`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Places that can be played on several client versions: NULL = only `Version`, 'All', or a
-- comma-separated list that includes `Version` (see ClientVersions.php).
ALTER TABLE `assets` ADD COLUMN IF NOT EXISTS `Versions` varchar(100) DEFAULT NULL;