0

Could someone help me figure out which values should I define as UNIQUE? I'm getting the ValueError: UNIQUE constraint failed: compras.id beacuase of the way I created my table for keeping tab of who bought what and when for finance of pset9. Thank you so much in advance and also for reading

CREATE TABLE users (id INTEGER, username TEXT NOT NULL, hash TEXT NOT NULL, cash NUMERIC NOT NULL DEFAULT 10000.00, PRIMARY KEY(id));

CREATE UNIQUE INDEX username ON users (username);

def buy():
"""Buy shares of stock"""
if request.method == "POST":
    user_id = session["user_id"]
    symbol = request.form.get("symbol")
    result = lookup(symbol)
    if not result:
        return apology("The symbol does not exist",403)
    shares = request.form.get("shares")
    price = result["price"]
    product = (result["price"]*int(shares))
    #if shares < 0:
    #    return apology("You forgot to type a positive integer.",403)
    cash = db.execute("SELECT cash FROM users WHERE id = ?", user_id)[0]['cash']
    # okay if avilableCash is a list of zero or more dict objets, which are its key and values ?
    alcanza = cash - product # for some reason it worked like this lol
    if alcanza > 0:
        ts = datetime.datetime.now().timestamp()
        db.execute("INSERT INTO compras (id,symbol,shares,price,date) VALUES(?,?,?,?,?)",user_id, symbol, shares, price,ts)
        return redirect("/")
    else:
        return apology("not enough money",403)
else:
    return render_template("buy.html")

1 Answer 1

1

The error is on compras.id, which implies it is defined as UNIQUE. (Perhaps edit the compras schema into the question). The INSERT into compras is setting id to user_id, which would allow one purchase per user, since id is UNIQUE.

2
  • I appreciate your comment a lot @DInoCoderSaurus also what a cool name you got. I wanted to ask your opinion if in order to define id as a NON UNIQUE should that be inside of the CREATE TABLE compras (id INTEGER NON UNIQUE, etc...) or should I use an INDEX ? that tbh I'm not very familiar with its usage. Commented Dec 16, 2021 at 19:27
  • There is no explicit "NON UNIQUE" clause. A column is implicitly not unique unless declared UNIQUE, or the PRIMARY KEY. Commented Dec 16, 2021 at 22:10

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .