问题
Intro: I have been working on building a Python backed PostgreSQL database of a Swiss style tournament using Vagrant running a Ubuntu VM for my Relational Database course in Udacity.
Question: Why does it say the table does not exist when I attempt to delete the information within the existing table?
I did a generic search to research
psycopg2.ProgrammingError
, but the information is mostly specific to other circumstances, and I was unable to make logical connections that would allow me fix this problem. I also found another Stack Overflow thread that is close to the same issue other thread here, however that issue was also never resolved. So I have created this question attempting to find someone capable of understanding my conundrum and provide some kind of hint or clue to get me working in the right direction.
I have imported the tournament database SQL file into the Vagrant VM. This deleted the two tables (players and matches) and the database (tournament) and then recreates this database and these tables. So I know the table (matches) exists. However, this is what I am getting...
Vagrant: (current vagrant error)
vagrant@vagrant:/vagrant/tournament$ python tournament_test.py
Traceback (most recent call last):
File "tournament_test.py", line 151, in <module>
testCount()
File "tournament_test.py", line 17, in testCount
deleteMatches()
File "/vagrant/tournament/tournament.py", line 18, in deleteMatches
cursor.execute("DELETE FROM matches;")
psycopg2.ProgrammingError: relation "matches" does not exist
LINE 1: DELETE FROM matches;
^
SQL: (All from tournament.sql)
-- Table definitions for the tournament project.
--
-- Put your SQL 'create table' statements in this file; also 'create view'
-- statements if you choose to use it.
--
-- You can write comments in this file by starting them with two dashes,
like
-- these lines here.
DROP TABLE matches;
DROP TABLE players;
DROP DATABASE tournament;
CREATE DATABASE tournament;
CREATE TABLE players (player_id SERIAL UNIQUE PRIMARY KEY, name
VARCHAR(40));
CREATE TABLE matches (match_id SERIAL UNIQUE PRIMARY KEY,
winner INTEGER REFERENCES players(player_id),
loser INTEGER REFERENCES players (player_id));
Python: (Minimal from tournament.py)
#!/usr/bin/env python
#
# tournament.py -- implementation of a Swiss-system tournament
#
import psycopg2
def connect():
"""Connect to the PostgreSQL database. Returns a database
connection."""
return psycopg2.connect("dbname=tournament")
def deleteMatches():
"""Remove all the match records from the database."""
db = connect()
cursor = db.cursor()
cursor.execute("TRUNCATE matches CASCADE;")
db.commit()
db.close()
Python: (minimal from tournament_test.py) this is the file that verifies the tournament.py functions are working with the tournament.sql database.
#!/usr/bin/env python
#
# Test cases for tournament.py
from tournament import *
def testCount():
"""
Test for initial player count,
player count after 1 and 2 players registered,
player count after players deleted.
"""
deleteMatches()
deletePlayers()
c = countPlayers()
if c == '0':
raise TypeError(
"countPlayers should return numeric zero, not string '0'.")
if c != 0:
raise ValueError("After deletion, countPlayers should return zero.")
print "1. countPlayers() returns 0 after initial deletePlayers()
execution."
registerPlayer("Chandra Nalaar")
c = countPlayers()
if c != 1:
raise ValueError(
"After one player registers, countPlayers() should be 1. Got
{c}".format(c=c))
print "2. countPlayers() returns 1 after one player is registered."
registerPlayer("Jace Beleren")
c = countPlayers()
if c != 2:
raise ValueError(
"After two players register, countPlayers() should be 2. Got
{c}".format(c=c))
print "3. countPlayers() returns 2 after two players are registered."
deletePlayers()
c = countPlayers()
if c != 0:
raise ValueError(
"After deletion, countPlayers should return zero.")
print "4. countPlayers() returns zero after registered players are
deleted.\n5. Player records successfully deleted."
testCount()
Vagrant (Confirming that the table 'matches' exists within the database):
vagrant=> \dt
List of relations
Schema | Name | Type | Owner
--------+---------+-------+---------
public | matches | table | vagrant
public | players | table | vagrant
(2 rows)
Update2: Clarification to comment
I connect to the db at the beginning of my python file.
def connect()
"""Connect to the PostgreSQL database. Returns a database
connection."""
return psycopg2.connect("dbname=tournament")
回答1:
This was user error. I was connecting to vagrant and the tournament database in the wrong way.
After logging into vagrant I was in the right folder accessing the right database but in the wrong method.
Error:
Once in vagrant I went to psql as user vagrant and imported the file.
\i tournament.sql
Then I connected to the database.
\c tournament
Then I was exiting psql to run the file and getting the relation does not exist error.
I needed to do one more step.
FIX:
Once connected and logged into the database tournament. I needed to import the tournament.sql file again.
That created the relations within the actual database and not just vagrant or wherever I was creating them before.
so from Vagrant after the command Vagrant ssh # run these commands separately cd /vagrant/tournament/
psql
\i tournament.sql
\c tournament
\i tournament
#last check to verify your relations were created
\dt
\d (table or view)
That is what did it for me. The rest of the project was easy. I hope this helps anyone searching for the answer on here and only finding more unanswered but heavily criticized questions. Thanks to all the experts who saw my beginner question and either gave me negative points or stopped to criticize the format of my question. I am still learning and if any of you had actually helped me understand or solve this I wouldn't have been able to do it all by myself over the course of 3 days.
来源:https://stackoverflow.com/questions/46679910/python-backed-sql-database-returning-a-psycopg2-programmingerror-relation-does