未创建行,但增加了主键

时间:2018-11-23 12:40:39

标签: sql python-3.x postgresql psycopg2

我正在尝试将新行插入到以下PostgreSQL表中:

                                       Table "public.users"
    Column     |           Type           | Collation | Nullable |                   Default
---------------+--------------------------+-----------+----------+----------------------------------------------
 user_id       | integer                  |           | not null | nextval('define_user_user_id_seq'::regclass)
 time_created  | timestamp with time zone |           | not null |
 is_active     | boolean                  |           | not null | true
 email_address | text                     |           | not null |
 password_hash | character varying(255)   |           | not null |
 first_name    | text                     |           |          |
 second_name   | text                     |           |          |

Indexes:
    "users_pkey" PRIMARY KEY, btree (user_id)
Referenced by:
    TABLE "user_to_device" CONSTRAINT "user_to_device_user_id_fkey" FOREIGN KEY (user_id) REFERENCES users(user_id)
    TABLE "user_to_horse" CONSTRAINT "user_to_horse_user_id_fkey" FOREIGN KEY (user_id) REFERENCES users(user_id)

该表当前仅包含10条记录,因为它仍在用于开发。没有修改表的范围。

我的问题是,从REST API更新表时,该操作似乎成功完成并返回了新的user_id;在查询表时,假定创建的用户不在表中。

如果我随后手动创建用户(通过SSH登录运行psql的服务器)并使用完全相同的查询,则操作成功,并且可以看到新创建的用户。有趣的是,user_id的值从REST API触发的查询创建的值开始递增。

这向我表明,通过REST API触发的查询成功(?),因为它创建的user_id似乎可以被后续查询识别-那么为什么新用户不出现在表中?

根本不会引发任何错误。这是我用来创建用户的查询:

INSERT INTO users (password_hash, is_active, first_name, email_address, second_name, time_created) VALUES ('mypasswordhash', True, 'Orson', 'user@example.com', 'Cart', '2018-11-23T12:23:00Z') RETURNING user_id;

通过API查询时,我正在Python 3.6中使用psycopg2。我还有多个其他API端点,可以成功将它们插入到其他表中,因此我完全不确定问题是什么。非常感谢您的任何帮助,因为这让我感到非常难过。

1 个答案:

答案 0 :(得分:1)

绝对确定吗? 您的commit函数被调用了吗? 在某些情况下 如果您是yieldreturn 在提交之前, 该函数被中止 在您做出更改之前。

在这种情况下,我希望看到 没有插入行的递增ID, 随着主键的增加 在检查查询之前。 如果您的连接突然终止, 该行将不会提交。

您最好的选择是 检查您的PostgreSQL服务器日志。

相关问题