or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

configuration.mddatabase-operations.mddevelopment-server.mdindex.mdproject-creation.mduser-management.md

database-operations.mddocs/

0

# Database Operations

1

2

The Medusa CLI provides comprehensive database management capabilities including migration management and database seeding. These commands are only available within Medusa project directories and integrate with the local Medusa installation's database management system.

3

4

## Capabilities

5

6

### Database Migrations

7

8

Manage database schema migrations for the Medusa project, including running, reverting, and viewing migration status.

9

10

```bash { .api }

11

medusa migrations [action]

12

```

13

14

**Parameters:**

15

- `action` (required): Migration action to perform

16

- `run`: Execute pending migrations

17

- `revert`: Revert the most recent migration

18

- `show`: Display migration status and history

19

20

**Usage Examples:**

21

22

```bash

23

# Run all pending migrations

24

medusa migrations run

25

26

# Revert the last migration

27

medusa migrations revert

28

29

# Show migration status

30

medusa migrations show

31

```

32

33

**Behavior:**

34

- Sets NODE_ENV to 'development' if not already configured

35

- Loads migration configuration from local Medusa project

36

- Connects to database using project's configuration

37

- Provides detailed feedback on migration execution

38

39

### Database Seeding

40

41

Populate the database with initial or sample data using custom seed files.

42

43

```bash { .api }

44

medusa seed --seed-file <path>

45

```

46

47

**Options:**

48

- `-f, --seed-file <string>` (required): Path to the seed file containing data and instructions

49

- `-m, --migrate <boolean>`: Run migrations before seeding (default: true)

50

51

**Usage Examples:**

52

53

```bash

54

# Seed database with specific file

55

medusa seed --seed-file ./data/sample-products.js

56

57

# Seed without running migrations first

58

medusa seed --seed-file ./data/users.js --migrate false

59

60

# Seed with migrations (default behavior)

61

medusa seed -f ./data/store-setup.js

62

```

63

64

**Behavior:**

65

- Optionally runs migrations before seeding based on --migrate flag

66

- Sets NODE_ENV to 'development' for seed execution

67

- Executes seed file in the context of the Medusa project

68

- Provides progress feedback during seeding process

69

70

## Migration Management

71

72

### Migration Execution Flow

73

74

The migration system follows a structured execution pattern:

75

76

**Run Migrations:**

77

1. Connects to database using project configuration

78

2. Checks for pending migrations in the migrations directory

79

3. Executes migrations in chronological order

80

4. Updates migration tracking table

81

5. Reports success or failure for each migration

82

83

**Revert Migrations:**

84

1. Identifies the most recently applied migration

85

2. Executes the migration's down/revert function

86

3. Updates migration tracking to reflect the reversion

87

4. Provides confirmation of successful reversion

88

89

**Show Migration Status:**

90

1. Queries migration tracking table

91

2. Compares with available migration files

92

3. Displays status of each migration (pending/applied)

93

4. Shows migration timestamps and descriptions

94

95

### Migration File Requirements

96

97

Migration files must follow Medusa's expected format:

98

99

**File Location:**

100

- Located in project's migrations directory

101

- Typically in `src/migrations/` or similar project structure

102

- Named with timestamp prefix for ordering

103

104

**File Structure:**

105

- Export functions for both up (apply) and down (revert) operations

106

- Include proper database connection handling

107

- Follow Medusa's migration API conventions

108

109

## Database Seeding

110

111

### Seed File Format

112

113

Seed files should be JavaScript modules that export seeding logic:

114

115

**Basic Structure:**

116

```javascript

117

// Example seed file structure

118

module.exports = async (container) => {

119

const productService = container.resolve("productService");

120

121

// Seeding logic here

122

await productService.create({

123

title: "Sample Product",

124

// ... other product data

125

});

126

};

127

```

128

129

**Container Access:**

130

- Seed functions receive Medusa's dependency injection container

131

- Access to all Medusa services and repositories

132

- Can perform complex data operations using Medusa's business logic

133

134

### Seeding Workflow

135

136

The seeding process follows these steps:

137

138

1. **Pre-Migration** (if enabled): Run pending migrations to ensure schema is current

139

2. **Container Setup**: Initialize Medusa's dependency injection container

140

3. **Seed Execution**: Load and execute the specified seed file

141

4. **Transaction Management**: Handle database transactions for data consistency

142

5. **Error Handling**: Provide detailed error reporting for failed seeding operations

143

6. **Cleanup**: Properly close database connections and clean up resources

144

145

## Database Configuration

146

147

### Connection Management

148

149

Database operations use the project's existing configuration:

150

151

**Configuration Sources:**

152

- Environment variables (DATABASE_URL, etc.)

153

- Project's medusa-config.js file

154

- Default connection parameters

155

156

**Connection Handling:**

157

- Automatic connection establishment using project settings

158

- Proper connection pooling and management

159

- Graceful handling of connection failures

160

161

### Environment Considerations

162

163

Database commands respect environment settings:

164

165

**NODE_ENV Handling:**

166

- Automatically sets to 'development' if not specified

167

- Affects database connection configuration

168

- Influences logging and error reporting levels

169

170

**Database Selection:**

171

- Uses project's configured database connection

172

- Supports multiple database environments through configuration

173

- Maintains separation between development, staging, and production

174

175

## Error Handling and Validation

176

177

### Migration Error Management

178

179

The migration system includes comprehensive error handling:

180

181

**Pre-execution Validation:**

182

- Verifies database connectivity before starting

183

- Checks for required migration files and structure

184

- Validates migration sequence and dependencies

185

186

**Runtime Error Handling:**

187

- Captures and reports migration execution errors

188

- Maintains database consistency during failures

189

- Provides detailed error messages for debugging

190

191

**Recovery Mechanisms:**

192

- Safe rollback procedures for failed migrations

193

- Database state preservation during errors

194

- Clear guidance for manual intervention when needed

195

196

### Seeding Error Management

197

198

Database seeding includes robust error handling:

199

200

**File Validation:**

201

- Verifies seed file existence and format

202

- Checks for required dependencies and services

203

- Validates seed file structure before execution

204

205

**Execution Monitoring:**

206

- Progress tracking during seed operations

207

- Detailed error reporting for failed seed operations

208

- Transaction rollback on critical failures

209

210

## Command Proxying and Integration

211

212

### Local Command Resolution

213

214

Database commands are proxied to the local Medusa installation:

215

216

**Dynamic Loading:**

217

- Commands resolved from `@medusajs/medusa/dist/commands/`

218

- Uses local project's Medusa version for compatibility

219

- Falls back to help display if commands unavailable

220

221

**Argument Forwarding:**

222

- All CLI options passed through to underlying commands

223

- Project context information automatically included

224

- Maintains full compatibility with Medusa's native database tools