Search code examples
node.jsnestjstypeorm

Is there a way to auto create a databse in typeORM?


I am migrating from sequelizeORM to typeORM. In sequelize-cli there are nice commands to drop database and create a new one for example:

node_modules/.bin/sequelize db:drop
node_modules/.bin/sequelize db:create
node_modules/.bin/sequelize db:migrate

Ok, for typeORM I know how to run migration but I can't find anywhere how to automatically create or drop a database. Tnx in advance.


Solution

  • You can also use typeorm-extension package, to create or drop the database specified for the connection, for nearly all database driver. The package also parses the extra parameter charset and characterSet of the extra parameter (ENV: TYPEORM_DRIVER_EXTRA)

    import {createDatabase} from "typeorm-extension";
    
    (async () => {
        await createDatabase({ifNotExist: true});
       
        await dropDatabase({ifExist: true});
    
        process.exit(0);
    })();
    

    You can also provide the charset and characterSet as properties for the first parameter to the createDatabase() function. F.e

    • postgres
    createDatabase({ifNotExist: true, characterSet: "UTF8"});
    
    • mysql
    createDatabase({ifNotExist: true, charset: "utf8mb4_general_ci", characterSet: "utf8mb4"});
    

    If you have any questions or concerns feel free to contact me or contribute to the codebase on Github