Skip to content

Timescale does not work with migrate dev and migrate reset: extension "timescaledb" has already been loaded with another version #8325

Open

Description

@janpio

Discussed in #6963

Originally posted by pfried May 6, 2021
This is a question on how to setup timescale with prisma. Thanks to the post from @janpio I tried to create a similar setup. So this is
related to ##3228

My goal is to ingest IoT data into timescaledb with the help of prisma since the whole raw sql stuff is just bad (I know some stuff will stay raw sql stuff for now, especially timescaledb functionality).

My desired setup

  1. Timescale 2.2.0 running on Timescale Forge
  2. Prisma / Prisma Client 2.22.0 used by AWS Lambda (will do a lambda layer / package as suggested by the docs).

Following the steps

The first step would be to create a migration which will install the timescale extension since the shadow database will run the migrations too (it is obiously already installed on Laravel forge). So the migration.sql file will look like:

CREATE EXTENSION IF NOT EXISTS timescaledb VERSION "2.2.0";

Case 1: Forge Database without shadow database

Try to run the npx prisma migrate dev command on the timescale forge database will result in an error since the command tries to create a table:

Error: Database error
Error querying the database: db error: ERROR: tsdb_admin: database prisma_migrate_shadow_db_ab8fe7fa-8d81-4493-bafe-bf5645e6d2cc is not an allowed database name
HINT: Contact your administrator to configure the "tsdb_admin.allowed_databases"

Following the suggestions in #4571 and here: https://www.prisma.io/docs/concepts/components/prisma-migrate#shadow-database the guess would be that it is not possible to use the timescale forge service for the shadow db. Which leads to:

Case 2: Forge database with shadow database on localhost

My localhost is a postgres 13 instance on windows with the timescale extension available.

Adding a shadow database in the environment and running the npx prisma migrate dev will result in an error telling that the timescaledb extension is already loaded (both instances run 2.2.0):

Error: P3006

Migration `20210505152706_` failed to apply cleanly to the shadow database. 
Error:
Database error
Error querying the database: db error: FEHLER: extension "timescaledb" has already been loaded with another version
DETAIL: The loaded version is "2.2.0".

If the timescale forge database has already has data a reset is suggested and if executed will result in:

Error: P3016

The fallback method for database resets failed, meaning Migrate could not clean up the database entirely. Original error: 
Database error
Error querying the database: db error: ERROR: must be owner of view pg_stat_statements
   0: sql_migration_connector::best_effort_reset

Case 3 Local Timescale database

If no shadow database is explicitly given (meaning the migrate command will create one) everything works on the local machine (different to Case 1).

Case 4 Local Timescale database with explicit shadow database on the same server

If I explicitly set a shadow database on my local machine I will end up in the same error as Case 2:

Error: P3006

Migration `20210505152706_` failed to apply cleanly to the shadow database. 
Error:
Database error
Error querying the database: db error: FEHLER: extension "timescaledb" has already been loaded with another version
DETAIL: The loaded version is "2.2.0".

Activity

  1. pantharshit00 commented on Jul 28, 2021

    @pantharshit00
    Contributor

    Hmm, we should close this in favour of #3228 until we decide to properly support timescale.

  2. pfried commented on Jan 20, 2022

    @pfried

    Okay, I gave this a new try ([email protected]):

    • database on timescale cloud
    • shadow database on timescale cloud (fomerly called timescale forge)

    Followed along the original gist and the blogpost from @orpheousff8

    The first step is to load the extension by adding to the migration (first line)

    CREATE EXTENSION IF NOT EXISTS timescaledb CASCADE;

    Which results in (on fresh deployed DBs):

    Error: P3006
    
    Migration `20220119070636_init` failed to apply cleanly to the shadow database. 
    Error:
    db error: ERROR: extension "timescaledb" has already been loaded with another version
    DETAIL: The loaded version is "2.5.1".
    HINT: Start a new session and execute CREATE EXTENSION as the first command. Make sure to pass the "-X" flag to psql.
       0: sql_migration_connector::flavour::postgres::sql_schema_from_migration_history
                 at migration-engine\connectors\sql-migration-connector\src\flavour\postgres.rs:333
       1: migration_core::api::EvaluateDataLoss
                 at migration-engine\core\src\api.rs:134
    

    I do not get why this happens since I can run this statement in both databases without an error and also the IF NOT EXISTS is added.

    Maybe the prisma clients runs statements before running the migration?

  3. pfried commented on Jan 20, 2022

    @pfried

    The docs say something like:

    Do not manually install extensions - the shadow database requires the same extensions, and since this database is created and deleted automatically, the only way to install extensions is to use migrations.

    But this does not work for e.g. Timescale Cloud where the extension is pre installed

    PS: I also tried to do:

    DROP EXTENSION IF EXISTS timescaledb;
    CREATE EXTENSION IF NOT EXISTS timescaledb CASCADE;
    

    But that does not work either

  4. orpheousff8 commented on Jan 20, 2022

    @orpheousff8

    @pfried I've tried my tutorial only on TimescaleDB docker image, never tried it on Timescale cloud.

    By the way, I once saw the error: db error: ERROR: extension "timescaledb" has already been loaded with another version when I tried to do (not first) migration with this CREATE EXTENSION IF NOT EXISTS timescaledb CASCADE; SQL command on the DB that has already been installed the extension at the first migration.
    (Even you use TimescaleDB docker image, you always have to install the extension as per my tutorial at the first migration anyway. I don't know why...)

    In your case, did you tried not to do anything with the EXTENSION commands, and just skip to next steps? Not sure if it works...

  5. pfried commented on Jan 20, 2022

    @pfried

    @orpheousff8 You cannot access timescale functions inside the session context if you do not call that function, at least I get errors when I call them without the statement

    Addtional info tough: The migrations will run but error in the console. The whole thing is not rolled back, so it actually works. To me this looks more like the migrate command translates the warning into an error

  6. pfried commented on Jan 20, 2022

    @pfried

    Funnily enough if you run prisma migrate reset twice quickly after each other (maybe connection reuse?) it works. Sry for not really having an idea what the root cause of all of this is, but I can only share observations

  7. added
    bug/0-unknown
    kind/bug
    and removed on Dec 14, 2022
  8. 8 remaining items

  9. janpio commented on Jul 14, 2023

    @janpio
    ContributorAuthor

    Happy to create the Timescaledb cloud databases myself if you just tell me roughly what to click and then how to use it in the app from your repository.

  10. janpio commented on Jul 17, 2023

    @janpio
    ContributorAuthor

    Before I get to the extension and reset problem, I confirmed along the way that the shadow database problem (that it can not be created automatically on Timescale Cloud) is handled properly today: #20266 (comment)

    ...
    Datasource "db": PostgreSQL database "tsdb", schema "public" at "opj14wxfkv.kn5o1onhbq.tsdb.cloud.timescale.com:30943"
    
    Error: P3014
    
    Prisma Migrate could not create the shadow database. Please make sure the database user has permission to create databases. Read more about the shadow database (and workarounds) at https://pris.ly/d/migrate-shadow
    
    Original error: 
    db error: ERROR: tsdb_admin: database prisma_migrate_shadow_db_1dc9385e-8a23-4b7d-8f30-1c037906c5ef is not an allowed database name
    HINT: Contact your administrator to configure the "tsdb_admin.allowed_databases"
       0: schema_core::state::DevDiagnostic
                 at schema-engine/core/src/state.rs:266
    
  11. janpio commented on Jul 17, 2023

    @janpio
    ContributorAuthor

    Ok, on to the migrate dev prboelm:

    I can definitely reproduce the problem that a migration file that installs the timescaledb extension does not work with a Timescale Cloud database as the shadow database:

    gitpod /workspace/prisma-timescale (main) $ npx prisma migrate dev
    Environment variables loaded from .env
    Prisma schema loaded from prisma/schema.prisma
    Datasource "db": PostgreSQL database "tsdb", schema "public" at "opj14wxfkv.kn5o1onhbq.tsdb.cloud.timescale.com:30943"
    
    Error: P3006
    
    Migration `0_init` failed to apply cleanly to the shadow database. 
    Error:
    db error: ERROR: extension "timescaledb" has already been loaded with another version
    DETAIL: The loaded version is "2.11.1".
    HINT: Start a new session and execute CREATE EXTENSION as the first command. Make sure to pass the "-X" flag to psql.
       0: schema_core::state::DevDiagnostic
                 at schema-engine/core/src/state.rs:266
    

    As you described, I can run CREATE EXTENSION IF NOT EXISTS "timescaledb"; on a clean (!) TimescaleDB database to reinstall the extension though, why does this not work here?

    It seems that as a first step, migrate dev cleans up the provided explicit shadow database:

      prisma:schemaEngine:rpc  starting Schema engine with binary: /workspace/prisma-timescale/node_modules/@prisma/engines/schema-engine-debian-openssl-3.0.x +0ms
      prisma:schemaEngine:rpc  SENDING RPC CALL {"id":1,"jsonrpc":"2.0","method":"devDiagnostic","params":{"migrationsDirectoryPath":"/workspace/prisma-timescale/prisma/migrations"}} +11ms
      prisma:schemaEngine:stderr  {"timestamp":"2023-07-17T16:57:05.375351828Z","level":"INFO","fields":{"message":"Starting schema engine RPC server","git_hash":"6b0aef69b7cdfc787f822ecd7cdc76d5f1991584"},"target":"schema_engine"} +0ms
      prisma:schemaEngine:stderr  {"timestamp":"2023-07-17T16:57:05.782921339Z","level":"INFO","fields":{"message":"Connecting to user-provided shadow database."},"target":"sql_schema_connector::flavour::postgres","span":{"name":"DevDiagnostic"},"spans":[{"name":"DevDiagnostic"}]} +408ms
      prisma:schemaEngine:stderr  {"timestamp":"2023-07-17T16:57:05.782958249Z","level":"INFO","fields":{"message":"Resetting schema(s)","schemas_to_reset":"[\"public\"]"},"target":"sql_schema_connector::flavour::postgres","span":{"name":"DevDiagnostic"},"spans":[{"name":"DevDiagnostic"}]} +0ms
      prisma:schemaEngine:rpc  {
      jsonrpc: '2.0',
      error: {
        code: 4466,
        message: 'An error happened. Check the data field for details.',
        data: {
          is_panic: false,
          message: 'Migration `0_init` failed to apply cleanly to the shadow database. \n' +
            'Error:\n' +
            'db error: ERROR: extension "timescaledb" has already been loaded with another version\n' +
            'DETAIL: The loaded version is "2.11.1".\n' +
            'HINT: Start a new session and execute CREATE EXTENSION as the first command. Make sure to pass the "-X" flag to psql.\n' +
            '   0: schema_core::state::DevDiagnostic\n' +
            '             at schema-engine/core/src/state.rs:266',
          meta: [Object],
          error_code: 'P3006'
        }
      },
    

    It does this by running these commands:

    DROP SCHEMA "public" CASCADE;
    CREATE SCHEMA "public";
    

    Afterward, public is in a clean state, without the timescaledb extension installed.

    Now the weird bit: Now I can not run CREATE EXTENSION ... any more on this database but get exactly the error message you are describing!

    So these command let you reproduce the situation:

    DROP SCHEMA "public" CASCADE;
    CREATE SCHEMA "public";
    SELECT * FROM pg_extension;
    CREATE EXTENSION IF NOT EXISTS "timescaledb";
    SELECT * FROM pg_extension;
    

    If I now disconnect from the database server (as indicated in the error message), and then reconnect I can run CREATE EXTENSION ... again and it will be correctly installed.

    Is this a PostgreSQL quirk of installing extensions?
    Or a Timescale extension problem in some form?


    I think the migrate reset problem, that only every second run works, that @rickbatka also reported, is essentially the same thing: If reset has to actually reset the schema, Migrate will not be able to execute the CREATE EXTENSION statement. Then on the next try, it does not because the schema is already fully clear so it can just run the migrations - and CREATE EXTENSION will work.

    Super weird, but it makes "sense" from that perspective.

  12. added
    bug/2-confirmed
    and removed
    bug/1-unconfirmed
    on Jul 17, 2023
  13. changed the title [-]Timescale Setup issues[/-] [+]Timescale does not work with `migrate dev` and `migrate reset`: `extension "timescaledb" has already been loaded with another version`[/+] on Jul 17, 2023
  14. added
    topic: prisma migrate dev
    topic: prisma migrate reset
    on Jul 17, 2023
  15. janpio commented on Jul 17, 2023

    @janpio
    ContributorAuthor

    I opened an issue with Timescale asking for information: timescale/timescaledb#5884

  16. RyKilleen commented on Feb 28, 2024

    @RyKilleen

    Is there a chance anyone here has found a reasonable workaround since July 2023? As a recent convert to Timescale and an advocate of Prisma, I find myself in this situation.

  17. alexanderdavide commented on Sep 3, 2024

    @alexanderdavide

    For my local development purposes, I decided to use the following workaround which is just a bit nicer than re-executing manually and explaining every new developer what is going on.

    prisma migrate reset || if [ $? -eq 1 ]; then echo \"🔁  \\e[33mResetting fails the first time on already initialized databases and must be repeated (see ticket #4711).\\e[0m\n\n\"; prisma migrate reset --force; fi
    1. resets with confirmation prompt
    2. if fails, prints message in yellow stating that reset is going to be repeated
    3. resets without confirmation prompt
  18. pdesjardins90 commented on Mar 28, 2025

    @pdesjardins90

    For anyone still hitting their heads with that here you go:

    Instead of

    npm exec -- prisma migrate reset --force --skip-seed

    do

    psql "$DATABASE_URL" -c "DROP SCHEMA public CASCADE; CREATE SCHEMA public;"
    psql -X "$DATABASE_URL" -c "CREATE EXTENSION IF NOT EXISTS timescaledb;"
    npm exec -- prisma migrate deploy
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug/2-confirmedkind/bugtopic: prisma migrate devtopic: prisma migrate resettopic: timescaledb

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions