Nick
Nick

Reputation: 6352

Diesel only supports tables with primary keys

I'm trying to create a migration with Diesel and an SQLite database and continue to get the following error:

Diesel only supports tables with primary keys. Table cycles has no primary key

However, I've whittled down the table to only have a primary key. Here's my entire up.sql file:

CREATE TABLE cycles (
    id INTEGER PRIMARY KEY,
);

For completeness, here's my migration command:

diesel migration run --database-url ~/.config/cycles/dev.sqlite

In case it helps, here's my diesel.toml:

# For documentation on how to configure this file,
# see https://diesel.rs/guides/configuring-diesel-cli

[print_schema]
file = "src-tauri/src/schema.rs"
custom_type_derives = ["diesel::query_builder::QueryId"]

[migrations_directory]
dir = "migrations"

What am I missing?

Upvotes: -1

Views: 262

Answers (2)

xemkis
xemkis

Reputation: 36

I would like to validate the original issue:

When running

diesel migration run --database-url 'postgres://postgres@localhost:5432'

with the up.sql:

CREATE TABLE IF NOT EXISTS adjectives (word UUID PRIMARY KEY);

(Note, there is no extra comma), I got the response

Diesel only supports tables with primary keys. Table `adjectives` has no primary key

I found the issue to be that in a previous attempt to run the migration, when I did not have a primary key in the up.sql, diesel created and kept the table that did not have a primary key, despite the migration run command failing. So, when I ran the command again after fixing the up.sql, the table already existed without a primary key, and when diesel tried to run print_schema, the primary-key-less version that was left over from the initial run is what was making it upset.

Deleting the previous instance of the table and re-running the command with a correct up.sql fixed the problem.

Upvotes: 0

weiznich
weiznich

Reputation: 3435

The provided migration does not reproduce the error in your question. For me applying the migration fails with the following error message:

$ cat migrations/2024-01-22-122221_test_stackoverflow/up.sql
-- Your SQL goes here

CREATE TABLE cycles (
    id INTEGER PRIMARY KEY,
);

$ diesel migration run --database-url /tmp/tests
Running migration 2024-01-22-122221_test_stackoverflow
Failed to run 2024-01-22-122221_test_stackoverflow with: near ")": syntax error

After fixing the syntax error pointed out in the error message diesel correctly generates the following schema.rs file for me:

// @generated automatically by Diesel CLI.

diesel::table! {
    cycles (id) {
        id -> Nullable<Integer>,
    }
}

Upvotes: 1

Related Questions