SHA256
Очень сильно переделать формат блоков
Внимание: версия ещё не проверена.
This commit is contained in:
@@ -17,60 +17,12 @@ import java.util.List;
|
||||
public final class DatabaseInitializer {
|
||||
|
||||
public static final String DB_SCHEMA_VERSION_TABLE = "db_schema_version";
|
||||
public static final String DB_FORMAT_MARKER_TABLE = "shine_database_metadata";
|
||||
public static final String DB_FORMAT_MARKER = "SHiNE_DB_V2";
|
||||
public static final int DB_FORMAT_VERSION = 2;
|
||||
public static final int SCHEMA_VERSION_1 = 1;
|
||||
public static final int SCHEMA_VERSION_2 = 2;
|
||||
public static final int SCHEMA_VERSION_3 = 3;
|
||||
public static final int SCHEMA_VERSION_4 = 4;
|
||||
public static final int SCHEMA_VERSION_5 = 5;
|
||||
public static final int SCHEMA_VERSION_6 = 6;
|
||||
public static final int SCHEMA_VERSION_7 = 7;
|
||||
public static final int SCHEMA_VERSION_8 = 8;
|
||||
public static final int SCHEMA_VERSION_9 = 9;
|
||||
public static final int SCHEMA_VERSION_10 = 10;
|
||||
public static final int SCHEMA_VERSION_11 = 11;
|
||||
public static final int SCHEMA_VERSION_12 = 12;
|
||||
public static final int SCHEMA_VERSION_13 = 13;
|
||||
public static final int SCHEMA_VERSION_14 = 14;
|
||||
public static final int SCHEMA_VERSION_15 = 15;
|
||||
public static final int SCHEMA_VERSION_16 = 16;
|
||||
public static final int SCHEMA_VERSION_17 = 17;
|
||||
public static final int SCHEMA_VERSION_18 = 18;
|
||||
public static final int SCHEMA_VERSION_19 = 19;
|
||||
public static final int SCHEMA_VERSION_20 = 20;
|
||||
public static final int SCHEMA_VERSION_21 = 21;
|
||||
public static final int SCHEMA_VERSION_22 = 22;
|
||||
public static final int SCHEMA_VERSION_23 = 23;
|
||||
public static final int SCHEMA_VERSION_24 = 24;
|
||||
public static final int SCHEMA_VERSION_25 = 25;
|
||||
public static final int SCHEMA_VERSION_26 = 26;
|
||||
public static final int SCHEMA_VERSION_27 = 27;
|
||||
public static final int SCHEMA_VERSION_29 = 29;
|
||||
public static final String POSTGRES_SCHEMA_RESOURCE = "postgres/schema_v1.sql";
|
||||
public static final String POSTGRES_MIGRATION_V2_RESOURCE = "postgres/migration_v2.sql";
|
||||
public static final String POSTGRES_MIGRATION_V3_RESOURCE = "postgres/migration_v3.sql";
|
||||
public static final String POSTGRES_MIGRATION_V4_RESOURCE = "postgres/migration_v4.sql";
|
||||
public static final String POSTGRES_MIGRATION_V5_RESOURCE = "postgres/migration_v5.sql";
|
||||
public static final String POSTGRES_MIGRATION_V6_RESOURCE = "postgres/migration_v6.sql";
|
||||
public static final String POSTGRES_MIGRATION_V7_RESOURCE = "postgres/migration_v7.sql";
|
||||
public static final String POSTGRES_MIGRATION_V8_RESOURCE = "postgres/migration_v8.sql";
|
||||
public static final String POSTGRES_MIGRATION_V9_RESOURCE = "postgres/migration_v9.sql";
|
||||
public static final String POSTGRES_MIGRATION_V10_RESOURCE = "postgres/migration_v10.sql";
|
||||
public static final String POSTGRES_MIGRATION_V11_RESOURCE = "postgres/migration_v11.sql";
|
||||
public static final String POSTGRES_MIGRATION_V12_RESOURCE = "postgres/migration_v12.sql";
|
||||
public static final String POSTGRES_MIGRATION_V13_RESOURCE = "postgres/migration_v13.sql";
|
||||
public static final String POSTGRES_MIGRATION_V14_RESOURCE = "postgres/migration_v14.sql";
|
||||
public static final String POSTGRES_MIGRATION_V15_RESOURCE = "postgres/migration_v15.sql";
|
||||
public static final String POSTGRES_MIGRATION_V16_RESOURCE = "postgres/migration_v16.sql";
|
||||
public static final String POSTGRES_MIGRATION_V17_RESOURCE = "postgres/migration_v17.sql";
|
||||
public static final String POSTGRES_MIGRATION_V18_RESOURCE = "postgres/migration_v18.sql";
|
||||
public static final String POSTGRES_MIGRATION_V19_RESOURCE = "postgres/migration_v19.sql";
|
||||
public static final String POSTGRES_MIGRATION_V20_RESOURCE = "postgres/migration_v20.sql";
|
||||
public static final String POSTGRES_MIGRATION_V21_RESOURCE = "postgres/migration_v21.sql";
|
||||
public static final String POSTGRES_MIGRATION_V22_RESOURCE = "postgres/migration_v22.sql";
|
||||
public static final String POSTGRES_MIGRATION_V23_RESOURCE = "postgres/migration_v23.sql";
|
||||
public static final String POSTGRES_MIGRATION_V24_RESOURCE = "postgres/migration_v24.sql";
|
||||
public static final String POSTGRES_MIGRATION_V25_RESOURCE = "postgres/migration_v25.sql";
|
||||
public static final String POSTGRES_MIGRATION_V26_RESOURCE = "postgres/migration_v26.sql";
|
||||
public static final String POSTGRES_MIGRATION_V27_RESOURCE = "postgres/migration_v27.sql";
|
||||
|
||||
private DatabaseInitializer() {}
|
||||
|
||||
@@ -139,114 +91,31 @@ public final class DatabaseInitializer {
|
||||
}
|
||||
|
||||
try (Connection conn = openConnection(jdbcUrl, user, password)) {
|
||||
if (!postgresSchemaVersionTableExists(conn)) {
|
||||
boolean markerTableExists = postgresTableExists(conn, DB_FORMAT_MARKER_TABLE);
|
||||
boolean schemaVersionTableExists = postgresTableExists(conn, DB_SCHEMA_VERSION_TABLE);
|
||||
|
||||
if (!markerTableExists) {
|
||||
if (schemaVersionTableExists || currentSchemaHasBaseTables(conn)) {
|
||||
throw new SQLException(
|
||||
"Legacy/non-v2 SHiNE PostgreSQL database detected. "
|
||||
+ "Stage 2 requires an empty database initialized as " + DB_FORMAT_MARKER
|
||||
+ "; automatic migration from the old database is intentionally disabled.");
|
||||
}
|
||||
runSqlScript(conn, POSTGRES_SCHEMA_RESOURCE);
|
||||
return;
|
||||
markerTableExists = postgresTableExists(conn, DB_FORMAT_MARKER_TABLE);
|
||||
schemaVersionTableExists = postgresTableExists(conn, DB_SCHEMA_VERSION_TABLE);
|
||||
}
|
||||
|
||||
if (!markerTableExists || !schemaVersionTableExists) {
|
||||
throw new SQLException(
|
||||
"Invalid SHiNE PostgreSQL database: required v2 metadata/schema tables are missing.");
|
||||
}
|
||||
|
||||
validateDatabaseFormatV2(conn);
|
||||
int currentVersion = readCurrentSchemaVersion(conn);
|
||||
if (currentVersion < SCHEMA_VERSION_2) {
|
||||
runSqlScript(conn, POSTGRES_MIGRATION_V2_RESOURCE);
|
||||
currentVersion = SCHEMA_VERSION_2;
|
||||
}
|
||||
if (currentVersion < SCHEMA_VERSION_3) {
|
||||
runSqlScript(conn, POSTGRES_MIGRATION_V3_RESOURCE);
|
||||
currentVersion = SCHEMA_VERSION_3;
|
||||
}
|
||||
if (currentVersion < SCHEMA_VERSION_4) {
|
||||
runSqlScript(conn, POSTGRES_MIGRATION_V4_RESOURCE);
|
||||
currentVersion = SCHEMA_VERSION_4;
|
||||
}
|
||||
if (currentVersion < SCHEMA_VERSION_5) {
|
||||
runSqlScript(conn, POSTGRES_MIGRATION_V5_RESOURCE);
|
||||
currentVersion = SCHEMA_VERSION_5;
|
||||
}
|
||||
if (currentVersion < SCHEMA_VERSION_6) {
|
||||
runSqlScript(conn, POSTGRES_MIGRATION_V6_RESOURCE);
|
||||
currentVersion = SCHEMA_VERSION_6;
|
||||
}
|
||||
if (currentVersion < SCHEMA_VERSION_7) {
|
||||
runSqlScript(conn, POSTGRES_MIGRATION_V7_RESOURCE);
|
||||
currentVersion = SCHEMA_VERSION_7;
|
||||
}
|
||||
if (currentVersion < SCHEMA_VERSION_8) {
|
||||
runSqlScript(conn, POSTGRES_MIGRATION_V8_RESOURCE);
|
||||
currentVersion = SCHEMA_VERSION_8;
|
||||
}
|
||||
if (currentVersion < SCHEMA_VERSION_9) {
|
||||
runSqlScript(conn, POSTGRES_MIGRATION_V9_RESOURCE);
|
||||
currentVersion = SCHEMA_VERSION_9;
|
||||
}
|
||||
if (currentVersion < SCHEMA_VERSION_10) {
|
||||
runSqlScript(conn, POSTGRES_MIGRATION_V10_RESOURCE);
|
||||
currentVersion = SCHEMA_VERSION_10;
|
||||
}
|
||||
if (currentVersion < SCHEMA_VERSION_11) {
|
||||
runSqlScript(conn, POSTGRES_MIGRATION_V11_RESOURCE);
|
||||
currentVersion = SCHEMA_VERSION_11;
|
||||
}
|
||||
if (currentVersion < SCHEMA_VERSION_12) {
|
||||
runSqlScript(conn, POSTGRES_MIGRATION_V12_RESOURCE);
|
||||
currentVersion = SCHEMA_VERSION_12;
|
||||
}
|
||||
if (currentVersion < SCHEMA_VERSION_13) {
|
||||
runSqlScript(conn, POSTGRES_MIGRATION_V13_RESOURCE);
|
||||
currentVersion = SCHEMA_VERSION_13;
|
||||
}
|
||||
if (currentVersion < SCHEMA_VERSION_14) {
|
||||
runSqlScript(conn, POSTGRES_MIGRATION_V14_RESOURCE);
|
||||
currentVersion = SCHEMA_VERSION_14;
|
||||
}
|
||||
if (currentVersion < SCHEMA_VERSION_15) {
|
||||
runSqlScript(conn, POSTGRES_MIGRATION_V15_RESOURCE);
|
||||
currentVersion = SCHEMA_VERSION_15;
|
||||
}
|
||||
if (currentVersion < SCHEMA_VERSION_16) {
|
||||
runSqlScript(conn, POSTGRES_MIGRATION_V16_RESOURCE);
|
||||
currentVersion = SCHEMA_VERSION_16;
|
||||
}
|
||||
if (currentVersion < SCHEMA_VERSION_17) {
|
||||
runSqlScript(conn, POSTGRES_MIGRATION_V17_RESOURCE);
|
||||
currentVersion = SCHEMA_VERSION_17;
|
||||
}
|
||||
if (currentVersion < SCHEMA_VERSION_18) {
|
||||
runSqlScript(conn, POSTGRES_MIGRATION_V18_RESOURCE);
|
||||
currentVersion = SCHEMA_VERSION_18;
|
||||
}
|
||||
if (currentVersion < SCHEMA_VERSION_19) {
|
||||
runSqlScript(conn, POSTGRES_MIGRATION_V19_RESOURCE);
|
||||
currentVersion = SCHEMA_VERSION_19;
|
||||
}
|
||||
if (currentVersion < SCHEMA_VERSION_20) {
|
||||
runSqlScript(conn, POSTGRES_MIGRATION_V20_RESOURCE);
|
||||
currentVersion = SCHEMA_VERSION_20;
|
||||
}
|
||||
if (currentVersion < SCHEMA_VERSION_21) {
|
||||
runSqlScript(conn, POSTGRES_MIGRATION_V21_RESOURCE);
|
||||
currentVersion = SCHEMA_VERSION_21;
|
||||
}
|
||||
if (currentVersion < SCHEMA_VERSION_22) {
|
||||
runSqlScript(conn, POSTGRES_MIGRATION_V22_RESOURCE);
|
||||
currentVersion = SCHEMA_VERSION_22;
|
||||
}
|
||||
if (currentVersion < SCHEMA_VERSION_23) {
|
||||
runSqlScript(conn, POSTGRES_MIGRATION_V23_RESOURCE);
|
||||
currentVersion = SCHEMA_VERSION_23;
|
||||
}
|
||||
if (currentVersion < SCHEMA_VERSION_24) {
|
||||
runSqlScript(conn, POSTGRES_MIGRATION_V24_RESOURCE);
|
||||
currentVersion = SCHEMA_VERSION_24;
|
||||
}
|
||||
if (currentVersion < SCHEMA_VERSION_25) {
|
||||
runSqlScript(conn, POSTGRES_MIGRATION_V25_RESOURCE);
|
||||
currentVersion = SCHEMA_VERSION_25;
|
||||
}
|
||||
if (currentVersion < SCHEMA_VERSION_26) {
|
||||
runSqlScript(conn, POSTGRES_MIGRATION_V26_RESOURCE);
|
||||
currentVersion = SCHEMA_VERSION_26;
|
||||
}
|
||||
if (currentVersion < SCHEMA_VERSION_27) {
|
||||
runSqlScript(conn, POSTGRES_MIGRATION_V27_RESOURCE);
|
||||
currentVersion = SCHEMA_VERSION_27;
|
||||
if (currentVersion != SCHEMA_VERSION_29) {
|
||||
throw new SQLException(
|
||||
"Unsupported SHiNE DB v2 schema version: expected 29, found " + currentVersion);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -258,23 +127,60 @@ public final class DatabaseInitializer {
|
||||
return DriverManager.getConnection(jdbcUrl, user, password == null ? "" : password);
|
||||
}
|
||||
|
||||
private static boolean postgresSchemaVersionTableExists(Connection conn) throws SQLException {
|
||||
private static boolean postgresTableExists(Connection conn, String tableName) throws SQLException {
|
||||
String sql = """
|
||||
SELECT EXISTS (
|
||||
SELECT 1
|
||||
FROM information_schema.tables
|
||||
WHERE table_schema = current_schema()
|
||||
AND table_name = ?
|
||||
AND table_type = 'BASE TABLE'
|
||||
)
|
||||
""";
|
||||
try (var ps = conn.prepareStatement(sql)) {
|
||||
ps.setString(1, DB_SCHEMA_VERSION_TABLE);
|
||||
ps.setString(1, tableName);
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
return rs.next() && rs.getBoolean(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean currentSchemaHasBaseTables(Connection conn) throws SQLException {
|
||||
String sql = """
|
||||
SELECT EXISTS (
|
||||
SELECT 1
|
||||
FROM information_schema.tables
|
||||
WHERE table_schema = current_schema()
|
||||
AND table_type = 'BASE TABLE'
|
||||
)
|
||||
""";
|
||||
try (Statement st = conn.createStatement(); ResultSet rs = st.executeQuery(sql)) {
|
||||
return rs.next() && rs.getBoolean(1);
|
||||
}
|
||||
}
|
||||
|
||||
private static void validateDatabaseFormatV2(Connection conn) throws SQLException {
|
||||
String sql = """
|
||||
SELECT database_format, database_generation
|
||||
FROM shine_database_metadata
|
||||
WHERE id = 1
|
||||
""";
|
||||
try (Statement st = conn.createStatement(); ResultSet rs = st.executeQuery(sql)) {
|
||||
if (!rs.next()) {
|
||||
throw new SQLException(
|
||||
"Invalid SHiNE PostgreSQL database: SHiNE_DB_V2 metadata row is missing.");
|
||||
}
|
||||
String format = rs.getString("database_format");
|
||||
int generation = rs.getInt("database_generation");
|
||||
if (!DB_FORMAT_MARKER.equals(format) || generation != DB_FORMAT_VERSION) {
|
||||
throw new SQLException(
|
||||
"Unsupported SHiNE PostgreSQL database format: expected " + DB_FORMAT_MARKER
|
||||
+ " generation " + DB_FORMAT_VERSION
|
||||
+ ", found format=" + format + ", generation=" + generation);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static int readCurrentSchemaVersion(Connection conn) throws SQLException {
|
||||
String sql = """
|
||||
SELECT schema_version
|
||||
|
||||
@@ -4,7 +4,7 @@ package shine.db;
|
||||
* MsgSubType — единое место для ВСЕХ subType сообщений (msg_sub_type).
|
||||
*
|
||||
* ВАЖНО:
|
||||
* - Значения должны совпадать с body-классами (TextBody/ReactionBody/ConnectionBody/UserParamBody/HeaderBody).
|
||||
* - Значения должны совпадать с body-классами (TextLineBody/TextReplyBody/TextRatingBody/ReactionBody/ConnectionBody/UserParamBody/HeaderBody).
|
||||
* - После релиза менять числа нельзя (иначе ломается совместимость данных).
|
||||
*/
|
||||
public final class MsgSubType {
|
||||
|
||||
@@ -28,7 +28,7 @@ public final class PostgresDbController {
|
||||
try {
|
||||
DatabaseInitializer.ensurePostgresSchemaInitialized(jdbcUrl, dbUser, dbPassword);
|
||||
} catch (SQLException e) {
|
||||
throw new RuntimeException("PostgreSQL schema auto-init failed", e);
|
||||
throw new RuntimeException("PostgreSQL database compatibility/init failed: " + e.getMessage(), e);
|
||||
}
|
||||
|
||||
this.delegate = new DriverManagerDbProvider(jdbcUrl, dbUser, dbPassword, connection -> {
|
||||
|
||||
+96
-575
@@ -1,603 +1,124 @@
|
||||
package shine.db.dao;
|
||||
|
||||
import shine.db.DatabaseInitializer;
|
||||
import shine.db.DbController;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.*;
|
||||
|
||||
/**
|
||||
* BlockchainResyncCleanupDAO — подготовительный "жёсткий reset" одной blockchain-цепочки
|
||||
* перед её полной повторной загрузкой от сервера-партнёра.
|
||||
*
|
||||
* Что делает этот DAO:
|
||||
* 1) в ОДНОЙ SQL-транзакции сначала аккуратно уменьшает чужие агрегаты,
|
||||
* которые были увеличены блоками удаляемой цепочки:
|
||||
* - likes_count
|
||||
* - replies_count
|
||||
* 2) затем удаляет все локальные записи самой цепочки и её производные состояния.
|
||||
*
|
||||
* Почему это вынесено в отдельный DAO-метод, а не в триггеры DELETE:
|
||||
* - нам нужен один понятный "блок операции", который можно вызвать из resync-flow;
|
||||
* - эта схема проще и прозрачнее, чем много обратных триггеров по разным таблицам;
|
||||
* - если любой шаг не удался, делаем rollback и БД остаётся в исходном состоянии;
|
||||
* - пользовательские blockchain-файлы больше не существуют; cleanup полностью DB-only.
|
||||
* SQL-транзакция и файловая система не коммитятся атомарно вместе;
|
||||
* поэтому БД-чистка делается здесь, а файловая чистка будет следующим шагом
|
||||
* отдельным recovery/resync-слоем после успешного commit.
|
||||
*
|
||||
* Важный смысл текущей реализации:
|
||||
* - мы НЕ трогаем current users слой (`solana_user_pda_current`) и НЕ трогаем DM-таблицы;
|
||||
* - мы очищаем только блокчейн пользователя и derived-state, который строится из неё;
|
||||
* - висячие cross-chain ссылки в чужих blocks допускаются как нормальное поведение системы.
|
||||
* Atomic cleanup of one physical fork before deterministic replay.
|
||||
* Physical fork identity is (login,fork_number). Incoming logical state is never rebound/deleted.
|
||||
*/
|
||||
public final class BlockchainResyncCleanupDAO {
|
||||
|
||||
private static final int BLOCKCHAIN_LOGIN_SUFFIX_LEN = 4; // "-001"
|
||||
|
||||
private static volatile BlockchainResyncCleanupDAO instance;
|
||||
private final DbController db=DbController.getInstance();
|
||||
private BlockchainResyncCleanupDAO(){}
|
||||
public static BlockchainResyncCleanupDAO getInstance(){ if(instance==null) synchronized(BlockchainResyncCleanupDAO.class){if(instance==null)instance=new BlockchainResyncCleanupDAO();} return instance; }
|
||||
|
||||
private final DbController db = DbController.getInstance();
|
||||
|
||||
private BlockchainResyncCleanupDAO() {}
|
||||
|
||||
public static BlockchainResyncCleanupDAO getInstance() {
|
||||
if (instance == null) {
|
||||
synchronized (BlockchainResyncCleanupDAO.class) {
|
||||
if (instance == null) instance = new BlockchainResyncCleanupDAO();
|
||||
}
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Полностью очищает одну blockchain-цепочку и локальные derived-state, собранные из неё.
|
||||
*
|
||||
* Порядок внутри транзакции намеренно такой:
|
||||
* 1. Сначала уменьшаем чужие likes_count для тех целей, где финальное состояние
|
||||
* реакции этой цепочки было LIKE.
|
||||
* 2. Сначала уменьшаем чужие replies_count для reply-блоков этой цепочки.
|
||||
* 3. После этого удаляем локальные derived-state самой цепочки.
|
||||
* 4. В конце удаляем blocks и blockchain_state.
|
||||
*
|
||||
* Это правильно потому, что агрегаты (`message_stats`) должны видеть исходные blocks
|
||||
* и reactions_state на момент пересчёта. Если удалить blocks раньше, мы потеряем
|
||||
* источник правды для корректного уменьшения счётчиков.
|
||||
*
|
||||
* Метод идемпотентен по смыслу:
|
||||
* - если часть данных уже удалена раньше, повторный вызов просто удалит "0 строк";
|
||||
* - если blockchain_state уже отсутствует, login берём из blockchainName.
|
||||
*
|
||||
* Отдельно важно:
|
||||
* - filesystem blockchain storage отсутствует;
|
||||
* - здесь НЕТ повторной загрузки цепочки;
|
||||
* - это только атомарная SQL-очистка БД, на которую потом будет опираться resync-flow.
|
||||
*/
|
||||
public CleanupResult cleanupBlockchainForFullResync(String blockchainName) throws SQLException {
|
||||
if (blockchainName == null || blockchainName.isBlank()) {
|
||||
throw new IllegalArgumentException("blockchainName is blank");
|
||||
}
|
||||
|
||||
try (Connection c = db.getConnection()) {
|
||||
boolean oldAutoCommit = c.getAutoCommit();
|
||||
c.setAutoCommit(false);
|
||||
try {
|
||||
String login = resolveLoginForCleanup(c, blockchainName);
|
||||
|
||||
int likesAdjusted = decreaseForeignLikesCount(c, blockchainName);
|
||||
int repliesAdjusted = decreaseForeignRepliesCount(c, blockchainName);
|
||||
|
||||
int deletedMessageStats = deleteMessageStatsForOwnTargets(c, blockchainName);
|
||||
int deletedReactionsState = deleteReactionsStateForActorChain(c, blockchainName);
|
||||
int deletedConnectionsState = deleteConnectionsStateForLogin(c, login);
|
||||
int deletedUsersParams = deleteUsersParamsForLogin(c, login);
|
||||
int deletedChannelNames = deleteChannelNamesForOwnerChain(c, blockchainName);
|
||||
int deletedChat200State = deleteChat200StateForOwnerChain(c, blockchainName);
|
||||
int deletedChat200Members = deleteChat200MembersForOwnerChain(c, blockchainName);
|
||||
int deletedBlocks = deleteBlocksForChain(c, blockchainName);
|
||||
int deletedBlockchainState = deleteBlockchainStateForChain(c, blockchainName);
|
||||
|
||||
rebuildStatsState(c);
|
||||
|
||||
c.commit();
|
||||
|
||||
return new CleanupResult(
|
||||
login,
|
||||
likesAdjusted,
|
||||
repliesAdjusted,
|
||||
deletedMessageStats,
|
||||
deletedReactionsState,
|
||||
deletedConnectionsState,
|
||||
deletedUsersParams,
|
||||
deletedChannelNames,
|
||||
deletedChat200State,
|
||||
deletedChat200Members,
|
||||
deletedBlocks,
|
||||
deletedBlockchainState
|
||||
);
|
||||
} catch (Exception e) {
|
||||
try { c.rollback(); } catch (Exception ignored) {}
|
||||
if (e instanceof SQLException sqlEx) throw sqlEx;
|
||||
throw new SQLException("Не удалось очистить blockchain для полного resync: " + blockchainName, e);
|
||||
} finally {
|
||||
try { c.setAutoCommit(oldAutoCommit); } catch (Exception ignored) {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* После смены fork обновляет только runtime-кэш физического blockchainName у логических target-ссылок.
|
||||
* Подписанная идентичность target уже задаётся login + blockNumber + blockHash; поэтому смена cache value
|
||||
* не меняет смысл ссылки и не требует переподписывать чужие блоки.
|
||||
*/
|
||||
public void refreshLogicalTargetBlockchainCache(String login, String oldBlockchainName, String newBlockchainName) throws SQLException {
|
||||
if (login == null || login.isBlank() || newBlockchainName == null || newBlockchainName.isBlank()) {
|
||||
throw new IllegalArgumentException("login/newBlockchainName are required");
|
||||
}
|
||||
try (Connection c = db.getConnection()) {
|
||||
boolean oldAutoCommit = c.getAutoCommit();
|
||||
c.setAutoCommit(false);
|
||||
try {
|
||||
updateTargetCacheByLogin(c, "blocks", login, newBlockchainName);
|
||||
updateTargetCacheByLogin(c, "connections_state", login, newBlockchainName);
|
||||
updateTargetCacheByLogin(c, "reactions_state", login, newBlockchainName);
|
||||
updateTargetCacheByLogin(c, "message_stats", login, newBlockchainName);
|
||||
if (oldBlockchainName != null && !oldBlockchainName.isBlank()) {
|
||||
try (PreparedStatement ps = c.prepareStatement("UPDATE message_views_state SET to_bch_name=? WHERE to_bch_name=?")) {
|
||||
ps.setString(1, newBlockchainName);
|
||||
ps.setString(2, oldBlockchainName);
|
||||
ps.executeUpdate();
|
||||
}
|
||||
try (PreparedStatement ps = c.prepareStatement("UPDATE channel_read_state SET owner_bch_name=? WHERE owner_bch_name=?")) {
|
||||
ps.setString(1, newBlockchainName);
|
||||
ps.setString(2, oldBlockchainName);
|
||||
ps.executeUpdate();
|
||||
}
|
||||
ChainRef ref=chainRef(blockchainName);
|
||||
try(Connection c=db.getConnection()){
|
||||
boolean ac=c.getAutoCommit(); c.setAutoCommit(false);
|
||||
try{
|
||||
// Targets liked by this actor must survive long enough to recount after actor rows are removed.
|
||||
try(Statement st=c.createStatement()){
|
||||
st.execute("CREATE TEMP TABLE IF NOT EXISTS shine_cleanup_targets(to_login TEXT,to_block_number INTEGER,to_block_hash BYTEA,PRIMARY KEY(to_login,to_block_number,to_block_hash)) ON COMMIT DROP");
|
||||
st.execute("TRUNCATE shine_cleanup_targets");
|
||||
st.execute("CREATE TEMP TABLE IF NOT EXISTS shine_cleanup_channels(owner_bch_name TEXT,root_number INTEGER,root_hash BYTEA,PRIMARY KEY(owner_bch_name,root_number,root_hash)) ON COMMIT DROP");
|
||||
st.execute("TRUNCATE shine_cleanup_channels");
|
||||
st.execute("CREATE TEMP TABLE IF NOT EXISTS shine_cleanup_users(login TEXT PRIMARY KEY) ON COMMIT DROP");
|
||||
st.execute("TRUNCATE shine_cleanup_users");
|
||||
}
|
||||
rebuildInboundMessageCounters(c, login, newBlockchainName);
|
||||
rebuildStatsState(c);
|
||||
c.commit();
|
||||
} catch (Exception e) {
|
||||
c.rollback();
|
||||
if (e instanceof SQLException sql) throw sql;
|
||||
throw new SQLException("Failed to refresh logical target blockchain cache for login=" + login, e);
|
||||
} finally {
|
||||
c.setAutoCommit(oldAutoCommit);
|
||||
}
|
||||
}
|
||||
}
|
||||
try(PreparedStatement ps=c.prepareStatement("""
|
||||
INSERT INTO shine_cleanup_targets(to_login,to_block_number,to_block_hash)
|
||||
SELECT DISTINCT to_login,to_block_number,to_block_hash FROM reactions_state
|
||||
WHERE LOWER(from_login)=LOWER(?) AND reaction_type=1 AND last_sub_type=1
|
||||
ON CONFLICT DO NOTHING
|
||||
""")){ ps.setString(1,ref.login()); ps.executeUpdate(); }
|
||||
|
||||
/**
|
||||
* После replay candidate-цепочки её собственные message_stats уже существуют, но входящие реакции/ответы
|
||||
* других пользователей были созданы раньше и не проходили триггеры повторно. Поэтому пересчитываем
|
||||
* агрегаты из исходных таблиц после перепривязки runtime to_bch_name cache.
|
||||
*/
|
||||
private void rebuildInboundMessageCounters(Connection c, String login, String newBlockchainName) throws SQLException {
|
||||
try (PreparedStatement ps = c.prepareStatement("""
|
||||
UPDATE message_stats ms
|
||||
SET likes_count = (
|
||||
SELECT COUNT(*)::INTEGER
|
||||
FROM reactions_state rs
|
||||
WHERE rs.reaction_type = ?
|
||||
AND rs.last_sub_type = ?
|
||||
AND LOWER(rs.to_login) = LOWER(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
|
||||
),
|
||||
replies_count = (
|
||||
SELECT COUNT(*)::INTEGER
|
||||
FROM blocks b
|
||||
WHERE b.msg_type = 1
|
||||
AND b.msg_sub_type = ?
|
||||
AND LOWER(b.to_login) = LOWER(ms.to_login)
|
||||
AND b.to_bch_name = ms.to_bch_name
|
||||
AND b.to_block_number = ms.to_block_number
|
||||
AND b.to_block_hash = ms.to_block_hash
|
||||
)
|
||||
WHERE LOWER(ms.to_login) = LOWER(?)
|
||||
AND ms.to_bch_name = ?
|
||||
""")) {
|
||||
ps.setInt(1, DatabaseInitializer.REACTION_LIKE);
|
||||
ps.setInt(2, DatabaseInitializer.REACTION_LIKE);
|
||||
ps.setInt(3, DatabaseInitializer.TEXT_REPLY);
|
||||
ps.setString(4, login);
|
||||
ps.setString(5, newBlockchainName);
|
||||
ps.executeUpdate();
|
||||
}
|
||||
}
|
||||
try(PreparedStatement ps=c.prepareStatement("""
|
||||
INSERT INTO shine_cleanup_users(login)
|
||||
SELECT DISTINCT to_login FROM connections_state
|
||||
WHERE LOWER(login)=LOWER(?) AND to_login IS NOT NULL AND btrim(to_login)<>''
|
||||
ON CONFLICT DO NOTHING
|
||||
""")){ps.setString(1,ref.login());ps.executeUpdate();}
|
||||
|
||||
private void updateTargetCacheByLogin(Connection c, String table, String login, String newBlockchainName) throws SQLException {
|
||||
String sql = "UPDATE " + table + " SET to_bch_name=? WHERE LOWER(to_login)=LOWER(?) AND to_bch_name IS DISTINCT FROM ?";
|
||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||
ps.setString(1, newBlockchainName);
|
||||
ps.setString(2, login);
|
||||
ps.setString(3, newBlockchainName);
|
||||
ps.executeUpdate();
|
||||
}
|
||||
}
|
||||
try(PreparedStatement ps=c.prepareStatement("""
|
||||
INSERT INTO shine_cleanup_channels(owner_bch_name,root_number,root_hash)
|
||||
SELECT DISTINCT cn.owner_bch_name,cn.channel_root_block_number,cn.channel_root_block_hash
|
||||
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(?) AND cs.rel_type=30
|
||||
ON CONFLICT DO NOTHING
|
||||
""")){ps.setString(1,ref.login());ps.executeUpdate();}
|
||||
|
||||
// Followers of channels owned by this login must be refreshed after those channel projections are removed.
|
||||
try(PreparedStatement ps=c.prepareStatement("""
|
||||
INSERT INTO shine_cleanup_users(login)
|
||||
SELECT DISTINCT cs.login
|
||||
FROM connections_state cs
|
||||
JOIN channel_names_state cn
|
||||
ON LOWER(cn.owner_login)=LOWER(?)
|
||||
AND LOWER(cs.to_login)=LOWER(cn.owner_login)
|
||||
AND cs.to_block_number=cn.channel_root_block_number
|
||||
AND cs.to_block_hash=cn.channel_root_block_hash
|
||||
WHERE cs.rel_type=30
|
||||
ON CONFLICT DO NOTHING
|
||||
""")){ps.setString(1,ref.login());ps.executeUpdate();}
|
||||
|
||||
private String resolveLoginForCleanup(Connection c, String blockchainName) throws SQLException {
|
||||
String sql = """
|
||||
SELECT login
|
||||
FROM blockchain_state
|
||||
WHERE blockchain_name = ?
|
||||
LIMIT 1
|
||||
""";
|
||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||
ps.setString(1, blockchainName);
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
if (rs.next()) {
|
||||
String login = rs.getString("login");
|
||||
if (login != null && !login.isBlank()) {
|
||||
return login;
|
||||
}
|
||||
int deletedReactions=delete(c,"DELETE FROM reactions_state WHERE LOWER(from_login)=LOWER(?)",ref.login());
|
||||
recountAffectedLikes(c);
|
||||
int deletedConnections=delete(c,"DELETE FROM connections_state WHERE LOWER(login)=LOWER(?)",ref.login());
|
||||
refreshAffectedChannelStats(c);
|
||||
int deletedUsersParams=delete(c,"DELETE FROM users_params WHERE LOWER(login)=LOWER(?)",ref.login());
|
||||
try(PreparedStatement ps=c.prepareStatement("SELECT shine_refresh_user_profile(?)")){ps.setString(1,ref.login());ps.execute();}
|
||||
try(PreparedStatement ps=c.prepareStatement("SELECT shine_refresh_related_user_stats(?)")){ps.setString(1,ref.login());ps.execute();}
|
||||
// Channel/chat projections are owned by login; replay recreates them. Incoming social stats are intentionally untouched.
|
||||
delete(c,"DELETE FROM channel_stats_state WHERE LOWER(owner_login)=LOWER(?)",ref.login());
|
||||
int deletedChannelNames=delete(c,"DELETE FROM channel_names_state WHERE LOWER(owner_login)=LOWER(?)",ref.login());
|
||||
refreshAffectedUserStats(c);
|
||||
int deletedChat200=delete(c,"DELETE FROM chat200_state WHERE LOWER(owner_login)=LOWER(?)",ref.login());
|
||||
int deletedChatMembers=delete(c,"DELETE FROM chat200_members_state WHERE owner_bch_name LIKE ?",ref.login()+"-%");
|
||||
try(PreparedStatement ps=c.prepareStatement("SELECT shine_refresh_user_stats(?)")){ps.setString(1,ref.login());ps.execute();}
|
||||
|
||||
int deletedBlocks;
|
||||
try(PreparedStatement ps=c.prepareStatement("DELETE FROM blocks_store WHERE LOWER(login)=LOWER(?) AND fork_number=?")){
|
||||
ps.setString(1,ref.login()); ps.setInt(2,ref.fork()); deletedBlocks=ps.executeUpdate();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
String loginFromName = loginFromBlockchainName(blockchainName);
|
||||
if (loginFromName == null || loginFromName.isBlank()) {
|
||||
throw new IllegalArgumentException("Cannot derive login from blockchainName: " + blockchainName);
|
||||
}
|
||||
return loginFromName;
|
||||
}
|
||||
|
||||
/**
|
||||
* DAO остаётся в модуле БД и не тянет зависимость на blockchain-utils модуль.
|
||||
* Поэтому здесь локально повторяем минимальное правило имени chain:
|
||||
* login + "-NNN".
|
||||
*/
|
||||
private String loginFromBlockchainName(String blockchainName) {
|
||||
if (blockchainName == null) return null;
|
||||
|
||||
String s = blockchainName.trim();
|
||||
if (s.length() <= BLOCKCHAIN_LOGIN_SUFFIX_LEN) return null;
|
||||
|
||||
int dashPos = s.length() - BLOCKCHAIN_LOGIN_SUFFIX_LEN;
|
||||
if (s.charAt(dashPos) != '-') return null;
|
||||
|
||||
for (int i = dashPos + 1; i < s.length(); i++) {
|
||||
char ch = s.charAt(i);
|
||||
if (ch < '0' || ch > '9') return null;
|
||||
}
|
||||
return s.substring(0, dashPos);
|
||||
}
|
||||
|
||||
/**
|
||||
* Уменьшаем likes_count только для ЧУЖИХ целей.
|
||||
*
|
||||
* Логика:
|
||||
* - если у удаляемой цепочки финальное состояние реакции на цель = LIKE,
|
||||
* значит при полном удалении цепочки этот активный лайк исчезает;
|
||||
* - значит у message_stats этой чужой цели нужно сделать -1;
|
||||
* - для целей внутри этой же chain этого делать не нужно, потому что сами цели
|
||||
* тоже будут удалены вместе с цепочкой.
|
||||
*/
|
||||
private int decreaseForeignLikesCount(Connection c, String blockchainName) throws SQLException {
|
||||
String sql = """
|
||||
UPDATE message_stats
|
||||
SET likes_count = GREATEST(
|
||||
0,
|
||||
likes_count - COALESCE((
|
||||
SELECT COUNT(*)::int
|
||||
FROM reactions_state rs
|
||||
WHERE rs.from_bch_name = ?
|
||||
AND rs.reaction_type = ?
|
||||
AND rs.last_sub_type = ?
|
||||
AND rs.to_login = message_stats.to_login
|
||||
AND rs.to_bch_name = message_stats.to_bch_name
|
||||
AND rs.to_block_number = message_stats.to_block_number
|
||||
AND rs.to_block_hash = message_stats.to_block_hash
|
||||
AND rs.to_bch_name <> ?
|
||||
), 0)
|
||||
)
|
||||
WHERE EXISTS (
|
||||
SELECT 1
|
||||
FROM reactions_state rs
|
||||
WHERE rs.from_bch_name = ?
|
||||
AND rs.reaction_type = ?
|
||||
AND rs.last_sub_type = ?
|
||||
AND rs.to_login = message_stats.to_login
|
||||
AND rs.to_bch_name = message_stats.to_bch_name
|
||||
AND rs.to_block_number = message_stats.to_block_number
|
||||
AND rs.to_block_hash = message_stats.to_block_hash
|
||||
AND rs.to_bch_name <> ?
|
||||
)
|
||||
""";
|
||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||
int i = 1;
|
||||
ps.setString(i++, blockchainName);
|
||||
ps.setInt(i++, DatabaseInitializer.REACTION_LIKE);
|
||||
ps.setInt(i++, DatabaseInitializer.REACTION_LIKE);
|
||||
ps.setString(i++, blockchainName);
|
||||
ps.setString(i++, blockchainName);
|
||||
ps.setInt(i++, DatabaseInitializer.REACTION_LIKE);
|
||||
ps.setInt(i++, DatabaseInitializer.REACTION_LIKE);
|
||||
ps.setString(i++, blockchainName);
|
||||
return ps.executeUpdate();
|
||||
int deletedState;
|
||||
try(PreparedStatement ps=c.prepareStatement("DELETE FROM blockchain_state_store WHERE LOWER(login)=LOWER(?) AND fork_number=?")){
|
||||
ps.setString(1,ref.login()); ps.setInt(2,ref.fork()); deletedState=ps.executeUpdate();
|
||||
}
|
||||
c.commit();
|
||||
return new CleanupResult(ref.login(),deletedReactions,deletedConnections,deletedUsersParams,deletedChannelNames,deletedChat200,deletedChatMembers,deletedBlocks,deletedState);
|
||||
}catch(Exception e){ try{c.rollback();}catch(Exception ignored){} if(e instanceof SQLException x)throw x; throw new SQLException("Stage2 fork cleanup failed: "+blockchainName,e); }
|
||||
finally{try{c.setAutoCommit(ac);}catch(Exception ignored){}}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Уменьшаем replies_count только для ЧУЖИХ целей.
|
||||
*
|
||||
* Если reply этой цепочки ссылался на сообщение из другой цепочки,
|
||||
* значит после удаления blocks этой цепочки чужой replies_count должен уменьшиться.
|
||||
* Reply на собственные сообщения здесь игнорируем: целевая цепочка тоже будет удалена.
|
||||
*/
|
||||
private int decreaseForeignRepliesCount(Connection c, String blockchainName) throws SQLException {
|
||||
String sql = """
|
||||
UPDATE message_stats
|
||||
SET replies_count = GREATEST(
|
||||
0,
|
||||
replies_count - COALESCE((
|
||||
SELECT COUNT(*)::int
|
||||
FROM blocks b
|
||||
WHERE b.bch_name = ?
|
||||
AND b.msg_type = 1
|
||||
AND b.msg_sub_type = ?
|
||||
AND b.to_login = message_stats.to_login
|
||||
AND b.to_bch_name = message_stats.to_bch_name
|
||||
AND b.to_block_number = message_stats.to_block_number
|
||||
AND b.to_block_hash = message_stats.to_block_hash
|
||||
AND b.to_bch_name <> ?
|
||||
), 0)
|
||||
)
|
||||
WHERE EXISTS (
|
||||
SELECT 1
|
||||
FROM blocks b
|
||||
WHERE b.bch_name = ?
|
||||
AND b.msg_type = 1
|
||||
AND b.msg_sub_type = ?
|
||||
AND b.to_login = message_stats.to_login
|
||||
AND b.to_bch_name = message_stats.to_bch_name
|
||||
AND b.to_block_number = message_stats.to_block_number
|
||||
AND b.to_block_hash = message_stats.to_block_hash
|
||||
AND b.to_bch_name <> ?
|
||||
)
|
||||
""";
|
||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||
int i = 1;
|
||||
ps.setString(i++, blockchainName);
|
||||
ps.setInt(i++, DatabaseInitializer.TEXT_REPLY);
|
||||
ps.setString(i++, blockchainName);
|
||||
ps.setString(i++, blockchainName);
|
||||
ps.setInt(i++, DatabaseInitializer.TEXT_REPLY);
|
||||
ps.setString(i++, blockchainName);
|
||||
return ps.executeUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Статистика сообщений самой удаляемой цепочки после reset не нужна,
|
||||
* потому что её цели исчезают вместе с chain source data.
|
||||
*/
|
||||
private int deleteMessageStatsForOwnTargets(Connection c, String blockchainName) throws SQLException {
|
||||
return executeDelete(c, """
|
||||
DELETE FROM message_stats
|
||||
WHERE to_bch_name = ?
|
||||
""", blockchainName);
|
||||
}
|
||||
|
||||
/**
|
||||
* reactions_state хранит финальное состояние реакций АКТОРА.
|
||||
* После удаления всей цепочки актор этой цепочки исчезает, поэтому
|
||||
* достаточно удалить все строки по from_bch_name.
|
||||
*/
|
||||
private int deleteReactionsStateForActorChain(Connection c, String blockchainName) throws SQLException {
|
||||
return executeDelete(c, """
|
||||
DELETE FROM reactions_state
|
||||
WHERE from_bch_name = ?
|
||||
""", blockchainName);
|
||||
}
|
||||
|
||||
/**
|
||||
* connections_state — текущее состояние связей, выставленных этим login.
|
||||
* Чистим по владельцу состояния.
|
||||
*/
|
||||
private int deleteConnectionsStateForLogin(Connection c, String login) throws SQLException {
|
||||
return executeDelete(c, """
|
||||
DELETE FROM connections_state
|
||||
WHERE LOWER(login) = LOWER(?)
|
||||
""", login);
|
||||
}
|
||||
|
||||
/**
|
||||
* users_params — актуальные параметры, собранные из блоков пользователя.
|
||||
*/
|
||||
private int deleteUsersParamsForLogin(Connection c, String login) throws SQLException {
|
||||
return executeDelete(c, """
|
||||
DELETE FROM users_params
|
||||
WHERE LOWER(login) = LOWER(?)
|
||||
""", login);
|
||||
}
|
||||
|
||||
/**
|
||||
* Каналы принадлежат owner_bch_name.
|
||||
*/
|
||||
private int deleteChannelNamesForOwnerChain(Connection c, String blockchainName) throws SQLException {
|
||||
return executeDelete(c, """
|
||||
DELETE FROM channel_names_state
|
||||
WHERE owner_bch_name = ?
|
||||
""", blockchainName);
|
||||
}
|
||||
|
||||
private int deleteChat200StateForOwnerChain(Connection c, String blockchainName) throws SQLException {
|
||||
return executeDelete(c, """
|
||||
DELETE FROM chat200_state
|
||||
WHERE owner_bch_name = ?
|
||||
""", blockchainName);
|
||||
}
|
||||
|
||||
private int deleteChat200MembersForOwnerChain(Connection c, String blockchainName) throws SQLException {
|
||||
return executeDelete(c, """
|
||||
DELETE FROM chat200_members_state
|
||||
WHERE owner_bch_name = ?
|
||||
""", blockchainName);
|
||||
}
|
||||
|
||||
/**
|
||||
* blocks удаляем в конце, потому что до этого шага они нужны как источник правды
|
||||
* для уменьшения replies_count.
|
||||
*/
|
||||
private int deleteBlocksForChain(Connection c, String blockchainName) throws SQLException {
|
||||
return executeDelete(c, """
|
||||
DELETE FROM blocks
|
||||
WHERE bch_name = ?
|
||||
""", blockchainName);
|
||||
}
|
||||
|
||||
/**
|
||||
* blockchain_state удаляем после blocks, чтобы не нарушать FK-связь blocks -> blockchain_state.
|
||||
*/
|
||||
private int deleteBlockchainStateForChain(Connection c, String blockchainName) throws SQLException {
|
||||
return executeDelete(c, """
|
||||
DELETE FROM blockchain_state
|
||||
WHERE blockchain_name = ?
|
||||
""", blockchainName);
|
||||
}
|
||||
|
||||
private void rebuildStatsState(Connection c) throws SQLException {
|
||||
try (PreparedStatement truncate = c.prepareStatement("""
|
||||
TRUNCATE TABLE user_stats_state, channel_stats_state
|
||||
""")) {
|
||||
truncate.executeUpdate();
|
||||
}
|
||||
|
||||
try (PreparedStatement ps = c.prepareStatement("""
|
||||
INSERT INTO user_stats_state (
|
||||
login,
|
||||
owned_public_channels_count,
|
||||
following_users_count,
|
||||
following_channels_count,
|
||||
close_friends_count,
|
||||
updated_at_ms
|
||||
)
|
||||
SELECT
|
||||
u.login,
|
||||
COALESCE(own.owned_public_channels_count, 0),
|
||||
COALESCE(fu.following_users_count, 0),
|
||||
COALESCE(fc.following_channels_count, 0),
|
||||
COALESCE(cf.close_friends_count, 0),
|
||||
CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT)
|
||||
FROM solana_user_pda_current u
|
||||
LEFT JOIN (
|
||||
SELECT owner_login, COUNT(*)::INTEGER AS owned_public_channels_count
|
||||
FROM channel_names_state
|
||||
WHERE channel_type_code = 1
|
||||
GROUP BY owner_login
|
||||
) own ON LOWER(own.owner_login) = LOWER(u.login)
|
||||
LEFT JOIN (
|
||||
SELECT login, COUNT(*)::INTEGER AS following_users_count
|
||||
FROM connections_state
|
||||
WHERE rel_type = 30
|
||||
AND to_block_number = 0
|
||||
GROUP BY login
|
||||
) fu ON LOWER(fu.login) = LOWER(u.login)
|
||||
LEFT JOIN (
|
||||
SELECT cs.login, COUNT(*)::INTEGER AS following_channels_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.channel_type_code = 1
|
||||
GROUP BY cs.login
|
||||
) fc ON LOWER(fc.login) = LOWER(u.login)
|
||||
LEFT JOIN (
|
||||
SELECT login, COUNT(*)::INTEGER AS close_friends_count
|
||||
FROM connections_state
|
||||
WHERE rel_type = 10
|
||||
GROUP BY login
|
||||
) cf ON LOWER(cf.login) = LOWER(u.login)
|
||||
""")) {
|
||||
ps.executeUpdate();
|
||||
}
|
||||
|
||||
|
||||
try (PreparedStatement ps = c.prepareStatement("SELECT shine_refresh_user_profile(login) FROM solana_user_pda_current")) {
|
||||
ps.execute();
|
||||
}
|
||||
try (PreparedStatement ps = c.prepareStatement("SELECT shine_refresh_user_stats(login) FROM solana_user_pda_current")) {
|
||||
ps.execute();
|
||||
}
|
||||
try (PreparedStatement ps = c.prepareStatement("""
|
||||
private void recountAffectedLikes(Connection c)throws SQLException{
|
||||
try(PreparedStatement ps=c.prepareStatement("""
|
||||
UPDATE message_stats ms SET
|
||||
primary_likes_count=(SELECT COUNT(*)::INTEGER 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(*)::INTEGER 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))
|
||||
""")) {
|
||||
ps.executeUpdate();
|
||||
}
|
||||
likes_count=(SELECT COUNT(*)::INTEGER 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_block_number=ms.to_block_number AND rs.to_block_hash=ms.to_block_hash),
|
||||
primary_likes_count=(SELECT COUNT(*)::INTEGER 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_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(*)::INTEGER 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_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))
|
||||
WHERE EXISTS(SELECT 1 FROM shine_cleanup_targets t WHERE t.to_login=ms.to_login AND t.to_block_number=ms.to_block_number AND t.to_block_hash=ms.to_block_hash)
|
||||
""")){ps.executeUpdate();}
|
||||
}
|
||||
|
||||
try (PreparedStatement ps = c.prepareStatement("""
|
||||
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
|
||||
)
|
||||
SELECT
|
||||
cn.owner_bch_name,
|
||||
cn.channel_root_block_number,
|
||||
cn.channel_root_block_hash,
|
||||
cn.owner_login,
|
||||
cn.channel_type_code,
|
||||
COUNT(DISTINCT cs.login)::INTEGER AS subscribers_count,
|
||||
CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT)
|
||||
FROM channel_names_state cn
|
||||
LEFT JOIN connections_state cs
|
||||
ON cs.rel_type = 30
|
||||
AND cs.to_bch_name = cn.owner_bch_name
|
||||
AND cs.to_block_number = cn.channel_root_block_number
|
||||
AND cs.to_block_hash = cn.channel_root_block_hash
|
||||
WHERE cn.channel_type_code = 1
|
||||
GROUP BY
|
||||
cn.owner_bch_name,
|
||||
cn.channel_root_block_number,
|
||||
cn.channel_root_block_hash,
|
||||
cn.owner_login,
|
||||
cn.channel_type_code
|
||||
""")) {
|
||||
ps.executeUpdate();
|
||||
private void refreshAffectedChannelStats(Connection c)throws SQLException{
|
||||
try(PreparedStatement q=c.prepareStatement("SELECT owner_bch_name,root_number,root_hash FROM shine_cleanup_channels"); ResultSet rs=q.executeQuery(); PreparedStatement p=c.prepareStatement("SELECT shine_refresh_channel_follow_stats(?,?,?)")){
|
||||
while(rs.next()){p.setString(1,rs.getString(1));p.setInt(2,rs.getInt(2));p.setBytes(3,rs.getBytes(3));p.execute();}
|
||||
}
|
||||
}
|
||||
|
||||
private int executeDelete(Connection c, String sql, String value) throws SQLException {
|
||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||
ps.setString(1, value);
|
||||
return ps.executeUpdate();
|
||||
private void refreshAffectedUserStats(Connection c)throws SQLException{
|
||||
try(PreparedStatement q=c.prepareStatement("SELECT login FROM shine_cleanup_users"); ResultSet rs=q.executeQuery(); PreparedStatement p=c.prepareStatement("SELECT shine_refresh_user_stats(?)")){
|
||||
while(rs.next()){p.setString(1,rs.getString(1));p.execute();}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Технический результат cleanup-операции.
|
||||
* Нужен для будущего логирования и ручной диагностики resync-flow.
|
||||
*/
|
||||
public record CleanupResult(
|
||||
String login,
|
||||
int likesAdjustedRows,
|
||||
int repliesAdjustedRows,
|
||||
int deletedMessageStatsRows,
|
||||
int deletedReactionsStateRows,
|
||||
int deletedConnectionsStateRows,
|
||||
int deletedUsersParamsRows,
|
||||
int deletedChannelNamesRows,
|
||||
int deletedChat200StateRows,
|
||||
int deletedChat200MembersRows,
|
||||
int deletedBlocksRows,
|
||||
int deletedBlockchainStateRows
|
||||
) {}
|
||||
private int delete(Connection c,String sql,String v)throws SQLException{try(PreparedStatement ps=c.prepareStatement(sql)){ps.setString(1,v);return ps.executeUpdate();}}
|
||||
private record ChainRef(String login,int fork){}
|
||||
private static ChainRef chainRef(String n){ if(n==null)throw new IllegalArgumentException("blockchainName is null"); String s=n.trim();int d=s.lastIndexOf('-');if(d<=0||s.length()-d-1!=3)throw new IllegalArgumentException("Bad blockchainName: "+n);try{int f=Integer.parseInt(s.substring(d+1));if(f<1||f>999)throw new IllegalArgumentException("fork out of range");return new ChainRef(s.substring(0,d),f);}catch(NumberFormatException e){throw new IllegalArgumentException("Bad blockchainName: "+n,e);} }
|
||||
|
||||
public record CleanupResult(String login,int deletedReactionsStateRows,int deletedConnectionsStateRows,int deletedUsersParamsRows,int deletedChannelNamesRows,int deletedChat200StateRows,int deletedChat200MembersRows,int deletedBlocksRows,int deletedBlockchainStateRows){}
|
||||
}
|
||||
|
||||
@@ -34,8 +34,8 @@ public final class BlockchainStateDAO {
|
||||
public BlockchainStateEntry getByBlockchainName(Connection c, String blockchainName) throws SQLException {
|
||||
String sql = """
|
||||
SELECT
|
||||
blockchain_name,
|
||||
login,
|
||||
fork_number,
|
||||
blockchain_key,
|
||||
size_limit,
|
||||
file_size_bytes,
|
||||
@@ -43,11 +43,13 @@ public final class BlockchainStateDAO {
|
||||
last_block_hash,
|
||||
updated_at_ms
|
||||
FROM blockchain_state
|
||||
WHERE blockchain_name = ?
|
||||
WHERE login = ? AND fork_number = ?
|
||||
""";
|
||||
|
||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||
ps.setString(1, blockchainName);
|
||||
ChainRef r=chainRef(blockchainName);
|
||||
ps.setString(1, r.login());
|
||||
ps.setInt(2, r.fork());
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
if (!rs.next()) return null;
|
||||
return mapRow(rs);
|
||||
@@ -66,8 +68,8 @@ public final class BlockchainStateDAO {
|
||||
public List<BlockchainStateEntry> listAll(Connection c) throws SQLException {
|
||||
String sql = """
|
||||
SELECT
|
||||
blockchain_name,
|
||||
login,
|
||||
fork_number,
|
||||
blockchain_key,
|
||||
size_limit,
|
||||
file_size_bytes,
|
||||
@@ -75,7 +77,7 @@ public final class BlockchainStateDAO {
|
||||
last_block_hash,
|
||||
updated_at_ms
|
||||
FROM blockchain_state
|
||||
ORDER BY LOWER(blockchain_name)
|
||||
ORDER BY LOWER(login), fork_number
|
||||
""";
|
||||
|
||||
List<BlockchainStateEntry> result = new ArrayList<>();
|
||||
@@ -98,9 +100,9 @@ public final class BlockchainStateDAO {
|
||||
/** UPSERT с внешним соединением. Соединение НЕ закрывает. */
|
||||
public void upsert(Connection c, BlockchainStateEntry e) throws SQLException {
|
||||
String sql = """
|
||||
INSERT INTO blockchain_state (
|
||||
blockchain_name,
|
||||
INSERT INTO blockchain_state_store (
|
||||
login,
|
||||
fork_number,
|
||||
blockchain_key,
|
||||
size_limit,
|
||||
file_size_bytes,
|
||||
@@ -108,9 +110,8 @@ public final class BlockchainStateDAO {
|
||||
last_block_hash,
|
||||
updated_at_ms
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(blockchain_name)
|
||||
ON CONFLICT(login, fork_number)
|
||||
DO UPDATE SET
|
||||
login = excluded.login,
|
||||
blockchain_key = excluded.blockchain_key,
|
||||
size_limit = excluded.size_limit,
|
||||
file_size_bytes = excluded.file_size_bytes,
|
||||
@@ -122,8 +123,8 @@ public final class BlockchainStateDAO {
|
||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||
int i = 1;
|
||||
|
||||
ps.setString(i++, e.getBlockchainName());
|
||||
ps.setString(i++, nn(e.getLogin()));
|
||||
ps.setInt(i++, e.getForkNumber());
|
||||
ps.setString(i++, nn(e.getBlockchainKey()));
|
||||
|
||||
ps.setLong(i++, e.getSizeLimit());
|
||||
@@ -148,9 +149,9 @@ public final class BlockchainStateDAO {
|
||||
*/
|
||||
public boolean insertIfMissing(Connection c, BlockchainStateEntry e) throws SQLException {
|
||||
String sql = """
|
||||
INSERT INTO blockchain_state (
|
||||
blockchain_name,
|
||||
INSERT INTO blockchain_state_store (
|
||||
login,
|
||||
fork_number,
|
||||
blockchain_key,
|
||||
size_limit,
|
||||
file_size_bytes,
|
||||
@@ -158,14 +159,14 @@ public final class BlockchainStateDAO {
|
||||
last_block_hash,
|
||||
updated_at_ms
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(blockchain_name) DO NOTHING
|
||||
ON CONFLICT(login, fork_number) DO NOTHING
|
||||
""";
|
||||
|
||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||
int i = 1;
|
||||
|
||||
ps.setString(i++, e.getBlockchainName());
|
||||
ps.setString(i++, nn(e.getLogin()));
|
||||
ps.setInt(i++, e.getForkNumber());
|
||||
ps.setString(i++, nn(e.getBlockchainKey()));
|
||||
|
||||
ps.setLong(i++, e.getSizeLimit());
|
||||
@@ -191,20 +192,22 @@ public final class BlockchainStateDAO {
|
||||
*/
|
||||
public boolean tryIncreaseFileSizeWithinLimit(Connection c, String blockchainName, long deltaBytes, long nowMs) throws SQLException {
|
||||
String sql = """
|
||||
UPDATE blockchain_state
|
||||
UPDATE blockchain_state_store
|
||||
SET
|
||||
file_size_bytes = file_size_bytes + ?,
|
||||
updated_at_ms = ?
|
||||
WHERE
|
||||
blockchain_name = ?
|
||||
login = ? AND fork_number = ?
|
||||
AND (file_size_bytes + ?) <= size_limit
|
||||
""";
|
||||
|
||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||
ps.setLong(1, deltaBytes);
|
||||
ps.setLong(2, nowMs);
|
||||
ps.setString(3, blockchainName);
|
||||
ps.setLong(4, deltaBytes);
|
||||
ChainRef r=chainRef(blockchainName);
|
||||
ps.setString(3, r.login());
|
||||
ps.setInt(4, r.fork());
|
||||
ps.setLong(5, deltaBytes);
|
||||
return ps.executeUpdate() > 0;
|
||||
}
|
||||
}
|
||||
@@ -212,8 +215,8 @@ public final class BlockchainStateDAO {
|
||||
private BlockchainStateEntry mapRow(ResultSet rs) throws SQLException {
|
||||
BlockchainStateEntry e = new BlockchainStateEntry();
|
||||
|
||||
e.setBlockchainName(rs.getString("blockchain_name"));
|
||||
e.setLogin(rs.getString("login"));
|
||||
e.setForkNumber(rs.getInt("fork_number"));
|
||||
e.setBlockchainKey(rs.getString("blockchain_key"));
|
||||
|
||||
e.setSizeLimit(rs.getLong("size_limit"));
|
||||
@@ -227,6 +230,15 @@ public final class BlockchainStateDAO {
|
||||
return e;
|
||||
}
|
||||
|
||||
private record ChainRef(String login,int fork) {}
|
||||
private static ChainRef chainRef(String name) {
|
||||
if(name==null) throw new IllegalArgumentException("blockchainName is null");
|
||||
String s=name.trim(); int d=s.lastIndexOf('-');
|
||||
if(d<=0 || s.length()-d-1 != 3) throw new IllegalArgumentException("Bad blockchainName: "+name);
|
||||
try { int f=Integer.parseInt(s.substring(d+1)); if(f<1||f>999) throw new IllegalArgumentException("fork out of range"); return new ChainRef(s.substring(0,d),f); }
|
||||
catch(NumberFormatException e){ throw new IllegalArgumentException("Bad blockchainName: "+name,e); }
|
||||
}
|
||||
|
||||
private static void setBytesNullable(PreparedStatement ps, int index, byte[] b) throws SQLException {
|
||||
if (b != null) ps.setBytes(index, b);
|
||||
else ps.setNull(index, Types.BINARY);
|
||||
|
||||
@@ -23,9 +23,9 @@ public final class BlocksDAO {
|
||||
|
||||
public void insert(Connection c, BlockEntry e) throws SQLException {
|
||||
String sql = """
|
||||
INSERT INTO blocks (
|
||||
login,bch_name,block_number,msg_type,msg_sub_type,block_bytes,
|
||||
to_login,to_bch_name,to_block_number,to_block_hash,
|
||||
INSERT INTO blocks_store (
|
||||
login,fork_number,block_number,msg_type,msg_sub_type,block_bytes,
|
||||
to_login,to_fork_number,to_block_number,to_block_hash,
|
||||
block_hash,block_signature,data_item_id,
|
||||
arweave_publish_pending,arweave_published_at_ms,
|
||||
edited_by_block_number,line_code,prev_line_number,prev_line_hash,this_line_number
|
||||
@@ -34,13 +34,13 @@ public final class BlocksDAO {
|
||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||
int i = 1;
|
||||
ps.setString(i++, e.getLogin());
|
||||
ps.setString(i++, e.getBchName());
|
||||
ps.setInt(i++, e.getForkNumber());
|
||||
ps.setInt(i++, e.getBlockNumber());
|
||||
ps.setInt(i++, e.getMsgType());
|
||||
ps.setInt(i++, e.getMsgSubType());
|
||||
ps.setBytes(i++, e.getBlockBytes());
|
||||
setNullableString(ps, i++, e.getToLogin());
|
||||
setNullableString(ps, i++, e.getToBchName());
|
||||
setNullableInt(ps, i++, e.getToForkNumber());
|
||||
setNullableInt(ps, i++, e.getToBlockNumber());
|
||||
setNullableBytes(ps, i++, e.getToBlockHash());
|
||||
ps.setBytes(i++, e.getBlockHash());
|
||||
@@ -71,13 +71,13 @@ public final class BlocksDAO {
|
||||
public List<BlockEntry> listPendingArweave(int limit) throws SQLException {
|
||||
int safeLimit = Math.max(1, Math.min(limit, 100_000));
|
||||
String sql = """
|
||||
SELECT login,bch_name,block_number,msg_type,msg_sub_type,block_bytes,
|
||||
to_login,to_bch_name,to_block_number,to_block_hash,block_hash,block_signature,data_item_id,
|
||||
SELECT login,fork_number,block_number,msg_type,msg_sub_type,block_bytes,
|
||||
to_login,to_fork_number,to_block_number,to_block_hash,block_hash,block_signature,data_item_id,
|
||||
arweave_publish_pending,arweave_published_at_ms,
|
||||
edited_by_block_number,line_code,prev_line_number,prev_line_hash,this_line_number
|
||||
FROM blocks
|
||||
WHERE arweave_publish_pending = TRUE
|
||||
ORDER BY bch_name ASC, block_number ASC
|
||||
ORDER BY login ASC, fork_number ASC, block_number ASC
|
||||
LIMIT ?
|
||||
""";
|
||||
List<BlockEntry> out = new ArrayList<>();
|
||||
@@ -91,7 +91,7 @@ public final class BlocksDAO {
|
||||
public void markArweavePublished(List<byte[]> dataItemIds, long publishedAtMs) throws SQLException {
|
||||
if (dataItemIds == null || dataItemIds.isEmpty()) return;
|
||||
String sql = """
|
||||
UPDATE blocks
|
||||
UPDATE blocks_store
|
||||
SET arweave_publish_pending=FALSE, arweave_published_at_ms=?
|
||||
WHERE data_item_id=?
|
||||
""";
|
||||
@@ -108,30 +108,32 @@ public final class BlocksDAO {
|
||||
}
|
||||
|
||||
public byte[] getHashByNumber(Connection c, String bchName, int blockNumber) throws SQLException {
|
||||
try (PreparedStatement ps = c.prepareStatement("SELECT block_hash FROM blocks WHERE bch_name=? AND block_number=? LIMIT 1")) {
|
||||
ps.setString(1,bchName); ps.setInt(2,blockNumber);
|
||||
try (PreparedStatement ps = c.prepareStatement("SELECT block_hash FROM blocks WHERE login=? AND fork_number=? AND block_number=? LIMIT 1")) {
|
||||
ChainRef r=chainRef(bchName); ps.setString(1,r.login()); ps.setInt(2,r.fork()); ps.setInt(3,blockNumber);
|
||||
try (ResultSet rs=ps.executeQuery()) { return rs.next()?rs.getBytes(1):null; }
|
||||
}
|
||||
}
|
||||
public byte[] getHashByNumber(String bchName, int blockNumber) throws SQLException { try(Connection c=db.getConnection()){return getHashByNumber(c,bchName,blockNumber);} }
|
||||
|
||||
public BlockEntry getByNumber(Connection c, String bchName, int blockNumber) throws SQLException {
|
||||
String sql = baseSelect()+" WHERE bch_name=? AND block_number=? LIMIT 1";
|
||||
try(PreparedStatement ps=c.prepareStatement(sql)){ ps.setString(1,bchName); ps.setInt(2,blockNumber); try(ResultSet rs=ps.executeQuery()){return rs.next()?mapRow(rs):null;} }
|
||||
String sql = baseSelect()+" WHERE login=? AND fork_number=? AND block_number=? LIMIT 1";
|
||||
ChainRef r=chainRef(bchName);
|
||||
try(PreparedStatement ps=c.prepareStatement(sql)){ ps.setString(1,r.login()); ps.setInt(2,r.fork()); ps.setInt(3,blockNumber); try(ResultSet rs=ps.executeQuery()){return rs.next()?mapRow(rs):null;} }
|
||||
}
|
||||
public BlockEntry getByNumber(String bchName,int blockNumber)throws SQLException{try(Connection c=db.getConnection()){return getByNumber(c,bchName,blockNumber);} }
|
||||
|
||||
public List<BlockEntry> listRangeByNumber(String bchName,int from,int to)throws SQLException{try(Connection c=db.getConnection()){return listRangeByNumber(c,bchName,from,to);} }
|
||||
public List<BlockEntry> listRangeByNumber(Connection c,String bchName,int from,int to)throws SQLException{
|
||||
String sql=baseSelect()+" WHERE bch_name=? AND block_number>=? AND block_number<=? ORDER BY block_number ASC";
|
||||
String sql=baseSelect()+" WHERE login=? AND fork_number=? AND block_number>=? AND block_number<=? ORDER BY block_number ASC";
|
||||
List<BlockEntry> out=new ArrayList<>();
|
||||
try(PreparedStatement ps=c.prepareStatement(sql)){ps.setString(1,bchName);ps.setInt(2,from);ps.setInt(3,to);try(ResultSet rs=ps.executeQuery()){while(rs.next())out.add(mapRow(rs));}}
|
||||
ChainRef r=chainRef(bchName);
|
||||
try(PreparedStatement ps=c.prepareStatement(sql)){ps.setString(1,r.login());ps.setInt(2,r.fork());ps.setInt(3,from);ps.setInt(4,to);try(ResultSet rs=ps.executeQuery()){while(rs.next())out.add(mapRow(rs));}}
|
||||
return out;
|
||||
}
|
||||
|
||||
private static String baseSelect(){return """
|
||||
SELECT login,bch_name,block_number,msg_type,msg_sub_type,block_bytes,
|
||||
to_login,to_bch_name,to_block_number,to_block_hash,block_hash,block_signature,data_item_id,
|
||||
SELECT login,fork_number,block_number,msg_type,msg_sub_type,block_bytes,
|
||||
to_login,to_fork_number,to_block_number,to_block_hash,block_hash,block_signature,data_item_id,
|
||||
arweave_publish_pending,arweave_published_at_ms,
|
||||
edited_by_block_number,line_code,prev_line_number,prev_line_hash,this_line_number
|
||||
FROM blocks
|
||||
@@ -139,15 +141,27 @@ public final class BlocksDAO {
|
||||
|
||||
private BlockEntry mapRow(ResultSet rs)throws SQLException{
|
||||
BlockEntry e=new BlockEntry();
|
||||
e.setLogin(rs.getString("login")); e.setBchName(rs.getString("bch_name")); e.setBlockNumber(rs.getInt("block_number"));
|
||||
e.setLogin(rs.getString("login")); e.setForkNumber(rs.getInt("fork_number")); e.setBlockNumber(rs.getInt("block_number"));
|
||||
e.setMsgType(rs.getInt("msg_type")); e.setMsgSubType(rs.getInt("msg_sub_type")); e.setBlockBytes(rs.getBytes("block_bytes"));
|
||||
e.setToLogin(rs.getString("to_login")); e.setToBchName(rs.getString("to_bch_name")); e.setToBlockNumber((Integer)rs.getObject("to_block_number")); e.setToBlockHash(rs.getBytes("to_block_hash"));
|
||||
e.setToLogin(rs.getString("to_login")); e.setToForkNumber((Integer)rs.getObject("to_fork_number")); e.setToBlockNumber((Integer)rs.getObject("to_block_number")); e.setToBlockHash(rs.getBytes("to_block_hash"));
|
||||
e.setBlockHash(rs.getBytes("block_hash")); e.setBlockSignature(rs.getBytes("block_signature")); e.setDataItemId(rs.getBytes("data_item_id"));
|
||||
e.setArweavePublishPending(rs.getBoolean("arweave_publish_pending")); e.setArweavePublishedAtMs((Long)rs.getObject("arweave_published_at_ms"));
|
||||
e.setEditedByBlockNumber((Integer)rs.getObject("edited_by_block_number")); e.setLineCode((Integer)rs.getObject("line_code")); e.setPrevLineNumber((Integer)rs.getObject("prev_line_number")); e.setPrevLineHash(rs.getBytes("prev_line_hash")); e.setThisLineNumber((Integer)rs.getObject("this_line_number"));
|
||||
return e;
|
||||
}
|
||||
|
||||
private record ChainRef(String login, int fork) {}
|
||||
private static ChainRef chainRef(String name) {
|
||||
if (name == null) throw new IllegalArgumentException("blockchainName is null");
|
||||
String s=name.trim(); int dash=s.lastIndexOf('-');
|
||||
if (dash <= 0 || s.length()-dash-1 != 3) throw new IllegalArgumentException("Bad blockchainName: "+name);
|
||||
try {
|
||||
int fork=Integer.parseInt(s.substring(dash+1));
|
||||
if (fork < 1 || fork > 999) throw new IllegalArgumentException("fork out of range: "+name);
|
||||
return new ChainRef(s.substring(0,dash),fork);
|
||||
} catch(NumberFormatException ex){ throw new IllegalArgumentException("Bad blockchainName: "+name,ex); }
|
||||
}
|
||||
|
||||
private static void setNullableString(PreparedStatement ps,int i,String v)throws SQLException{if(v==null)ps.setNull(i,Types.VARCHAR);else ps.setString(i,v);}
|
||||
private static void setNullableInt(PreparedStatement ps,int i,Integer v)throws SQLException{if(v==null)ps.setNull(i,Types.INTEGER);else ps.setInt(i,v);}
|
||||
private static void setNullableBytes(PreparedStatement ps,int i,byte[] v)throws SQLException{if(v==null)ps.setNull(i,Types.BINARY);else ps.setBytes(i,v);}
|
||||
|
||||
@@ -39,12 +39,12 @@ public final class ChannelReadStateDAO {
|
||||
String sql = """
|
||||
SELECT read_count, unread_count, read_updated_at_ms, client_key, read_signature
|
||||
FROM channel_read_state
|
||||
WHERE LOWER(viewer_login)=LOWER(?) AND owner_bch_name=? AND channel_name=?
|
||||
WHERE LOWER(viewer_login)=LOWER(?) AND LOWER(owner_login)=LOWER(?) AND channel_name=?
|
||||
LIMIT 1
|
||||
""";
|
||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||
ps.setString(1, viewerLogin);
|
||||
ps.setString(2, ownerBchName);
|
||||
ps.setString(2, loginFromChainName(ownerBchName));
|
||||
ps.setString(3, channelName);
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
if (!rs.next()) return null;
|
||||
@@ -74,10 +74,10 @@ public final class ChannelReadStateDAO {
|
||||
JOIN connections_state cs
|
||||
ON LOWER(cs.login)=LOWER(crs.viewer_login)
|
||||
AND cs.rel_type=30
|
||||
AND cs.to_bch_name=cns.owner_bch_name
|
||||
AND LOWER(cs.to_login)=LOWER(cns.owner_login)
|
||||
AND COALESCE(cs.to_block_number,0)=cns.channel_root_block_number
|
||||
AND cs.to_block_hash=cns.channel_root_block_hash
|
||||
WHERE cns.owner_bch_name=crs.owner_bch_name
|
||||
WHERE LOWER(cns.owner_login)=LOWER(crs.owner_login)
|
||||
AND cns.slug=crs.channel_name
|
||||
AND cns.channel_type_code=1
|
||||
)
|
||||
@@ -101,7 +101,7 @@ public final class ChannelReadStateDAO {
|
||||
JOIN connections_state cs
|
||||
ON LOWER(cs.login)=LOWER(?)
|
||||
AND cs.rel_type=?
|
||||
AND cs.to_bch_name=cns.owner_bch_name
|
||||
AND LOWER(cs.to_login)=LOWER(cns.owner_login)
|
||||
AND COALESCE(cs.to_block_number,0)=cns.channel_root_block_number
|
||||
AND cs.to_block_hash=cns.channel_root_block_hash
|
||||
WHERE cns.owner_bch_name=?
|
||||
@@ -189,9 +189,10 @@ public final class ChannelReadStateDAO {
|
||||
read_count, unread_count,
|
||||
read_updated_at_ms, client_key, read_signature, updated_at_ms
|
||||
) VALUES (?, ?, ?, ?, ?, 0, ?, ?, ?, ?)
|
||||
ON CONFLICT (viewer_login, owner_bch_name, channel_name)
|
||||
ON CONFLICT (viewer_login, owner_login, channel_name)
|
||||
DO UPDATE SET
|
||||
owner_login = EXCLUDED.owner_login,
|
||||
owner_bch_name = EXCLUDED.owner_bch_name,
|
||||
unread_count = GREATEST(
|
||||
0,
|
||||
channel_read_state.unread_count -
|
||||
@@ -244,7 +245,7 @@ public final class ChannelReadStateDAO {
|
||||
UPDATE channel_read_state crs
|
||||
SET unread_count = crs.unread_count + 1,
|
||||
updated_at_ms = ?
|
||||
WHERE crs.owner_bch_name = ?
|
||||
WHERE LOWER(crs.owner_login)=LOWER(?)
|
||||
AND crs.channel_name = ?
|
||||
AND LOWER(crs.viewer_login) <> LOWER(crs.owner_login)
|
||||
AND EXISTS (
|
||||
@@ -253,10 +254,10 @@ public final class ChannelReadStateDAO {
|
||||
JOIN connections_state cs
|
||||
ON LOWER(cs.login)=LOWER(crs.viewer_login)
|
||||
AND cs.rel_type=?
|
||||
AND cs.to_bch_name=cns.owner_bch_name
|
||||
AND LOWER(cs.to_login)=LOWER(cns.owner_login)
|
||||
AND COALESCE(cs.to_block_number,0)=cns.channel_root_block_number
|
||||
AND cs.to_block_hash=cns.channel_root_block_hash
|
||||
WHERE cns.owner_bch_name=crs.owner_bch_name
|
||||
WHERE LOWER(cns.owner_login)=LOWER(crs.owner_login)
|
||||
AND cns.slug=crs.channel_name
|
||||
AND cns.channel_type_code=1
|
||||
)
|
||||
@@ -265,7 +266,7 @@ public final class ChannelReadStateDAO {
|
||||
List<String> affected = new ArrayList<>();
|
||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||
ps.setLong(1, nowMs);
|
||||
ps.setString(2, ownerBchName);
|
||||
ps.setString(2, loginFromChainName(ownerBchName));
|
||||
ps.setString(3, channelName);
|
||||
ps.setInt(4, followRelType);
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
@@ -282,17 +283,19 @@ public final class ChannelReadStateDAO {
|
||||
DELETE FROM channel_read_state crs
|
||||
USING channel_names_state cns
|
||||
WHERE LOWER(crs.viewer_login)=LOWER(?)
|
||||
AND crs.owner_bch_name=?
|
||||
AND cns.owner_bch_name=crs.owner_bch_name
|
||||
AND LOWER(crs.owner_login)=LOWER(?)
|
||||
AND LOWER(cns.owner_login)=LOWER(crs.owner_login)
|
||||
AND cns.slug=crs.channel_name
|
||||
AND cns.channel_root_block_number=?
|
||||
AND cns.channel_type_code=1
|
||||
""";
|
||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||
ps.setString(1, viewerLogin);
|
||||
ps.setString(2, ownerBchName);
|
||||
ps.setString(2, loginFromChainName(ownerBchName));
|
||||
ps.setInt(3, rootBlockNumber);
|
||||
return ps.executeUpdate() > 0;
|
||||
}
|
||||
}
|
||||
private static String loginFromChainName(String bch){ if(bch==null)return null; int d=bch.lastIndexOf('-'); return d>0?bch.substring(0,d):bch; }
|
||||
|
||||
}
|
||||
|
||||
@@ -39,19 +39,14 @@ public final class ConnectionsStateDAO {
|
||||
*/
|
||||
public List<String> listOutgoingByRelTypeCanonical(Connection c, String loginAnyCase, int relType) throws SQLException {
|
||||
String sql = """
|
||||
SELECT COALESCE(u_login.login, u_bch.login, cs.to_login) AS friend_login
|
||||
SELECT COALESCE(u_login.login, cs.to_login) AS friend_login
|
||||
FROM connections_state cs
|
||||
LEFT JOIN %s
|
||||
ON LOWER(u_login.login) = LOWER(cs.to_login)
|
||||
LEFT JOIN %s
|
||||
ON LOWER(u_bch.blockchain_name) = LOWER(cs.to_bch_name)
|
||||
WHERE LOWER(cs.login) = LOWER(?)
|
||||
AND cs.rel_type = ?
|
||||
ORDER BY friend_login
|
||||
""".formatted(
|
||||
CurrentUsersSql.usersSubquery("u_login"),
|
||||
CurrentUsersSql.usersSubquery("u_bch")
|
||||
);
|
||||
""".formatted(CurrentUsersSql.usersSubquery("u_login"));
|
||||
|
||||
List<String> out = new ArrayList<>();
|
||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||
@@ -73,19 +68,14 @@ public final class ConnectionsStateDAO {
|
||||
FROM connections_state cs
|
||||
LEFT JOIN %s
|
||||
ON LOWER(u_login.login) = LOWER(cs.to_login)
|
||||
LEFT JOIN %s
|
||||
ON LOWER(u_bch.blockchain_name) = LOWER(cs.to_bch_name)
|
||||
WHERE LOWER(cs.login) = LOWER(?)
|
||||
AND cs.rel_type = ?
|
||||
AND (
|
||||
LOWER(cs.to_login) = LOWER(?)
|
||||
OR LOWER(COALESCE(u_login.login, u_bch.login, cs.to_login)) = LOWER(?)
|
||||
OR LOWER(COALESCE(u_login.login, cs.to_login)) = LOWER(?)
|
||||
)
|
||||
LIMIT 1
|
||||
""".formatted(
|
||||
CurrentUsersSql.usersSubquery("u_login"),
|
||||
CurrentUsersSql.usersSubquery("u_bch")
|
||||
);
|
||||
""".formatted(CurrentUsersSql.usersSubquery("u_login"));
|
||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||
ps.setString(1, loginAnyCase);
|
||||
ps.setInt(2, relType);
|
||||
@@ -104,33 +94,12 @@ public final class ConnectionsStateDAO {
|
||||
String sql = """
|
||||
SELECT COALESCE(u_actor.login, cs.login) AS friend_login
|
||||
FROM connections_state cs
|
||||
LEFT JOIN %s
|
||||
ON LOWER(u_actor.login) = LOWER(cs.login)
|
||||
LEFT JOIN %s
|
||||
ON LOWER(u_target.login) = LOWER(?)
|
||||
WHERE (
|
||||
LOWER(cs.to_login) = LOWER(?)
|
||||
OR (u_target.blockchain_name IS NOT NULL AND LOWER(cs.to_bch_name) = LOWER(u_target.blockchain_name))
|
||||
)
|
||||
AND cs.rel_type = ?
|
||||
LEFT JOIN %s ON LOWER(u_actor.login)=LOWER(cs.login)
|
||||
WHERE LOWER(cs.to_login)=LOWER(?) AND cs.rel_type=?
|
||||
ORDER BY friend_login
|
||||
""".formatted(
|
||||
CurrentUsersSql.usersSubquery("u_actor"),
|
||||
CurrentUsersSql.usersSubquery("u_target")
|
||||
);
|
||||
|
||||
List<String> out = new ArrayList<>();
|
||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||
ps.setString(1, loginAnyCase);
|
||||
ps.setString(2, loginAnyCase);
|
||||
ps.setInt(3, relType);
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
while (rs.next()) {
|
||||
String v = rs.getString("friend_login");
|
||||
if (v != null) out.add(v);
|
||||
}
|
||||
}
|
||||
}
|
||||
""".formatted(CurrentUsersSql.usersSubquery("u_actor"));
|
||||
List<String> out=new ArrayList<>();
|
||||
try(PreparedStatement ps=c.prepareStatement(sql)){ ps.setString(1,loginAnyCase); ps.setInt(2,relType); try(ResultSet rs=ps.executeQuery()){while(rs.next()){String v=rs.getString("friend_login");if(v!=null)out.add(v);}}}
|
||||
return out;
|
||||
}
|
||||
|
||||
@@ -189,21 +158,17 @@ public final class ConnectionsStateDAO {
|
||||
}
|
||||
|
||||
String sql = """
|
||||
INSERT INTO connections_state (login, rel_type, to_login, to_bch_name, to_block_number, to_block_hash)
|
||||
VALUES (?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(login, rel_type, to_login, to_bch_name, to_block_number, to_block_hash) DO UPDATE SET
|
||||
to_bch_name=excluded.to_bch_name,
|
||||
to_block_number=excluded.to_block_number,
|
||||
to_block_hash=excluded.to_block_hash
|
||||
INSERT INTO connections_state (login, rel_type, to_login, to_block_number, to_block_hash)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
ON CONFLICT(login, rel_type, to_login, to_block_number, to_block_hash) DO NOTHING
|
||||
""";
|
||||
|
||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||
ps.setString(1, login);
|
||||
ps.setInt(2, relType);
|
||||
ps.setString(3, toLogin);
|
||||
ps.setString(4, toBchName);
|
||||
if (toBlockNumber == null) ps.setNull(5, java.sql.Types.INTEGER); else ps.setInt(5, toBlockNumber);
|
||||
ps.setBytes(6, toBlockHash);
|
||||
if (toBlockNumber == null) ps.setNull(4, java.sql.Types.INTEGER); else ps.setInt(4, toBlockNumber);
|
||||
ps.setBytes(5, toBlockHash);
|
||||
ps.executeUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -94,6 +94,7 @@ public final class SolanaUserPdaCurrentDAO {
|
||||
FROM solana_user_pda_current u
|
||||
CROSS JOIN LATERAL jsonb_array_elements(COALESCE(NULLIF(u.blockchain_forks_json, ''), '[]')::jsonb) AS fork_item(value)
|
||||
WHERE fork_item.value ->> 'blockchainKey' = ?
|
||||
AND ((fork_item.value ->> 'forkIndex')::integer + 1) BETWEEN 1 AND 999
|
||||
LIMIT 1
|
||||
""";
|
||||
try (Connection c = db.getConnection(); PreparedStatement ps = c.prepareStatement(sql)) {
|
||||
|
||||
@@ -106,11 +106,12 @@ public final class SubscriptionsDAO {
|
||||
WITH subs AS (
|
||||
-- 1) FOLLOW-каналы
|
||||
SELECT
|
||||
cs.to_login AS channel_login,
|
||||
cs.to_bch_name AS channel_bch_name
|
||||
cs.to_login AS channel_login,
|
||||
cn.owner_bch_name AS channel_bch_name
|
||||
FROM connections_state cs
|
||||
WHERE cs.login = ?
|
||||
AND cs.rel_type = ?
|
||||
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 cs.login = ? AND cs.rel_type = ?
|
||||
|
||||
UNION
|
||||
|
||||
|
||||
@@ -37,9 +37,8 @@ public final class UserProfileStateDAO {
|
||||
/**
|
||||
* Effective outgoing social relation with priority close_friend > friend > contact > none.
|
||||
*
|
||||
* Use the canonical relation lookup instead of comparing only connections_state.to_login:
|
||||
* older/current blocks may address a user by blockchain name, so a direct to_login-only
|
||||
* query can incorrectly report "none" even when ListContacts/Connections sees the relation.
|
||||
* Use the canonical relation lookup so all UI paths share the same normalized login matching.
|
||||
* Stage 2 connections_state identity is logical and no longer contains a physical target fork.
|
||||
*/
|
||||
public String getEffectiveRelationType(Connection c, String ownerLogin, String targetLogin) throws SQLException {
|
||||
if (ownerLogin == null || ownerLogin.isBlank() || targetLogin == null || targetLogin.isBlank()) return "none";
|
||||
@@ -124,7 +123,7 @@ public final class UserProfileStateDAO {
|
||||
} else if ("following".equals(mode)) {
|
||||
sql="""
|
||||
SELECT DISTINCT cn.owner_login, cn.slug, cn.display_name, cn.ava_ar, cn.owner_bch_name, cn.channel_root_block_number, encode(cn.channel_root_block_hash,'hex') root_hash
|
||||
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
|
||||
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(?) AND cs.rel_type=30 AND cn.channel_type_code=1
|
||||
ORDER BY cn.display_name, cn.slug LIMIT ? OFFSET ?
|
||||
""";
|
||||
|
||||
@@ -4,7 +4,7 @@ package shine.db.entities;
|
||||
* Запись блока (таблица blocks) — обновлённая модель под новый формат.
|
||||
*
|
||||
* Храним:
|
||||
* - login, bch_name (как было в проекте, чтобы не ломать общую БД)
|
||||
* - login + fork_number (physical fork identity; bch_name is derived only for display/API)
|
||||
* - block_number (глобальный номер в этой цепочке)
|
||||
* - block_bytes (полный блок: preimage + signature)
|
||||
* - block_hash (32 байта вычисленный SHA-256(preimage))
|
||||
@@ -21,7 +21,7 @@ package shine.db.entities;
|
||||
public class BlockEntry {
|
||||
|
||||
private String login;
|
||||
private String bchName;
|
||||
private int forkNumber;
|
||||
|
||||
private int blockNumber;
|
||||
|
||||
@@ -31,7 +31,7 @@ public class BlockEntry {
|
||||
private byte[] blockBytes;
|
||||
|
||||
private String toLogin;
|
||||
private String toBchName;
|
||||
private Integer toForkNumber;
|
||||
private Integer toBlockNumber;
|
||||
private byte[] toBlockHash;
|
||||
|
||||
@@ -55,8 +55,14 @@ public class BlockEntry {
|
||||
public String getLogin() { return login; }
|
||||
public void setLogin(String login) { this.login = login; }
|
||||
|
||||
public String getBchName() { return bchName; }
|
||||
public void setBchName(String bchName) { this.bchName = bchName; }
|
||||
public int getForkNumber() { return forkNumber; }
|
||||
public void setForkNumber(int forkNumber) { if (forkNumber < 1 || forkNumber > 999) throw new IllegalArgumentException("forkNumber must be 1..999"); this.forkNumber = forkNumber; }
|
||||
|
||||
/** Compatibility/display helper. DB does not store bch_name anymore. */
|
||||
public String getBchName() {
|
||||
if (login == null || login.isBlank() || forkNumber < 1 || forkNumber > 999) return null;
|
||||
return login + "-" + String.format("%03d", forkNumber);
|
||||
}
|
||||
|
||||
public int getBlockNumber() { return blockNumber; }
|
||||
public void setBlockNumber(int blockNumber) { this.blockNumber = blockNumber; }
|
||||
@@ -73,8 +79,14 @@ public class BlockEntry {
|
||||
public String getToLogin() { return toLogin; }
|
||||
public void setToLogin(String toLogin) { this.toLogin = toLogin; }
|
||||
|
||||
public String getToBchName() { return toBchName; }
|
||||
public void setToBchName(String toBchName) { this.toBchName = toBchName; }
|
||||
/** Derived historical display value only; never part of target identity. */
|
||||
public String getToBchName() {
|
||||
if (toLogin == null || toLogin.isBlank() || toForkNumber == null || toForkNumber < 1 || toForkNumber > 999) return null;
|
||||
return toLogin + "-" + String.format("%03d", toForkNumber);
|
||||
}
|
||||
|
||||
public Integer getToForkNumber() { return toForkNumber; }
|
||||
public void setToForkNumber(Integer toForkNumber) { if (toForkNumber != null && (toForkNumber < 0 || toForkNumber > 999)) throw new IllegalArgumentException("toForkNumber must be 0..999"); this.toForkNumber = toForkNumber; }
|
||||
|
||||
public Integer getToBlockNumber() { return toBlockNumber; }
|
||||
public void setToBlockNumber(Integer toBlockNumber) { this.toBlockNumber = toBlockNumber; }
|
||||
|
||||
+17
-3
@@ -16,8 +16,8 @@ import java.util.Base64;
|
||||
*/
|
||||
public final class BlockchainStateEntry {
|
||||
|
||||
private String blockchainName;
|
||||
private String login;
|
||||
private int forkNumber;
|
||||
|
||||
private String blockchainKey; // Base64(32)
|
||||
|
||||
@@ -31,8 +31,22 @@ public final class BlockchainStateEntry {
|
||||
|
||||
public BlockchainStateEntry() {}
|
||||
|
||||
public String getBlockchainName() { return blockchainName; }
|
||||
public void setBlockchainName(String blockchainName) { this.blockchainName = blockchainName; }
|
||||
public String getBlockchainName() {
|
||||
if (login == null || login.isBlank() || forkNumber < 1 || forkNumber > 999) return null;
|
||||
return login + "-" + String.format("%03d", forkNumber);
|
||||
}
|
||||
/** Compatibility setter for API/import code; DB stores login + forkNumber. */
|
||||
public void setBlockchainName(String blockchainName) {
|
||||
if (blockchainName == null) return;
|
||||
int dash=blockchainName.lastIndexOf('-');
|
||||
if (dash <= 0 || blockchainName.length()-dash-1 != 3) throw new IllegalArgumentException("Bad blockchainName: "+blockchainName);
|
||||
int parsedFork=Integer.parseInt(blockchainName.substring(dash+1));
|
||||
if (parsedFork < 1 || parsedFork > 999) throw new IllegalArgumentException("forkNumber must be 1..999");
|
||||
this.login=blockchainName.substring(0,dash);
|
||||
this.forkNumber=parsedFork;
|
||||
}
|
||||
public int getForkNumber() { return forkNumber; }
|
||||
public void setForkNumber(int forkNumber) { if (forkNumber < 1 || forkNumber > 999) throw new IllegalArgumentException("forkNumber must be 1..999"); this.forkNumber = forkNumber; }
|
||||
|
||||
public String getLogin() { return login; }
|
||||
public void setLogin(String login) { this.login = login; }
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
-- SHiNE PostgreSQL runtime schema v1
|
||||
-- Дата: 2026-07-28
|
||||
-- SHiNE PostgreSQL database format v2 / runtime schema revision 29
|
||||
-- Stage 2 baseline. This file is only for a NEW, EMPTY database.
|
||||
-- Дата: 2026-09-29
|
||||
--
|
||||
-- Назначение:
|
||||
-- - поднять пустую PostgreSQL БД сервера SHiNE с нуля;
|
||||
@@ -15,14 +16,42 @@
|
||||
|
||||
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, 26, CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT))
|
||||
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;
|
||||
@@ -494,6 +523,7 @@ CREATE TABLE IF NOT EXISTS blocks (
|
||||
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,
|
||||
@@ -2184,8 +2214,330 @@ ALTER TABLE solana_user_pda_current
|
||||
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);
|
||||
BEGIN
|
||||
IF p_login IS NULL OR btrim(p_login)='' 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),
|
||||
(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),
|
||||
(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;
|
||||
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;
|
||||
IF NEW.prev_line_number=NEW.line_code THEN
|
||||
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 prev_block.this_line_number IS NULL THEN RAISE EXCEPTION 'LINE_ERR_THIS_LINE_BAD_STEP'; END IF;
|
||||
IF NEW.msg_type=1 THEN
|
||||
IF NEW.this_line_number<>prev_block.this_line_number AND NEW.this_line_number<>prev_block.this_line_number+1 THEN RAISE EXCEPTION 'LINE_ERR_THIS_LINE_BAD_STEP'; END IF;
|
||||
ELSE
|
||||
IF NEW.this_line_number<>prev_block.this_line_number+1 THEN RAISE EXCEPTION 'LINE_ERR_THIS_LINE_BAD_STEP'; END IF;
|
||||
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=NEW.login AND rel_type=NEW.msg_sub_type AND to_login=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(NEW.login,NEW.msg_sub_type,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=NEW.login AND rel_type=positive_rel_type AND to_login=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(NEW.login);
|
||||
PERFORM shine_refresh_user_stats(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(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=NEW.login AND reaction_type=1 AND to_login=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=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=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(NEW.login,1,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(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();
|
||||
|
||||
INSERT INTO db_schema_version(id,schema_version,updated_at_ms)
|
||||
VALUES(1,27,CAST(EXTRACT(EPOCH FROM clock_timestamp())*1000 AS BIGINT))
|
||||
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;
|
||||
|
||||
COMMIT;
|
||||
|
||||
Reference in New Issue
Block a user