Guest User

Untitled

a guest
Feb 15th, 2024
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.79 KB | None | 0 0
  1. import time,psycopg2,random,sys
  2.  
  3. def query(s,*args,**kwargs):
  4.     print(s)
  5.     try:
  6.         c.execute( s,*args,**kwargs )
  7.         print( "%d rows" % c.rowcount )
  8.     except Exception as e:
  9.         print(e)
  10.         query("ROLLBACK")
  11.         sys.exit(-1)
  12.  
  13. def drop():
  14.     query( "DROP TABLE IF EXISTS sales CASCADE" );
  15.     query("COMMIT")
  16.  
  17. def build():
  18.     query( """create table if not exists sales
  19. (
  20.    category_a  smallint,    -- sequential integer values from 0 - 10000
  21.    category_b  varchar(3),  -- 3-digit ids (all numeric, padded with zeros)
  22.    product     varchar(14), -- essentially random 14 character identifiers
  23.    location_id varchar(5),  -- location id, 5-digit number (left padded with zeros)
  24.    units       int,         -- value of interest
  25.    sales       float       -- second value of interest
  26. ) partition by range (category_a);""" )
  27.     for part in range(1,51):
  28.         query("""CREATE UNLOGGED TABLE sales_a%03d PARTITION OF sales
  29.    FOR VALUES FROM (%s) TO (%s);"""%(part,part,part+1))
  30.  
  31. def fill():
  32.     query( """insert into sales
  33.    (category_a, category_b, product, location_id, units, sales)
  34. select cat_a,
  35.       lpad(cat_b::varchar, 3, '0'),
  36.       lpad(product::varchar, 14, '0'),
  37.       lpad(location_id::varchar, 5, '0'),
  38.       (random() * 10000)::int,
  39.       (random() * 100000)::int
  40. from generate_series(1, 50) cat_a
  41.         cross join generate_series(1, 25) cat_b
  42.         cross join generate_series(1, 10) location_id
  43.         cross join generate_series(1, 5000) product;""")
  44.  
  45. db = psycopg2.connect("dbname=test")
  46. c = db.cursor()
  47. if 1:
  48.     drop()
  49.     build()
  50.     fill()
  51.     query("COMMIT")
  52.     query("ALTER TABLE sales ADD primary key (category_a, category_b, product, location_id)")
  53.     query("COMMIT")
  54.     query("VACUUM ANALYZE sales" )
  55.  
  56.  
Advertisement
Add Comment
Please, Sign In to add comment