1 import { CodeTabs, CodeTab, TypeList } from "docs-ui"
2
3 export const metadata = {
4 title: `${pageNumber} Perform Database Operations in a Service`,
5 }
6
7 # {metadata.title}
8
9 In this chapter, you'll learn how to perform database operations in a module's service.
10
11 <Note>
12
13 This chapter is intended for more advanced database use-cases where you need more control over queries and operations. For basic database operations, such as creating or retrieving data of a model, use the [Service Factory](../service-factory/page.mdx) instead.
14
15 </Note>
16
17 ## Run Queries
18
19 [MikroORM's entity manager](https://mikro-orm.io/docs/entity-manager) is a class that has methods to run queries on the database and perform operations.
20
21 Medusa provides an `InjectManager` decorator from the Modules SDK that injects a service's method with a [forked entity manager](https://mikro-orm.io/docs/identity-map#forking-entity-manager).
22
23 So, to run database queries in a service:
24
25 1. Add the `InjectManager` decorator to the method.
26 2. Add as a last parameter an optional `sharedContext` parameter that has the `MedusaContext` decorator from the Modules SDK. This context holds database-related context, including the manager injected by `InjectManager`
27
28 For example, in your service, add the following methods:
29
30 <Note>
31
32 As of [Medusa v2.11.0](https://github.com/medusajs/medusa/releases/tag/v2.11.0), MikroORM dependencies are included in the `@medusajs/framework` package. If you're using an older version of Medusa, change the import statement to `@mikro-orm/knex`.
33
34 </Note>
35
36 export const methodsHighlight = [
37 ["13", "getCount", "Retrieves the number of records in `my_custom` using the `count` method."],
38 ["20", "getCountSql", "Retrieves the number of records in `my_custom` using the `execute` method."]
39 ]
40
41 ```ts highlights={methodsHighlight}
42 // other imports...
43 import {
44 InjectManager,
45 MedusaContext,
46 } from "@medusajs/framework/utils"
47 import { Context } from "@medusajs/framework/types"
48 import { EntityManager } from "@medusajs/framework/mikro-orm/knex"
49
50 class BlogModuleService {
51 // ...
52
53 @InjectManager()
54 async getCount(
55 @MedusaContext() sharedContext?: Context<EntityManager>
56 ): Promise<number | undefined> {
57 return await sharedContext?.manager?.count("my_custom")
58 }
59
60 @InjectManager()
61 async getCountSql(
62 @MedusaContext() sharedContext?: Context<EntityManager>
63 ): Promise<number> {
64 const data = await sharedContext?.manager?.execute(
65 "SELECT COUNT(*) as num FROM my_custom"
66 )
67
68 return parseInt(data?.[0].num || 0)
69 }
70 }
71 ```
72
73 You add two methods `getCount` and `getCountSql` that have the `InjectManager` decorator. Each of the methods also accept the `sharedContext` parameter which has the `MedusaContext` decorator.
74
75 The entity manager is injected to the `sharedContext.manager` property, which is an instance of [EntityManager from the `@medusajs/framework/mikro-orm/knex` package](https://mikro-orm.io/api/knex/class/EntityManager).
76
77 You use the manager in the `getCount` method to retrieve the number of records in a table, and in the `getCountSql` to run a PostgreSQL query that retrieves the count.
78
79 <Note>
80
81 Refer to [MikroORM's reference](https://mikro-orm.io/api/knex/class/EntityManager) for a full list of the entity manager's methods.
82
83 </Note>
84
85 ---
86
87 ## Perform Database Operations
88
89 There are two ways to perform database operations in transactional methods:
90
91 1. Using the [data model repositories](#perform-database-operations-with-data-model-repositories) in your module.
92 2. Using the [transactional entity manager](#perform-database-operations-with-the-transactional-entity-manager) injected into the method's shared context.
93
94 For both approaches, you must wrap the method performing the database operations in a transaction.
95
96 ### Wrap Database Operations in Transactions
97
98 When performing database operations without using the [Service Factory](../service-factory/page.mdx), you must wrap the method performing the database operations in a transaction.
99
100 To wrap database operations in a transaction, you create two methods:
101
102 1. A private or protected method that's wrapped in a transaction. To wrap it in a transaction, you use the `InjectTransactionManager` decorator from the Modules SDK.
103 2. A public method that calls the transactional method. You use on it the `InjectManager` decorator as explained in the previous section.
104
105 Both methods must accept as a last parameter an optional `sharedContext` parameter that has the `MedusaContext` decorator from the Modules SDK. It holds database-related contexts passed through the Medusa application.
106
107 For example:
108
109 export const opHighlights = [
110 ["11", "InjectTransactionManager", "A decorator that injects the a transactional entity manager into the `sharedContext` parameter."],
111 ["17", "MedusaContext", "A decorator to use Medusa's shared context."],
112 ["24", "InjectManager", "A decorator that injects a forked entity manager into the context."],
113 ]
114
115 ```ts highlights={opHighlights}
116 import {
117 InjectManager,
118 InjectTransactionManager,
119 MedusaContext,
120 } from "@medusajs/framework/utils"
121 import { Context } from "@medusajs/framework/types"
122 import { EntityManager } from "@medusajs/framework/mikro-orm/knex"
123
124 class BlogModuleService {
125 // ...
126 @InjectTransactionManager()
127 protected async update_(
128 input: {
129 id: string,
130 name: string
131 },
132 @MedusaContext() sharedContext?: Context<EntityManager>
133 ): Promise<any> {
134 const transactionManager = sharedContext?.transactionManager
135
136 // TODO: update the record
137 }
138
139 @InjectManager()
140 async update(
141 input: {
142 id: string,
143 name: string
144 },
145 @MedusaContext() sharedContext?: Context<EntityManager>
146 ) {
147 return await this.update_(input, sharedContext)
148 }
149 }
150 ```
151
152 The `BlogModuleService` has two methods:
153
154 - A protected `update_` that performs the database operations inside a transaction.
155 - A public `update` that executes the transactional protected method.
156
157 You can then perform in the transactional method the database operations either using the [data model repository](#perform-database-operations-with-data-model-repositories) or the [transactional entity manager](#perform-database-operations-with-the-transactional-entity-manager).
158
159 #### Why Wrap a Transactional Method
160
161 The variables in the transactional method (such as `update_`) hold values that are uncommitted to the database. They're only committed once the method finishes execution.
162
163 So, if in your method you perform database operations, then use their result to perform other actions, such as connecting to a third-party service, you'll be working with uncommitted data.
164
165 By placing only the database operations in a method that has the `InjectTransactionManager` and using it in a wrapper method, the wrapper method receives the committed result of the transactional method.
166
167 <Note title="Optimization Tip">
168
169 This is also useful if you perform heavy data normalization outside of the database operations. In that case, you don't hold the transaction for a longer time than needed.
170
171 </Note>
172
173 For example, the `update` method may call other methods than `update_` to perform other actions:
174
175 ```ts
176 // other imports...
177 import {
178 InjectManager,
179 InjectTransactionManager,
180 MedusaContext,
181 } from "@medusajs/framework/utils"
182 import { Context } from "@medusajs/framework/types"
183 import { EntityManager } from "@medusajs/framework/mikro-orm/knex"
184
185 class BlogModuleService {
186 // ...
187 @InjectTransactionManager()
188 protected async update_(
189 // ...
190 ): Promise<any> {
191 // ...
192 }
193 @InjectManager()
194 async update(
195 input: {
196 id: string,
197 name: string
198 },
199 @MedusaContext() sharedContext?: Context<EntityManager>
200 ) {
201 const newData = await this.update_(input, sharedContext)
202
203 // example method that sends data to another system
204 await this.sendNewDataToSystem(newData)
205
206 return newData
207 }
208 }
209 ```
210
211 In this case, only the `update_` method is wrapped in a transaction. The returned value `newData` holds the committed result, which can be used for other operations, such as passed to a `sendNewDataToSystem` method.
212
213 #### Using Methods in Transactional Methods
214
215 If your protected transactional method uses other methods that accept a Medusa context, pass the shared context to those methods.
216
217 For example:
218
219 export const anotherMethodHighlights = [
220 ["26", "sharedContext", "Pass the context to the other transactional method."]
221 ]
222
223 ```ts highlights={anotherMethodHighlights}
224 // other imports...
225 import {
226 InjectTransactionManager,
227 MedusaContext,
228 } from "@medusajs/framework/utils"
229 import { Context } from "@medusajs/framework/types"
230 import { EntityManager } from "@medusajs/framework/mikro-orm/knex"
231
232 class BlogModuleService {
233 // ...
234 @InjectTransactionManager()
235 protected async anotherMethod(
236 @MedusaContext() sharedContext?: Context<EntityManager>
237 ) {
238 // ...
239 }
240
241 @InjectTransactionManager()
242 protected async update_(
243 input: {
244 id: string,
245 name: string
246 },
247 @MedusaContext() sharedContext?: Context<EntityManager>
248 ): Promise<any> {
249 this.anotherMethod(sharedContext)
250 }
251 }
252 ```
253
254 You use the `anotherMethod` transactional method in the `update_` transactional method, so you pass it the shared context.
255
256 The `anotherMethod` now runs in the same transaction as the `update_` method.
257
258 ### Perform Database Operations with Data Model Repositories
259
260 For every data model in your module, Medusa generates a data model repository that has methods to perform database operations.
261
262 For example, if your module has a `Post` model, it has a `postRepository` in the container.
263
264 The data model repository is a wrapper around the [entity manager](https://mikro-orm.io/api/knex/class/EntityManager) that provides a higher-level API for performing database operations.
265
266 <Note>
267
268 To use the low-level entity manager, use the [transactional entity manager](#perform-database-operations-with-the-transactional-entity-manager) instead.
269
270 </Note>
271
272 #### Resolve Data Model Repository
273
274 When the Medusa application injects a data model repository into a module's container, it formats the registration name by:
275
276 - Taking the data model's name that's passed as the first parameter of `model.define`
277 - Lower-casing the first character
278 - Suffixing the result with `Repository`.
279
280 For example:
281
282 - `Post` model: `postRepository`
283 - `My_Custom` model: `my_CustomRepository`
284
285 So, to resolve a data model repository from a module's container, pass the expected registration name of the repository in the first parameter of the module's constructor (the container).
286
287 For example:
288
289 <CodeTabs group="service-type">
290 <CodeTab label="Extending Service Factory" value="service-factory">
291
292 export const serviceFactoryRepoHighlights = [
293 ["20", "postRepository", "Resolve the data model repository of the `Post` model."],
294 ]
295
296 ```ts highlights={serviceFactoryRepoHighlights}
297 import { MedusaService } from "@medusajs/framework/utils"
298 import { InferTypeOf, DAL } from "@medusajs/framework/types"
299 import Post from "./models/post"
300
301 type Post = InferTypeOf<typeof Post>
302
303 type InjectedDependencies = {
304 postRepository: DAL.RepositoryService<Post>
305 }
306
307 class BlogModuleService extends MedusaService({
308 Post,
309 }){
310 protected postRepository_: DAL.RepositoryService<Post>
311
312 constructor({
313 postRepository,
314 }: InjectedDependencies) {
315 super(...arguments)
316 this.postRepository_ = postRepository
317 }
318 }
319
320 export default BlogModuleService
321 ```
322 </CodeTab>
323 <CodeTab label="Without Service Factory" value="no-service-factory">
324
325 export const noServiceFactoryRepoHighlights = [
326 ["17", "postRepository", "Resolve the data model repository of the `Post` model."],
327 ]
328
329 ```ts highlights={noServiceFactoryRepoHighlights}
330 import { InferTypeOf, DAL } from "@medusajs/framework/types"
331 import Post from "./models/post"
332
333 type Post = InferTypeOf<typeof Post>
334
335 type InjectedDependencies = {
336 postRepository: DAL.RepositoryService<Post>
337 }
338
339 class BlogModuleService {
340 protected postRepository_: DAL.RepositoryService<Post>
341
342 constructor({
343 postRepository,
344 }: InjectedDependencies) {
345 super(...arguments)
346 this.postRepository_ = postRepository
347 }
348 }
349
350 export default BlogModuleService
351 ```
352
353 </CodeTab>
354 </CodeTabs>
355
356 You can then use the data model repository in your service to perform database operations.
357
358 #### Data Model Repository Methods
359
360 A data model repository has methods that allows you to create, update, and delete records, among other operations.
361
362 To learn about the methods available in a data model repository, refer to the [Data Model Repository](!resources!/data-model-repository-reference) reference.
363
364 ### Perform Database Operations with the Transactional Entity Manager
365
366 Your transactional method can use the transactional entity manager injected into the method's shared context to perform database operations. It's an instance of the [MikroORM EntityManager](https://mikro-orm.io/api/knex/class/EntityManager) class.
367
368 <Note>
369
370 To use an easier higher-level API focused on each data model, use the [data model repository](#perform-database-operations-with-data-model-repositories) instead.
371
372 </Note>
373
374 For example:
375
376 export const transactionalEntityManagerHighlights = [
377 ["19", "transactionManager", "Use the transactional entity manager injected\ninto the `sharedContext` parameter."],
378 ["20", "nativeUpdate", "Perform a native update operation."],
379 ["31", "execute", "Perform a native query operation."],
380 ]
381
382 ```ts highlights={transactionalEntityManagerHighlights}
383 import {
384 InjectManager,
385 InjectTransactionManager,
386 MedusaContext,
387 } from "@medusajs/framework/utils"
388 import { Context } from "@medusajs/framework/types"
389 import { EntityManager } from "@medusajs/framework/mikro-orm/knex"
390
391 class BlogModuleService {
392 // ...
393 @InjectTransactionManager()
394 protected async update_(
395 input: {
396 id: string,
397 name: string
398 },
399 @MedusaContext() sharedContext?: Context<EntityManager>
400 ): Promise<any> {
401 const transactionManager = sharedContext?.transactionManager
402 await transactionManager?.nativeUpdate(
403 "my_custom",
404 {
405 id: input.id,
406 },
407 {
408 name: input.name,
409 }
410 )
411
412 // retrieve again
413 const updatedRecord = await transactionManager?.execute(
414 `SELECT * FROM my_custom WHERE id = '${input.id}'`
415 )
416
417 return updatedRecord
418 }
419
420 @InjectManager()
421 async update(
422 input: {
423 id: string,
424 name: string
425 },
426 @MedusaContext() sharedContext?: Context<EntityManager>
427 ) {
428 return await this.update_(input, sharedContext)
429 }
430 }
431 ```
432
433 The `update_` method uses the transactional entity manager injected into the `sharedContext.transactionManager` property to perform the database operations.
434
435 Find all available methods in the [MikroORM EntityManager](https://mikro-orm.io/api/knex/class/EntityManager) reference.
436
437 ---
438
439 ## Configure Transactions with the Base Repository
440
441 To configure the transaction, such as its [isolation level](https://www.postgresql.org/docs/current/transaction-iso.html), use the `baseRepository` class registered in your module's container.
442
443 The `baseRepository` is an instance of a repository class that provides methods to create transactions, run database operations, and more.
444
445 The `baseRepository` has a `transaction` method that allows you to run a function within a transaction and configure that transaction.
446
447 For example, resolve the `baseRepository` in your service's constructor:
448
449 <CodeTabs group="service-type">
450 <CodeTab label="Extending Service Factory" value="service-factory">
451
452 export const baseRepoHighlights = [
453 ["16", "baseRepository", "Resolve the base repository."],
454 ]
455
456 ```ts highlights={baseRepoHighlights}
457 import { MedusaService } from "@medusajs/framework/utils"
458 import Post from "./models/post"
459 import { DAL } from "@medusajs/framework/types"
460
461 type InjectedDependencies = {
462 baseRepository: DAL.RepositoryService
463 }
464
465 class BlogModuleService extends MedusaService({
466 Post,
467 }){
468 protected baseRepository_: DAL.RepositoryService
469
470 constructor({ baseRepository }: InjectedDependencies) {
471 super(...arguments)
472 this.baseRepository_ = baseRepository
473 }
474 }
475
476 export default BlogModuleService
477 ```
478
479 </CodeTab>
480 <CodeTab label="Without Service Factory" value="no-service-factory">
481
482 export const noServiceFactoryBaseRepoHighlights = [
483 ["11", "baseRepository", "Resolve the base repository."],
484 ]
485
486 ```ts highlights={noServiceFactoryBaseRepoHighlights}
487 import { DAL } from "@medusajs/framework/types"
488
489 type InjectedDependencies = {
490 baseRepository: DAL.RepositoryService
491 }
492
493 class BlogModuleService {
494 protected baseRepository_: DAL.RepositoryService
495
496 constructor({ baseRepository }: InjectedDependencies) {
497 this.baseRepository_ = baseRepository
498 }
499 }
500
501 export default BlogModuleService
502 ```
503
504 </CodeTab>
505 </CodeTabs>
506
507 Then, use it in the service's transactional methods:
508
509 export const repoHighlights = [
510 ["20", "transaction", "Wrap the function parameter in a transaction."]
511 ]
512
513 ```ts highlights={repoHighlights}
514 // ...
515 import {
516 InjectManager,
517 InjectTransactionManager,
518 MedusaContext,
519 } from "@medusajs/framework/utils"
520 import { Context } from "@medusajs/framework/types"
521 import { EntityManager } from "@medusajs/framework/mikro-orm/knex"
522
523 class BlogModuleService {
524 // ...
525 @InjectTransactionManager()
526 protected async update_(
527 input: {
528 id: string,
529 name: string
530 },
531 @MedusaContext() sharedContext?: Context<EntityManager>
532 ): Promise<any> {
533 return await this.baseRepository_.transaction(
534 async (transactionManager) => {
535 await transactionManager.nativeUpdate(
536 "my_custom",
537 {
538 id: input.id,
539 },
540 {
541 name: input.name,
542 }
543 )
544
545 // retrieve again
546 const updatedRecord = await transactionManager.execute(
547 `SELECT * FROM my_custom WHERE id = '${input.id}'`
548 )
549
550 return updatedRecord
551 },
552 {
553 transaction: sharedContext?.transactionManager,
554 }
555 )
556 }
557
558 @InjectManager()
559 async update(
560 input: {
561 id: string,
562 name: string
563 },
564 @MedusaContext() sharedContext?: Context<EntityManager>
565 ) {
566 return await this.update_(input, sharedContext)
567 }
568 }
569 ```
570
571 The `update_` method uses the `baseRepository_.transaction` method to wrap a function in a transaction.
572
573 The function parameter receives a transactional entity manager as a parameter. Use it to perform the database operations.
574
575 The `baseRepository_.transaction` method also receives as a second parameter an object of options. You must pass in it the `transaction` property and set its value to the `sharedContext.transactionManager` property so that the function wrapped in the transaction uses the injected transaction manager.
576
577 <Note>
578
579 Refer to [MikroORM's reference](https://mikro-orm.io/api/knex/class/EntityManager) for a full list of the entity manager's methods.
580
581 </Note>
582
583 ### Transaction Options
584
585 The second parameter of the `baseRepository_.transaction` method is an object of options that accepts the following properties:
586
587 1. `transaction`: Set the transactional entity manager passed to the function. You must provide this option as explained in the previous section.
588
589 ```ts highlights={[["24"]]}
590 // other imports...
591 import { EntityManager } from "@medusajs/framework/mikro-orm/knex"
592 import {
593 InjectTransactionManager,
594 MedusaContext,
595 } from "@medusajs/framework/utils"
596 import { Context } from "@medusajs/framework/types"
597
598 class BlogModuleService {
599 // ...
600 @InjectTransactionManager()
601 async update_(
602 input: {
603 id: string,
604 name: string
605 },
606 @MedusaContext() sharedContext?: Context<EntityManager>
607 ): Promise<any> {
608 return await this.baseRepository_.transaction<EntityManager>(
609 async (transactionManager) => {
610 // ...
611 },
612 {
613 transaction: sharedContext?.transactionManager,
614 }
615 )
616 }
617 }
618 ```
619
620 2. `isolationLevel`: Sets the transaction's [isolation level](https://www.postgresql.org/docs/current/transaction-iso.html). Its values can be:
621 - `read committed`
622 - `read uncommitted`
623 - `snapshot`
624 - `repeatable read`
625 - `serializable`
626
627 ```ts highlights={[["25"]]}
628 // other imports...
629 import {
630 InjectTransactionManager,
631 MedusaContext,
632 } from "@medusajs/framework/utils"
633 import { Context } from "@medusajs/framework/types"
634 import { EntityManager } from "@medusajs/framework/mikro-orm/knex"
635 import { IsolationLevel } from "@medusajs/framework/mikro-orm/core"
636
637 class BlogModuleService {
638 // ...
639 @InjectTransactionManager()
640 async update_(
641 input: {
642 id: string,
643 name: string
644 },
645 @MedusaContext() sharedContext?: Context<EntityManager>
646 ): Promise<any> {
647 return await this.baseRepository_.transaction<EntityManager>(
648 async (transactionManager) => {
649 // ...
650 },
651 {
652 isolationLevel: IsolationLevel.READ_COMMITTED,
653 }
654 )
655 }
656 }
657 ```
658
659 3. `enableNestedTransactions`: (default: `false`) whether to allow using nested transactions.
660 - If `transaction` is provided and this is disabled, the manager in `transaction` is re-used.
661
662 ```ts highlights={[["24"]]}
663 // other imports...
664 import {
665 InjectTransactionManager,
666 MedusaContext,
667 } from "@medusajs/framework/utils"
668 import { Context } from "@medusajs/framework/types"
669 import { EntityManager } from "@medusajs/framework/mikro-orm/knex"
670
671 class BlogModuleService {
672 // ...
673 @InjectTransactionManager()
674 async update_(
675 input: {
676 id: string,
677 name: string
678 },
679 @MedusaContext() sharedContext?: Context<EntityManager>
680 ): Promise<any> {
681 return await this.baseRepository_.transaction<EntityManager>(
682 async (transactionManager) => {
683 // ...
684 },
685 {
686 enableNestedTransactions: false,
687 }
688 )
689 }
690 }
691 ```