asyncpg fetch feedback (python)











up vote
2
down vote

favorite












I have been using psycopg2 to manage items in my PostgreSQL database. Recently someone suggested that I could improve my database transactions by using asyncio and asyncpg in my code. I have looked around Stack Overflow and read though the documentation for examples. I have been able to create tables and insert records, but I haven't been able to get the execution feedback that I desire.



For example in my psycopg2 code, I can verify that a table exists or doesn't exist prior to inserting records.



def table_exists(self, verify_table_existence, name):
'''Verifies the existence of a table within the PostgreSQL database'''
try:
self.cursor.execute(verify_table_existence, name)

answer = self.cursor.fetchone()[0]

if answer == True:
print('The table - {} - exists'.format(name))
return True
else:
print ('The table - {} - does NOT exist'.format(name))
return False

except Exception as error:

logger.info('An error has occurred while trying to verify the existence of the table {}'.format(name))
logger.info('Error message: {}').format(error)
sys.exit(1)


I haven't been able to get the same feedback using asyncpg. How do I accomplish this?



import asyncpg
import asyncio

async def main():
conn = await asyncpg.connect('postgresql://postgres:mypassword@localhost:5432/mydatabase')

answer = await conn.fetch('''
SELECT EXISTS (
SELECT 1
FROM pg_tables
WHERE schemaname = 'public'
AND tablename = 'test01'
); ''')

await conn.close()

#####################
# the fetch returns
# [<Record exists=True>]
# but prints 'The table does NOT exist'
#####################

if answer == True:
print('The table exists')
else:
print('The table does NOT exist')


asyncio.get_event_loop().run_until_complete(main())









share|improve this question




















  • 1




    You used fetchone()[0] with psycopg2, but just fetch(...) with asyncpg. The former will retrieve the first column of the first row, while the latter will retrieve a whole list of rows. Being a list, it doesn't compare as equal to True. Try using answer = await conn.fetchval(...) instead.
    – user4815162342
    Nov 6 at 5:30










  • Thanks that worked.
    – Life is complex
    Nov 6 at 9:54










  • Glad to hear! I've now reposted it as an answer.
    – user4815162342
    Nov 6 at 18:48















up vote
2
down vote

favorite












I have been using psycopg2 to manage items in my PostgreSQL database. Recently someone suggested that I could improve my database transactions by using asyncio and asyncpg in my code. I have looked around Stack Overflow and read though the documentation for examples. I have been able to create tables and insert records, but I haven't been able to get the execution feedback that I desire.



For example in my psycopg2 code, I can verify that a table exists or doesn't exist prior to inserting records.



def table_exists(self, verify_table_existence, name):
'''Verifies the existence of a table within the PostgreSQL database'''
try:
self.cursor.execute(verify_table_existence, name)

answer = self.cursor.fetchone()[0]

if answer == True:
print('The table - {} - exists'.format(name))
return True
else:
print ('The table - {} - does NOT exist'.format(name))
return False

except Exception as error:

logger.info('An error has occurred while trying to verify the existence of the table {}'.format(name))
logger.info('Error message: {}').format(error)
sys.exit(1)


I haven't been able to get the same feedback using asyncpg. How do I accomplish this?



import asyncpg
import asyncio

async def main():
conn = await asyncpg.connect('postgresql://postgres:mypassword@localhost:5432/mydatabase')

answer = await conn.fetch('''
SELECT EXISTS (
SELECT 1
FROM pg_tables
WHERE schemaname = 'public'
AND tablename = 'test01'
); ''')

await conn.close()

#####################
# the fetch returns
# [<Record exists=True>]
# but prints 'The table does NOT exist'
#####################

if answer == True:
print('The table exists')
else:
print('The table does NOT exist')


asyncio.get_event_loop().run_until_complete(main())









share|improve this question




















  • 1




    You used fetchone()[0] with psycopg2, but just fetch(...) with asyncpg. The former will retrieve the first column of the first row, while the latter will retrieve a whole list of rows. Being a list, it doesn't compare as equal to True. Try using answer = await conn.fetchval(...) instead.
    – user4815162342
    Nov 6 at 5:30










  • Thanks that worked.
    – Life is complex
    Nov 6 at 9:54










  • Glad to hear! I've now reposted it as an answer.
    – user4815162342
    Nov 6 at 18:48













up vote
2
down vote

favorite









up vote
2
down vote

favorite











I have been using psycopg2 to manage items in my PostgreSQL database. Recently someone suggested that I could improve my database transactions by using asyncio and asyncpg in my code. I have looked around Stack Overflow and read though the documentation for examples. I have been able to create tables and insert records, but I haven't been able to get the execution feedback that I desire.



For example in my psycopg2 code, I can verify that a table exists or doesn't exist prior to inserting records.



def table_exists(self, verify_table_existence, name):
'''Verifies the existence of a table within the PostgreSQL database'''
try:
self.cursor.execute(verify_table_existence, name)

answer = self.cursor.fetchone()[0]

if answer == True:
print('The table - {} - exists'.format(name))
return True
else:
print ('The table - {} - does NOT exist'.format(name))
return False

except Exception as error:

logger.info('An error has occurred while trying to verify the existence of the table {}'.format(name))
logger.info('Error message: {}').format(error)
sys.exit(1)


I haven't been able to get the same feedback using asyncpg. How do I accomplish this?



import asyncpg
import asyncio

async def main():
conn = await asyncpg.connect('postgresql://postgres:mypassword@localhost:5432/mydatabase')

answer = await conn.fetch('''
SELECT EXISTS (
SELECT 1
FROM pg_tables
WHERE schemaname = 'public'
AND tablename = 'test01'
); ''')

await conn.close()

#####################
# the fetch returns
# [<Record exists=True>]
# but prints 'The table does NOT exist'
#####################

if answer == True:
print('The table exists')
else:
print('The table does NOT exist')


asyncio.get_event_loop().run_until_complete(main())









share|improve this question















I have been using psycopg2 to manage items in my PostgreSQL database. Recently someone suggested that I could improve my database transactions by using asyncio and asyncpg in my code. I have looked around Stack Overflow and read though the documentation for examples. I have been able to create tables and insert records, but I haven't been able to get the execution feedback that I desire.



For example in my psycopg2 code, I can verify that a table exists or doesn't exist prior to inserting records.



def table_exists(self, verify_table_existence, name):
'''Verifies the existence of a table within the PostgreSQL database'''
try:
self.cursor.execute(verify_table_existence, name)

answer = self.cursor.fetchone()[0]

if answer == True:
print('The table - {} - exists'.format(name))
return True
else:
print ('The table - {} - does NOT exist'.format(name))
return False

except Exception as error:

logger.info('An error has occurred while trying to verify the existence of the table {}'.format(name))
logger.info('Error message: {}').format(error)
sys.exit(1)


I haven't been able to get the same feedback using asyncpg. How do I accomplish this?



import asyncpg
import asyncio

async def main():
conn = await asyncpg.connect('postgresql://postgres:mypassword@localhost:5432/mydatabase')

answer = await conn.fetch('''
SELECT EXISTS (
SELECT 1
FROM pg_tables
WHERE schemaname = 'public'
AND tablename = 'test01'
); ''')

await conn.close()

#####################
# the fetch returns
# [<Record exists=True>]
# but prints 'The table does NOT exist'
#####################

if answer == True:
print('The table exists')
else:
print('The table does NOT exist')


asyncio.get_event_loop().run_until_complete(main())






python-3.x postgresql python-asyncio asyncpg






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 5 at 23:20

























asked Nov 5 at 17:23









Life is complex

14317




14317








  • 1




    You used fetchone()[0] with psycopg2, but just fetch(...) with asyncpg. The former will retrieve the first column of the first row, while the latter will retrieve a whole list of rows. Being a list, it doesn't compare as equal to True. Try using answer = await conn.fetchval(...) instead.
    – user4815162342
    Nov 6 at 5:30










  • Thanks that worked.
    – Life is complex
    Nov 6 at 9:54










  • Glad to hear! I've now reposted it as an answer.
    – user4815162342
    Nov 6 at 18:48














  • 1




    You used fetchone()[0] with psycopg2, but just fetch(...) with asyncpg. The former will retrieve the first column of the first row, while the latter will retrieve a whole list of rows. Being a list, it doesn't compare as equal to True. Try using answer = await conn.fetchval(...) instead.
    – user4815162342
    Nov 6 at 5:30










  • Thanks that worked.
    – Life is complex
    Nov 6 at 9:54










  • Glad to hear! I've now reposted it as an answer.
    – user4815162342
    Nov 6 at 18:48








1




1




You used fetchone()[0] with psycopg2, but just fetch(...) with asyncpg. The former will retrieve the first column of the first row, while the latter will retrieve a whole list of rows. Being a list, it doesn't compare as equal to True. Try using answer = await conn.fetchval(...) instead.
– user4815162342
Nov 6 at 5:30




You used fetchone()[0] with psycopg2, but just fetch(...) with asyncpg. The former will retrieve the first column of the first row, while the latter will retrieve a whole list of rows. Being a list, it doesn't compare as equal to True. Try using answer = await conn.fetchval(...) instead.
– user4815162342
Nov 6 at 5:30












Thanks that worked.
– Life is complex
Nov 6 at 9:54




Thanks that worked.
– Life is complex
Nov 6 at 9:54












Glad to hear! I've now reposted it as an answer.
– user4815162342
Nov 6 at 18:48




Glad to hear! I've now reposted it as an answer.
– user4815162342
Nov 6 at 18:48












1 Answer
1






active

oldest

votes

















up vote
1
down vote



accepted










You used fetchone()[0] with psycopg2, but just fetch(...) with asyncpg. The former will retrieve the first column of the first row, while the latter will retrieve a whole list of rows. Being a list, it doesn't compare as equal to True.



To fetch a single value from a single row, use something like answer = await conn.fetchval(...).






share|improve this answer





















    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














     

    draft saved


    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53159231%2fasyncpg-fetch-feedback-python%23new-answer', 'question_page');
    }
    );

    Post as a guest
































    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    1
    down vote



    accepted










    You used fetchone()[0] with psycopg2, but just fetch(...) with asyncpg. The former will retrieve the first column of the first row, while the latter will retrieve a whole list of rows. Being a list, it doesn't compare as equal to True.



    To fetch a single value from a single row, use something like answer = await conn.fetchval(...).






    share|improve this answer

























      up vote
      1
      down vote



      accepted










      You used fetchone()[0] with psycopg2, but just fetch(...) with asyncpg. The former will retrieve the first column of the first row, while the latter will retrieve a whole list of rows. Being a list, it doesn't compare as equal to True.



      To fetch a single value from a single row, use something like answer = await conn.fetchval(...).






      share|improve this answer























        up vote
        1
        down vote



        accepted







        up vote
        1
        down vote



        accepted






        You used fetchone()[0] with psycopg2, but just fetch(...) with asyncpg. The former will retrieve the first column of the first row, while the latter will retrieve a whole list of rows. Being a list, it doesn't compare as equal to True.



        To fetch a single value from a single row, use something like answer = await conn.fetchval(...).






        share|improve this answer












        You used fetchone()[0] with psycopg2, but just fetch(...) with asyncpg. The former will retrieve the first column of the first row, while the latter will retrieve a whole list of rows. Being a list, it doesn't compare as equal to True.



        To fetch a single value from a single row, use something like answer = await conn.fetchval(...).







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 6 at 18:47









        user4815162342

        58.3k487138




        58.3k487138






























             

            draft saved


            draft discarded



















































             


            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53159231%2fasyncpg-fetch-feedback-python%23new-answer', 'question_page');
            }
            );

            Post as a guest




















































































            這個網誌中的熱門文章

            Hercules Kyvelos

            Tangent Lines Diagram Along Smooth Curve

            Yusuf al-Mu'taman ibn Hud