PostgreSQL migration issue - error: duplicate type found

exports.up = async (knex) => {
  await knex.raw(`
    ALTER TABLE users.sessions RENAME COLUMN role TO old_role;
    CREATE TYPE newest_user_role AS ENUM('admin', 'editor', 'viewer');
    ALTER TABLE users.sessions ADD COLUMN role newest_user_role;
  `);

  const roles = await knex('users.sessions').select('old_role', 'user_id');

  await Promise.all(roles.map(async ({ user_id, old_role }) => {
    return knex('users.sessions').where('user_id', user_id).update({ role: old_role });
  }));

  await knex.raw(`
    ALTER TABLE users.sessions DROP COLUMN old_role;
  `);
};

exports.down = async (knex) => {
  await knex.raw(`
    ALTER TYPE newest_user_role RENAME TO old_user_role;
    CREATE TYPE newest_user_role AS ENUM('admin', 'editor', 'viewer');
    ALTER TABLE users.sessions ALTER COLUMN role TYPE newest_user_role USING role::text::newest_user_role;
    DROP TYPE old_user_role;
  `);
};

After successfully running the migration and rollback processes, reapplying the migration throws the error:

error: type "newest_user_role" already exists

I'm facing this issue during the migrations. Any help on what I might be missing is greatly appreciated. Thank you.

Answer №1

element, it's quite surprising to see how that particular code manages to work. The issue lies in the fact that the 'up' script assumes that 'newest_login_type' does not exist, while the 'down' script fails to completely remove this type and only renames or re-creates it instead. To break it down: 1. When running the 'up' command, 'newest_login_type' gets created. 2. Upon executing the 'down' command, 'newest_login_type' undergoes modification. 3. Any subsequent attempt to run the 'up' command will result in failure because 'newest_login_type' already exists. On a side note, it's worth mentioning that passing multiple SQL statements within a single call to 'knex.raw' isn't recommended. This practice is not supported by many database drivers, including the 'pg' driver used in conjunction with knex's postgresql dialect.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Steps for verifying the existence of a value within an array in relation to another object and generating a new object based on the result

Within my coding realm, I possess an array const dataCheck = ["Rohit", "Ravi"]; In addition to this first array, I also have a secondary array filled with objects const userData = [ { name: "Sagar" }, { name: "V ...

Deactivate click events in the container div

Here is the html code snippet that I am working with: <div class="parent" ng-click="ParentClick()"> . . . <div class="child" ng-click="ChildClick()"> Some Text </div> </div> When clicking on Som ...

Javascript event fails to trigger following completion of Ajax request

I'm encountering an issue with my form (input, textarea, and submit button) and a list of items. I've written a script that should: Display the text content of a list item in the textarea when clicked Submit the form via ajax without refreshing ...

When navigating to a subsite or subfolder, the SVG href ID cannot be located

The topic at hand revolves around another issue: The challenge of creating an Ajax website with links from multiple subfolders. Take a look at the discussion where a solution for that problem was discovered. However, my current dilemma with that solution ...

Utilizing Subdirectories in a Command Manager

My goal is to organize my commands into sub folders, but for some reason my bot is not recognizing the commands inside those folders. Strangely, no error message is being displayed. const fs = require('node:fs'); const Discord = require('dis ...

Many mistakes encountered while trying to import web3 into app.js

Encountered 9 errors while trying to import web3 into App.js import React from "react"; import Web3 from "web3"; function App() { return ( <div className="App"> <h1>TEST APP</h1> </div> ...

What is the best way to open multiple tabs simultaneously on Google Chrome?

I'm in the process of developing a coupon product and I want to be able to open 4 tabs with just one click of a button. Interestingly, this works smoothly on Firefox, however, when it comes to Chrome, only 2 links are able to open while the other two ...

Searching for values using keys in Angular

Currently, I am working on a project using Angular where I need to store information based on specific identifiers. To display this information in the Angular application, I am pulling data for different identifiers and showing it on the screen. At the mo ...

Passing all emitted events from Vue 3 child component to its parent - A complete guide

My Vue components are structured as follows: <TopParent> <!-- Listening for events from EventProducer here --> <Child_1> <Child_2> <Child_3> ... <Child_N> <EventProducer /> &l ...

Guide on properly documenting custom function types in JSDoc or TypeScript to ensure accurate referencing for VSCode IntelliSense functionality

I am currently working on documenting custom function types within an object and would greatly appreciate any assistance: A Closer Look at the Issue Consider this basic object declaration with several function properties (addCoordinate, addCoordinateOne, ...

navigating through a specific section of a data chart

I need the first column of a table to stay fixed while the rest of the columns scroll horizontally. Here's the code I have: <div id="outerDiv"> <div id="innerDIv"> <table> <tr><td>1</td><t ...

The initial row's Id will be used as the Id for all subsequent rows within a JSON object

After dragging a tr in a table and confirming by clicking a button, I need the order list to be updated in the database. To achieve this, I created a JSON object where I intend to save the ids and their corresponding new orders. The issue I am facing is t ...

Is there a way to determine the orientation of an image in React-Native, whether it is horizontal or vertical

When working with react-native, I aim to utilize the 'contain' feature for vertical images and the 'stretch' feature for horizontal images. What would be the best way to determine the orientation of an image as either horizontal or vert ...

What steps can be taken to ensure that specific elements stand out when they are clicked on

I'm in the process of creating a graph featuring bars with distinct data, color-coded for clarity. The legend explains the meaning behind each color. My goal is to implement a feature where clicking on a circle in the legend will highlight bars of the ...

Changing a file object into an image object in AngularJS

Can a file object be converted to an image object? I am in need of the width and height from the file (which is an image). Here is my code: view: <button id="image_file" class="md-button md-raised md-primary" type="file" ngf-select="uploadFile($file ...

What is the best way to send a parameter to an express.js Router?

Here's a unique spin on an example taken from Express.js's routing guide: var express = require('express'); var router = express.Router(); router.get('/', function(req, res) { res.send('Welcome to the home of Birds&ap ...

Removing duplicate loops within a table in a Vue component

I am facing an issue with duplicate json data and need help removing the duplicates based on the id_cms_users. How can I display the cleaned data in a table? I found a method on https://codepen.io/roverv/pen/YQvdya but it only displays data from one colum ...

Ways to enlarge the parent container and reveal a concealed child element upon hovering without impacting neighboring containers

Currently, I am diligently working on the company service boxes and have a particular need... When hovering over: 1. The parent div should scale up and acquire box shadow without impacting the neighboring service boxes (it should appear to stand out above ...

Steps for extracting the value of a new Date object passed in a JSON format

After retrieving data from a REST service, I encountered the following JSON structure: { "data":{ "virt":false, "someValue":"0.0", "dateFrom":new Date(1519772400000), "anotherValue":"" } } I am unsure how to properl ...

What is the best way to reset react-id-swiper every time an event handler is triggered in a React application?

I have incorporated the react-id-swiper module into my React project to create a dynamic image slider. By setting onClick event handlers on buttons with different id attributes, I trigger API calls that update the state and populate the ImageSlider compone ...