-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpgversion.py
More file actions
294 lines (221 loc) · 8.54 KB
/
Copy pathpgversion.py
File metadata and controls
294 lines (221 loc) · 8.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
# This script aims to assist working with Postgres Version Numbers.
# Features
# - Validation of Postgres Version Strings
# - Conversion of Postgres version string to version number (for e.g. v10.14 -> 100014)
# - Get Release Date information for a given Postgres Version
# - Compare release dates of 2 version numbers
# - Attempt auto-correction of minor versions
# - Extract Major (or Minor) version from Version String
# Read more in the README at
# https://github.com/robins/pgversion/blob/master/README.md
# Original Source: https://github.com/robins/pgversion/blob/master/pgversion.py
import sys
import re
from datetime import datetime
debug_level = 0
default_debug_level = 1
import os
import json
_current_dir = os.path.dirname(os.path.abspath(__file__))
_json_path = os.path.join(_current_dir, 'pg_versions.json')
try:
with open(_json_path, 'r') as f:
_verReleaseDates = json.load(f)
except Exception as e:
print(f"Failed to load pg_versions.json: {e}", file=sys.stderr)
_verReleaseDates = {}
def dprint(s, debug = default_debug_level):
if (debug_level >= debug):
print (s)
# Returns: True if the postgres version has already been released
# Input: Version number in "Major.Minor" format.
# Detail: It accepts both "a.b.c" and "a.b" version formats.
# Error: Return False if invalid input is provided, or hasn't been released yet (even if valid)
def isReleasedPGVersion(_s, debug = default_debug_level):
s= str(_s)
if (isValidPGVersion(s)):
if (s in _verReleaseDates):
return True
else:
dprint("Version hasn't been released yet - " + s, debug)
else:
dprint("Invalid PG Version - " + s, debug)
return False
# Returns: True if the postgres version is already released or technically valid
# Input: Version number in "Major.Minor" format.
# Detail: It accepts both "a.b.c" and "a.b" version formats.
# Error: Return False if invalid input is provided
# Valid Version: Both 10<=MajorVersion<100 and 0<=MinorVersion<10000.
def isValidPGVersion(_s, debug = default_debug_level):
s= str(_s)
# Old (v9.3.1) or New (v11.0) require at least 4 characters for
# being a valid version string
if (len(s)<4):
dprint('Invalid Version String - Requires at least 4 characters - ' + s, debug)
return False
if (re.match(r"^\.|.*\.$", s)):
dprint("Invalid Version String. Shouldn't begin or end with period / dot (.) - " + s, debug)
return False
# Fail if there are 2 or more adjacent dots (.)
if (re.match(r".*[\.]{2,}", s)):
dprint("Invalid Version String. There are 2+ adjacent periods / dots (.) - " + s, debug)
return False
dots = s.count('.')
# Fail if it has anything except numbers and dot (.)
if (not re.match(r'^[0-9\.]*$', s)):
dprint("Invalid Version String. Shouldn't have anything except numbers and period / dot (.) - " + s, debug)
return False
# Fail if it has no dots. A Version requires both Major AND Minor
# version to be present.
#
# There are other functions that act as fallback, that can convert
# some Major Version strings to a valid Postgres Versions by appending
# a ".0" minor version, but that is beyond scope of this function
if (dots == 0):
dprint("Invalid Version String. Should have both Major and Minor version - " + s, debug)
return False
# Fail if it has more than 2 dots
if (dots > 2):
dprint("Invalid Version String. Has more than 2 periods / dots (.) - " + s, debug)
return False
x = list(map(int, s.split('.', dots)))
if (dots == 2):
# This numbering is pre v10- and we have an accurate list of all valid versions.
# Lets leave the math aside, and just check that list.
# A good reason here is versions like v9.7.1 would pass all major checks and still
# would be Invalid, since it was never released.
if (not s in _verReleaseDates):
dprint("Invalid pre v10 version. Not in the version list - " + s, debug)
return False
if (dots == 1):
if (x[0]<=10):
# This version is already EOL and we have an accurate list of all EOL versions.
# Lets leave the math aside, and just check that list. A good reason here is
# versions like v9.7.1 would pass all major checks and would still be Invalid,
# since it was never released.
if (not s in _verReleaseDates):
dprint("Invalid EOL version. Not in the version list - " + s, debug)
return False
if (x[0] >= 100):
dprint("Invalid Version String. Major Version should be less than 100 - " + s, debug)
return False
if (x[1] >= 10000):
dprint("Invalid Version String. Minor Version should be less than 10000 - " + s, debug)
return False
return True
# Return: Major version part of the postgres version provided
# Error: Return False if invalid input is provided
def getMajorPGVersion(v):
s=appendMinorVersionIfRequired(v)
if (not isValidPGVersion(s)):
return False
dots = s.count('.')
x = list(map(int, s.split('.', dots)))
# This is pre-v10
if (dots == 2):
return float(str(x[0]) + "." + str(x[1]))
# This is v10+
elif (dots == 1):
return int(x[0])
# We shouldn't reach here. Something went wrong
return False
# Return: Minor version of the postgres version provided
# Error: Return False if invalid input is provided
def getMinorPGVersion(_s):
s= str(_s)
if (not isValidPGVersion(s)):
return False
dots = s.count('.')
x = list(map(int, s.split('.', dots)))
# This is pre-v10
if (dots == 2):
return x[2]
# This is v10+
elif (dots == 1):
return x[1]
# We shouldn't reach here. Something went wrong
return False
# Return: A dict of [Major, Minor] extracted from postgres version provided
# Error: Return False if invalid input is provided
def parsePGVersion(_s):
s= str(_s)
if (not isValidPGVersion(s)):
return False
Maj = getMajorPGVersion(s)
Min = getMinorPGVersion(s)
if (Maj >= 0):
if (Min >= 0):
return [Maj, Min]
return False
# Return: Return an appended .0 if that allows the input string to pass the isValidPGVersion() check
# Error: Return input string if input can't be converted into a valid PG version
def appendMinorVersionIfRequired(_s):
s= str(_s)
if (not isValidPGVersion(s)):
attempt1 = s + ".0"
if (isValidPGVersion(attempt1)):
# Additionally also check whether we already have this in the lookup list.
# This is a best-effort function and unlike in IsValidPGVersion() we can
# rely on the release date list and fail if it doesn't exist there.
# This avoids some scenarios such as v1.1 becomes v.1.1.0, which is wrong.
if (attempt1 in _verReleaseDates):
return attempt1
return s
# Return: The PostgresVersionNum Integer from the postgres version provided
# Detail: For e.g. v10.14 would return 100014
# Documentation: https://www.postgresql.org/docs/devel/runtime-config-preset.html#GUC-SERVER-VERSION-NUM
def getPGVerNumFromString(_s):
s= str(_s)
if (not isValidPGVersion(s)):
return False
dots = s.count('.')
x = list(map(int, s.split('.', dots)))
if (x[0]>=10):
versionnum = int(x[0]*10000)
if (dots == 1):
versionnum += x[1]
else:
versionnum = x[0]*10000 + (x[1]*100)
if (dots ==2):
versionnum += x[2]
return versionnum
# Return: Release Date when the postgres version was released
# Detail: For e.g. v12.2 would return 13th Feb 2020 in the date-format yyyy-mm-dd.
def getVerReleaseDate(ver):
if not isValidPGVersion(ver):
return '0'
if (ver in _verReleaseDates):
return _verReleaseDates[ver]
else:
dprint('Release date unavailable for release: ' + ver)
return '0'
# Return: Return date in YYYYMMDD format
# Input: Date in YYYY-MM-DD
def convToYYYYMMDD(dt):
return int(datetime.strptime(dt, '%Y-%m-%d').strftime('%Y%m%d'))
# Return: True if v1 was released *after* v2
# Detail: For e.g. IsVerReleasedAfter('10.12', '11.5') returns True
def IsVerReleasedAfter(v1, v2):
if not isValidPGVersion(v1):
return False
if not isValidPGVersion(v2):
return False
if (v1 in _verReleaseDates) and (v2 in _verReleaseDates):
if (v1 in _verReleaseDates) and (v2 in _verReleaseDates):
if (convToYYYYMMDD(_verReleaseDates[v1])>convToYYYYMMDD(_verReleaseDates[v2])):
return True
else:
dprint('Release date unavailable for release: ' + v2)
else:
dprint('Release date unavailable for release: ' + v1)
return False
def main(argv):
if len(sys.argv) == 2:
s = sys.argv[1]
else:
dprint('Invalid number of arguments - ' + str(len(sys.argv)), 0)
exit()
print (isValidPGVersion(s))
if (__name__ == '__main__'):
main(sys.argv)
#print (getPGVerNumFromString(sys.argv[1]))