Reputation: 504
I am trying to do a continous integration with timescaleDB but is impossible to create a materialized view directly from my code i get the error:
ERROR: CREATE MATERIALIZED VIEW ... WITH DATA cannot run inside a transaction block
Is it possible for me to setup the view directly from my code? Instead of using the terminal to create the view?
sql_create_table = """
CREATE TABLE IF NOT EXISTS bin1s (
time TIMESTAMP,
symbol VARCHAR(50),
price NUMERIC,
qty INTEGER
);
"""
sql_aggregate = """
CREATE MATERIALIZED VIEW ohlc_data_minute
WITH (timescaledb.continuous) AS
SELECT symbol,
time_bucket(INTERVAL '1 minute', time) AS date,
FIRST(price, time) as open,
MAX(price) as high,
MIN(price) as low,
LAST(price, time) as close,
SUM(qty) as volume
FROM bin1s
GROUP BY symbol, date;
"""
sql_create_hypertable = "SELECT create_hypertable('bin1s', 'time');"
sql_create_index = "CREATE INDEX IF NOT EXISTS ix_symbol_time ON bin1s (symbol, time DESC);"
async def connect_to_database():
while True:
try:
await asyncio.sleep(1)
connection = psycopg2.connect(user="postgres", password="password", host="timescaledb", port="5432", database="postgres")
cursor = connection.cursor()
cursor.execute("SELECT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'bin1s')")
table_exists = cursor.fetchone()[0]
if not table_exists:
cursor.execute(sql_create_table)
cursor.execute(sql_create_hypertable)
cursor.execute(sql_create_index)
connection.commit()
cursor.execute(sql_aggregate)
connection.commit()
print("Table 'bin1s' created successfully!")
else:
print("Table 'bin1s' already exists. Skipping table creation.")
print("Database setup successful")
return cursor, connection
except psycopg2.Error as e:
print(f"Error connecting to database: {e}")
print("Retrying in 1 second...")
# Retry after 1 second
await asyncio.sleep(1)
Upvotes: 0
Views: 56