diff --git a/README.md b/README.md index 43aa1f1..b01d1e1 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186). -_1306 TILs and counting..._ +_1307 TILs and counting..._ --- @@ -745,6 +745,7 @@ _1306 TILs and counting..._ - [Batch Insert Records With createMany](prisma/batch-insert-records-with-create-many.md) - [Execute A Raw SQL Query](prisma/execute-a-raw-sql-query.md) - [Grab A Limited Set Of Records](prisma/grab-a-limited-set-of-records.md) +- [Open Connections To Multiple Databases](prisma/open-connections-to-multiple-databases.md) - [Specify Alternate Location For Prisma Schema](prisma/specify-alternate-location-for-prisma-schema.md) ### Python diff --git a/prisma/open-connections-to-multiple-databases.md b/prisma/open-connections-to-multiple-databases.md new file mode 100644 index 0000000..a92f833 --- /dev/null +++ b/prisma/open-connections-to-multiple-databases.md @@ -0,0 +1,39 @@ +# Open Connections To Multiple Databases + +A standard database connection with Prisma is determined by a `DATABASE_URL` +env var set in the `.env` file of your project. Typically, the Prisma client +connecting to that URL will be configured in a separate file and imported +wherever it is used. + +```javascript +import {prisma} from './utils/prisma' +``` + +What if you want to connect to a second, alternate database? + +You can create a new Prisma client with the data source configured to be a +different connection URL. + +```javascript +import {prisma as primaryPrismaClient} from '@skillrecordings/database' +import {PrismaClient} from '@prisma/client' + +const secondaryDatabaseUrl = 'mysql://root@localhost:3399/my-database' + +const secondaryPrismaClient = new PrismaClient({ + datasources: { + db: { + url: secondaryDatabaseUrl + } + }, +}) +``` + +And with that, you can execute queries against both databases. + +```javascript +const primaryUserCount = await primaryPrismaClient.user.count() +const secondaryUserCount = await secondaryPrismaClient.user.count() +``` + +[source](https://www.prisma.io/docs/reference/api-reference/prisma-client-reference#programmatically-override-a-datasource-url)