lbry-sdk/lbry/db/queries/base.py

82 lines
2.3 KiB
Python
Raw Normal View History

from sqlalchemy import text, between
2020-07-11 18:18:33 -04:00
from sqlalchemy.future import select
from ..query_context import context
from ..tables import (
SCHEMA_VERSION, metadata, Version,
2020-12-28 10:34:08 -05:00
Claim, Support, Block, TX,
2020-10-21 16:48:40 -04:00
pg_add_account_address_constraints_and_indexes
)
2020-07-11 18:18:33 -04:00
def execute(sql):
return context().execute(text(sql))
def execute_sql_object(sql):
return context().execute(sql)
2020-07-11 18:18:33 -04:00
def execute_fetchall(sql):
return context().fetchall(text(sql))
def has_claims():
return context().has_records(Claim)
def has_supports():
return context().has_records(Support)
def get_best_block_height():
return context().fetchmax(Block.c.height, -1)
2020-07-11 18:18:33 -04:00
def insert_block(block):
2020-12-16 10:54:39 -05:00
context().get_bulk_loader().add_block(block).flush(return_row_count_for_table=None)
2020-07-11 18:18:33 -04:00
2020-10-16 12:52:57 -04:00
def get_block_headers(first, last=None):
if last is not None:
query = (
select('*').select_from(Block)
.where(between(Block.c.height, first, last))
.order_by(Block.c.height)
)
else:
query = select('*').select_from(Block).where(Block.c.height == first)
return context().fetchall(query)
2020-07-11 18:18:33 -04:00
def insert_transaction(block_hash, tx):
2020-08-20 13:31:58 -04:00
context().get_bulk_loader().add_transaction(block_hash, tx).flush(TX)
2020-07-11 18:18:33 -04:00
def check_version_and_create_tables():
with context("db.connecting") as ctx:
if ctx.has_table('version'):
version = ctx.fetchone(select(Version.c.version).limit(1))
if version and version['version'] == SCHEMA_VERSION:
return
metadata.drop_all(ctx.engine)
metadata.create_all(ctx.engine)
ctx.execute(Version.insert().values(version=SCHEMA_VERSION))
for table in metadata.sorted_tables:
disable_trigger_and_constraints(table.name)
2020-10-21 16:48:40 -04:00
if ctx.is_postgres:
2020-12-08 18:34:40 -03:00
for statement in pg_add_account_address_constraints_and_indexes:
ctx.execute(text(statement))
2020-07-11 18:18:33 -04:00
def disable_trigger_and_constraints(table_name):
ctx = context()
if ctx.is_postgres:
ctx.execute(text(f"ALTER TABLE {table_name} DISABLE TRIGGER ALL;"))
2020-12-28 10:34:08 -05:00
if table_name in ('tag', 'stake', 'block_filter', 'mempool_filter'):
2020-07-11 18:18:33 -04:00
return
if ctx.is_postgres:
ctx.execute(text(
f"ALTER TABLE {table_name} DROP CONSTRAINT {table_name}_pkey CASCADE;"
))