import asyncio
import pathlib
import psycopg2
from faker import Factory

import aiohttpdemo_polls.db as db
from aiohttpdemo_polls.utils import init_postgres
from sqlalchemy.schema import CreateTable, DropTable, DropConstraint


PROJ_ROOT = pathlib.Path(__file__).parent.parent

conf = {"host": "127.0.0.1",
        "port": 8080,
        "postgres": {
            "database": "aiohttp_admin_polls",
            "user": "aiohttp_admin",
            "password": "mysecretpassword",
            "host": "192.168.99.100",
            "port": 5432,
            "minsize": 1,
            "maxsize": 5}
        }


async def preapre_tables(pg):
    tables = [db.choice, db.question]
    async with pg.acquire() as conn:
        for table in tables:
            drop_expr = DropTable(table)
            create_expr = CreateTable(table)
            for c in table.constraints:
                dc = DropConstraint(c)
                try:
                    await conn.execute(dc)
                except psycopg2.ProgrammingError:
                    pass
            try:
                await conn.execute(drop_expr)
            except psycopg2.ProgrammingError:
                pass
            await conn.execute(create_expr)


async def init(loop):
    print("Generating Fake Data")
    pg = await init_postgres(conf['postgres'], loop)
    fake = Factory.create()
    fake.seed(1234)
    await preapre_tables(pg)

    values = []
    rows = 100000
    for i in range(rows):
        values.append({
            'question_text': fake.sentence(nb_words=10)[:200],
            'pub_date': fake.iso8601(),
        })

    query = db.question.insert().values(values)
    async with pg.acquire() as conn:
        await conn.execute(query)

    async with pg.acquire() as conn:
        query = db.question.select()
        resp = await conn.execute(query)
        values = []
        for q in list(resp):
            for i in range(5):
                values.append({
                    'question_id': q['id'],
                    'choice_text': fake.sentence(nb_words=10)[:200],
                    'votes': i})

        await conn.execute(db.choice.insert().values(values))

    pg.close()
    await pg.wait_closed()


def main():
    loop = asyncio.get_event_loop()
    loop.run_until_complete(init(loop))

if __name__ == "__main__":
    main()

@@ -27,24 +27,8 @@
 lib%0A
-import psycopg2%0A
 from
@@ -179,35 +179,8 @@
 able
-, DropTable, DropConstraint
 %0A%0A%0AP
@@ -339,22 +339,16 @@
 tp_admin
-_polls
 %22,%0A     
@@ -368,32 +368,37 @@
 : %22aiohttp_admin
+_user
 %22,%0A            %22
@@ -454,21 +454,16 @@
 : %221
-92.168.99.100
+27.0.0.1
 %22,%0A 
@@ -689,49 +689,8 @@
 es:%0A
-            drop_expr = DropTable(table)%0A
     
@@ -746,230 +746,189 @@
     
-for c in table.constraints:%0A                dc = DropConstraint(c)%0A                try:%0A                    await conn.execute(dc)%0A                except psycopg2.ProgrammingError:%0A                    pass%0A            try:
+await conn.execute(create_expr)%0A%0A%0Aasync def insert_data(pg, table, values):%0A    async with pg.acquire() as conn:%0A        query = db.tag.insert().values(values).returning(table.c.id)
 %0A   
@@ -928,31 +928,32 @@
 id)%0A        
-       
+cursor =
  await conn.
@@ -964,17 +964,13 @@
 ute(
-drop_expr
+query
 )%0A  
@@ -979,333 +979,124 @@
     
-    except psycopg2.ProgrammingError:%0A                pass%0A            await conn.execute(create_expr)%0A%0A%0Aasync def init(loop):%0A    print(%22Generating Fake Data%22)%0A    pg = await init_postgres(conf%5B'postgres'%5D, loop)%0A    fake = Factory.create()%0A    fake.seed(1234)%0A    await preapre_tables(pg)%0A%0A    values = %5B%5D%0A    rows = 100000
+resp = await cursor.fetchall()%0A    return list(resp)%0A%0A%0Aasync def generate_questions(pg, rows, fake):%0A    values = %5B%5D
 %0A   
@@ -1260,248 +1260,136 @@
  %7D)%0A
-%0A
     
-query = db.question.insert().values(values)%0A    async with pg.acquire() as conn:%0A        await conn.execute(query)%0A%0A    async with pg.acquire() as conn:%0A        query = db.question.select()%0A        resp = await conn.execute(query)%0A    
+ids = await insert_data(pg, db.question, values)%0A    return ids%0A%0A%0Aasync def generate_choices(pg, rows, fake, question_ids):%0A
     
@@ -1408,37 +1408,34 @@
     
-  
-  
 for q
+_id
  in 
-list(resp):%0A    
+question_ids:%0A
     
@@ -1453,17 +1453,20 @@
 n range(
-5
+rows
 ):%0A     
@@ -1468,28 +1468,24 @@
             
-    
 values.appen
@@ -1480,36 +1480,32 @@
 values.append(%7B%0A
-    
                 
@@ -1524,20 +1524,13 @@
 ': q
-%5B'id'%5D,%0A    
+_id,%0A
     
@@ -1606,20 +1606,16 @@
         
-   
- 
 'votes':
@@ -1623,69 +1623,443 @@
 i%7D)%0A
-%0A        await conn.execute(db.choice.insert().values(values)
+    ids = await insert_data(pg, db.choice, values)%0A    return ids%0A%0A%0Aasync def init(loop):%0A    print(%22Generating Fake Data%22)%0A    pg = await init_postgres(conf%5B'postgres'%5D, loop)%0A    fake = Factory.create()%0A    fake.seed(1234)%0A    await preapre_tables(pg)%0A%0A    quiestion_num = 100000%0A    choices_num = 5%0A    question_ids = await generate_questions(pg, quiestion_num, fake)%0A    await generate_questions(pg, choices_num, fake, question_ids
 )%0A%0A 

clean up data generator for polls demo