Skip to content

Preview feature feedback: Integrated seeding  #5161

Closed

Description

@2color

Please share your feedback about the integrated seeding functionality that was released in v2.15.0 in this issue.

  • If you encounter a bug, please open a bug report in this repo.
  • If the feature is working well for you, please share this in a comment below or leave a 👍 on this issue.

If you have any questions, don't hesitate to ask them in the #prisma-migrate channel in the Prisma Slack.

Activity

  1. added
    topic: previewFeatures
    on Jan 18, 2021
  2. barakcoh commented on Jan 21, 2021

    @barakcoh
  3. albertoperdomo commented on Jan 21, 2021

    @albertoperdomo
  4. bobbyflowstate commented on Jan 21, 2021

    @bobbyflowstate

    Just tried this today. I'm getting the following error:

    Running `ts-node seed.ts` ...
    /Users/ashok/src/flixed/api/prisma/seed.ts:37
    import { PrismaClient } from '@prisma/client';
    ^^^^^^
    
    SyntaxError: Cannot use import statement outside a module
        at wrapSafe (internal/modules/cjs/loader.js:1172:16)
        at Module._compile (internal/modules/cjs/loader.js:1220:27)
        at Module.m._compile (/usr/local/lib/node_modules/ts-node/src/index.ts:1056:23)
        at Module._extensions..js (internal/modules/cjs/loader.js:1277:10)
        at Object.require.extensions.<computed> [as .ts] (/usr/local/lib/node_modules/ts-node/src/index.ts:1059:12)
        at Module.load (internal/modules/cjs/loader.js:1105:32)
        at Function.Module._load (internal/modules/cjs/loader.js:967:14)
        at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)
        at main (/usr/local/lib/node_modules/ts-node/src/bin.ts:198:14)
        at Object.<anonymous> (/usr/local/lib/node_modules/ts-node/src/bin.ts:288:3)
    Error: Command failed with exit code 1: ts-node /Users/ashok/src/flixed/api/prisma/seed.ts
    
  5. bobbyflowstate commented on Jan 21, 2021

    @bobbyflowstate

    Changing my tsconfig.json to have this:

    "module": "commonjs",

    instead of this:

    "module": "esnext",

    fixed it.

  6. pm-dev commented on Jan 22, 2021

    @pm-dev

    This script is saying it can't find my seed.ts file:
    Screen Shot 2021-01-21 at 9 21 56 PM

    Other prisma commands work as expected.

  7. 2color commented on Jan 22, 2021

    @2color
    ContributorAuthor

    @pm-dev It looks like you are running the npx prisma db seed --preview-feature from the prisma folder.

    Running it in the root of your repository (where the package.json is) should fix that.

  8. pm-dev commented on Jan 23, 2021

    @pm-dev

    @pm-dev It looks like you are running the npx prisma db seed --preview-feature from the prisma folder.

    Running it in the root of your repository (where the package.json is) should fix that.

    Confirming that did work. (Thought I had tried that). Thanks @2color

  9. aruld commented on Jan 23, 2021

    @aruld
    Contributor

    I am not seeing the data getting seeded in sqlite, I can confirm the data is getting deleted from sqlite. Here is my seed.js script: https://github.com/aruld/server-components-demo/blob/sqlite/prisma/seed.js

    Screen Shot 2021-01-23 at 3 00 40 PM

    any clue what might be happening here?

  10. thetw commented on Jan 23, 2021

    @thetw

    Running it in the root of your repository (where the package.json is) should fix that.

    The seed command doesn't seem to correctly escape whitespace, because when i run npx prisma db seed --preview-feature from the project root it breaks with an incomplete path. The problem seems to be that i've got whitespace in my hard drives name.

    Running `ts-node seed.ts` ...
    Error: Cannot find module '/Volumes/Storage'
        at Function.Module._resolveFilename (internal/modules/cjs/loader.js:880:15)
        at Function.Module._load (internal/modules/cjs/loader.js:725:27)
        at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
        at main (/Volumes/Storage SSD/Users/thetw/Coding/prisma-test/node_modules/.pnpm/[email protected][email protected]/node_modules/ts-node/src/bin.ts:198:14)
        at Object.<anonymous> (/Volumes/Storage SSD/Users/thetw/Coding/prisma-test/node_modules/.pnpm/[email protected][email protected]/node_modules/ts-node/src/bin.ts:288:3)
        at Module._compile (internal/modules/cjs/loader.js:1063:30)
        at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
        at Module.load (internal/modules/cjs/loader.js:928:32)
        at Function.Module._load (internal/modules/cjs/loader.js:769:14)
        at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
    Error: Command failed with exit code 1: ts-node /Volumes/Storage SSD/Users/thetw/Coding/prisma-test/prisma/seed.ts
    

    When i run ts-node ./prisma/seed.ts myself with a relative path it indeed works.

  11. StErMi commented on Jan 24, 2021

    @StErMi

    Changing my tsconfig.json to have this:

    "module": "commonjs",

    instead of this:

    "module": "esnext",

    fixed it.

    what are the implications of your change? I also get that seed.ts error

  12. JakubKoralewski commented on Jan 24, 2021

    @JakubKoralewski

    what are the implications of your change? I also get that seed.ts error

    I was also hesitant; but my Next.js app builds fine, and IDE seems to not throw any errors with this in my project, so I guess it must be fine(?).


    Another error regarding the "baseUrl" config option in tsconfig.json:

    Cannot find module 'lib/prisma/prisma'
    
    I'm using `baseUrl` in my `tsconfig.json`
    {
      "compilerOptions": {
        "target": "es5",
        "lib": ["dom", "dom.iterable", "esnext"],
        "allowJs": true,
        "skipLibCheck": true,
        "strict": false,
        "forceConsistentCasingInFileNames": true,
        "noEmit": true,
        "noImplicitAny": true,
        "esModuleInterop": true,
        "module": "commonjs",
        "moduleResolution": "node",
        "resolveJsonModule": true,
        "isolatedModules": true,
        "jsx": "preserve",
        "baseUrl": "./src",
        "sourceMap": true
      },
      "exclude": ["node_modules", ".next", "out"],
      "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", "**/*.js"]
    }
    

    In my custom seeding script I work around this by running my seeding script as follows: ts-node -r tsconfig-paths/register -P prisma/seeding/tsconfig.script.json prisma/seeding/initiateDb.ts. I guess I'll stick to my custom script for now. (Note that the tsconfig.script.json is not needed anymore as I have just changed my tsconfig.json "compilerOptions"."module" from ESNext to commonjs.

    Will tsconfig-paths be used to support baseUrl and other custom paths?

    EDIT: Thanks to the official implementation I was able to finally close my script after seeding with process.exit(1) 🎉 (And yes I was disconnecting properly it wasn't closing anyway)

  13. 35 remaining items

  14. nghiepdev commented on Jul 11, 2021

    @nghiepdev

    How to seeding with the specific object to run individually?
    For example to create seed file and run specific:

    $ npx prisma db seed --create=UserSeed
    $ npx prisma db seed --class=UserSeed
  15. benbender commented on Jul 31, 2021

    @benbender

    To use prisma db seed --preview-feature in a native es-module project (type: module in package.json), I found the following solution, which converts typescript into a native es-module which can be run in my project:

    1. npm add ts-node
    2. add "ts-node": "node --loader ts-node/esm" to scripts in package.json`
    3. use a prisma/seed.ts similar to this (the important part is the import on top):
    import prisma from '@prisma/client';
    
    const { PrismaClient } = prisma;
    
    const db = new PrismaClient();
    
    const main = async () => {
    	// await db.post.deleteMany();
    	// await db.user.deleteMany();
    
    	// Prisma create query to seed models in database
    	const alice = await db.user.upsert({
    		where: { email: '[email protected]' },
    		update: {},
    		create: {
    			email: '[email protected]',
    			name: 'Alice',
    			hashedPassword: 'foobar',
    			posts: {
    				create: {
    					title: 'Check out Prisma with Next.js',
    					content: 'https://www.prisma.io/nextjs'
    					// published: true
    				}
    			}
    		}
    	});
    
    	const bob = await db.user.upsert({
    		where: { email: '[email protected]' },
    		update: {},
    		create: {
    			email: '[email protected]',
    			name: 'Bob',
    			hashedPassword: 'foobar',
    			posts: {
    				create: [
    					{
    						title: 'Follow Prisma on Twitter',
    						content: 'https://twitter.com/prisma'
    						// published: true
    					},
    					{
    						title: 'Follow Nexus on Twitter',
    						content: 'https://twitter.com/nexusgql'
    						// published: true
    					}
    				]
    			}
    		}
    	});
    
    	console.log({ alice, bob });
    };
    
    main()
    	.catch((error) => {
    		console.error(error);
    		process.exit(1);
    	})
    	.finally(async () => {
    		await db.$disconnect();
    	});
  16. benbender commented on Jul 31, 2021

    @benbender

    Hey, thanks for this feature. Here are my

    feedback/Wishlist:
    [ ] define one clear way how the seed-file is supposed to be called (instead of multiple options of exporting it)
    [ ] add a way to customize the seed-runner-script as there may be esoteric setups which may have problems with yours
    [ ] programatic api to use the seed-runner from scripts (f.e. tests)
    [ ] handle db-connection-setup/teardown in the runner and inject it into the seed-file
    [ ] ability to have a directory with individual seeders per model
    [ ] ability to run individual model-seed-files (f.e. nice for testing)

  17. Jolg42 commented on Aug 2, 2021

    @Jolg42
    Contributor

    Hi @benbender Thank you for the suggestions!

    We are reworking the seeding feature at the moment:
    The gist of it is that we want seeding to always work like that ts-node escape hatch, but with a clearer naming and guidance in the CLI.

    Would you be interested in testing a preview version of the feature and giving us your feedback? (that offer applies to anyone reading this message).

  18. benbender commented on Aug 2, 2021

    @benbender

    @Jolg42 sure, why not? :) anything I need to do?

  19. AlexKMarshall commented on Aug 11, 2021

    @AlexKMarshall

    I am seeing something similar to @blazestudios23 - in a NextJS project, using sqlite, my seed function (a named export) is not getting called.

    I've created an issue #8685 for that.

    I have a repo branch demonstrating the issue https://github.com/AlexKMarshall/next-prisma-starter/tree/prisma-seeds

    Hope that that helps in tracking down what's going on. I'll try running it as a script file, rather than a function, but it would be very useful to be able to call it from tests too, so I'd definitely like to get the function working if possible.

    edit: can confirm running it as a script file does work

    Thanks

  20. gex commented on Aug 13, 2021

    @gex

    i'm using the the seed command with the newer named export syntax but the process doesn't exit.

    seed.ts:

    import { PrismaClient } from '@prisma/client'
    
    const prisma = new PrismaClient()
    
    export async function seed() {
      const user = await prisma.user.upsert({
        create: {
          name: 'User,
          email: '[email protected]',
        },
        update: {},
        where: {
          email: '[email protected]',
        },
      })
    
      console.log({ user })
    }

    this is pretty much the same as in the example. everything seems fine (record is created in the db), except it just hangs and doesn't exit at the end. tried prisma db seed --preview-feature and prisma migrate reset as well, with the same result.

    prisma version and env:

    prisma               : 2.29.0
    @prisma/client       : 2.29.0
    Current platform     : linux-musl
    Query Engine         : query-engine 1be4cd60b89afa04b192acb1ef47758a39810f3a (at node_modules/@prisma/engines/query-engine-linux-musl)
    Migration Engine     : migration-engine-cli 1be4cd60b89afa04b192acb1ef47758a39810f3a (at node_modules/@prisma/engines/migration-engine-linux-musl)
    Introspection Engine : introspection-core 1be4cd60b89afa04b192acb1ef47758a39810f3a (at node_modules/@prisma/engines/introspection-engine-linux-musl)
    Format Binary        : prisma-fmt 1be4cd60b89afa04b192acb1ef47758a39810f3a (at node_modules/@prisma/engines/prisma-fmt-linux-musl)
    Default Engines Hash : 1be4cd60b89afa04b192acb1ef47758a39810f3a
    Studio               : 0.419.0
    
  21. modified the milestones: 2.27.0, 2.31.0 / 3.0.x on Aug 13, 2021
  22. Jolg42 commented on Aug 13, 2021

    @Jolg42
    Contributor

    Hi @gex so you will need to call await prisma.$disconnect() at the end of your seed function. That should work.

  23. Jolg42 commented on Aug 13, 2021

    @Jolg42
    Contributor

    🗒️ We heard the feedback and we are planning a redesign of db seed (currently planned to be released early September)

    How it will work is that a prisma.seed property in the package.json of your project will be required if you want to use prisma db seed.

    This property is where you will be able to put any command you want to execute your seed script.

    More info/details & how to try it out now in:
    #8732

  24. gex commented on Aug 14, 2021

    @gex

    thanks @Jolg42 ! it seems like my "pretty much the same as in the example implementation" missed a key part 😅 i read @benbender 's idea of automatically setup the db connection first and i think script vs function and that idea added up in my head and assumed it's already working like that (at least the teardown). long story short it would be definitely awesome of having the db connection passed to the exported seed function automatically. otherwise it's just confusing that there is a script and a function syntax. or does #8732 mean the latter won't work anymore?

  25. 2color commented on Sep 7, 2021

    @2color
    ContributorAuthor

    Closing this now that this has been released to General Availability in the 3.0.1 release

    You can explore the revamped seeding functionality in the docs

  26. removed their assignment
    on May 3, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

topic: previewFeaturestopic: prisma db seed

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions