0
# Version Management
1
2
dbt-core provides utilities for version checking, update notifications, and version information display. This is useful for ensuring compatibility and staying current with releases.
3
4
## Version Information Functions
5
6
```python { .api }
7
def get_version_information() -> str:
8
"""
9
Get comprehensive version information for dbt-core and installed plugins.
10
11
Returns formatted string containing:
12
- dbt-core version and update status
13
- All installed dbt adapter plugin versions
14
- Update recommendations
15
16
Returns:
17
str: Multi-line formatted version information
18
"""
19
20
def get_installed_version():
21
"""
22
Get the currently installed dbt-core version.
23
24
Returns:
25
str: Version string (e.g., "1.10.10")
26
"""
27
28
def get_latest_version():
29
"""
30
Get the latest available dbt-core version from PyPI.
31
32
Makes HTTP request to PyPI API to check for newer releases.
33
34
Returns:
35
str: Latest version string, or None if check fails
36
"""
37
```
38
39
## Version Checking
40
41
### Basic Version Information
42
43
```python
44
from dbt.version import get_installed_version, get_latest_version
45
46
# Get current version
47
current = get_installed_version()
48
print(f"Installed dbt-core: {current}")
49
50
# Check for updates
51
latest = get_latest_version()
52
if latest and latest != current:
53
print(f"Update available: {latest}")
54
else:
55
print("dbt-core is up to date")
56
```
57
58
### Comprehensive Version Report
59
60
```python
61
from dbt.version import get_version_information
62
63
# Get full version report
64
version_info = get_version_information()
65
print(version_info)
66
67
# Example output:
68
# Core:
69
# - dbt-core: 1.10.10 (latest)
70
#
71
# Plugins:
72
# - dbt-postgres: 1.10.10 (latest)
73
# - dbt-snowflake: 1.10.10 (latest)
74
# - dbt-bigquery: 1.10.10 (latest)
75
```
76
77
## Version Comparison
78
79
### Semantic Version Utilities
80
81
dbt uses semantic versioning and includes utilities for version comparison:
82
83
```python
84
import dbt_common.semver as semver
85
86
def check_version_compatibility(required_version, current_version):
87
"""Check if current version meets requirements."""
88
try:
89
required = semver.VersionSpecifier(required_version)
90
current = semver.Version(current_version)
91
return required.is_satisfied_by(current)
92
except Exception:
93
return False
94
95
# Usage
96
if check_version_compatibility(">=1.10.0", get_installed_version()):
97
print("Version meets requirements")
98
else:
99
print("Version upgrade required")
100
```
101
102
### Plugin Version Checking
103
104
```python
105
def check_adapter_versions():
106
"""Check versions of installed adapter plugins."""
107
version_info = get_version_information()
108
lines = version_info.split('\n')
109
110
plugins = {}
111
in_plugins = False
112
113
for line in lines:
114
if line.startswith('Plugins:'):
115
in_plugins = True
116
continue
117
elif in_plugins and line.strip().startswith('- '):
118
# Parse plugin line: " - dbt-postgres: 1.10.10 (latest)"
119
plugin_info = line.strip()[2:] # Remove "- "
120
if ':' in plugin_info:
121
name, version_part = plugin_info.split(':', 1)
122
version = version_part.strip().split()[0]
123
plugins[name.strip()] = version
124
125
return plugins
126
127
# Get adapter versions
128
adapters = check_adapter_versions()
129
for adapter, version in adapters.items():
130
print(f"{adapter}: {version}")
131
```
132
133
## Update Notifications
134
135
### Custom Update Checking
136
137
```python
138
from dbt.version import get_installed_version, get_latest_version
139
import requests
140
from packaging import version
141
142
def check_for_updates(notify=True):
143
"""
144
Check for dbt-core updates with custom notification.
145
146
Args:
147
notify: Whether to print update notifications
148
149
Returns:
150
dict: Update information
151
"""
152
current = get_installed_version()
153
latest = get_latest_version()
154
155
update_info = {
156
'current': current,
157
'latest': latest,
158
'update_available': False,
159
'is_prerelease': False
160
}
161
162
if latest and current:
163
try:
164
current_ver = version.parse(current)
165
latest_ver = version.parse(latest)
166
167
update_info['update_available'] = latest_ver > current_ver
168
update_info['is_prerelease'] = latest_ver.is_prerelease
169
170
if notify and update_info['update_available']:
171
print(f"dbt-core update available: {current} → {latest}")
172
if not update_info['is_prerelease']:
173
print("Run: pip install --upgrade dbt-core")
174
175
except Exception as e:
176
if notify:
177
print(f"Could not check for updates: {e}")
178
179
return update_info
180
```
181
182
### Automated Update Checks
183
184
```python
185
import os
186
import time
187
from pathlib import Path
188
189
def should_check_updates():
190
"""Check if it's time for an update check (daily)."""
191
check_file = Path.home() / '.dbt' / 'last_update_check'
192
193
if not check_file.exists():
194
return True
195
196
try:
197
last_check = float(check_file.read_text())
198
return time.time() - last_check > 86400 # 24 hours
199
except:
200
return True
201
202
def record_update_check():
203
"""Record that we performed an update check."""
204
check_file = Path.home() / '.dbt' / 'last_update_check'
205
check_file.parent.mkdir(exist_ok=True)
206
check_file.write_text(str(time.time()))
207
208
def periodic_update_check():
209
"""Perform periodic update check."""
210
if should_check_updates():
211
update_info = check_for_updates(notify=True)
212
record_update_check()
213
return update_info
214
return None
215
```
216
217
## Version-Dependent Features
218
219
### Feature Compatibility
220
221
```python
222
from dbt.version import get_installed_version
223
from packaging import version
224
225
def supports_feature(feature_name, min_version):
226
"""Check if current version supports a feature."""
227
current = get_installed_version()
228
if not current:
229
return False
230
231
try:
232
return version.parse(current) >= version.parse(min_version)
233
except:
234
return False
235
236
# Feature checking
237
if supports_feature("contracts", "1.5.0"):
238
print("Model contracts supported")
239
240
if supports_feature("saved_queries", "1.8.0"):
241
print("Saved queries supported")
242
243
if supports_feature("unit_tests", "1.8.0"):
244
print("Unit tests supported")
245
```
246
247
### Version-Specific Configuration
248
249
```python
250
def get_version_config():
251
"""Get configuration based on dbt version."""
252
current = get_installed_version()
253
if not current:
254
return {}
255
256
config = {}
257
current_ver = version.parse(current)
258
259
# Version-specific features
260
if current_ver >= version.parse("1.8.0"):
261
config['supports_unit_tests'] = True
262
config['supports_saved_queries'] = True
263
264
if current_ver >= version.parse("1.5.0"):
265
config['supports_contracts'] = True
266
config['supports_model_versions'] = True
267
268
if current_ver >= version.parse("1.0.0"):
269
config['supports_metrics'] = True
270
config['supports_exposures'] = True
271
272
return config
273
274
# Usage
275
config = get_version_config()
276
if config.get('supports_contracts'):
277
print("Can use model contracts")
278
```
279
280
## Integration Examples
281
282
### CLI Integration
283
284
```python
285
import click
286
from dbt.version import get_version_information
287
288
@click.command()
289
@click.option('--check-updates', is_flag=True, help='Check for updates')
290
def version_command(check_updates):
291
"""Display version information."""
292
version_info = get_version_information()
293
click.echo(version_info)
294
295
if check_updates:
296
update_info = check_for_updates()
297
if update_info['update_available']:
298
click.echo(f"\nUpdate available: {update_info['latest']}")
299
else:
300
click.echo("\ndbt-core is up to date")
301
```
302
303
### Application Health Check
304
305
```python
306
def health_check():
307
"""Perform application health check including version validation."""
308
health = {
309
'dbt_version': get_installed_version(),
310
'update_available': False,
311
'plugins': {},
312
'status': 'healthy'
313
}
314
315
try:
316
# Check for updates
317
update_info = check_for_updates(notify=False)
318
health['update_available'] = update_info['update_available']
319
health['latest_version'] = update_info['latest']
320
321
# Check plugin versions
322
health['plugins'] = check_adapter_versions()
323
324
# Validate minimum version requirements
325
min_required = "1.8.0"
326
if not supports_feature("minimum", min_required):
327
health['status'] = 'warning'
328
health['message'] = f"dbt-core {min_required}+ recommended"
329
330
except Exception as e:
331
health['status'] = 'error'
332
health['error'] = str(e)
333
334
return health
335
336
# Usage in monitoring
337
health = health_check()
338
if health['status'] != 'healthy':
339
print(f"Health check warning: {health.get('message', 'Unknown issue')}")
340
```
341
342
### Dependency Management
343
344
```python
345
def validate_environment():
346
"""Validate that the dbt environment meets requirements."""
347
issues = []
348
349
# Check core version
350
current = get_installed_version()
351
if not current:
352
issues.append("dbt-core not installed")
353
return issues
354
355
# Check for major version compatibility
356
current_ver = version.parse(current)
357
if current_ver.major < 1:
358
issues.append(f"dbt-core {current} is outdated (1.0+ required)")
359
360
# Check for adapter compatibility
361
adapters = check_adapter_versions()
362
for adapter, adapter_version in adapters.items():
363
try:
364
adapter_ver = version.parse(adapter_version)
365
if adapter_ver.major != current_ver.major:
366
issues.append(f"{adapter} version mismatch: {adapter_version} vs core {current}")
367
except:
368
issues.append(f"Could not parse {adapter} version: {adapter_version}")
369
370
return issues
371
372
# Environment validation
373
issues = validate_environment()
374
if issues:
375
print("Environment issues found:")
376
for issue in issues:
377
print(f" - {issue}")
378
else:
379
print("Environment validation passed")
380
```