db.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. #
  2. # Copyright BitBake Contributors
  3. #
  4. # SPDX-License-Identifier: GPL-2.0-only
  5. #
  6. import logging
  7. import os.path
  8. import errno
  9. import prserv
  10. import sqlite3
  11. from contextlib import closing
  12. from . import increase_revision, revision_greater, revision_smaller
  13. logger = logging.getLogger("BitBake.PRserv")
  14. #
  15. # "No History" mode - for a given query tuple (version, pkgarch, checksum),
  16. # the returned value will be the largest among all the values of the same
  17. # (version, pkgarch). This means the PR value returned can NOT be decremented.
  18. #
  19. # "History" mode - Return a new higher value for previously unseen query
  20. # tuple (version, pkgarch, checksum), otherwise return historical value.
  21. # Value can decrement if returning to a previous build.
  22. class PRTable(object):
  23. def __init__(self, conn, table, read_only):
  24. self.conn = conn
  25. self.read_only = read_only
  26. self.table = table
  27. # Creating the table even if the server is read-only.
  28. # This avoids a race condition if a shared database
  29. # is accessed by a read-only server first.
  30. with closing(self.conn.cursor()) as cursor:
  31. cursor.execute("CREATE TABLE IF NOT EXISTS %s \
  32. (version TEXT NOT NULL, \
  33. pkgarch TEXT NOT NULL, \
  34. checksum TEXT NOT NULL, \
  35. value TEXT, \
  36. PRIMARY KEY (version, pkgarch, checksum, value));" % self.table)
  37. self.conn.commit()
  38. def _extremum_value(self, rows, is_max):
  39. value = None
  40. for row in rows:
  41. current_value = row[0]
  42. if value is None:
  43. value = current_value
  44. else:
  45. if is_max:
  46. is_new_extremum = revision_greater(current_value, value)
  47. else:
  48. is_new_extremum = revision_smaller(current_value, value)
  49. if is_new_extremum:
  50. value = current_value
  51. return value
  52. def _max_value(self, rows):
  53. return self._extremum_value(rows, True)
  54. def _min_value(self, rows):
  55. return self._extremum_value(rows, False)
  56. def test_package(self, version, pkgarch):
  57. """Returns whether the specified package version is found in the database for the specified architecture"""
  58. # Just returns the value if found or None otherwise
  59. with closing(self.conn.cursor()) as cursor:
  60. data=cursor.execute("SELECT value FROM %s WHERE version=? AND pkgarch=?;" % self.table,
  61. (version, pkgarch))
  62. row=data.fetchone()
  63. if row is not None:
  64. return True
  65. else:
  66. return False
  67. def test_checksum_value(self, version, pkgarch, checksum, value):
  68. """Returns whether the specified value is found in the database for the specified package, architecture and checksum"""
  69. with closing(self.conn.cursor()) as cursor:
  70. data=cursor.execute("SELECT value FROM %s WHERE version=? AND pkgarch=? and checksum=? and value=?;" % self.table,
  71. (version, pkgarch, checksum, value))
  72. row=data.fetchone()
  73. if row is not None:
  74. return True
  75. else:
  76. return False
  77. def test_value(self, version, pkgarch, value):
  78. """Returns whether the specified value is found in the database for the specified package and architecture"""
  79. # Just returns the value if found or None otherwise
  80. with closing(self.conn.cursor()) as cursor:
  81. data=cursor.execute("SELECT value FROM %s WHERE version=? AND pkgarch=? and value=?;" % self.table,
  82. (version, pkgarch, value))
  83. row=data.fetchone()
  84. if row is not None:
  85. return True
  86. else:
  87. return False
  88. def find_package_max_value(self, version, pkgarch):
  89. """Returns the greatest value for (version, pkgarch), or None if not found. Doesn't create a new value"""
  90. with closing(self.conn.cursor()) as cursor:
  91. data = cursor.execute("SELECT value FROM %s where version=? AND pkgarch=?;" % (self.table),
  92. (version, pkgarch))
  93. rows = data.fetchall()
  94. value = self._max_value(rows)
  95. return value
  96. def find_value(self, version, pkgarch, checksum, history=False):
  97. """Returns the value for the specified checksum if found or None otherwise."""
  98. if history:
  99. return self.find_min_value(version, pkgarch, checksum)
  100. else:
  101. return self.find_max_value(version, pkgarch, checksum)
  102. def _find_extremum_value(self, version, pkgarch, checksum, is_max):
  103. """Returns the maximum (if is_max is True) or minimum (if is_max is False) value
  104. for (version, pkgarch, checksum), or None if not found. Doesn't create a new value"""
  105. with closing(self.conn.cursor()) as cursor:
  106. data = cursor.execute("SELECT value FROM %s where version=? AND pkgarch=? AND checksum=?;" % (self.table),
  107. (version, pkgarch, checksum))
  108. rows = data.fetchall()
  109. return self._extremum_value(rows, is_max)
  110. def find_max_value(self, version, pkgarch, checksum):
  111. return self._find_extremum_value(version, pkgarch, checksum, True)
  112. def find_min_value(self, version, pkgarch, checksum):
  113. return self._find_extremum_value(version, pkgarch, checksum, False)
  114. def find_new_subvalue(self, version, pkgarch, base):
  115. """Take and increase the greatest "<base>.y" value for (version, pkgarch), or return "<base>.0" if not found.
  116. This doesn't store a new value."""
  117. with closing(self.conn.cursor()) as cursor:
  118. data = cursor.execute("SELECT value FROM %s where version=? AND pkgarch=? AND value LIKE '%s.%%';" % (self.table, base),
  119. (version, pkgarch))
  120. rows = data.fetchall()
  121. value = self._max_value(rows)
  122. if value is not None:
  123. return increase_revision(value)
  124. else:
  125. return base + ".0"
  126. def store_value(self, version, pkgarch, checksum, value):
  127. """Store value in the database"""
  128. if not self.read_only and not self.test_checksum_value(version, pkgarch, checksum, value):
  129. with closing(self.conn.cursor()) as cursor:
  130. cursor.execute("INSERT INTO %s VALUES (?, ?, ?, ?);" % (self.table),
  131. (version, pkgarch, checksum, value))
  132. self.conn.commit()
  133. def _get_value(self, version, pkgarch, checksum, history):
  134. max_value = self.find_package_max_value(version, pkgarch)
  135. if max_value is None:
  136. # version, pkgarch completely unknown. Return initial value.
  137. return "0"
  138. value = self.find_value(version, pkgarch, checksum, history)
  139. if value is None:
  140. # version, pkgarch found but not checksum. Create a new value from the maximum one
  141. return increase_revision(max_value)
  142. if history:
  143. return value
  144. # "no history" mode - If the value is not the maximum value for the package, need to increase it.
  145. if max_value > value:
  146. return increase_revision(max_value)
  147. else:
  148. return value
  149. def get_value(self, version, pkgarch, checksum, history):
  150. value = self._get_value(version, pkgarch, checksum, history)
  151. if not self.read_only:
  152. self.store_value(version, pkgarch, checksum, value)
  153. return value
  154. def importone(self, version, pkgarch, checksum, value):
  155. self.store_value(version, pkgarch, checksum, value)
  156. return value
  157. def export(self, version, pkgarch, checksum, colinfo, history=False):
  158. metainfo = {}
  159. with closing(self.conn.cursor()) as cursor:
  160. #column info
  161. if colinfo:
  162. metainfo["tbl_name"] = self.table
  163. metainfo["core_ver"] = prserv.__version__
  164. metainfo["col_info"] = []
  165. data = cursor.execute("PRAGMA table_info(%s);" % self.table)
  166. for row in data:
  167. col = {}
  168. col["name"] = row["name"]
  169. col["type"] = row["type"]
  170. col["notnull"] = row["notnull"]
  171. col["dflt_value"] = row["dflt_value"]
  172. col["pk"] = row["pk"]
  173. metainfo["col_info"].append(col)
  174. #data info
  175. datainfo = []
  176. if history:
  177. sqlstmt = "SELECT * FROM %s as T1 WHERE 1=1 " % self.table
  178. else:
  179. sqlstmt = "SELECT T1.version, T1.pkgarch, T1.checksum, T1.value FROM %s as T1, \
  180. (SELECT version, pkgarch, max(value) as maxvalue FROM %s GROUP BY version, pkgarch) as T2 \
  181. WHERE T1.version=T2.version AND T1.pkgarch=T2.pkgarch AND T1.value=T2.maxvalue " % (self.table, self.table)
  182. sqlarg = []
  183. where = ""
  184. if version:
  185. where += "AND T1.version=? "
  186. sqlarg.append(str(version))
  187. if pkgarch:
  188. where += "AND T1.pkgarch=? "
  189. sqlarg.append(str(pkgarch))
  190. if checksum:
  191. where += "AND T1.checksum=? "
  192. sqlarg.append(str(checksum))
  193. sqlstmt += where + ";"
  194. if len(sqlarg):
  195. data = cursor.execute(sqlstmt, tuple(sqlarg))
  196. else:
  197. data = cursor.execute(sqlstmt)
  198. for row in data:
  199. if row["version"]:
  200. col = {}
  201. col["version"] = row["version"]
  202. col["pkgarch"] = row["pkgarch"]
  203. col["checksum"] = row["checksum"]
  204. col["value"] = row["value"]
  205. datainfo.append(col)
  206. return (metainfo, datainfo)
  207. def dump_db(self, fd):
  208. writeCount = 0
  209. for line in self.conn.iterdump():
  210. writeCount = writeCount + len(line) + 1
  211. fd.write(line)
  212. fd.write("\n")
  213. return writeCount
  214. class PRData(object):
  215. """Object representing the PR database"""
  216. def __init__(self, filename, read_only=False):
  217. self.filename=os.path.abspath(filename)
  218. self.read_only = read_only
  219. #build directory hierarchy
  220. try:
  221. os.makedirs(os.path.dirname(self.filename))
  222. except OSError as e:
  223. if e.errno != errno.EEXIST:
  224. raise e
  225. uri = "file:%s%s" % (self.filename, "?mode=ro" if self.read_only else "")
  226. logger.debug("Opening PRServ database '%s'" % (uri))
  227. self.connection=sqlite3.connect(uri, uri=True)
  228. self.connection.row_factory=sqlite3.Row
  229. self.connection.execute("PRAGMA synchronous = OFF;")
  230. self.connection.execute("PRAGMA journal_mode = WAL;")
  231. self.connection.commit()
  232. self._tables={}
  233. def disconnect(self):
  234. self.connection.commit()
  235. self.connection.close()
  236. def __getitem__(self, tblname):
  237. if not isinstance(tblname, str):
  238. raise TypeError("tblname argument must be a string, not '%s'" %
  239. type(tblname))
  240. if tblname in self._tables:
  241. return self._tables[tblname]
  242. else:
  243. tableobj = self._tables[tblname] = PRTable(self.connection, tblname, self.read_only)
  244. return tableobj
  245. def __delitem__(self, tblname):
  246. if tblname in self._tables:
  247. del self._tables[tblname]
  248. logger.info("drop table %s" % (tblname))
  249. self.connection.execute("DROP TABLE IF EXISTS %s;" % tblname)
  250. self.connection.commit()