-- SHiNE PostgreSQL database format v2 / runtime schema revision 30 -- Stage 2 baseline. This file is only for a NEW, EMPTY database. -- Дата: 2026-09-29 -- -- Назначение: -- - поднять пустую PostgreSQL БД сервера SHiNE с нуля; -- - включить таблицы модуля синхронизации Solana users; -- - включить runtime-таблицы сервера без legacy-таблиц старого runtime; -- - основной runtime DM storage = signed_messages -- -- Важно: -- - источник истины по пользователям: solana_user_pda_current; -- - runtime table blockchain_state остаётся как локальное серверное состояние chain, -- но не мигрируется из старого локального runtime и не считается identity-слоем; -- - триггеры переписаны под PostgreSQL и сохраняют текущую серверную логику. BEGIN; -- Safety guard: DB v2 is a fresh-baseline format, not an in-place migration. DO $$ BEGIN IF EXISTS ( SELECT 1 FROM information_schema.tables WHERE table_schema = current_schema() AND table_type = 'BASE TABLE' ) THEN RAISE EXCEPTION 'SHiNE_DB_V2 bootstrap requires an empty PostgreSQL schema; legacy/in-place migration is disabled'; END IF; END $$; CREATE TABLE IF NOT EXISTS db_schema_version ( id INTEGER PRIMARY KEY, schema_version INTEGER NOT NULL, updated_at_ms BIGINT NOT NULL ); -- Hard database-generation marker. Stage 2 server MUST NOT run on an older SHiNE DB. CREATE TABLE IF NOT EXISTS shine_database_metadata ( id INTEGER PRIMARY KEY CHECK (id = 1), database_format TEXT NOT NULL CHECK (database_format = 'SHiNE_DB_V2'), database_generation INTEGER NOT NULL CHECK (database_generation = 2), created_at_ms BIGINT NOT NULL ); INSERT INTO shine_database_metadata(id, database_format, database_generation, created_at_ms) VALUES (1, 'SHiNE_DB_V2', 2, CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT)) ON CONFLICT (id) DO NOTHING; COMMENT ON TABLE shine_database_metadata IS 'SHiNE database generation marker. Stage 2 requires SHiNE_DB_V2 / generation 2.'; INSERT INTO db_schema_version (id, schema_version, updated_at_ms) VALUES (1, 29, CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT)) ON CONFLICT (id) DO UPDATE SET schema_version = EXCLUDED.schema_version, updated_at_ms = EXCLUDED.updated_at_ms; CREATE TABLE IF NOT EXISTS solana_sync_state ( id INTEGER PRIMARY KEY, status TEXT NOT NULL, ready BOOLEAN NOT NULL, last_poll_at_ms BIGINT, last_successful_poll_at_ms BIGINT, last_seen_signature TEXT, last_seen_slot BIGINT, last_relevant_signature TEXT, last_relevant_slot BIGINT, last_error TEXT, economy_config_version INTEGER, registration_fee_lamports BIGINT, lamports_per_limit_step BIGINT, start_bonus_limit BIGINT, updated_at_ms BIGINT ); INSERT INTO solana_sync_state (id, status, ready) VALUES (1, 'EMPTY', FALSE) ON CONFLICT (id) DO NOTHING; CREATE TABLE IF NOT EXISTS solana_sync_tx_history ( id BIGSERIAL PRIMARY KEY, signature TEXT NOT NULL UNIQUE, slot BIGINT NOT NULL, block_time BIGINT, tx_kind TEXT NOT NULL, is_relevant BOOLEAN NOT NULL, affected_pda_address TEXT, affected_login TEXT, raw_summary_json TEXT NOT NULL, processed_at_ms BIGINT NOT NULL ); CREATE INDEX IF NOT EXISTS idx_sync_tx_history_slot ON solana_sync_tx_history(slot); CREATE INDEX IF NOT EXISTS idx_sync_tx_history_relevant ON solana_sync_tx_history(is_relevant); CREATE INDEX IF NOT EXISTS idx_sync_tx_history_login ON solana_sync_tx_history(affected_login); CREATE TABLE IF NOT EXISTS solana_user_pda_current ( pda_address TEXT PRIMARY KEY, login TEXT NOT NULL UNIQUE, normalized_login TEXT NOT NULL, record_number INTEGER NOT NULL, slot BIGINT NOT NULL, last_tx_signature TEXT NOT NULL, recovery_key TEXT NOT NULL, root_key TEXT NOT NULL, client_key TEXT NOT NULL, blockchain_name TEXT NOT NULL, blockchain_key TEXT NOT NULL, paid_limit_bytes BIGINT NOT NULL, blockchain_forks_json TEXT NOT NULL DEFAULT '[]', used_bytes BIGINT NOT NULL, last_block_number INTEGER NOT NULL, last_block_hash TEXT NOT NULL, last_block_signature TEXT NOT NULL, arweave_tx_id TEXT NOT NULL, is_server BOOLEAN NOT NULL, address_format_type INTEGER NOT NULL, address_format_version INTEGER NOT NULL, server_address TEXT NOT NULL, sync_servers_json TEXT NOT NULL, access_servers_json TEXT NOT NULL, sessions_mode INTEGER NOT NULL, sessions_json TEXT NOT NULL, trusted_count INTEGER NOT NULL, created_at_ms BIGINT NOT NULL, updated_at_ms BIGINT NOT NULL, prev_record_hash TEXT NOT NULL, record_signature TEXT NOT NULL, raw_data_base64 TEXT NOT NULL, first_seen_at_ms BIGINT NOT NULL, last_synced_at_ms BIGINT NOT NULL ); CREATE INDEX IF NOT EXISTS idx_user_pda_current_slot ON solana_user_pda_current(slot); CREATE UNIQUE INDEX IF NOT EXISTS uq_solana_user_pda_current_normalized_login ON solana_user_pda_current(normalized_login); CREATE INDEX IF NOT EXISTS idx_user_pda_current_normalized_login ON solana_user_pda_current(normalized_login); CREATE TABLE IF NOT EXISTS user_access_servers_current ( user_login TEXT NOT NULL REFERENCES solana_user_pda_current(login) ON DELETE CASCADE, server_login TEXT NOT NULL REFERENCES solana_user_pda_current(login) ON DELETE CASCADE, server_url TEXT NOT NULL, server_client_key TEXT NOT NULL, user_record_number INTEGER NOT NULL, user_updated_at_ms BIGINT NOT NULL, server_record_number INTEGER NOT NULL, server_updated_at_ms BIGINT NOT NULL, refreshed_at_ms BIGINT NOT NULL, PRIMARY KEY (user_login, server_login) ); CREATE INDEX IF NOT EXISTS idx_user_access_servers_user ON user_access_servers_current(user_login); CREATE INDEX IF NOT EXISTS idx_user_access_servers_server ON user_access_servers_current(server_login); CREATE OR REPLACE FUNCTION shine_refresh_user_access_servers_for_user(p_user_login TEXT) RETURNS VOID LANGUAGE plpgsql AS $$ BEGIN IF p_user_login IS NULL OR btrim(p_user_login) = '' THEN RETURN; END IF; DELETE FROM user_access_servers_current WHERE LOWER(user_login) = LOWER(p_user_login); INSERT INTO user_access_servers_current ( user_login, server_login, server_url, server_client_key, user_record_number, user_updated_at_ms, server_record_number, server_updated_at_ms, refreshed_at_ms ) SELECT u.login, s.login, s.server_address, s.client_key, u.record_number, u.updated_at_ms, s.record_number, s.updated_at_ms, CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT) FROM solana_user_pda_current u CROSS JOIN LATERAL ( SELECT login_value FROM jsonb_array_elements_text( CASE WHEN btrim(COALESCE(u.access_servers_json, '')) = '' THEN '[]'::jsonb ELSE u.access_servers_json::jsonb END ) WITH ORDINALITY AS access_server(login_value, ord) WHERE ord = 1 ) AS access_server JOIN solana_user_pda_current s ON LOWER(s.login) = LOWER(btrim(access_server.login_value)) AND s.is_server = TRUE AND btrim(COALESCE(s.server_address, '')) <> '' WHERE LOWER(u.login) = LOWER(p_user_login) ON CONFLICT (user_login, server_login) DO UPDATE SET server_url = EXCLUDED.server_url, server_client_key = EXCLUDED.server_client_key, user_record_number = EXCLUDED.user_record_number, user_updated_at_ms = EXCLUDED.user_updated_at_ms, server_record_number = EXCLUDED.server_record_number, server_updated_at_ms = EXCLUDED.server_updated_at_ms, refreshed_at_ms = EXCLUDED.refreshed_at_ms; END; $$; CREATE OR REPLACE FUNCTION shine_refresh_user_access_servers_for_server(p_server_login TEXT) RETURNS VOID LANGUAGE plpgsql AS $$ DECLARE affected_user RECORD; BEGIN IF p_server_login IS NULL OR btrim(p_server_login) = '' THEN RETURN; END IF; DELETE FROM user_access_servers_current WHERE LOWER(server_login) = LOWER(p_server_login); FOR affected_user IN SELECT u.login FROM solana_user_pda_current u CROSS JOIN LATERAL ( SELECT login_value FROM jsonb_array_elements_text( CASE WHEN btrim(COALESCE(u.access_servers_json, '')) = '' THEN '[]'::jsonb ELSE u.access_servers_json::jsonb END ) WITH ORDINALITY AS access_server(login_value, ord) WHERE ord = 1 ) AS access_server WHERE LOWER(btrim(access_server.login_value)) = LOWER(p_server_login) LOOP PERFORM shine_refresh_user_access_servers_for_user(affected_user.login); END LOOP; END; $$; CREATE OR REPLACE FUNCTION shine_refresh_user_access_servers_all() RETURNS VOID LANGUAGE plpgsql AS $$ DECLARE affected_user RECORD; BEGIN TRUNCATE TABLE user_access_servers_current; FOR affected_user IN SELECT login FROM solana_user_pda_current LOOP PERFORM shine_refresh_user_access_servers_for_user(affected_user.login); END LOOP; END; $$; CREATE OR REPLACE FUNCTION trg_refresh_user_access_servers_from_user_pda_row() RETURNS TRIGGER LANGUAGE plpgsql AS $$ BEGIN IF TG_OP = 'DELETE' THEN PERFORM shine_refresh_user_access_servers_for_user(OLD.login); PERFORM shine_refresh_user_access_servers_for_server(OLD.login); RETURN OLD; END IF; IF TG_OP = 'UPDATE' AND LOWER(OLD.login) <> LOWER(NEW.login) THEN PERFORM shine_refresh_user_access_servers_for_user(OLD.login); PERFORM shine_refresh_user_access_servers_for_server(OLD.login); END IF; PERFORM shine_refresh_user_access_servers_for_user(NEW.login); PERFORM shine_refresh_user_access_servers_for_server(NEW.login); RETURN NEW; END; $$; CREATE OR REPLACE FUNCTION trg_refresh_user_access_servers_from_user_pda_truncate() RETURNS TRIGGER LANGUAGE plpgsql AS $$ BEGIN TRUNCATE TABLE user_access_servers_current; RETURN NULL; END; $$; DROP TRIGGER IF EXISTS trg_refresh_user_access_servers_row ON solana_user_pda_current; CREATE TRIGGER trg_refresh_user_access_servers_row AFTER INSERT OR UPDATE OR DELETE ON solana_user_pda_current FOR EACH ROW EXECUTE FUNCTION trg_refresh_user_access_servers_from_user_pda_row(); DROP TRIGGER IF EXISTS trg_refresh_user_access_servers_truncate ON solana_user_pda_current; CREATE TRIGGER trg_refresh_user_access_servers_truncate AFTER TRUNCATE ON solana_user_pda_current FOR EACH STATEMENT EXECUTE FUNCTION trg_refresh_user_access_servers_from_user_pda_truncate(); CREATE TABLE IF NOT EXISTS solana_user_pda_history ( id BIGSERIAL PRIMARY KEY, tx_signature TEXT NOT NULL, slot BIGINT NOT NULL, block_time BIGINT, pda_address TEXT NOT NULL, login TEXT NOT NULL, record_number INTEGER NOT NULL, recovery_key TEXT NOT NULL, root_key TEXT NOT NULL, client_key TEXT NOT NULL, blockchain_name TEXT NOT NULL, blockchain_key TEXT NOT NULL, paid_limit_bytes BIGINT NOT NULL, used_bytes BIGINT NOT NULL, last_block_number INTEGER NOT NULL, last_block_hash TEXT NOT NULL, last_block_signature TEXT NOT NULL, arweave_tx_id TEXT NOT NULL, is_server BOOLEAN NOT NULL, address_format_type INTEGER NOT NULL, address_format_version INTEGER NOT NULL, server_address TEXT NOT NULL, sync_servers_json TEXT NOT NULL, access_servers_json TEXT NOT NULL, sessions_mode INTEGER NOT NULL, sessions_json TEXT NOT NULL, trusted_count INTEGER NOT NULL, created_at_ms BIGINT NOT NULL, updated_at_ms BIGINT NOT NULL, prev_record_hash TEXT NOT NULL, record_signature TEXT NOT NULL, raw_data_base64 TEXT NOT NULL, saved_at_ms BIGINT NOT NULL, UNIQUE (pda_address, record_number) ); CREATE INDEX IF NOT EXISTS idx_user_pda_history_login ON solana_user_pda_history(login); CREATE INDEX IF NOT EXISTS idx_user_pda_history_slot ON solana_user_pda_history(slot); CREATE TABLE IF NOT EXISTS active_sessions ( session_id TEXT PRIMARY KEY, login TEXT NOT NULL REFERENCES solana_user_pda_current(login), session_key TEXT NOT NULL, storage_pwd TEXT NOT NULL, session_created_at_ms BIGINT NOT NULL, last_authirificated_at_ms BIGINT NOT NULL, push_endpoint TEXT, push_p256dh_key TEXT, push_auth_key TEXT, client_ip TEXT, client_info_from_client TEXT, client_info_from_request TEXT, session_type INTEGER NOT NULL DEFAULT 1, client_platform TEXT NOT NULL DEFAULT '', user_language TEXT ); CREATE INDEX IF NOT EXISTS idx_active_sessions_login ON active_sessions(login); CREATE TABLE IF NOT EXISTS esp_pairing_settings ( login TEXT PRIMARY KEY REFERENCES solana_user_pda_current(login), enabled INTEGER NOT NULL DEFAULT 0, password_hash TEXT NOT NULL DEFAULT '', ttl_seconds INTEGER NOT NULL DEFAULT 300, failed_attempts INTEGER NOT NULL DEFAULT 0, first_failed_at_ms BIGINT NOT NULL DEFAULT 0, blocked_until_ms BIGINT NOT NULL DEFAULT 0, updated_at_ms BIGINT NOT NULL ); CREATE TABLE IF NOT EXISTS esp_pairing_requests ( pairing_id TEXT PRIMARY KEY, login TEXT NOT NULL REFERENCES solana_user_pda_current(login), requester_session_key TEXT NOT NULL, requester_session_type INTEGER NOT NULL DEFAULT 1, requester_client_platform TEXT NOT NULL DEFAULT '', payload_type INTEGER NOT NULL, status TEXT NOT NULL, short_code TEXT NOT NULL, fingerprint_b58 TEXT NOT NULL, encrypted_payload TEXT, reject_reason TEXT, approved_by_session_id TEXT, created_at_ms BIGINT NOT NULL, expires_at_ms BIGINT NOT NULL, updated_at_ms BIGINT NOT NULL, delivered_to_homeserver INTEGER NOT NULL DEFAULT 0 ); CREATE INDEX IF NOT EXISTS idx_esp_pairing_requests_login_status ON esp_pairing_requests(login, status, expires_at_ms); CREATE TABLE IF NOT EXISTS users_params ( login TEXT NOT NULL REFERENCES solana_user_pda_current(login), param TEXT NOT NULL, time_ms BIGINT NOT NULL, value TEXT NOT NULL, client_key TEXT, signature TEXT, UNIQUE (login, param) ); CREATE INDEX IF NOT EXISTS idx_users_params_login ON users_params(login); CREATE TABLE IF NOT EXISTS user_settings ( login TEXT NOT NULL REFERENCES solana_user_pda_current(login), setting_type INTEGER NOT NULL, setting_key TEXT NOT NULL, time_ms BIGINT NOT NULL, value_text TEXT NOT NULL DEFAULT '', value_num BIGINT NOT NULL DEFAULT 0, client_key TEXT NOT NULL DEFAULT '', signature TEXT NOT NULL DEFAULT '', UNIQUE (login, setting_type, setting_key) ); CREATE INDEX IF NOT EXISTS idx_user_settings_login ON user_settings(login); CREATE INDEX IF NOT EXISTS idx_user_settings_type_key ON user_settings(setting_type, setting_key); CREATE TABLE IF NOT EXISTS channel_read_state ( viewer_login TEXT NOT NULL REFERENCES solana_user_pda_current(login), owner_login TEXT NOT NULL, owner_bch_name TEXT NOT NULL, channel_name TEXT NOT NULL, read_count BIGINT NOT NULL DEFAULT 0 CHECK (read_count >= 0), unread_count BIGINT NOT NULL DEFAULT 0 CHECK (unread_count >= 0), read_updated_at_ms BIGINT NOT NULL, client_key TEXT NOT NULL, read_signature TEXT NOT NULL, updated_at_ms BIGINT NOT NULL, PRIMARY KEY (viewer_login, owner_bch_name, channel_name) ); CREATE INDEX IF NOT EXISTS idx_channel_read_state_viewer ON channel_read_state(viewer_login); CREATE INDEX IF NOT EXISTS idx_channel_read_state_channel ON channel_read_state(owner_bch_name, channel_name); CREATE TABLE IF NOT EXISTS ip_geo_cache ( ip TEXT PRIMARY KEY, geo TEXT, updated_at_ms BIGINT NOT NULL ); CREATE INDEX IF NOT EXISTS idx_ip_geo_cache_updated_at ON ip_geo_cache(updated_at_ms); CREATE TABLE IF NOT EXISTS test_free_avatar_uploads ( login TEXT PRIMARY KEY REFERENCES solana_user_pda_current(login), used_count INTEGER NOT NULL DEFAULT 0, updated_at_ms BIGINT NOT NULL, last_tx_id TEXT NOT NULL DEFAULT '' ); CREATE INDEX IF NOT EXISTS idx_test_free_avatar_uploads_updated ON test_free_avatar_uploads(updated_at_ms); CREATE TABLE IF NOT EXISTS sync_servers ( login TEXT PRIMARY KEY, server_address TEXT NOT NULL DEFAULT '', updated_at_ms BIGINT NOT NULL ); CREATE INDEX IF NOT EXISTS idx_sync_servers_updated ON sync_servers(updated_at_ms); CREATE TABLE IF NOT EXISTS blockchain_state ( blockchain_name TEXT PRIMARY KEY, login TEXT NOT NULL REFERENCES solana_user_pda_current(login), blockchain_key TEXT NOT NULL, size_limit BIGINT NOT NULL, file_size_bytes BIGINT NOT NULL, last_block_number INTEGER NOT NULL, last_block_hash BYTEA, updated_at_ms BIGINT NOT NULL ); CREATE INDEX IF NOT EXISTS idx_blockchain_state_login ON blockchain_state(login); CREATE INDEX IF NOT EXISTS idx_blockchain_state_updated_at ON blockchain_state(updated_at_ms); CREATE TABLE IF NOT EXISTS blocks ( login TEXT NOT NULL REFERENCES solana_user_pda_current(normalized_login), bch_name TEXT NOT NULL REFERENCES blockchain_state(blockchain_name), block_number INTEGER NOT NULL CHECK (block_number >= 0), msg_type INTEGER NOT NULL, msg_sub_type INTEGER NOT NULL, block_bytes BYTEA NOT NULL, to_login TEXT, to_bch_name TEXT, to_fork_number INTEGER CHECK (to_fork_number IS NULL OR (to_fork_number >= 0 AND to_fork_number <= 999)), to_block_number INTEGER CHECK (to_block_number IS NULL OR to_block_number >= 0), to_block_hash BYTEA, block_hash BYTEA NOT NULL, block_signature BYTEA NOT NULL, data_item_id BYTEA NOT NULL, arweave_publish_pending BOOLEAN NOT NULL DEFAULT FALSE, arweave_published_at_ms BIGINT, arweave_root_tx_id TEXT, edited_by_block_number INTEGER CHECK (edited_by_block_number IS NULL OR edited_by_block_number >= 0), line_code INTEGER CHECK (line_code IS NULL OR line_code >= 0), prev_line_number INTEGER CHECK (prev_line_number IS NULL OR prev_line_number >= 0), prev_line_hash BYTEA, this_line_number INTEGER CHECK (this_line_number IS NULL OR this_line_number >= 0), UNIQUE (bch_name, block_number) ); CREATE INDEX IF NOT EXISTS idx_blocks_by_chain_number ON blocks (bch_name, block_number); CREATE UNIQUE INDEX IF NOT EXISTS uq_blocks_data_item_id ON blocks(data_item_id); CREATE INDEX IF NOT EXISTS idx_blocks_arweave_publish_pending ON blocks(block_number) WHERE arweave_publish_pending = TRUE; CREATE INDEX IF NOT EXISTS idx_blocks_to_target ON blocks (to_login, to_bch_name, to_block_number); CREATE INDEX IF NOT EXISTS idx_blocks_by_line ON blocks (bch_name, line_code, this_line_number); CREATE TABLE IF NOT EXISTS arweave_block_sync_state ( id SMALLINT PRIMARY KEY CHECK (id = 1), last_block_height BIGINT NOT NULL DEFAULT 0, updated_at_ms BIGINT NOT NULL DEFAULT 0 ); INSERT INTO arweave_block_sync_state(id, last_block_height, updated_at_ms) VALUES (1, 0, 0) ON CONFLICT (id) DO NOTHING; CREATE TABLE IF NOT EXISTS arweave_block_import_queue ( data_item_id BYTEA PRIMARY KEY, root_tx_id TEXT NOT NULL, block_height BIGINT NOT NULL, raw_data_item BYTEA NOT NULL, status TEXT NOT NULL, last_error TEXT NOT NULL DEFAULT '', first_seen_at_ms BIGINT NOT NULL, updated_at_ms BIGINT NOT NULL, parsed_login TEXT, parsed_fork_number INTEGER CHECK (parsed_fork_number IS NULL OR parsed_fork_number BETWEEN 1 AND 999), parsed_block_number INTEGER CHECK (parsed_block_number IS NULL OR parsed_block_number >= 0), parsed_block_hash BYTEA, metadata_validated BOOLEAN NOT NULL DEFAULT FALSE ); CREATE INDEX IF NOT EXISTS idx_arweave_block_import_queue_pending ON arweave_block_import_queue(block_height,first_seen_at_ms) WHERE status='PENDING'; CREATE INDEX IF NOT EXISTS idx_arweave_block_import_queue_canonical_order ON arweave_block_import_queue(parsed_login,parsed_block_number,parsed_fork_number,first_seen_at_ms) WHERE status='PENDING' AND metadata_validated=TRUE; CREATE TABLE IF NOT EXISTS connections_state ( login TEXT NOT NULL REFERENCES solana_user_pda_current(normalized_login), rel_type INTEGER NOT NULL, to_login TEXT NOT NULL, to_bch_name TEXT NOT NULL, to_block_number INTEGER NOT NULL, to_block_hash BYTEA NOT NULL, UNIQUE (login, rel_type, to_login, to_bch_name, to_block_number, to_block_hash) ); CREATE INDEX IF NOT EXISTS idx_connections_state_login ON connections_state(login); CREATE INDEX IF NOT EXISTS idx_connections_state_to_login ON connections_state(to_login); CREATE INDEX IF NOT EXISTS idx_connections_state_pair ON connections_state(login, to_login); CREATE INDEX IF NOT EXISTS idx_connections_state_target ON connections_state(login, rel_type, to_bch_name, to_block_number); CREATE TABLE IF NOT EXISTS message_stats ( to_login TEXT NOT NULL, to_bch_name TEXT NOT NULL, to_block_number INTEGER NOT NULL, to_block_hash BYTEA NOT NULL, likes_count INTEGER NOT NULL DEFAULT 0, replies_count INTEGER NOT NULL DEFAULT 0, edits_count INTEGER NOT NULL DEFAULT 0, UNIQUE (to_login, to_bch_name, to_block_number, to_block_hash) ); CREATE INDEX IF NOT EXISTS idx_message_stats_target ON message_stats (to_bch_name, to_block_number, to_block_hash); CREATE INDEX IF NOT EXISTS idx_message_stats_login ON message_stats (to_login); CREATE TABLE IF NOT EXISTS reactions_state ( from_login TEXT NOT NULL, from_bch_name TEXT NOT NULL, reaction_type INTEGER NOT NULL, to_login TEXT NOT NULL, to_bch_name TEXT NOT NULL, to_block_number INTEGER NOT NULL, to_block_hash BYTEA NOT NULL, last_sub_type INTEGER NOT NULL, UNIQUE ( from_login, from_bch_name, reaction_type, to_login, to_bch_name, to_block_number, to_block_hash ) ); CREATE INDEX IF NOT EXISTS idx_reactions_state_target ON reactions_state (to_bch_name, to_block_number, to_block_hash); CREATE INDEX IF NOT EXISTS idx_reactions_state_actor ON reactions_state (from_login, from_bch_name, reaction_type); CREATE TABLE IF NOT EXISTS channel_names_state ( slug TEXT NOT NULL, display_name TEXT NOT NULL, channel_description TEXT NOT NULL DEFAULT '', owner_login TEXT NOT NULL, owner_bch_name TEXT NOT NULL, channel_type_code INTEGER NOT NULL DEFAULT 1, channel_type_version INTEGER NOT NULL DEFAULT 1, channel_root_block_number INTEGER NOT NULL, channel_root_block_hash BYTEA NOT NULL, created_at_ms BIGINT NOT NULL, ava_ar TEXT NOT NULL DEFAULT '', ava_sha256 TEXT NOT NULL DEFAULT '', ava_size BIGINT NOT NULL DEFAULT 0, meta_updated_at_ms BIGINT NOT NULL DEFAULT 0, is_deleted BOOLEAN NOT NULL DEFAULT FALSE, deleted_at_ms BIGINT NOT NULL DEFAULT 0, deleted_block_number INTEGER ); CREATE UNIQUE INDEX IF NOT EXISTS uq_channel_names_state_owner_type_slug ON channel_names_state (owner_bch_name, channel_type_code, slug); CREATE UNIQUE INDEX IF NOT EXISTS uq_channel_names_state_target ON channel_names_state (owner_bch_name, channel_root_block_number, channel_root_block_hash); CREATE INDEX IF NOT EXISTS idx_channel_names_state_owner ON channel_names_state (owner_login, owner_bch_name); CREATE TABLE IF NOT EXISTS user_stats_state ( login TEXT PRIMARY KEY REFERENCES solana_user_pda_current(login) ON DELETE CASCADE, owned_public_channels_count INTEGER NOT NULL DEFAULT 0 CHECK (owned_public_channels_count >= 0), following_users_count INTEGER NOT NULL DEFAULT 0 CHECK (following_users_count >= 0), following_channels_count INTEGER NOT NULL DEFAULT 0 CHECK (following_channels_count >= 0), close_friends_count INTEGER NOT NULL DEFAULT 0 CHECK (close_friends_count >= 0), updated_at_ms BIGINT NOT NULL ); CREATE INDEX IF NOT EXISTS idx_user_stats_state_following_users_count ON user_stats_state (following_users_count); CREATE TABLE IF NOT EXISTS channel_stats_state ( owner_bch_name TEXT NOT NULL, channel_root_block_number INTEGER NOT NULL CHECK (channel_root_block_number >= 0), channel_root_block_hash BYTEA NOT NULL, owner_login TEXT NOT NULL, channel_type_code INTEGER NOT NULL DEFAULT 1, subscribers_count INTEGER NOT NULL DEFAULT 0 CHECK (subscribers_count >= 0), updated_at_ms BIGINT NOT NULL, PRIMARY KEY (owner_bch_name, channel_root_block_number, channel_root_block_hash) ); CREATE INDEX IF NOT EXISTS idx_channel_stats_state_owner_login ON channel_stats_state (owner_login); CREATE TABLE IF NOT EXISTS chat200_state ( owner_login TEXT NOT NULL, owner_bch_name TEXT NOT NULL, channel_root_block_number INTEGER NOT NULL, channel_root_block_hash BYTEA NOT NULL, channel_name TEXT NOT NULL, channel_type_version INTEGER NOT NULL, chat_title TEXT NOT NULL DEFAULT '', updated_at_ms BIGINT NOT NULL, PRIMARY KEY (owner_bch_name, channel_root_block_number) ); CREATE INDEX IF NOT EXISTS idx_chat200_state_owner ON chat200_state (owner_login, owner_bch_name); CREATE TABLE IF NOT EXISTS chat200_members_state ( owner_bch_name TEXT NOT NULL, channel_root_block_number INTEGER NOT NULL, member_login TEXT NOT NULL, member_channel_name TEXT NOT NULL, is_active INTEGER NOT NULL, updated_at_ms BIGINT NOT NULL, updated_by_block_number INTEGER NOT NULL, PRIMARY KEY ( owner_bch_name, channel_root_block_number, member_login, member_channel_name ) ); CREATE INDEX IF NOT EXISTS idx_chat200_members_owner ON chat200_members_state (owner_bch_name, channel_root_block_number, is_active); CREATE TABLE IF NOT EXISTS user_push_tokens ( token_id TEXT PRIMARY KEY, login TEXT NOT NULL REFERENCES solana_user_pda_current(login), session_id TEXT NOT NULL, provider TEXT NOT NULL, token TEXT NOT NULL, platform TEXT, user_agent TEXT, updated_at_ms BIGINT NOT NULL ); CREATE INDEX IF NOT EXISTS idx_user_push_tokens_login ON user_push_tokens(login); CREATE INDEX IF NOT EXISTS idx_user_push_tokens_login_session ON user_push_tokens(login, session_id); CREATE TABLE IF NOT EXISTS signed_direct_message_replay ( from_login TEXT NOT NULL, time_ms BIGINT NOT NULL, nonce BIGINT NOT NULL, created_at_ms BIGINT NOT NULL, UNIQUE (from_login, time_ms, nonce) ); CREATE INDEX IF NOT EXISTS idx_signed_dm_replay_created ON signed_direct_message_replay(created_at_ms); CREATE TABLE IF NOT EXISTS signed_direct_messages_history ( message_id TEXT PRIMARY KEY, from_login TEXT NOT NULL, to_login TEXT NOT NULL, target_mode INTEGER NOT NULL, target_session_id TEXT, message_type INTEGER NOT NULL, time_ms BIGINT NOT NULL, nonce BIGINT NOT NULL, raw_packet BYTEA NOT NULL, created_at_ms BIGINT NOT NULL ); CREATE INDEX IF NOT EXISTS idx_signed_dm_history_to ON signed_direct_messages_history(to_login, created_at_ms); CREATE TABLE IF NOT EXISTS signed_messages ( message_key TEXT PRIMARY KEY, base_key TEXT NOT NULL, target_login TEXT NOT NULL, from_login TEXT NOT NULL, to_login TEXT NOT NULL, time_ms BIGINT NOT NULL, nonce BIGINT NOT NULL, message_type INTEGER NOT NULL, revision_time_ms BIGINT NOT NULL DEFAULT 0, reencrypted_at_ms BIGINT NOT NULL DEFAULT 0, raw_block BYTEA NOT NULL, created_at_ms BIGINT NOT NULL, source_api TEXT NOT NULL, origin_session_id TEXT, receipt_ref_base_key TEXT, receipt_ref_type INTEGER, read_at_ms BIGINT ); CREATE INDEX IF NOT EXISTS idx_signed_messages_target ON signed_messages(target_login, time_ms, created_at_ms); CREATE INDEX IF NOT EXISTS idx_signed_messages_base ON signed_messages(base_key, message_type); CREATE INDEX IF NOT EXISTS idx_signed_messages_sync_cursor ON signed_messages(target_login, created_at_ms, message_key); CREATE INDEX IF NOT EXISTS idx_signed_messages_sync_cursor_lower ON signed_messages(LOWER(target_login), created_at_ms, message_key); CREATE INDEX IF NOT EXISTS idx_signed_messages_delete_from_sync_cursor ON signed_messages(from_login, created_at_ms, message_key) WHERE message_type IN (5, 6, 7, 8); CREATE INDEX IF NOT EXISTS idx_signed_messages_delete_to_sync_cursor ON signed_messages(to_login, created_at_ms, message_key) WHERE message_type IN (5, 6, 7, 8); CREATE INDEX IF NOT EXISTS idx_signed_messages_delete_from_sync_cursor_lower ON signed_messages(LOWER(from_login), created_at_ms, message_key) WHERE message_type IN (5, 6, 7, 8); CREATE INDEX IF NOT EXISTS idx_signed_messages_delete_to_sync_cursor_lower ON signed_messages(LOWER(to_login), created_at_ms, message_key) WHERE message_type IN (5, 6, 7, 8); CREATE UNIQUE INDEX IF NOT EXISTS uq_signed_messages_receipt_incoming ON signed_messages(target_login, receipt_ref_base_key) WHERE message_type = 3 AND receipt_ref_base_key IS NOT NULL; CREATE UNIQUE INDEX IF NOT EXISTS uq_signed_messages_receipt_outgoing ON signed_messages(target_login, receipt_ref_base_key) WHERE message_type = 4 AND receipt_ref_base_key IS NOT NULL; CREATE TABLE IF NOT EXISTS signed_message_session_delivery ( message_key TEXT NOT NULL REFERENCES signed_messages(message_key), session_id TEXT NOT NULL, delivered INTEGER NOT NULL DEFAULT 0, delivered_at_ms BIGINT, created_at_ms BIGINT NOT NULL, PRIMARY KEY (message_key, session_id) ); CREATE INDEX IF NOT EXISTS idx_signed_message_delivery_session ON signed_message_session_delivery(session_id, delivered); CREATE TABLE IF NOT EXISTS user_notifications_state ( owner_login TEXT NOT NULL REFERENCES solana_user_pda_current(normalized_login), notification_kind TEXT NOT NULL CHECK (notification_kind IN ('reply', 'connection', 'event')), created_at_ms BIGINT NOT NULL, source_login TEXT NOT NULL, source_bch_name TEXT NOT NULL, source_block_number INTEGER NOT NULL CHECK (source_block_number >= 0), source_block_hash BYTEA NOT NULL, target_login TEXT, target_bch_name TEXT, target_block_number INTEGER, target_block_hash BYTEA, source_msg_sub_type INTEGER NOT NULL, source_text TEXT NOT NULL DEFAULT '', UNIQUE (owner_login, notification_kind, source_bch_name, source_block_number, source_block_hash) ); CREATE INDEX IF NOT EXISTS idx_user_notifications_state_owner_kind_time ON user_notifications_state(owner_login, notification_kind, created_at_ms DESC, source_block_number DESC); CREATE INDEX IF NOT EXISTS idx_user_notifications_state_owner_time ON user_notifications_state(owner_login, created_at_ms DESC); CREATE TABLE IF NOT EXISTS dm_dialog_state ( owner_login TEXT NOT NULL, peer_login TEXT NOT NULL, relation_flag TEXT NOT NULL DEFAULT 'none', last_message_blob_b64 TEXT NOT NULL DEFAULT '', last_message_key TEXT NOT NULL DEFAULT '', last_message_type INTEGER NOT NULL DEFAULT 0, last_message_time_ms BIGINT NOT NULL DEFAULT 0, last_message_revision_ms BIGINT NOT NULL DEFAULT 0, unread_count INTEGER NOT NULL DEFAULT 0, last_read_receipt_time_ms BIGINT NOT NULL DEFAULT 0, updated_at_ms BIGINT NOT NULL, PRIMARY KEY (owner_login, peer_login) ); CREATE INDEX IF NOT EXISTS idx_dm_dialog_state_owner_last_time ON dm_dialog_state(owner_login, last_message_time_ms DESC, peer_login); -- Изменяемое состояние доставки исходящей пары. Подписанные блоки остаются -- неизменяемыми; эта таблица описывает только сетевую доставку пары 1/2 или 3/4. CREATE TABLE IF NOT EXISTS dm_delivery_state ( outgoing_message_key TEXT PRIMARY KEY, event_id TEXT NOT NULL UNIQUE, base_key TEXT NOT NULL, from_login TEXT NOT NULL, to_login TEXT NOT NULL, incoming_message_key TEXT NOT NULL, created_at_ms BIGINT NOT NULL, delivery_expires_at_ms BIGINT NOT NULL, delivery_state INTEGER NOT NULL DEFAULT 0 CHECK (delivery_state IN (0, 1, 2, 3)), delivered_server_login TEXT, recipient_routes_hash TEXT, attempt_index INTEGER NOT NULL DEFAULT 0, next_attempt_at_ms BIGINT, last_attempt_at_ms BIGINT, last_error TEXT, updated_at_ms BIGINT NOT NULL ); CREATE INDEX IF NOT EXISTS idx_dm_delivery_state_due ON dm_delivery_state(next_attempt_at_ms, delivery_state) WHERE delivery_state = 0 AND next_attempt_at_ms IS NOT NULL; CREATE INDEX IF NOT EXISTS idx_dm_delivery_state_base ON dm_delivery_state(base_key, from_login); CREATE TABLE IF NOT EXISTS message_views_state ( viewer_login TEXT NOT NULL, to_bch_name TEXT NOT NULL, to_block_number INTEGER NOT NULL, to_block_hash BYTEA NOT NULL, first_seen_at_ms BIGINT NOT NULL, PRIMARY KEY (viewer_login, to_bch_name, to_block_number, to_block_hash) ); CREATE INDEX IF NOT EXISTS idx_message_views_state_target ON message_views_state(to_bch_name, to_block_number, to_block_hash); CREATE INDEX IF NOT EXISTS idx_message_views_state_viewer_channel ON message_views_state(viewer_login, to_bch_name); CREATE OR REPLACE FUNCTION shine_login_from_blockchain_name(blockchain_name_in TEXT) RETURNS TEXT LANGUAGE plpgsql AS $$ DECLARE dash_pos INTEGER; suffix TEXT; BEGIN IF blockchain_name_in IS NULL OR length(blockchain_name_in) <= 4 THEN RETURN NULL; END IF; dash_pos := length(blockchain_name_in) - 3; IF substr(blockchain_name_in, dash_pos, 1) <> '-' THEN RETURN NULL; END IF; suffix := substr(blockchain_name_in, dash_pos + 1); IF suffix !~ '^[0-9]{3}$' THEN RETURN NULL; END IF; RETURN substr(blockchain_name_in, 1, dash_pos - 1); END; $$; CREATE OR REPLACE FUNCTION shine_resolve_login(target_login_in TEXT, target_bch_name_in TEXT) RETURNS TEXT LANGUAGE plpgsql AS $$ DECLARE resolved_login TEXT; BEGIN IF target_login_in IS NOT NULL AND btrim(target_login_in) <> '' THEN RETURN target_login_in; END IF; IF target_bch_name_in IS NOT NULL AND btrim(target_bch_name_in) <> '' THEN SELECT login INTO resolved_login FROM solana_user_pda_current WHERE blockchain_name = target_bch_name_in LIMIT 1; IF resolved_login IS NOT NULL AND btrim(resolved_login) <> '' THEN RETURN resolved_login; END IF; END IF; RETURN shine_login_from_blockchain_name(target_bch_name_in); END; $$; CREATE OR REPLACE FUNCTION shine_user_stats_state_ai() RETURNS TRIGGER LANGUAGE plpgsql AS $$ DECLARE now_ms BIGINT; BEGIN now_ms := CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT); INSERT INTO user_stats_state ( login, owned_public_channels_count, following_users_count, following_channels_count, close_friends_count, updated_at_ms ) VALUES ( NEW.login, 0, 0, 0, 0, now_ms ) ON CONFLICT (login) DO NOTHING; RETURN NEW; END; $$; CREATE OR REPLACE FUNCTION shine_channel_names_state_stats_ai() RETURNS TRIGGER LANGUAGE plpgsql AS $$ DECLARE now_ms BIGINT; public_subscribers_count INTEGER; BEGIN now_ms := CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT); IF NEW.owner_login IS NULL OR btrim(NEW.owner_login) = '' THEN RETURN NEW; END IF; IF NEW.channel_type_code = 1 THEN IF EXISTS ( SELECT 1 FROM solana_user_pda_current su WHERE su.login = NEW.owner_login ) THEN INSERT INTO user_stats_state ( login, owned_public_channels_count, following_users_count, following_channels_count, close_friends_count, updated_at_ms ) VALUES ( NEW.owner_login, 1, 0, 0, 0, now_ms ) ON CONFLICT (login) DO UPDATE SET owned_public_channels_count = user_stats_state.owned_public_channels_count + 1, updated_at_ms = EXCLUDED.updated_at_ms; END IF; SELECT COUNT(*)::INTEGER INTO public_subscribers_count FROM connections_state cs JOIN channel_names_state cn ON cn.owner_bch_name = cs.to_bch_name AND cn.channel_root_block_number = cs.to_block_number AND cn.channel_root_block_hash = cs.to_block_hash WHERE cs.rel_type = 30 AND cn.owner_bch_name = NEW.owner_bch_name AND cn.channel_root_block_number = NEW.channel_root_block_number AND cn.channel_root_block_hash = NEW.channel_root_block_hash AND cn.channel_type_code = 1; INSERT INTO channel_stats_state ( owner_bch_name, channel_root_block_number, channel_root_block_hash, owner_login, channel_type_code, subscribers_count, updated_at_ms ) VALUES ( NEW.owner_bch_name, NEW.channel_root_block_number, NEW.channel_root_block_hash, NEW.owner_login, NEW.channel_type_code, COALESCE(public_subscribers_count, 0), now_ms ) ON CONFLICT (owner_bch_name, channel_root_block_number, channel_root_block_hash) DO UPDATE SET owner_login = EXCLUDED.owner_login, channel_type_code = EXCLUDED.channel_type_code, subscribers_count = EXCLUDED.subscribers_count, updated_at_ms = EXCLUDED.updated_at_ms; ELSE WITH pending AS ( SELECT cs.login, COUNT(*)::INTEGER AS cnt FROM connections_state cs WHERE cs.rel_type = 30 AND cs.to_bch_name = NEW.owner_bch_name AND cs.to_block_number = NEW.channel_root_block_number AND cs.to_block_hash = NEW.channel_root_block_hash GROUP BY cs.login ) UPDATE user_stats_state us SET following_channels_count = GREATEST(0, us.following_channels_count - pending.cnt), updated_at_ms = now_ms FROM pending WHERE us.login = pending.login; END IF; RETURN NEW; END; $$; CREATE OR REPLACE FUNCTION shine_blocks_line_integrity_bi() RETURNS TRIGGER LANGUAGE plpgsql AS $$ DECLARE prev_block RECORD; tail_block_number INTEGER; BEGIN IF NEW.line_code IS NULL AND NEW.prev_line_number IS NULL AND NEW.prev_line_hash IS NULL AND NEW.this_line_number IS NULL THEN RETURN NEW; END IF; IF NEW.msg_type NOT IN (0, 1, 3, 4) THEN RAISE EXCEPTION 'LINE_ERR_UNSUPPORTED_TYPE_WITH_LINE'; END IF; IF NEW.line_code IS NULL OR NEW.prev_line_number IS NULL OR NEW.prev_line_hash IS NULL OR NEW.this_line_number IS NULL THEN RAISE EXCEPTION 'LINE_ERR_PARTIAL_FIELDS'; END IF; SELECT * INTO prev_block FROM blocks WHERE bch_name = NEW.bch_name AND block_number = NEW.prev_line_number LIMIT 1; IF NOT FOUND THEN RAISE EXCEPTION 'LINE_ERR_NO_PREV'; END IF; IF prev_block.block_hash IS DISTINCT FROM NEW.prev_line_hash THEN RAISE EXCEPTION 'LINE_ERR_PREV_HASH_MISMATCH'; END IF; IF NEW.prev_line_number <> NEW.line_code AND prev_block.line_code IS DISTINCT FROM NEW.line_code THEN RAISE EXCEPTION 'LINE_ERR_LINE_CODE_MISMATCH'; END IF; SELECT block_number INTO tail_block_number FROM blocks WHERE bch_name = NEW.bch_name AND msg_type = NEW.msg_type AND line_code = NEW.line_code ORDER BY block_number DESC LIMIT 1; IF tail_block_number IS NULL THEN IF NEW.prev_line_number <> NEW.line_code THEN RAISE EXCEPTION 'LINE_ERR_NOT_CURRENT_TAIL'; END IF; IF NEW.this_line_number <> (CASE WHEN NEW.msg_type = 1 THEN 0 ELSE 1 END) THEN RAISE EXCEPTION 'LINE_ERR_FIRST_STEP_BAD_THIS'; END IF; RETURN NEW; END IF; IF NEW.prev_line_number <> tail_block_number THEN RAISE EXCEPTION 'LINE_ERR_NOT_CURRENT_TAIL'; END IF; IF prev_block.this_line_number IS NULL THEN RAISE EXCEPTION 'LINE_ERR_THIS_LINE_BAD_STEP'; END IF; IF NEW.this_line_number <> prev_block.this_line_number + 1 THEN RAISE EXCEPTION 'LINE_ERR_THIS_LINE_BAD_STEP'; END IF; RETURN NEW; END; $$; CREATE OR REPLACE FUNCTION shine_blocks_connection_state_ai() RETURNS TRIGGER LANGUAGE plpgsql AS $$ DECLARE resolved_login TEXT; positive_rel_type INTEGER; existed_before BOOLEAN; target_channel_type INTEGER; BEGIN IF NEW.msg_type <> 3 THEN RETURN NEW; END IF; resolved_login := shine_resolve_login(NEW.to_login, NEW.to_bch_name); IF NEW.msg_sub_type IN (10, 14, 20, 30, 40, 50, 52, 54, 60, 70, 74, 80) THEN IF resolved_login IS NULL OR NEW.to_bch_name IS NULL THEN RETURN NEW; END IF; SELECT EXISTS ( SELECT 1 FROM connections_state WHERE login = NEW.login AND rel_type = NEW.msg_sub_type AND to_login = resolved_login AND to_bch_name = NEW.to_bch_name AND to_block_number = COALESCE(NEW.to_block_number, 0) AND to_block_hash = COALESCE(NEW.to_block_hash, decode(repeat('00', 32), 'hex')) ) INTO existed_before; IF NOT existed_before THEN IF NEW.msg_sub_type = 10 THEN INSERT INTO user_stats_state ( login, owned_public_channels_count, following_users_count, following_channels_count, close_friends_count, updated_at_ms ) VALUES ( NEW.login, 0, 0, 0, 1, CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT) ) ON CONFLICT (login) DO UPDATE SET close_friends_count = user_stats_state.close_friends_count + 1, updated_at_ms = EXCLUDED.updated_at_ms; ELSIF NEW.msg_sub_type = 30 THEN IF NEW.to_block_number IS NULL THEN INSERT INTO user_stats_state ( login, owned_public_channels_count, following_users_count, following_channels_count, close_friends_count, updated_at_ms ) VALUES ( NEW.login, 0, 0, 1, 0, CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT) ) ON CONFLICT (login) DO UPDATE SET following_channels_count = user_stats_state.following_channels_count + 1, updated_at_ms = EXCLUDED.updated_at_ms; ELSIF NEW.to_block_number = 0 THEN INSERT INTO user_stats_state ( login, owned_public_channels_count, following_users_count, following_channels_count, close_friends_count, updated_at_ms ) VALUES ( NEW.login, 0, 1, 0, 0, CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT) ) ON CONFLICT (login) DO UPDATE SET following_users_count = user_stats_state.following_users_count + 1, updated_at_ms = EXCLUDED.updated_at_ms; ELSE SELECT cn.channel_type_code INTO target_channel_type FROM channel_names_state cn WHERE cn.owner_bch_name = NEW.to_bch_name AND cn.channel_root_block_number = NEW.to_block_number AND cn.channel_root_block_hash = NEW.to_block_hash LIMIT 1; IF target_channel_type = 1 THEN INSERT INTO user_stats_state ( login, owned_public_channels_count, following_users_count, following_channels_count, close_friends_count, updated_at_ms ) VALUES ( NEW.login, 0, 0, 1, 0, CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT) ) ON CONFLICT (login) DO UPDATE SET following_channels_count = user_stats_state.following_channels_count + 1, updated_at_ms = EXCLUDED.updated_at_ms; INSERT INTO channel_stats_state ( owner_bch_name, channel_root_block_number, channel_root_block_hash, owner_login, channel_type_code, subscribers_count, updated_at_ms ) VALUES ( NEW.to_bch_name, NEW.to_block_number, NEW.to_block_hash, resolved_login, target_channel_type, 1, CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT) ) ON CONFLICT (owner_bch_name, channel_root_block_number, channel_root_block_hash) DO UPDATE SET owner_login = EXCLUDED.owner_login, channel_type_code = EXCLUDED.channel_type_code, subscribers_count = channel_stats_state.subscribers_count + 1, updated_at_ms = EXCLUDED.updated_at_ms; ELSIF target_channel_type IS NULL THEN INSERT INTO user_stats_state ( login, owned_public_channels_count, following_users_count, following_channels_count, close_friends_count, updated_at_ms ) VALUES ( NEW.login, 0, 0, 1, 0, CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT) ) ON CONFLICT (login) DO UPDATE SET following_channels_count = user_stats_state.following_channels_count + 1, updated_at_ms = EXCLUDED.updated_at_ms; END IF; END IF; END IF; END IF; DELETE FROM connections_state WHERE login = NEW.login AND rel_type = NEW.msg_sub_type AND to_login = resolved_login AND to_bch_name = NEW.to_bch_name AND to_block_number = COALESCE(NEW.to_block_number, 0) AND to_block_hash = COALESCE(NEW.to_block_hash, decode(repeat('00', 32), 'hex')); INSERT INTO connections_state ( login, rel_type, to_login, to_bch_name, to_block_number, to_block_hash ) VALUES ( NEW.login, NEW.msg_sub_type, resolved_login, NEW.to_bch_name, COALESCE(NEW.to_block_number, 0), COALESCE(NEW.to_block_hash, decode(repeat('00', 32), 'hex')) ); RETURN NEW; END IF; positive_rel_type := CASE NEW.msg_sub_type WHEN 11 THEN 10 WHEN 15 THEN 14 WHEN 21 THEN 20 WHEN 31 THEN 30 WHEN 41 THEN 40 WHEN 51 THEN 50 WHEN 53 THEN 52 WHEN 55 THEN 54 WHEN 61 THEN 60 WHEN 71 THEN 70 WHEN 75 THEN 74 WHEN 81 THEN 80 ELSE NULL END; IF positive_rel_type IS NULL OR resolved_login IS NULL THEN RETURN NEW; END IF; SELECT EXISTS ( SELECT 1 FROM connections_state WHERE login = NEW.login AND rel_type = positive_rel_type AND to_login = resolved_login AND to_bch_name = NEW.to_bch_name AND to_block_number = COALESCE(NEW.to_block_number, 0) AND to_block_hash = COALESCE(NEW.to_block_hash, decode(repeat('00', 32), 'hex')) ) INTO existed_before; IF NOT existed_before THEN RETURN NEW; END IF; IF positive_rel_type = 10 THEN INSERT INTO user_stats_state ( login, owned_public_channels_count, following_users_count, following_channels_count, close_friends_count, updated_at_ms ) VALUES ( NEW.login, 0, 0, 0, 0, CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT) ) ON CONFLICT (login) DO UPDATE SET close_friends_count = GREATEST(0, user_stats_state.close_friends_count - 1), updated_at_ms = EXCLUDED.updated_at_ms; ELSIF positive_rel_type = 30 THEN IF NEW.to_block_number IS NULL THEN INSERT INTO user_stats_state ( login, owned_public_channels_count, following_users_count, following_channels_count, close_friends_count, updated_at_ms ) VALUES ( NEW.login, 0, 0, 0, 0, CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT) ) ON CONFLICT (login) DO UPDATE SET following_channels_count = GREATEST(0, user_stats_state.following_channels_count - 1), updated_at_ms = EXCLUDED.updated_at_ms; ELSIF NEW.to_block_number = 0 THEN INSERT INTO user_stats_state ( login, owned_public_channels_count, following_users_count, following_channels_count, close_friends_count, updated_at_ms ) VALUES ( NEW.login, 0, 0, 0, 0, CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT) ) ON CONFLICT (login) DO UPDATE SET following_users_count = GREATEST(0, user_stats_state.following_users_count - 1), updated_at_ms = EXCLUDED.updated_at_ms; ELSE SELECT cn.channel_type_code INTO target_channel_type FROM channel_names_state cn WHERE cn.owner_bch_name = NEW.to_bch_name AND cn.channel_root_block_number = NEW.to_block_number AND cn.channel_root_block_hash = NEW.to_block_hash LIMIT 1; IF target_channel_type = 1 THEN INSERT INTO user_stats_state ( login, owned_public_channels_count, following_users_count, following_channels_count, close_friends_count, updated_at_ms ) VALUES ( NEW.login, 0, 0, 0, 0, CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT) ) ON CONFLICT (login) DO UPDATE SET following_channels_count = GREATEST(0, user_stats_state.following_channels_count - 1), updated_at_ms = EXCLUDED.updated_at_ms; INSERT INTO channel_stats_state ( owner_bch_name, channel_root_block_number, channel_root_block_hash, owner_login, channel_type_code, subscribers_count, updated_at_ms ) VALUES ( NEW.to_bch_name, NEW.to_block_number, NEW.to_block_hash, resolved_login, target_channel_type, 0, CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT) ) ON CONFLICT (owner_bch_name, channel_root_block_number, channel_root_block_hash) DO UPDATE SET owner_login = EXCLUDED.owner_login, channel_type_code = EXCLUDED.channel_type_code, subscribers_count = GREATEST(0, channel_stats_state.subscribers_count - 1), updated_at_ms = EXCLUDED.updated_at_ms; ELSIF target_channel_type IS NULL THEN INSERT INTO user_stats_state ( login, owned_public_channels_count, following_users_count, following_channels_count, close_friends_count, updated_at_ms ) VALUES ( NEW.login, 0, 0, 0, 0, CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT) ) ON CONFLICT (login) DO UPDATE SET following_channels_count = GREATEST(0, user_stats_state.following_channels_count - 1), updated_at_ms = EXCLUDED.updated_at_ms; END IF; END IF; END IF; DELETE FROM connections_state WHERE login = NEW.login AND rel_type = positive_rel_type AND to_login = resolved_login AND to_bch_name = NEW.to_bch_name AND to_block_number = COALESCE(NEW.to_block_number, 0) AND to_block_hash = COALESCE(NEW.to_block_hash, decode(repeat('00', 32), 'hex')); RETURN NEW; END; $$; CREATE OR REPLACE FUNCTION shine_blocks_message_stats_like_ai() RETURNS TRIGGER LANGUAGE plpgsql AS $$ DECLARE previous_sub_type INTEGER; BEGIN IF NEW.msg_type <> 2 OR NEW.msg_sub_type NOT IN (1, 2) THEN RETURN NEW; END IF; IF NEW.to_login IS NULL OR NEW.to_bch_name IS NULL OR NEW.to_block_number IS NULL OR NEW.to_block_hash IS NULL THEN RETURN NEW; END IF; INSERT INTO message_stats ( to_login, to_bch_name, to_block_number, to_block_hash, likes_count, replies_count, edits_count ) VALUES ( NEW.to_login, NEW.to_bch_name, NEW.to_block_number, NEW.to_block_hash, 0, 0, 0 ) ON CONFLICT (to_login, to_bch_name, to_block_number, to_block_hash) DO NOTHING; SELECT last_sub_type INTO previous_sub_type FROM reactions_state WHERE from_login = NEW.login AND from_bch_name = NEW.bch_name AND reaction_type = 1 AND to_login = NEW.to_login AND to_bch_name = NEW.to_bch_name AND to_block_number = NEW.to_block_number AND to_block_hash = NEW.to_block_hash LIMIT 1; IF NEW.msg_sub_type = 1 AND previous_sub_type IS DISTINCT FROM 1 THEN UPDATE message_stats SET likes_count = likes_count + 1 WHERE to_login = NEW.to_login AND to_bch_name = NEW.to_bch_name AND to_block_number = NEW.to_block_number AND to_block_hash = NEW.to_block_hash; ELSIF NEW.msg_sub_type = 2 AND previous_sub_type = 1 THEN UPDATE message_stats SET likes_count = GREATEST(0, likes_count - 1) WHERE to_login = NEW.to_login AND to_bch_name = NEW.to_bch_name AND to_block_number = NEW.to_block_number AND to_block_hash = NEW.to_block_hash; END IF; INSERT INTO reactions_state ( from_login, from_bch_name, reaction_type, to_login, to_bch_name, to_block_number, to_block_hash, last_sub_type ) VALUES ( NEW.login, NEW.bch_name, 1, NEW.to_login, NEW.to_bch_name, NEW.to_block_number, NEW.to_block_hash, NEW.msg_sub_type ) ON CONFLICT ( from_login, from_bch_name, reaction_type, to_login, to_bch_name, to_block_number, to_block_hash ) DO UPDATE SET last_sub_type = EXCLUDED.last_sub_type; RETURN NEW; END; $$; CREATE OR REPLACE FUNCTION shine_blocks_message_stats_reply_ai() RETURNS TRIGGER LANGUAGE plpgsql AS $$ BEGIN IF NEW.msg_type <> 1 OR NEW.msg_sub_type <> 20 THEN RETURN NEW; END IF; IF NEW.to_login IS NULL OR NEW.to_bch_name IS NULL OR NEW.to_block_number IS NULL OR NEW.to_block_hash IS NULL THEN RETURN NEW; END IF; INSERT INTO message_stats ( to_login, to_bch_name, to_block_number, to_block_hash, likes_count, replies_count, edits_count ) VALUES ( NEW.to_login, NEW.to_bch_name, NEW.to_block_number, NEW.to_block_hash, 0, 0, 0 ) ON CONFLICT (to_login, to_bch_name, to_block_number, to_block_hash) DO NOTHING; UPDATE message_stats SET replies_count = replies_count + 1 WHERE to_login = NEW.to_login AND to_bch_name = NEW.to_bch_name AND to_block_number = NEW.to_block_number AND to_block_hash = NEW.to_block_hash; RETURN NEW; END; $$; CREATE OR REPLACE FUNCTION shine_blocks_edit_apply_ai() RETURNS TRIGGER LANGUAGE plpgsql AS $$ BEGIN IF NEW.msg_type <> 1 OR NEW.msg_sub_type NOT IN (11, 21) THEN RETURN NEW; END IF; UPDATE blocks SET edited_by_block_number = NEW.block_number WHERE login = NEW.login AND bch_name = NEW.bch_name AND block_number = NEW.to_block_number AND NEW.to_block_number IS NOT NULL; IF NEW.to_login IS NULL OR NEW.to_bch_name IS NULL OR NEW.to_block_number IS NULL OR NEW.to_block_hash IS NULL THEN RETURN NEW; END IF; INSERT INTO message_stats ( to_login, to_bch_name, to_block_number, to_block_hash, likes_count, replies_count, edits_count ) VALUES ( NEW.to_login, NEW.to_bch_name, NEW.to_block_number, NEW.to_block_hash, 0, 0, 0 ) ON CONFLICT (to_login, to_bch_name, to_block_number, to_block_hash) DO NOTHING; UPDATE message_stats SET edits_count = edits_count + 1 WHERE to_login = NEW.to_login AND to_bch_name = NEW.to_bch_name AND to_block_number = NEW.to_block_number AND to_block_hash = NEW.to_block_hash; RETURN NEW; END; $$; DROP TRIGGER IF EXISTS trg_blocks_line_integrity_bi ON blocks; CREATE TRIGGER trg_blocks_line_integrity_bi BEFORE INSERT ON blocks FOR EACH ROW EXECUTE FUNCTION shine_blocks_line_integrity_bi(); DROP TRIGGER IF EXISTS trg_blocks_connection_state_ai ON blocks; CREATE TRIGGER trg_blocks_connection_state_ai AFTER INSERT ON blocks FOR EACH ROW EXECUTE FUNCTION shine_blocks_connection_state_ai(); DROP TRIGGER IF EXISTS trg_blocks_message_stats_like_ai ON blocks; CREATE TRIGGER trg_blocks_message_stats_like_ai AFTER INSERT ON blocks FOR EACH ROW EXECUTE FUNCTION shine_blocks_message_stats_like_ai(); DROP TRIGGER IF EXISTS trg_blocks_message_stats_reply_ai ON blocks; CREATE TRIGGER trg_blocks_message_stats_reply_ai AFTER INSERT ON blocks FOR EACH ROW EXECUTE FUNCTION shine_blocks_message_stats_reply_ai(); DROP TRIGGER IF EXISTS trg_blocks_edit_apply_ai ON blocks; CREATE TRIGGER trg_blocks_edit_apply_ai AFTER INSERT ON blocks FOR EACH ROW EXECUTE FUNCTION shine_blocks_edit_apply_ai(); DROP TRIGGER IF EXISTS trg_user_stats_state_ai ON solana_user_pda_current; CREATE TRIGGER trg_user_stats_state_ai AFTER INSERT ON solana_user_pda_current FOR EACH ROW EXECUTE FUNCTION shine_user_stats_state_ai(); DROP TRIGGER IF EXISTS trg_channel_names_state_stats_ai ON channel_names_state; CREATE TRIGGER trg_channel_names_state_stats_ai AFTER INSERT ON channel_names_state FOR EACH ROW EXECUTE FUNCTION shine_channel_names_state_stats_ai(); -- v18 integrated fresh-schema definitions -- v18: fast profile projection, effective social/voting statistics and qualified likes. -- Source of truth remains users_params / connections_state / reactions_state / channel_names_state. CREATE TABLE IF NOT EXISTS user_profile_state ( login TEXT PRIMARY KEY, first_name TEXT NOT NULL DEFAULT '', last_name TEXT NOT NULL DEFAULT '', ava_ar TEXT NOT NULL DEFAULT '', account_role TEXT, shine_status TEXT, updated_at_ms BIGINT NOT NULL DEFAULT 0 ); CREATE INDEX IF NOT EXISTS idx_user_profile_state_name ON user_profile_state (LOWER(last_name), LOWER(first_name), LOWER(login)); ALTER TABLE user_stats_state ADD COLUMN IF NOT EXISTS friends_count INTEGER NOT NULL DEFAULT 0 CHECK (friends_count >= 0), ADD COLUMN IF NOT EXISTS primary_confirmations_received_count INTEGER NOT NULL DEFAULT 0 CHECK (primary_confirmations_received_count >= 0), ADD COLUMN IF NOT EXISTS primary_confirmations_given_count INTEGER NOT NULL DEFAULT 0 CHECK (primary_confirmations_given_count >= 0), ADD COLUMN IF NOT EXISTS shine_confirmations_received_count INTEGER NOT NULL DEFAULT 0 CHECK (shine_confirmations_received_count >= 0), ADD COLUMN IF NOT EXISTS shine_confirmations_given_count INTEGER NOT NULL DEFAULT 0 CHECK (shine_confirmations_given_count >= 0); ALTER TABLE message_stats ADD COLUMN IF NOT EXISTS primary_likes_count INTEGER NOT NULL DEFAULT 0 CHECK (primary_likes_count >= 0), ADD COLUMN IF NOT EXISTS shining_likes_count INTEGER NOT NULL DEFAULT 0 CHECK (shining_likes_count >= 0); CREATE OR REPLACE FUNCTION shine_refresh_user_profile(p_login TEXT) RETURNS VOID LANGUAGE plpgsql AS $$ DECLARE v_first_name TEXT := ''; v_last_name TEXT := ''; v_ava_ar TEXT := ''; v_account_role TEXT := NULL; v_shine TEXT := NULL; v_updated BIGINT := 0; BEGIN IF p_login IS NULL OR btrim(p_login) = '' THEN RETURN; END IF; SELECT COALESCE(MAX(value) FILTER (WHERE param = 'first_name'), ''), COALESCE(MAX(value) FILTER (WHERE param = 'last_name'), ''), COALESCE(MAX(value) FILTER (WHERE param = 'ava'), ''), MAX(value) FILTER (WHERE param = 'account_role'), MAX(value) FILTER (WHERE param = 'shine'), COALESCE(MAX(time_ms), 0) INTO v_first_name, v_last_name, v_ava_ar, v_account_role, v_shine, v_updated FROM users_params WHERE LOWER(login) = LOWER(p_login); v_account_role := LOWER(BTRIM(COALESCE(v_account_role, ''))); IF v_account_role NOT IN ('primary', 'non_voting') THEN v_account_role := NULL; END IF; v_shine := LOWER(BTRIM(COALESCE(v_shine, ''))); IF v_shine = 'yes' THEN v_shine := 'shining'; END IF; -- legacy compatibility IF v_shine NOT IN ('shining', 'unknown', 'not_interested') THEN v_shine := NULL; END IF; INSERT INTO user_profile_state(login, first_name, last_name, ava_ar, account_role, shine_status, updated_at_ms) VALUES (p_login, v_first_name, v_last_name, v_ava_ar, v_account_role, v_shine, v_updated) ON CONFLICT (login) DO UPDATE SET first_name = EXCLUDED.first_name, last_name = EXCLUDED.last_name, ava_ar = EXCLUDED.ava_ar, account_role = EXCLUDED.account_role, shine_status = EXCLUDED.shine_status, updated_at_ms = EXCLUDED.updated_at_ms; END; $$; CREATE OR REPLACE FUNCTION shine_is_primary(p_login TEXT) RETURNS BOOLEAN LANGUAGE sql STABLE AS $$ SELECT COALESCE((SELECT account_role = 'primary' FROM user_profile_state WHERE LOWER(login)=LOWER(p_login) LIMIT 1), FALSE) $$; CREATE OR REPLACE FUNCTION shine_is_shining(p_login TEXT) RETURNS BOOLEAN LANGUAGE sql STABLE AS $$ SELECT COALESCE((SELECT shine_status = 'shining' FROM user_profile_state WHERE LOWER(login)=LOWER(p_login) LIMIT 1), FALSE) $$; CREATE OR REPLACE FUNCTION shine_target_accepts_primary_confirmation(p_login TEXT) RETURNS BOOLEAN LANGUAGE sql STABLE AS $$ SELECT COALESCE((SELECT account_role IS DISTINCT FROM 'non_voting' FROM user_profile_state WHERE LOWER(login)=LOWER(p_login) LIMIT 1), TRUE) $$; CREATE OR REPLACE FUNCTION shine_target_accepts_shine_confirmation(p_login TEXT) RETURNS BOOLEAN LANGUAGE sql STABLE AS $$ SELECT COALESCE((SELECT shine_status IS DISTINCT FROM 'not_interested' FROM user_profile_state WHERE LOWER(login)=LOWER(p_login) LIMIT 1), TRUE) $$; CREATE OR REPLACE FUNCTION shine_refresh_user_stats(p_login TEXT) RETURNS VOID LANGUAGE plpgsql AS $$ DECLARE v_now BIGINT := CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT); BEGIN IF p_login IS NULL OR btrim(p_login) = '' THEN RETURN; END IF; IF NOT EXISTS ( SELECT 1 FROM solana_user_pda_current WHERE login = p_login LIMIT 1 ) THEN RETURN; END IF; INSERT INTO user_stats_state(login, owned_public_channels_count, following_users_count, following_channels_count, close_friends_count, friends_count, primary_confirmations_received_count, primary_confirmations_given_count, shine_confirmations_received_count, shine_confirmations_given_count, updated_at_ms) SELECT p_login, (SELECT COUNT(*)::INT FROM channel_names_state cn WHERE LOWER(cn.owner_login)=LOWER(p_login) AND cn.channel_type_code=1 AND NOT cn.is_deleted), 0, (SELECT COUNT(*)::INT FROM connections_state cs JOIN channel_names_state cn ON cn.owner_bch_name=cs.to_bch_name AND cn.channel_root_block_number=cs.to_block_number AND cn.channel_root_block_hash=cs.to_block_hash WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=30 AND cn.channel_type_code=1 AND NOT cn.is_deleted), (SELECT COUNT(DISTINCT LOWER(cs.to_login))::INT FROM connections_state cs WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=10), (SELECT COUNT(DISTINCT LOWER(cs.to_login))::INT FROM connections_state cs WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=14 AND NOT EXISTS (SELECT 1 FROM connections_state cf WHERE LOWER(cf.login)=LOWER(p_login) AND LOWER(cf.to_login)=LOWER(cs.to_login) AND cf.rel_type=10)), (SELECT COUNT(DISTINCT LOWER(cs.login))::INT FROM connections_state cs WHERE LOWER(cs.to_login)=LOWER(p_login) AND cs.rel_type=80 AND shine_is_primary(cs.login) AND shine_target_accepts_primary_confirmation(p_login)), (SELECT COUNT(DISTINCT LOWER(cs.to_login))::INT FROM connections_state cs WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=80 AND shine_is_primary(p_login) AND shine_target_accepts_primary_confirmation(cs.to_login)), (SELECT COUNT(DISTINCT LOWER(cs.login))::INT FROM connections_state cs WHERE LOWER(cs.to_login)=LOWER(p_login) AND cs.rel_type=70 AND shine_is_primary(cs.login) AND shine_is_shining(cs.login) AND shine_target_accepts_shine_confirmation(p_login)), (SELECT COUNT(DISTINCT LOWER(cs.to_login))::INT FROM connections_state cs WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=70 AND shine_is_primary(p_login) AND shine_is_shining(p_login) AND shine_target_accepts_shine_confirmation(cs.to_login)), v_now ON CONFLICT (login) DO UPDATE SET owned_public_channels_count=EXCLUDED.owned_public_channels_count, following_users_count=0, following_channels_count=EXCLUDED.following_channels_count, close_friends_count=EXCLUDED.close_friends_count, friends_count=EXCLUDED.friends_count, primary_confirmations_received_count=EXCLUDED.primary_confirmations_received_count, primary_confirmations_given_count=EXCLUDED.primary_confirmations_given_count, shine_confirmations_received_count=EXCLUDED.shine_confirmations_received_count, shine_confirmations_given_count=EXCLUDED.shine_confirmations_given_count, updated_at_ms=EXCLUDED.updated_at_ms; END; $$; CREATE OR REPLACE FUNCTION shine_refresh_related_user_stats(p_login TEXT) RETURNS VOID LANGUAGE plpgsql AS $$ DECLARE r RECORD; BEGIN PERFORM shine_refresh_user_stats(p_login); FOR r IN SELECT DISTINCT x.login FROM ( SELECT cs.login FROM connections_state cs WHERE LOWER(cs.to_login)=LOWER(p_login) AND cs.rel_type IN (70,80) UNION SELECT cs.to_login AS login FROM connections_state cs WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type IN (70,80) ) x LOOP PERFORM shine_refresh_user_stats(r.login); END LOOP; END; $$; CREATE OR REPLACE FUNCTION shine_refresh_message_qualified_likes_for_actor(p_login TEXT) RETURNS VOID LANGUAGE plpgsql AS $$ DECLARE r RECORD; BEGIN FOR r IN SELECT DISTINCT rs.to_login, rs.to_bch_name, rs.to_block_number, rs.to_block_hash FROM reactions_state rs WHERE LOWER(rs.from_login)=LOWER(p_login) AND rs.reaction_type=1 AND rs.last_sub_type=1 LOOP UPDATE message_stats ms SET primary_likes_count=(SELECT COUNT(*)::INT FROM reactions_state x WHERE x.reaction_type=1 AND x.last_sub_type=1 AND x.to_login=r.to_login AND x.to_bch_name=r.to_bch_name AND x.to_block_number=r.to_block_number AND x.to_block_hash=r.to_block_hash AND shine_is_primary(x.from_login)), shining_likes_count=(SELECT COUNT(*)::INT FROM reactions_state x WHERE x.reaction_type=1 AND x.last_sub_type=1 AND x.to_login=r.to_login AND x.to_bch_name=r.to_bch_name AND x.to_block_number=r.to_block_number AND x.to_block_hash=r.to_block_hash AND shine_is_primary(x.from_login) AND shine_is_shining(x.from_login)) WHERE ms.to_login=r.to_login AND ms.to_bch_name=r.to_bch_name AND ms.to_block_number=r.to_block_number AND ms.to_block_hash=r.to_block_hash; END LOOP; END; $$; CREATE OR REPLACE FUNCTION shine_refresh_channel_follow_stats(p_bch_name TEXT, p_block_number INTEGER, p_block_hash BYTEA) RETURNS VOID LANGUAGE plpgsql AS $$ DECLARE v_owner_login TEXT; v_channel_type INTEGER; v_count INTEGER := 0; v_now BIGINT := CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT); BEGIN IF p_bch_name IS NULL OR p_block_number IS NULL OR p_block_hash IS NULL OR p_block_number <= 0 THEN RETURN; END IF; SELECT cn.owner_login, cn.channel_type_code INTO v_owner_login, v_channel_type FROM channel_names_state cn WHERE cn.owner_bch_name=p_bch_name AND cn.channel_root_block_number=p_block_number AND cn.channel_root_block_hash=p_block_hash LIMIT 1; IF v_channel_type IS NULL THEN RETURN; END IF; SELECT COUNT(DISTINCT LOWER(cs.login))::INT INTO v_count FROM connections_state cs WHERE cs.rel_type=30 AND cs.to_bch_name=p_bch_name AND cs.to_block_number=p_block_number AND cs.to_block_hash=p_block_hash; INSERT INTO channel_stats_state(owner_bch_name,channel_root_block_number,channel_root_block_hash,owner_login,channel_type_code,subscribers_count,updated_at_ms) VALUES(p_bch_name,p_block_number,p_block_hash,COALESCE(v_owner_login,''),v_channel_type,v_count,v_now) ON CONFLICT(owner_bch_name,channel_root_block_number,channel_root_block_hash) DO UPDATE SET owner_login=EXCLUDED.owner_login, channel_type_code=EXCLUDED.channel_type_code, subscribers_count=EXCLUDED.subscribers_count, updated_at_ms=EXCLUDED.updated_at_ms; END; $$; -- Replace incremental channel-name counter with idempotent recomputation. CREATE OR REPLACE FUNCTION shine_channel_names_state_stats_ai() RETURNS TRIGGER LANGUAGE plpgsql AS $$ BEGIN IF NEW.channel_type_code = 1 THEN PERFORM shine_refresh_user_stats(NEW.owner_login); END IF; RETURN NEW; END; $$; -- Rebuild connection state without incremental user counters; then recompute affected users. CREATE OR REPLACE FUNCTION shine_blocks_connection_state_ai() RETURNS TRIGGER LANGUAGE plpgsql AS $$ DECLARE resolved_login TEXT; positive_rel_type INTEGER; BEGIN IF NEW.msg_type <> 3 THEN RETURN NEW; END IF; resolved_login := shine_resolve_login(NEW.to_login, NEW.to_bch_name); IF resolved_login IS NULL OR NEW.to_bch_name IS NULL THEN RETURN NEW; END IF; IF NEW.msg_sub_type IN (10,14,20,30,40,50,52,54,60,70,74,80) THEN DELETE FROM connections_state WHERE login=NEW.login AND rel_type=NEW.msg_sub_type AND to_login=resolved_login AND to_bch_name=NEW.to_bch_name AND to_block_number=COALESCE(NEW.to_block_number,0) AND to_block_hash=COALESCE(NEW.to_block_hash,decode(repeat('00',32),'hex')); INSERT INTO connections_state(login,rel_type,to_login,to_bch_name,to_block_number,to_block_hash) VALUES(NEW.login,NEW.msg_sub_type,resolved_login,NEW.to_bch_name,COALESCE(NEW.to_block_number,0),COALESCE(NEW.to_block_hash,decode(repeat('00',32),'hex'))); ELSE positive_rel_type := CASE NEW.msg_sub_type WHEN 11 THEN 10 WHEN 15 THEN 14 WHEN 21 THEN 20 WHEN 31 THEN 30 WHEN 41 THEN 40 WHEN 51 THEN 50 WHEN 53 THEN 52 WHEN 55 THEN 54 WHEN 61 THEN 60 WHEN 71 THEN 70 WHEN 75 THEN 74 WHEN 81 THEN 80 ELSE NULL END; IF positive_rel_type IS NULL THEN RETURN NEW; END IF; DELETE FROM connections_state WHERE login=NEW.login AND rel_type=positive_rel_type AND to_login=resolved_login AND to_bch_name=NEW.to_bch_name AND to_block_number=COALESCE(NEW.to_block_number,0) AND to_block_hash=COALESCE(NEW.to_block_hash,decode(repeat('00',32),'hex')); END IF; PERFORM shine_refresh_user_stats(NEW.login); PERFORM shine_refresh_user_stats(resolved_login); IF NEW.msg_sub_type IN (30,31) AND NEW.to_block_number IS NOT NULL AND NEW.to_block_number > 0 AND NEW.to_block_hash IS NOT NULL THEN PERFORM shine_refresh_channel_follow_stats(NEW.to_bch_name, NEW.to_block_number, NEW.to_block_hash); END IF; RETURN NEW; END; $$; CREATE OR REPLACE FUNCTION shine_blocks_message_stats_like_ai() RETURNS TRIGGER LANGUAGE plpgsql AS $$ DECLARE previous_sub_type INTEGER; BEGIN IF NEW.msg_type<>2 OR NEW.msg_sub_type NOT IN (1,2) THEN RETURN NEW; END IF; IF NEW.to_login IS NULL OR NEW.to_bch_name IS NULL OR NEW.to_block_number IS NULL OR NEW.to_block_hash IS NULL THEN RETURN NEW; END IF; INSERT INTO message_stats(to_login,to_bch_name,to_block_number,to_block_hash,likes_count,primary_likes_count,shining_likes_count,replies_count,edits_count) VALUES(NEW.to_login,NEW.to_bch_name,NEW.to_block_number,NEW.to_block_hash,0,0,0,0,0) ON CONFLICT(to_login,to_bch_name,to_block_number,to_block_hash) DO NOTHING; SELECT last_sub_type INTO previous_sub_type FROM reactions_state WHERE from_login=NEW.login AND from_bch_name=NEW.bch_name AND reaction_type=1 AND to_login=NEW.to_login AND to_bch_name=NEW.to_bch_name AND to_block_number=NEW.to_block_number AND to_block_hash=NEW.to_block_hash LIMIT 1; IF NEW.msg_sub_type=1 AND previous_sub_type IS DISTINCT FROM 1 THEN UPDATE message_stats SET likes_count=likes_count+1, primary_likes_count=primary_likes_count + CASE WHEN shine_is_primary(NEW.login) THEN 1 ELSE 0 END, shining_likes_count=shining_likes_count + CASE WHEN shine_is_primary(NEW.login) AND shine_is_shining(NEW.login) THEN 1 ELSE 0 END WHERE to_login=NEW.to_login AND to_bch_name=NEW.to_bch_name AND to_block_number=NEW.to_block_number AND to_block_hash=NEW.to_block_hash; ELSIF NEW.msg_sub_type=2 AND previous_sub_type=1 THEN UPDATE message_stats SET likes_count=GREATEST(0,likes_count-1), primary_likes_count=GREATEST(0,primary_likes_count - CASE WHEN shine_is_primary(NEW.login) THEN 1 ELSE 0 END), shining_likes_count=GREATEST(0,shining_likes_count - CASE WHEN shine_is_primary(NEW.login) AND shine_is_shining(NEW.login) THEN 1 ELSE 0 END) WHERE to_login=NEW.to_login AND to_bch_name=NEW.to_bch_name AND to_block_number=NEW.to_block_number AND to_block_hash=NEW.to_block_hash; END IF; INSERT INTO reactions_state(from_login,from_bch_name,reaction_type,to_login,to_bch_name,to_block_number,to_block_hash,last_sub_type) VALUES(NEW.login,NEW.bch_name,1,NEW.to_login,NEW.to_bch_name,NEW.to_block_number,NEW.to_block_hash,NEW.msg_sub_type) ON CONFLICT(from_login,from_bch_name,reaction_type,to_login,to_bch_name,to_block_number,to_block_hash) DO UPDATE SET last_sub_type=EXCLUDED.last_sub_type; RETURN NEW; END; $$; -- Initial projection/rebuild. DO $$ DECLARE r RECORD; BEGIN FOR r IN SELECT DISTINCT login FROM users_params LOOP PERFORM shine_refresh_user_profile(r.login); END LOOP; END $$; DO $$ DECLARE r RECORD; BEGIN FOR r IN SELECT login FROM solana_user_pda_current LOOP PERFORM shine_refresh_user_stats(r.login); END LOOP; END $$; DO $$ DECLARE r RECORD; BEGIN FOR r IN SELECT owner_bch_name, channel_root_block_number, channel_root_block_hash FROM channel_names_state WHERE channel_type_code=1 LOOP PERFORM shine_refresh_channel_follow_stats(r.owner_bch_name, r.channel_root_block_number, r.channel_root_block_hash); END LOOP; END $$; UPDATE message_stats ms SET primary_likes_count=(SELECT COUNT(*)::INT FROM reactions_state rs WHERE rs.reaction_type=1 AND rs.last_sub_type=1 AND rs.to_login=ms.to_login AND rs.to_bch_name=ms.to_bch_name AND rs.to_block_number=ms.to_block_number AND rs.to_block_hash=ms.to_block_hash AND shine_is_primary(rs.from_login)), shining_likes_count=(SELECT COUNT(*)::INT FROM reactions_state rs WHERE rs.reaction_type=1 AND rs.last_sub_type=1 AND rs.to_login=ms.to_login AND rs.to_bch_name=ms.to_bch_name AND rs.to_block_number=ms.to_block_number AND rs.to_block_hash=ms.to_block_hash AND shine_is_primary(rs.from_login) AND shine_is_shining(rs.from_login)); CREATE TABLE IF NOT EXISTS user_notification_seen_state ( owner_login VARCHAR(60) NOT NULL, category TEXT NOT NULL CHECK (category IN ('replies', 'connections', 'events')), seen_at_ms BIGINT NOT NULL DEFAULT 0, signed_blob BYTEA NOT NULL, signed_at_ms BIGINT NOT NULL, updated_at_ms BIGINT NOT NULL, PRIMARY KEY (owner_login, category) ); ALTER TABLE solana_user_pda_current ADD COLUMN IF NOT EXISTS archive_head_tx_id TEXT NOT NULL DEFAULT ''; ALTER TABLE solana_user_pda_current ADD COLUMN IF NOT EXISTS archive_head_hash TEXT NOT NULL DEFAULT ''; ALTER TABLE solana_user_pda_history ADD COLUMN IF NOT EXISTS archive_head_tx_id TEXT NOT NULL DEFAULT ''; ALTER TABLE solana_user_pda_history ADD COLUMN IF NOT EXISTS archive_head_hash TEXT NOT NULL DEFAULT ''; ALTER TABLE solana_user_pda_current ADD COLUMN IF NOT EXISTS archive_imported BOOLEAN NOT NULL DEFAULT FALSE; ALTER TABLE solana_user_pda_current ADD COLUMN IF NOT EXISTS archive_last_imported_tx_id TEXT NOT NULL DEFAULT ''; CREATE INDEX IF NOT EXISTS idx_solana_user_pda_current_archive_pending ON solana_user_pda_current(is_server, archive_imported) WHERE archive_head_tx_id <> ''; -- Server-local key rotation state machine (schema v26). -- Эти поля не являются частью Solana PDA и не перезаписываются Solana sync upsert-ом. ALTER TABLE solana_user_pda_current ADD COLUMN IF NOT EXISTS rotation_status TEXT NOT NULL DEFAULT 'NONE'; ALTER TABLE solana_user_pda_current ADD COLUMN IF NOT EXISTS rotation_session_id BIGINT; ALTER TABLE solana_user_pda_current DROP CONSTRAINT IF EXISTS chk_solana_user_pda_current_rotation_status; ALTER TABLE solana_user_pda_current ADD CONSTRAINT chk_solana_user_pda_current_rotation_status CHECK ( rotation_status IN ( 'NONE','COPYING_CHAIN','CHAIN_READY','ROTATING_PDA','PDA_ROTATED', 'REBUILDING_SERVER','WALLET_MIGRATION','MESSAGE_MIGRATION','FINALIZING' ) ); CREATE INDEX IF NOT EXISTS idx_solana_user_pda_current_rotation_active ON solana_user_pda_current(rotation_status) WHERE rotation_status <> 'NONE'; CREATE TABLE IF NOT EXISTS key_rotation_sessions ( id BIGSERIAL PRIMARY KEY, login TEXT NOT NULL REFERENCES solana_user_pda_current(login) ON DELETE CASCADE, status TEXT NOT NULL CHECK ( status IN ( 'COPYING_CHAIN','CHAIN_READY','ROTATING_PDA','PDA_ROTATED', 'REBUILDING_SERVER','WALLET_MIGRATION','MESSAGE_MIGRATION','FINALIZING', 'COMPLETE','ABORTED' ) ), source_blockchain_name TEXT NOT NULL, candidate_blockchain_name TEXT NOT NULL, old_root_key TEXT NOT NULL, old_blockchain_key TEXT NOT NULL, old_client_key TEXT NOT NULL, new_root_key TEXT NOT NULL, new_blockchain_key TEXT NOT NULL, new_client_key TEXT NOT NULL, fork_from_block INTEGER NOT NULL CHECK (fork_from_block >= 0), fork_from_hash BYTEA NOT NULL CHECK (octet_length(fork_from_hash) = 32), source_tip_block INTEGER NOT NULL CHECK (source_tip_block >= 0), source_tip_hash BYTEA NOT NULL CHECK (octet_length(source_tip_hash) = 32), reason_code SMALLINT NOT NULL CHECK (reason_code BETWEEN 1 AND 4), comment TEXT NOT NULL DEFAULT '' CHECK (octet_length(convert_to(comment, 'UTF8')) <= 1024), progress_current INTEGER NOT NULL DEFAULT 0 CHECK (progress_current >= 0), progress_total INTEGER NOT NULL DEFAULT 0 CHECK (progress_total >= 0), pda_rotation_signature TEXT, wallet_migration_status TEXT NOT NULL DEFAULT 'PENDING' CHECK ( wallet_migration_status IN ('PENDING','COMPLETE','SKIPPED','NOT_IMPLEMENTED') ), message_migration_status TEXT NOT NULL DEFAULT 'PENDING' CHECK ( message_migration_status IN ('PENDING','COMPLETE','SKIPPED','NOT_IMPLEMENTED') ), last_error TEXT, last_error_at_ms BIGINT, retry_count INTEGER NOT NULL DEFAULT 0 CHECK (retry_count >= 0), created_at_ms BIGINT NOT NULL, updated_at_ms BIGINT NOT NULL, completed_at_ms BIGINT, aborted_at_ms BIGINT, CHECK (progress_current <= progress_total), CHECK (fork_from_block <= source_tip_block) ); CREATE UNIQUE INDEX IF NOT EXISTS uq_key_rotation_sessions_active_login ON key_rotation_sessions(login) WHERE status NOT IN ('COMPLETE','ABORTED'); CREATE INDEX IF NOT EXISTS idx_key_rotation_sessions_login_created ON key_rotation_sessions(login, created_at_ms DESC); CREATE INDEX IF NOT EXISTS idx_key_rotation_sessions_status ON key_rotation_sessions(status); CREATE TABLE IF NOT EXISTS key_rotation_candidate_blocks ( id BIGSERIAL PRIMARY KEY, rotation_session_id BIGINT NOT NULL REFERENCES key_rotation_sessions(id) ON DELETE CASCADE, login TEXT NOT NULL, candidate_blockchain_name TEXT NOT NULL, block_number INTEGER NOT NULL CHECK (block_number >= 0), block_hash BYTEA NOT NULL CHECK (octet_length(block_hash) = 32), data_item_id BYTEA NOT NULL CHECK (octet_length(data_item_id) = 32), block_bytes BYTEA NOT NULL, arweave_publish_pending BOOLEAN NOT NULL DEFAULT TRUE, arweave_published_at_ms BIGINT, created_at_ms BIGINT NOT NULL, UNIQUE (rotation_session_id, block_number), UNIQUE (rotation_session_id, data_item_id) ); CREATE INDEX IF NOT EXISTS idx_key_rotation_candidate_blocks_pending ON key_rotation_candidate_blocks(id) WHERE arweave_publish_pending = TRUE; CREATE INDEX IF NOT EXISTS idx_key_rotation_candidate_blocks_session ON key_rotation_candidate_blocks(rotation_session_id, block_number); ALTER TABLE solana_user_pda_current DROP CONSTRAINT IF EXISTS fk_solana_user_pda_current_rotation_session; ALTER TABLE solana_user_pda_current ADD CONSTRAINT fk_solana_user_pda_current_rotation_session FOREIGN KEY (rotation_session_id) REFERENCES key_rotation_sessions(id) ON DELETE SET NULL; -- Stage 2 final schema: numeric physical forks and logical cross-fork targets. -- Stage 2: physical fork identity = (login,fork_number); logical target = (login,block_number,hash). ALTER TABLE solana_user_pda_current ADD CONSTRAINT chk_solana_current_blockchain_name_fork CHECK (blockchain_name ~ '-[0-9]{3}$' AND substring(blockchain_name from '([0-9]{3})$')::INTEGER BETWEEN 1 AND 999); ALTER TABLE blockchain_state ADD COLUMN IF NOT EXISTS fork_number INTEGER; UPDATE blockchain_state SET fork_number = NULLIF(regexp_replace(blockchain_name, '^.*-([0-9]{3})$', '\1'), blockchain_name)::INTEGER WHERE fork_number IS NULL AND blockchain_name ~ '-[0-9]{3}$'; ALTER TABLE blockchain_state ALTER COLUMN fork_number SET NOT NULL; ALTER TABLE blockchain_state ADD CONSTRAINT chk_blockchain_state_fork CHECK (fork_number BETWEEN 1 AND 999); CREATE UNIQUE INDEX IF NOT EXISTS uq_blockchain_state_login_fork ON blockchain_state(login,fork_number); ALTER TABLE blocks ADD COLUMN IF NOT EXISTS fork_number INTEGER; UPDATE blocks b SET fork_number=s.fork_number FROM blockchain_state s WHERE b.bch_name=s.blockchain_name AND b.fork_number IS NULL; ALTER TABLE blocks ALTER COLUMN fork_number SET NOT NULL; ALTER TABLE blocks ADD CONSTRAINT chk_blocks_fork CHECK (fork_number BETWEEN 1 AND 999); -- Triggers stay attached when tables are renamed; replace their functions below before new writes. ALTER TABLE blocks DROP CONSTRAINT IF EXISTS blocks_bch_name_fkey; ALTER TABLE blocks RENAME TO blocks_store; ALTER TABLE blockchain_state RENAME TO blockchain_state_store; ALTER TABLE blocks_store DROP COLUMN bch_name; ALTER TABLE blocks_store DROP COLUMN to_bch_name; ALTER TABLE blockchain_state_store DROP CONSTRAINT IF EXISTS blockchain_state_pkey; ALTER TABLE blockchain_state_store DROP COLUMN blockchain_name; ALTER TABLE blockchain_state_store ADD PRIMARY KEY(login,fork_number); ALTER TABLE blocks_store ADD CONSTRAINT fk_blocks_physical_fork FOREIGN KEY(login,fork_number) REFERENCES blockchain_state_store(login,fork_number); DROP INDEX IF EXISTS idx_blocks_by_chain_number; DROP INDEX IF EXISTS idx_blocks_to_target; DROP INDEX IF EXISTS idx_blocks_by_line; CREATE UNIQUE INDEX uq_blocks_physical_number ON blocks_store(login,fork_number,block_number); CREATE INDEX idx_blocks_to_logical_target ON blocks_store(to_login,to_block_number,to_block_hash); CREATE INDEX idx_blocks_by_line_v29 ON blocks_store(login,fork_number,line_code,this_line_number); -- Compatibility views: names are derived, never stored. CREATE VIEW blockchain_state AS SELECT login || '-' || lpad(fork_number::text,3,'0') AS blockchain_name, s.* FROM blockchain_state_store s; CREATE VIEW blocks AS SELECT b.login, b.login || '-' || lpad(b.fork_number::text,3,'0') AS bch_name, b.fork_number,b.block_number,b.msg_type,b.msg_sub_type,b.block_bytes, b.to_login, CASE WHEN b.to_login IS NOT NULL AND b.to_fork_number BETWEEN 1 AND 999 THEN b.to_login || '-' || lpad(b.to_fork_number::text,3,'0') END AS to_bch_name, b.to_fork_number,b.to_block_number,b.to_block_hash,b.block_hash,b.block_signature,b.data_item_id, b.arweave_publish_pending,b.arweave_published_at_ms,b.arweave_root_tx_id,b.edited_by_block_number, b.line_code,b.prev_line_number,b.prev_line_hash,b.this_line_number FROM blocks_store b; -- Channel read state keeps the signed/display owner_bch_name, but identity no longer depends on a fork. ALTER TABLE channel_read_state DROP CONSTRAINT IF EXISTS channel_read_state_pkey; ALTER TABLE channel_read_state ADD PRIMARY KEY(viewer_login,owner_login,channel_name); -- Derived social state is cheap to rebuild and intentionally loses physical fork names. DROP TABLE IF EXISTS reactions_state CASCADE; DROP TABLE IF EXISTS message_stats CASCADE; DROP TABLE IF EXISTS connections_state CASCADE; CREATE TABLE connections_state( login TEXT NOT NULL, rel_type INTEGER NOT NULL, to_login TEXT NOT NULL, to_block_number INTEGER NOT NULL, to_block_hash BYTEA NOT NULL, UNIQUE(login,rel_type,to_login,to_block_number,to_block_hash) ); CREATE INDEX idx_connections_state_login_v29 ON connections_state(login); CREATE INDEX idx_connections_state_to_login_v29 ON connections_state(to_login); CREATE INDEX idx_connections_state_target_v29 ON connections_state(to_login,to_block_number,to_block_hash); CREATE TABLE message_stats( to_login TEXT NOT NULL, to_block_number INTEGER NOT NULL, to_block_hash BYTEA NOT NULL, likes_count INTEGER NOT NULL DEFAULT 0, primary_likes_count INTEGER NOT NULL DEFAULT 0, shining_likes_count INTEGER NOT NULL DEFAULT 0, replies_count INTEGER NOT NULL DEFAULT 0, UNIQUE(to_login,to_block_number,to_block_hash) ); CREATE INDEX idx_message_stats_target_v29 ON message_stats(to_login,to_block_number,to_block_hash); CREATE TABLE reactions_state( from_login TEXT NOT NULL, reaction_type INTEGER NOT NULL, to_login TEXT NOT NULL, to_block_number INTEGER NOT NULL, to_block_hash BYTEA NOT NULL, last_sub_type INTEGER NOT NULL, UNIQUE(from_login,reaction_type,to_login,to_block_number,to_block_hash) ); CREATE INDEX idx_reactions_state_target_v29 ON reactions_state(to_login,to_block_number,to_block_hash); CREATE INDEX idx_reactions_state_actor_v29 ON reactions_state(from_login,reaction_type); DROP TABLE IF EXISTS message_views_state; CREATE TABLE message_views_state( viewer_login TEXT NOT NULL, to_login TEXT NOT NULL, to_block_number INTEGER NOT NULL, to_block_hash BYTEA NOT NULL, first_seen_at_ms BIGINT NOT NULL, PRIMARY KEY(viewer_login,to_login,to_block_number,to_block_hash) ); CREATE INDEX idx_message_views_target_v29 ON message_views_state(to_login,to_block_number,to_block_hash); CREATE OR REPLACE FUNCTION shine_refresh_user_stats(p_login TEXT) RETURNS VOID LANGUAGE plpgsql AS $$ DECLARE v_now BIGINT:=CAST(EXTRACT(EPOCH FROM clock_timestamp())*1000 AS BIGINT); v_canonical_login TEXT; BEGIN IF p_login IS NULL OR btrim(p_login)='' THEN RETURN; END IF; -- В FK остаётся исходный регистр владельца, но поиск/сопоставления регистронезависимы. SELECT login INTO v_canonical_login FROM user_identity_current WHERE normalized_login=lower(btrim(p_login)) LIMIT 1; IF v_canonical_login IS NULL THEN RETURN; END IF; INSERT INTO user_stats_state(login,owned_public_channels_count,following_users_count,following_channels_count,close_friends_count,friends_count, primary_confirmations_received_count,primary_confirmations_given_count,shine_confirmations_received_count,shine_confirmations_given_count,updated_at_ms) SELECT v_canonical_login, (SELECT COUNT(*)::INT FROM channel_names_state cn WHERE LOWER(cn.owner_login)=LOWER(p_login) AND cn.channel_type_code=1 AND NOT cn.is_deleted), (SELECT COUNT(DISTINCT LOWER(cs.to_login))::INT FROM connections_state cs WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=30 AND cs.to_block_number=0), (SELECT COUNT(*)::INT FROM connections_state cs JOIN channel_names_state cn ON LOWER(cn.owner_login)=LOWER(cs.to_login) AND cn.channel_root_block_number=cs.to_block_number AND cn.channel_root_block_hash=cs.to_block_hash WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=30 AND cn.channel_type_code=1 AND NOT cn.is_deleted), (SELECT COUNT(DISTINCT LOWER(cs.to_login))::INT FROM connections_state cs WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=10), (SELECT COUNT(DISTINCT LOWER(cs.to_login))::INT FROM connections_state cs WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=14 AND NOT EXISTS(SELECT 1 FROM connections_state cf WHERE LOWER(cf.login)=LOWER(p_login) AND LOWER(cf.to_login)=LOWER(cs.to_login) AND cf.rel_type=10)), (SELECT COUNT(DISTINCT LOWER(cs.login))::INT FROM connections_state cs WHERE LOWER(cs.to_login)=LOWER(p_login) AND cs.rel_type=80 AND shine_is_primary(cs.login) AND shine_target_accepts_primary_confirmation(p_login)), (SELECT COUNT(DISTINCT LOWER(cs.to_login))::INT FROM connections_state cs WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=80 AND shine_is_primary(p_login) AND shine_target_accepts_primary_confirmation(cs.to_login)), (SELECT COUNT(DISTINCT LOWER(cs.login))::INT FROM connections_state cs WHERE LOWER(cs.to_login)=LOWER(p_login) AND cs.rel_type=70 AND shine_is_primary(cs.login) AND shine_is_shining(cs.login) AND shine_target_accepts_shine_confirmation(p_login)), (SELECT COUNT(DISTINCT LOWER(cs.to_login))::INT FROM connections_state cs WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=70 AND shine_is_primary(p_login) AND shine_is_shining(p_login) AND shine_target_accepts_shine_confirmation(cs.to_login)),v_now ON CONFLICT(login) DO UPDATE SET owned_public_channels_count=EXCLUDED.owned_public_channels_count,following_users_count=EXCLUDED.following_users_count,following_channels_count=EXCLUDED.following_channels_count,close_friends_count=EXCLUDED.close_friends_count,friends_count=EXCLUDED.friends_count,primary_confirmations_received_count=EXCLUDED.primary_confirmations_received_count,primary_confirmations_given_count=EXCLUDED.primary_confirmations_given_count,shine_confirmations_received_count=EXCLUDED.shine_confirmations_received_count,shine_confirmations_given_count=EXCLUDED.shine_confirmations_given_count,updated_at_ms=EXCLUDED.updated_at_ms; END $$; CREATE OR REPLACE FUNCTION shine_refresh_message_qualified_likes_for_actor(p_login TEXT) RETURNS VOID LANGUAGE plpgsql AS $$ DECLARE r RECORD; BEGIN FOR r IN SELECT DISTINCT to_login,to_block_number,to_block_hash FROM reactions_state WHERE LOWER(from_login)=LOWER(p_login) AND reaction_type=1 AND last_sub_type=1 LOOP UPDATE message_stats ms SET primary_likes_count=(SELECT COUNT(*)::INT FROM reactions_state x WHERE x.reaction_type=1 AND x.last_sub_type=1 AND x.to_login=r.to_login AND x.to_block_number=r.to_block_number AND x.to_block_hash=r.to_block_hash AND shine_is_primary(x.from_login)), shining_likes_count=(SELECT COUNT(*)::INT FROM reactions_state x WHERE x.reaction_type=1 AND x.last_sub_type=1 AND x.to_login=r.to_login AND x.to_block_number=r.to_block_number AND x.to_block_hash=r.to_block_hash AND shine_is_primary(x.from_login) AND shine_is_shining(x.from_login)) WHERE ms.to_login=r.to_login AND ms.to_block_number=r.to_block_number AND ms.to_block_hash=r.to_block_hash; END LOOP; END $$; CREATE OR REPLACE FUNCTION shine_refresh_channel_follow_stats(p_bch_name TEXT,p_block_number INTEGER,p_block_hash BYTEA) RETURNS VOID LANGUAGE plpgsql AS $$ DECLARE v_owner TEXT; v_type INTEGER; v_count INTEGER; v_now BIGINT:=CAST(EXTRACT(EPOCH FROM clock_timestamp())*1000 AS BIGINT); BEGIN SELECT owner_login,channel_type_code INTO v_owner,v_type FROM channel_names_state WHERE owner_bch_name=p_bch_name AND channel_root_block_number=p_block_number AND channel_root_block_hash=p_block_hash LIMIT 1; IF v_owner IS NULL THEN RETURN; END IF; SELECT COUNT(DISTINCT cs.login)::INTEGER INTO v_count FROM connections_state cs WHERE cs.rel_type=30 AND LOWER(cs.to_login)=LOWER(v_owner) AND cs.to_block_number=p_block_number AND cs.to_block_hash=p_block_hash; INSERT INTO channel_stats_state(owner_bch_name,channel_root_block_number,channel_root_block_hash,owner_login,channel_type_code,subscribers_count,updated_at_ms) VALUES(p_bch_name,p_block_number,p_block_hash,v_owner,v_type,COALESCE(v_count,0),v_now) ON CONFLICT(owner_bch_name,channel_root_block_number,channel_root_block_hash) DO UPDATE SET subscribers_count=EXCLUDED.subscribers_count,owner_login=EXCLUDED.owner_login,channel_type_code=EXCLUDED.channel_type_code,updated_at_ms=EXCLUDED.updated_at_ms; END $$; -- Channel-name projection must also use logical connection targets; the physical owner name is display/state only. CREATE OR REPLACE FUNCTION shine_channel_names_state_stats_ai() RETURNS TRIGGER LANGUAGE plpgsql AS $$ DECLARE now_ms BIGINT; public_subscribers_count INTEGER; r RECORD; BEGIN now_ms := CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT); IF NEW.owner_login IS NULL OR btrim(NEW.owner_login) = '' THEN RETURN NEW; END IF; IF NEW.channel_type_code = 1 THEN IF EXISTS ( SELECT 1 FROM solana_user_pda_current su WHERE LOWER(su.login)=LOWER(NEW.owner_login) ) THEN INSERT INTO user_stats_state ( login, owned_public_channels_count, following_users_count, following_channels_count, close_friends_count, updated_at_ms ) VALUES (NEW.owner_login, 1, 0, 0, 0, now_ms) ON CONFLICT (login) DO UPDATE SET owned_public_channels_count = user_stats_state.owned_public_channels_count + 1, updated_at_ms = EXCLUDED.updated_at_ms; END IF; SELECT COUNT(*)::INTEGER INTO public_subscribers_count FROM connections_state cs WHERE cs.rel_type = 30 AND LOWER(cs.to_login)=LOWER(NEW.owner_login) AND cs.to_block_number = NEW.channel_root_block_number AND cs.to_block_hash = NEW.channel_root_block_hash; INSERT INTO channel_stats_state ( owner_bch_name, channel_root_block_number, channel_root_block_hash, owner_login, channel_type_code, subscribers_count, updated_at_ms ) VALUES ( NEW.owner_bch_name, NEW.channel_root_block_number, NEW.channel_root_block_hash, NEW.owner_login, NEW.channel_type_code, COALESCE(public_subscribers_count, 0), now_ms ) ON CONFLICT (owner_bch_name, channel_root_block_number, channel_root_block_hash) DO UPDATE SET owner_login = EXCLUDED.owner_login, channel_type_code = EXCLUDED.channel_type_code, subscribers_count = EXCLUDED.subscribers_count, updated_at_ms = EXCLUDED.updated_at_ms; -- A channel may disappear during cleanup and reappear during replay. Recompute followers from logical state. FOR r IN SELECT DISTINCT cs.login FROM connections_state cs WHERE cs.rel_type = 30 AND LOWER(cs.to_login)=LOWER(NEW.owner_login) AND cs.to_block_number = NEW.channel_root_block_number AND cs.to_block_hash = NEW.channel_root_block_hash LOOP PERFORM shine_refresh_user_stats(r.login); END LOOP; ELSE WITH pending AS ( SELECT cs.login, COUNT(*)::INTEGER AS cnt FROM connections_state cs WHERE cs.rel_type = 30 AND LOWER(cs.to_login)=LOWER(NEW.owner_login) AND cs.to_block_number = NEW.channel_root_block_number AND cs.to_block_hash = NEW.channel_root_block_hash GROUP BY cs.login ) UPDATE user_stats_state us SET following_channels_count = GREATEST(0, us.following_channels_count - pending.cnt), updated_at_ms = now_ms FROM pending WHERE LOWER(us.login)=LOWER(pending.login); END IF; RETURN NEW; END; $$; -- Physical chain integrity uses numeric fork identity. CREATE OR REPLACE FUNCTION shine_blocks_line_integrity_bi() RETURNS TRIGGER LANGUAGE plpgsql AS $$ DECLARE prev_block RECORD; tail_block_number INTEGER; BEGIN IF NEW.line_code IS NULL AND NEW.prev_line_number IS NULL AND NEW.prev_line_hash IS NULL AND NEW.this_line_number IS NULL THEN RETURN NEW; END IF; IF NEW.msg_type NOT IN (0,1,3,4) THEN RAISE EXCEPTION 'LINE_ERR_UNSUPPORTED_TYPE_WITH_LINE'; END IF; IF NEW.line_code IS NULL OR NEW.prev_line_number IS NULL OR NEW.prev_line_hash IS NULL OR NEW.this_line_number IS NULL THEN RAISE EXCEPTION 'LINE_ERR_PARTIAL_FIELDS'; END IF; SELECT * INTO prev_block FROM blocks_store WHERE login=NEW.login AND fork_number=NEW.fork_number AND block_number=NEW.prev_line_number LIMIT 1; IF NOT FOUND THEN RAISE EXCEPTION 'LINE_ERR_NO_PREV'; END IF; IF prev_block.block_hash IS DISTINCT FROM NEW.prev_line_hash THEN RAISE EXCEPTION 'LINE_ERR_PREV_HASH_MISMATCH'; END IF; IF NEW.prev_line_number<>NEW.line_code AND prev_block.line_code IS DISTINCT FROM NEW.line_code THEN RAISE EXCEPTION 'LINE_ERR_LINE_CODE_MISMATCH'; END IF; SELECT block_number INTO tail_block_number FROM blocks_store WHERE login=NEW.login AND fork_number=NEW.fork_number AND msg_type=NEW.msg_type AND line_code=NEW.line_code ORDER BY block_number DESC LIMIT 1; IF tail_block_number IS NULL THEN IF NEW.prev_line_number<>NEW.line_code THEN RAISE EXCEPTION 'LINE_ERR_NOT_CURRENT_TAIL'; END IF; IF NEW.this_line_number<>(CASE WHEN NEW.msg_type=1 THEN 0 ELSE 1 END) THEN RAISE EXCEPTION 'LINE_ERR_FIRST_STEP_BAD_THIS'; END IF; RETURN NEW; END IF; IF NEW.prev_line_number<>tail_block_number THEN RAISE EXCEPTION 'LINE_ERR_NOT_CURRENT_TAIL'; END IF; IF prev_block.this_line_number IS NULL THEN RAISE EXCEPTION 'LINE_ERR_THIS_LINE_BAD_STEP'; END IF; IF NEW.this_line_number<>prev_block.this_line_number+1 THEN RAISE EXCEPTION 'LINE_ERR_THIS_LINE_BAD_STEP'; END IF; RETURN NEW; END $$; CREATE OR REPLACE FUNCTION shine_blocks_connection_state_ai() RETURNS TRIGGER LANGUAGE plpgsql AS $$ DECLARE positive_rel_type INTEGER; channel_bch TEXT; BEGIN IF NEW.msg_type<>3 OR NEW.to_login IS NULL OR NEW.to_block_number IS NULL OR NEW.to_block_hash IS NULL THEN RETURN NEW; END IF; IF NEW.msg_sub_type IN (10,14,20,30,40,50,52,54,60,70,74,80) THEN DELETE FROM connections_state WHERE login=lower(NEW.login) AND rel_type=NEW.msg_sub_type AND to_login=lower(NEW.to_login) AND to_block_number=NEW.to_block_number AND to_block_hash=NEW.to_block_hash; INSERT INTO connections_state(login,rel_type,to_login,to_block_number,to_block_hash) VALUES(lower(NEW.login),NEW.msg_sub_type,lower(NEW.to_login),NEW.to_block_number,NEW.to_block_hash); ELSE positive_rel_type := CASE NEW.msg_sub_type WHEN 11 THEN 10 WHEN 15 THEN 14 WHEN 21 THEN 20 WHEN 31 THEN 30 WHEN 41 THEN 40 WHEN 51 THEN 50 WHEN 53 THEN 52 WHEN 55 THEN 54 WHEN 61 THEN 60 WHEN 71 THEN 70 WHEN 75 THEN 74 WHEN 81 THEN 80 ELSE NULL END; IF positive_rel_type IS NOT NULL THEN DELETE FROM connections_state WHERE login=lower(NEW.login) AND rel_type=positive_rel_type AND to_login=lower(NEW.to_login) AND to_block_number=NEW.to_block_number AND to_block_hash=NEW.to_block_hash; END IF; END IF; PERFORM shine_refresh_user_stats(lower(NEW.login)); PERFORM shine_refresh_user_stats(lower(NEW.to_login)); IF NEW.msg_sub_type IN (30,31) AND NEW.to_block_number>0 THEN SELECT owner_bch_name INTO channel_bch FROM channel_names_state WHERE LOWER(owner_login)=LOWER(NEW.to_login) AND channel_root_block_number=NEW.to_block_number AND channel_root_block_hash=NEW.to_block_hash LIMIT 1; IF channel_bch IS NOT NULL THEN PERFORM shine_refresh_channel_follow_stats(channel_bch,NEW.to_block_number,NEW.to_block_hash); END IF; END IF; RETURN NEW; END $$; CREATE OR REPLACE FUNCTION shine_blocks_message_stats_like_ai() RETURNS TRIGGER LANGUAGE plpgsql AS $$ DECLARE previous_sub_type INTEGER; BEGIN IF NEW.msg_type<>2 OR NEW.msg_sub_type NOT IN (1,2) THEN RETURN NEW; END IF; IF NEW.to_login IS NULL OR NEW.to_block_number IS NULL OR NEW.to_block_hash IS NULL THEN RETURN NEW; END IF; INSERT INTO message_stats(to_login,to_block_number,to_block_hash) VALUES(lower(NEW.to_login),NEW.to_block_number,NEW.to_block_hash) ON CONFLICT(to_login,to_block_number,to_block_hash) DO NOTHING; SELECT last_sub_type INTO previous_sub_type FROM reactions_state WHERE from_login=lower(NEW.login) AND reaction_type=1 AND to_login=lower(NEW.to_login) AND to_block_number=NEW.to_block_number AND to_block_hash=NEW.to_block_hash LIMIT 1; IF NEW.msg_sub_type=1 AND previous_sub_type IS DISTINCT FROM 1 THEN UPDATE message_stats SET likes_count=likes_count+1, primary_likes_count=primary_likes_count+CASE WHEN shine_is_primary(NEW.login) THEN 1 ELSE 0 END, shining_likes_count=shining_likes_count+CASE WHEN shine_is_primary(NEW.login) AND shine_is_shining(NEW.login) THEN 1 ELSE 0 END WHERE to_login=lower(NEW.to_login) AND to_block_number=NEW.to_block_number AND to_block_hash=NEW.to_block_hash; ELSIF NEW.msg_sub_type=2 AND previous_sub_type=1 THEN UPDATE message_stats SET likes_count=GREATEST(0,likes_count-1), primary_likes_count=GREATEST(0,primary_likes_count-CASE WHEN shine_is_primary(NEW.login) THEN 1 ELSE 0 END), shining_likes_count=GREATEST(0,shining_likes_count-CASE WHEN shine_is_primary(NEW.login) AND shine_is_shining(NEW.login) THEN 1 ELSE 0 END) WHERE to_login=lower(NEW.to_login) AND to_block_number=NEW.to_block_number AND to_block_hash=NEW.to_block_hash; END IF; INSERT INTO reactions_state(from_login,reaction_type,to_login,to_block_number,to_block_hash,last_sub_type) VALUES(lower(NEW.login),1,lower(NEW.to_login),NEW.to_block_number,NEW.to_block_hash,NEW.msg_sub_type) ON CONFLICT(from_login,reaction_type,to_login,to_block_number,to_block_hash) DO UPDATE SET last_sub_type=EXCLUDED.last_sub_type; RETURN NEW; END $$; -- Existing REPLY counter semantics are preserved; only the removed physical target-name column is adapted. CREATE OR REPLACE FUNCTION shine_blocks_message_stats_reply_ai() RETURNS TRIGGER LANGUAGE plpgsql AS $$ BEGIN IF NEW.msg_type<>1 OR NEW.msg_sub_type<>20 THEN RETURN NEW; END IF; IF NEW.to_login IS NULL OR NEW.to_block_number IS NULL OR NEW.to_block_hash IS NULL THEN RETURN NEW; END IF; INSERT INTO message_stats(to_login,to_block_number,to_block_hash,replies_count) VALUES(lower(NEW.to_login),NEW.to_block_number,NEW.to_block_hash,1) ON CONFLICT(to_login,to_block_number,to_block_hash) DO UPDATE SET replies_count=message_stats.replies_count+1; RETURN NEW; END $$; -- EDIT applies to own physical fork; no edits_count aggregate is maintained. CREATE OR REPLACE FUNCTION shine_blocks_edit_apply_ai() RETURNS TRIGGER LANGUAGE plpgsql AS $$ BEGIN IF NEW.msg_type<>1 OR NEW.msg_sub_type NOT IN (11,21) THEN RETURN NEW; END IF; IF NEW.to_block_number IS NULL OR NEW.to_block_hash IS NULL THEN RETURN NEW; END IF; UPDATE blocks_store SET edited_by_block_number=NEW.block_number WHERE login=NEW.login AND fork_number=NEW.fork_number AND block_number=NEW.to_block_number AND block_hash=NEW.to_block_hash; RETURN NEW; END $$; -- Triggers moved with blocks_store on rename; make sure they exist there. DROP TRIGGER IF EXISTS trg_blocks_line_integrity_bi ON blocks_store; CREATE TRIGGER trg_blocks_line_integrity_bi BEFORE INSERT ON blocks_store FOR EACH ROW EXECUTE FUNCTION shine_blocks_line_integrity_bi(); DROP TRIGGER IF EXISTS trg_blocks_connection_state_ai ON blocks_store; CREATE TRIGGER trg_blocks_connection_state_ai AFTER INSERT ON blocks_store FOR EACH ROW EXECUTE FUNCTION shine_blocks_connection_state_ai(); DROP TRIGGER IF EXISTS trg_blocks_message_stats_like_ai ON blocks_store; CREATE TRIGGER trg_blocks_message_stats_like_ai AFTER INSERT ON blocks_store FOR EACH ROW EXECUTE FUNCTION shine_blocks_message_stats_like_ai(); DROP TRIGGER IF EXISTS trg_blocks_message_stats_reply_ai ON blocks_store; CREATE TRIGGER trg_blocks_message_stats_reply_ai AFTER INSERT ON blocks_store FOR EACH ROW EXECUTE FUNCTION shine_blocks_message_stats_reply_ai(); DROP TRIGGER IF EXISTS trg_blocks_edit_apply_ai ON blocks_store; CREATE TRIGGER trg_blocks_edit_apply_ai AFTER INSERT ON blocks_store FOR EACH ROW EXECUTE FUNCTION shine_blocks_edit_apply_ai(); -- Segmented fork ancestry (schema v30). CREATE TABLE IF NOT EXISTS blockchain_fork_segments ( login TEXT NOT NULL, fork_number INTEGER NOT NULL CHECK (fork_number BETWEEN 1 AND 999), parent_fork_number INTEGER, fork_point_block_number INTEGER NOT NULL DEFAULT -1, fork_point_block_hash BYTEA, first_physical_block_number INTEGER NOT NULL DEFAULT 0, created_at_ms BIGINT NOT NULL DEFAULT 0, PRIMARY KEY(login,fork_number), CHECK ((fork_number=1 AND parent_fork_number IS NULL AND fork_point_block_number=-1 AND first_physical_block_number=0) OR (fork_number>1 AND parent_fork_number IS NOT NULL AND parent_fork_number BETWEEN 1 AND 999 AND fork_point_block_number>=0 AND octet_length(fork_point_block_hash)=32 AND first_physical_block_number=fork_point_block_number+1)) ); CREATE INDEX IF NOT EXISTS idx_blockchain_fork_segments_parent ON blockchain_fork_segments(login,parent_fork_number); -- Existing chains predate segmented forks. Their current physical fork is self-contained; -- register fork 1 where possible. Later segmented forks are inserted by key rotation/recovery. INSERT INTO blockchain_fork_segments(login,fork_number,parent_fork_number,fork_point_block_number,fork_point_block_hash,first_physical_block_number,created_at_ms) SELECT login,fork_number,NULL,-1,NULL,0,updated_at_ms FROM blockchain_state_store WHERE fork_number=1 ON CONFLICT(login,fork_number) DO NOTHING; -- Segmented-fork canonical helpers/triggers (schema v30 final overrides). CREATE OR REPLACE FUNCTION shine_canonical_fork(p_login TEXT,p_active_fork INTEGER,p_block_number INTEGER) RETURNS INTEGER LANGUAGE plpgsql STABLE AS $$ DECLARE f INTEGER:=p_active_fork; seg RECORD; guard INTEGER:=0; BEGIN LOOP guard:=guard+1; IF guard>1000 THEN RAISE EXCEPTION 'fork ancestry cycle'; END IF; SELECT * INTO seg FROM blockchain_fork_segments WHERE LOWER(login)=LOWER(p_login) AND fork_number=f; IF NOT FOUND THEN RETURN f; END IF; IF seg.parent_fork_number IS NULL OR p_block_number>=seg.first_physical_block_number THEN RETURN f; END IF; f:=seg.parent_fork_number; END LOOP; END $$; CREATE OR REPLACE FUNCTION shine_blocks_line_integrity_bi() RETURNS TRIGGER LANGUAGE plpgsql AS $$ DECLARE prev_block RECORD; tail_block RECORD; prev_fork INTEGER; BEGIN IF NEW.line_code IS NULL AND NEW.prev_line_number IS NULL AND NEW.prev_line_hash IS NULL AND NEW.this_line_number IS NULL THEN RETURN NEW; END IF; IF NEW.msg_type NOT IN (0,1,3,4) THEN RAISE EXCEPTION 'LINE_ERR_UNSUPPORTED_TYPE_WITH_LINE'; END IF; IF NEW.line_code IS NULL OR NEW.prev_line_number IS NULL OR NEW.prev_line_hash IS NULL OR NEW.this_line_number IS NULL THEN RAISE EXCEPTION 'LINE_ERR_PARTIAL_FIELDS'; END IF; prev_fork:=shine_canonical_fork(NEW.login,NEW.fork_number,NEW.prev_line_number); SELECT * INTO prev_block FROM blocks_store WHERE LOWER(login)=LOWER(NEW.login) AND fork_number=prev_fork AND block_number=NEW.prev_line_number LIMIT 1; IF NOT FOUND THEN RAISE EXCEPTION 'LINE_ERR_NO_PREV'; END IF; IF prev_block.block_hash IS DISTINCT FROM NEW.prev_line_hash THEN RAISE EXCEPTION 'LINE_ERR_PREV_HASH_MISMATCH'; END IF; IF NEW.prev_line_number<>NEW.line_code AND prev_block.line_code IS DISTINCT FROM NEW.line_code THEN RAISE EXCEPTION 'LINE_ERR_LINE_CODE_MISMATCH'; END IF; SELECT b.* INTO tail_block FROM blocks_store b WHERE LOWER(b.login)=LOWER(NEW.login) AND b.block_numberNEW.line_code THEN RAISE EXCEPTION 'LINE_ERR_NOT_CURRENT_TAIL'; END IF; IF NEW.this_line_number<>(CASE WHEN NEW.msg_type=1 THEN 0 ELSE 1 END) THEN RAISE EXCEPTION 'LINE_ERR_FIRST_STEP_BAD_THIS'; END IF; RETURN NEW; END IF; IF NEW.prev_line_number<>tail_block.block_number THEN RAISE EXCEPTION 'LINE_ERR_NOT_CURRENT_TAIL'; END IF; IF prev_block.this_line_number IS NULL THEN RAISE EXCEPTION 'LINE_ERR_THIS_LINE_BAD_STEP'; END IF; IF NEW.this_line_number<>prev_block.this_line_number+1 THEN RAISE EXCEPTION 'LINE_ERR_THIS_LINE_BAD_STEP'; END IF; RETURN NEW; END $$; CREATE OR REPLACE FUNCTION shine_blocks_edit_apply_ai() RETURNS TRIGGER LANGUAGE plpgsql AS $$ DECLARE target_fork INTEGER; BEGIN IF NEW.msg_type<>1 OR NEW.msg_sub_type NOT IN (11,21) THEN RETURN NEW; END IF; IF NEW.to_block_number IS NULL OR NEW.to_block_hash IS NULL THEN RETURN NEW; END IF; target_fork:=shine_canonical_fork(NEW.login,NEW.fork_number,NEW.to_block_number); UPDATE blocks_store SET edited_by_block_number=NEW.block_number WHERE LOWER(login)=LOWER(NEW.login) AND fork_number=target_fork AND block_number=NEW.to_block_number AND block_hash=NEW.to_block_hash; RETURN NEW; END $$; CREATE TABLE IF NOT EXISTS key_rotation_rebuild_staging ( rotation_session_id BIGINT NOT NULL REFERENCES key_rotation_sessions(id) ON DELETE CASCADE, logical_block_number INTEGER NOT NULL, physical_fork_number INTEGER NOT NULL, blockchain_key TEXT NOT NULL, block_bytes BYTEA NOT NULL, block_hash BYTEA NOT NULL, PRIMARY KEY(rotation_session_id,logical_block_number) ); CREATE INDEX IF NOT EXISTS idx_key_rotation_rebuild_staging_session ON key_rotation_rebuild_staging(rotation_session_id,logical_block_number); -- Generic crash-safe staging used when this server learns a remote fork through Arweave. CREATE TABLE IF NOT EXISTS canonical_rebuild_staging ( login TEXT NOT NULL, logical_block_number INTEGER NOT NULL, physical_fork_number INTEGER NOT NULL, block_bytes BYTEA NOT NULL, block_hash BYTEA NOT NULL, PRIMARY KEY(login,logical_block_number) ); CREATE INDEX IF NOT EXISTS idx_canonical_rebuild_staging_login ON canonical_rebuild_staging(login,logical_block_number); -- v32: триграммные индексы публичного поиска. CREATE EXTENSION IF NOT EXISTS pg_trgm; CREATE INDEX IF NOT EXISTS idx_channel_names_search_display ON channel_names_state USING gin ((replace(lower(display_name), 'ё', 'е')) gin_trgm_ops) WHERE channel_type_code = 1 AND NOT is_deleted; CREATE INDEX IF NOT EXISTS idx_channel_names_search_slug ON channel_names_state USING gin ((replace(lower(slug), 'ё', 'е')) gin_trgm_ops) WHERE channel_type_code = 1 AND NOT is_deleted; CREATE INDEX IF NOT EXISTS idx_channel_names_search_owner ON channel_names_state USING gin ((replace(lower(owner_login), 'ё', 'е')) gin_trgm_ops) WHERE channel_type_code = 1 AND NOT is_deleted; CREATE INDEX IF NOT EXISTS idx_user_profile_search_name ON user_profile_state USING gin ((replace(lower(coalesce(first_name, '') || ' ' || coalesce(last_name, '')), 'ё', 'е')) gin_trgm_ops); CREATE INDEX IF NOT EXISTS idx_user_profile_search_name_reverse ON user_profile_state USING gin ((replace(lower(coalesce(last_name, '') || ' ' || coalesce(first_name, '')), 'ё', 'е')) gin_trgm_ops); INSERT INTO db_schema_version(id,schema_version,updated_at_ms) VALUES(1,32,CAST(EXTRACT(EPOCH FROM clock_timestamp())*1000 AS BIGINT)) ON CONFLICT(id) DO UPDATE SET schema_version=EXCLUDED.schema_version,updated_at_ms=EXCLUDED.updated_at_ms; COMMIT;