dbconn.py 76 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347
  1. """ DB access class
  2. @contact: Debian FTPMaster <ftpmaster@debian.org>
  3. @copyright: 2000, 2001, 2002, 2003, 2004, 2006 James Troup <james@nocrew.org>
  4. @copyright: 2008-2009 Mark Hymers <mhy@debian.org>
  5. @copyright: 2009, 2010 Joerg Jaspert <joerg@debian.org>
  6. @copyright: 2009 Mike O'Connor <stew@debian.org>
  7. @license: GNU General Public License version 2 or later
  8. """
  9. # This program is free software; you can redistribute it and/or modify
  10. # it under the terms of the GNU General Public License as published by
  11. # the Free Software Foundation; either version 2 of the License, or
  12. # (at your option) any later version.
  13. # This program is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU General Public License for more details.
  17. # You should have received a copy of the GNU General Public License
  18. # along with this program; if not, write to the Free Software
  19. # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  20. ################################################################################
  21. # < mhy> I need a funny comment
  22. # < sgran> two peanuts were walking down a dark street
  23. # < sgran> one was a-salted
  24. # * mhy looks up the definition of "funny"
  25. ################################################################################
  26. import apt_pkg
  27. import functools
  28. import inspect
  29. import os
  30. from os.path import normpath
  31. import re
  32. import subprocess
  33. import warnings
  34. from collections.abc import Iterable
  35. from typing import Optional, TYPE_CHECKING, Union
  36. from debian.debfile import Deb822
  37. from tarfile import TarFile
  38. import sqlalchemy
  39. from sqlalchemy import create_engine, Table, desc
  40. from sqlalchemy.orm import sessionmaker, mapper, relation, object_session, \
  41. backref, object_mapper
  42. import sqlalchemy.types
  43. from sqlalchemy.orm.collections import attribute_mapped_collection
  44. from sqlalchemy.ext.associationproxy import association_proxy
  45. # Don't remove this, we re-export the exceptions to scripts which import us
  46. from sqlalchemy.exc import *
  47. from sqlalchemy.orm.exc import NoResultFound
  48. import daklib.gpg
  49. from .aptversion import AptVersion
  50. # Only import Config until Queue stuff is changed to store its config
  51. # in the database
  52. from .config import Config
  53. from .textutils import fix_maintainer
  54. # suppress some deprecation warnings in squeeze related to sqlalchemy
  55. warnings.filterwarnings('ignore',
  56. "Predicate of partial index .* ignored during reflection",
  57. SAWarning)
  58. # (Debian 12 "bookworm") Silence warning targeted at SQLAlchemy dialect maintainers
  59. warnings.filterwarnings(
  60. "ignore",
  61. "Dialect postgresql:psycopg2 will not make use of SQL compilation caching.*",
  62. SAWarning)
  63. from .database.base import Base
  64. if TYPE_CHECKING:
  65. import sqlalchemy.orm.query
  66. ################################################################################
  67. # Patch in support for the debversion field type so that it works during
  68. # reflection
  69. class DebVersion(sqlalchemy.types.UserDefinedType):
  70. def get_col_spec(self):
  71. return "DEBVERSION"
  72. def bind_processor(self, dialect):
  73. return None
  74. def result_processor(self, dialect, coltype):
  75. return None
  76. from sqlalchemy.databases import postgresql
  77. postgresql.ischema_names['debversion'] = DebVersion
  78. ################################################################################
  79. __all__ = ['IntegrityError', 'SQLAlchemyError', 'DebVersion']
  80. ################################################################################
  81. def session_wrapper(fn):
  82. """
  83. Wrapper around common ".., session=None):" handling. If the wrapped
  84. function is called without passing 'session', we create a local one
  85. and destroy it when the function ends.
  86. Also attaches a commit_or_flush method to the session; if we created a
  87. local session, this is a synonym for session.commit(), otherwise it is a
  88. synonym for session.flush().
  89. """
  90. @functools.wraps(fn)
  91. def wrapped(*args, **kwargs):
  92. private_transaction = False
  93. # Find the session object
  94. session = kwargs.get('session')
  95. if session is None:
  96. if len(args) < len(inspect.getfullargspec(fn).args):
  97. # No session specified as last argument or in kwargs
  98. private_transaction = True
  99. session = kwargs['session'] = DBConn().session()
  100. else:
  101. # Session is last argument in args
  102. session = args[-1]
  103. if session is None:
  104. args = list(args)
  105. session = args[-1] = DBConn().session()
  106. private_transaction = True
  107. if private_transaction:
  108. session.commit_or_flush = session.commit
  109. else:
  110. session.commit_or_flush = session.flush
  111. try:
  112. return fn(*args, **kwargs)
  113. finally:
  114. if private_transaction:
  115. # We created a session; close it.
  116. session.close()
  117. return wrapped
  118. __all__.append('session_wrapper')
  119. ################################################################################
  120. class ORMObject:
  121. """
  122. ORMObject is a base class for all ORM classes mapped by SQLalchemy. All
  123. derived classes must implement the properties() method.
  124. """
  125. def properties(self) -> list[str]:
  126. '''
  127. This method should be implemented by all derived classes and returns a
  128. list of the important properties. The properties 'created' and
  129. 'modified' will be added automatically. A suffix '_count' should be
  130. added to properties that are lists or query objects. The most important
  131. property name should be returned as the first element in the list
  132. because it is used by repr().
  133. '''
  134. return []
  135. def classname(self) -> str:
  136. '''
  137. Returns the name of the class.
  138. '''
  139. return type(self).__name__
  140. def __repr__(self):
  141. '''
  142. Returns a short string representation of the object using the first
  143. element from the properties() method.
  144. '''
  145. primary_property = self.properties()[0]
  146. value = getattr(self, primary_property)
  147. return '<%s %s>' % (self.classname(), str(value))
  148. def __str__(self):
  149. '''
  150. Returns a human readable form of the object using the properties()
  151. method.
  152. '''
  153. return '<%s(...)>' % (self.classname())
  154. @classmethod
  155. @session_wrapper
  156. def get(cls, primary_key, session=None):
  157. '''
  158. This is a support function that allows getting an object by its primary
  159. key.
  160. Architecture.get(3[, session])
  161. instead of the more verbose
  162. session.query(Architecture).get(3)
  163. '''
  164. return session.query(cls).get(primary_key)
  165. def session(self):
  166. '''
  167. Returns the current session that is associated with the object. May
  168. return None is object is in detached state.
  169. '''
  170. return object_session(self)
  171. __all__.append('ORMObject')
  172. ################################################################################
  173. class ACL(ORMObject):
  174. def __repr__(self):
  175. return "<ACL {0}>".format(self.name)
  176. __all__.append('ACL')
  177. class ACLPerSource(ORMObject):
  178. def __repr__(self):
  179. return "<ACLPerSource acl={0} fingerprint={1} source={2} reason={3}>".format(self.acl.name, self.fingerprint.fingerprint, self.source, self.reason)
  180. __all__.append('ACLPerSource')
  181. class ACLPerSuite(ORMObject):
  182. def __repr__(self):
  183. return "<ACLPerSuite acl={0} fingerprint={1} suite={2} reason={3}>".format(self.acl.name, self.fingerprint.fingerprint, self.suite.suite_name, self.reason)
  184. __all__.append('ACLPerSuite')
  185. ################################################################################
  186. from .database.architecture import Architecture
  187. __all__.append('Architecture')
  188. @session_wrapper
  189. def get_architecture(architecture: str, session=None) -> Optional[Architecture]:
  190. """
  191. Returns database id for given `architecture`.
  192. :param architecture: The name of the architecture
  193. :param session: Optional SQLA session object (a temporary one will be
  194. generated if not supplied)
  195. :return: Architecture object for the given arch (None if not present)
  196. """
  197. q = session.query(Architecture).filter_by(arch_string=architecture)
  198. return q.one_or_none()
  199. __all__.append('get_architecture')
  200. ################################################################################
  201. class Archive:
  202. def __init__(self, *args, **kwargs):
  203. pass
  204. def __repr__(self):
  205. return '<Archive %s>' % self.archive_name
  206. __all__.append('Archive')
  207. @session_wrapper
  208. def get_archive(archive: str, session=None) -> Optional[Archive]:
  209. """
  210. returns database id for given `archive`.
  211. :param archive: the name of the arhive
  212. :param session: Optional SQLA session object (a temporary one will be
  213. generated if not supplied)
  214. :return: Archive object for the given name (None if not present)
  215. """
  216. archive = archive.lower()
  217. q = session.query(Archive).filter_by(archive_name=archive)
  218. return q.one_or_none()
  219. __all__.append('get_archive')
  220. ################################################################################
  221. class ArchiveFile:
  222. def __init__(self, archive=None, component=None, file=None):
  223. self.archive = archive
  224. self.component = component
  225. self.file = file
  226. @property
  227. def path(self):
  228. return os.path.join(self.archive.path, 'pool', self.component.component_name, self.file.filename)
  229. __all__.append('ArchiveFile')
  230. ################################################################################
  231. class BinContents(ORMObject):
  232. def __init__(self, file=None, binary=None):
  233. self.file = file
  234. self.binary = binary
  235. def properties(self) -> list[str]:
  236. return ['file', 'binary']
  237. __all__.append('BinContents')
  238. ################################################################################
  239. class DBBinary(ORMObject):
  240. def __init__(self, package=None, source=None, version=None,
  241. maintainer=None, architecture=None, poolfile=None,
  242. binarytype='deb', fingerprint=None):
  243. self.package = package
  244. self.source = source
  245. self.version = version
  246. self.maintainer = maintainer
  247. self.architecture = architecture
  248. self.poolfile = poolfile
  249. self.binarytype = binarytype
  250. self.fingerprint = fingerprint
  251. @property
  252. def pkid(self) -> int:
  253. return self.binary_id
  254. @property
  255. def name(self) -> str:
  256. return self.package
  257. @property
  258. def arch_string(self) -> str:
  259. return "%s" % self.architecture
  260. def properties(self) -> list[str]:
  261. return ['package', 'version', 'maintainer', 'source', 'architecture',
  262. 'poolfile', 'binarytype', 'fingerprint', 'install_date',
  263. 'suites_count', 'binary_id', 'contents_count', 'extra_sources']
  264. metadata = association_proxy('key', 'value')
  265. def scan_contents(self) -> Iterable[str]:
  266. '''
  267. Yields the contents of the package. Only regular files are yielded and
  268. the path names are normalized after converting them from either utf-8
  269. or iso8859-1 encoding. It yields the string ' <EMPTY PACKAGE>' if the
  270. package does not contain any regular file.
  271. '''
  272. fullpath = self.poolfile.fullpath
  273. dpkg_cmd = ('dpkg-deb', '--fsys-tarfile', fullpath)
  274. dpkg = subprocess.Popen(dpkg_cmd, stdout=subprocess.PIPE)
  275. tar = TarFile.open(fileobj=dpkg.stdout, mode='r|')
  276. for member in tar.getmembers():
  277. if not member.isdir():
  278. name = normpath(member.name)
  279. yield name
  280. tar.close()
  281. dpkg.stdout.close()
  282. dpkg.wait()
  283. def read_control(self) -> bytes:
  284. '''
  285. Reads the control information from a binary.
  286. :return: stanza text of the control section.
  287. '''
  288. from . import utils
  289. fullpath = self.poolfile.fullpath
  290. return utils.deb_extract_control(fullpath)
  291. def read_control_fields(self) -> apt_pkg.TagSection:
  292. '''
  293. Reads the control information from a binary and return
  294. as a dictionary.
  295. :return: fields of the control section as a dictionary.
  296. '''
  297. stanza = self.read_control()
  298. return apt_pkg.TagSection(stanza)
  299. @property
  300. def proxy(self) -> "MetadataProxy":
  301. session = object_session(self)
  302. query = session.query(BinaryMetadata).filter_by(binary=self)
  303. return MetadataProxy(session, query)
  304. __all__.append('DBBinary')
  305. @session_wrapper
  306. def get_suites_binary_in(package: str, session=None) -> 'list[Suite]':
  307. """
  308. Returns list of Suite objects which given `package` name is in
  309. :param package: DBBinary package name to search for
  310. :return: list of Suite objects for the given package
  311. """
  312. return session.query(Suite).filter(Suite.binaries.any(DBBinary.package == package)).all()
  313. __all__.append('get_suites_binary_in')
  314. @session_wrapper
  315. def get_component_by_package_suite(package: str, suite_list: list[str], arch_list: Optional[str] = None, session=None) -> Optional[str]:
  316. '''
  317. Returns the component name of the newest binary package in suite_list or
  318. None if no package is found. The result can be optionally filtered by a list
  319. of architecture names.
  320. :param package: DBBinary package name to search for
  321. :param suite_list: list of suite_name items
  322. :param arch_list: optional list of arch_string items that defaults to []
  323. :return: name of component or None
  324. '''
  325. q = session.query(DBBinary).filter_by(package=package). \
  326. join(DBBinary.suites).filter(Suite.suite_name.in_(suite_list))
  327. if arch_list:
  328. q = q.join(DBBinary.architecture). \
  329. filter(Architecture.arch_string.in_(arch_list))
  330. binary = q.order_by(desc(DBBinary.version)).first()
  331. if binary is None:
  332. return None
  333. else:
  334. return binary.poolfile.component.component_name
  335. __all__.append('get_component_by_package_suite')
  336. ################################################################################
  337. class BuildQueue:
  338. def __init__(self, *args, **kwargs):
  339. pass
  340. def __repr__(self):
  341. return '<BuildQueue %s>' % self.queue_name
  342. __all__.append('BuildQueue')
  343. ################################################################################
  344. class Component(ORMObject):
  345. def __init__(self, component_name=None):
  346. self.component_name = component_name
  347. def __eq__(self, val):
  348. if isinstance(val, str):
  349. warnings.warn("comparison with a `str` is deprecated", DeprecationWarning, stacklevel=2)
  350. return (self.component_name == val)
  351. # This signals to use the normal comparison operator
  352. return NotImplemented
  353. def __ne__(self, val):
  354. if isinstance(val, str):
  355. warnings.warn("comparison with a `str` is deprecated", DeprecationWarning, stacklevel=2)
  356. return (self.component_name != val)
  357. # This signals to use the normal comparison operator
  358. return NotImplemented
  359. __hash__ = ORMObject.__hash__
  360. def properties(self) -> list[str]:
  361. return ['component_name', 'component_id', 'description',
  362. 'meets_dfsg', 'overrides_count']
  363. __all__.append('Component')
  364. @session_wrapper
  365. def get_component(component: str, session=None) -> Optional[Component]:
  366. """
  367. Returns database id for given `component`.
  368. :param component: The name of the override type
  369. :return: the database id for the given component
  370. """
  371. component = component.lower()
  372. q = session.query(Component).filter_by(component_name=component)
  373. return q.one_or_none()
  374. __all__.append('get_component')
  375. def get_mapped_component_name(component_name):
  376. cnf = Config()
  377. for m in cnf.value_list("ComponentMappings"):
  378. (src, dst) = m.split()
  379. if component_name == src:
  380. component_name = dst
  381. return component_name
  382. __all__.append('get_mapped_component_name')
  383. @session_wrapper
  384. def get_mapped_component(component_name: str, session=None) -> Optional[Component]:
  385. """get component after mappings
  386. Evaluate component mappings from ComponentMappings in dak.conf for the
  387. given component name.
  388. .. todo::
  389. ansgar wants to get rid of this. It's currently only used for
  390. the security archive
  391. :param component_name: component name
  392. :param session: database session
  393. :return: component after applying maps or :const:`None`
  394. """
  395. component_name = get_mapped_component_name(component_name)
  396. component = session.query(Component).filter_by(component_name=component_name).first()
  397. return component
  398. __all__.append('get_mapped_component')
  399. @session_wrapper
  400. def get_component_names(session=None) -> list[str]:
  401. """
  402. Returns list of strings of component names.
  403. :return: list of strings of component names
  404. """
  405. return [x.component_name for x in session.query(Component).all()]
  406. __all__.append('get_component_names')
  407. ################################################################################
  408. class DBConfig:
  409. def __init__(self, *args, **kwargs):
  410. pass
  411. def __repr__(self):
  412. return '<DBConfig %s>' % self.name
  413. __all__.append('DBConfig')
  414. ################################################################################
  415. class DSCFile:
  416. def __init__(self, *args, **kwargs):
  417. pass
  418. def __repr__(self):
  419. return '<DSCFile %s>' % self.dscfile_id
  420. __all__.append('DSCFile')
  421. @session_wrapper
  422. def get_dscfiles(
  423. dscfile_id: Optional[int] = None,
  424. source_id: Optional[int] = None,
  425. poolfile_id: Optional[int] = None,
  426. session=None
  427. ) -> list[DSCFile]:
  428. """
  429. Returns a list of DSCFiles which may be empty
  430. :param dscfile_id: the dscfile_id of the DSCFiles to find
  431. :param source_id: the source id related to the DSCFiles to find
  432. :param poolfile_id: the poolfile id related to the DSCFiles to find
  433. :return: Possibly empty list of DSCFiles
  434. """
  435. q = session.query(DSCFile)
  436. if dscfile_id is not None:
  437. q = q.filter_by(dscfile_id=dscfile_id)
  438. if source_id is not None:
  439. q = q.filter_by(source_id=source_id)
  440. if poolfile_id is not None:
  441. q = q.filter_by(poolfile_id=poolfile_id)
  442. return q.all()
  443. __all__.append('get_dscfiles')
  444. ################################################################################
  445. class ExternalOverride(ORMObject):
  446. def __init__(self, *args, **kwargs):
  447. pass
  448. def __repr__(self):
  449. return '<ExternalOverride %s = %s: %s>' % (self.package, self.key, self.value)
  450. __all__.append('ExternalOverride')
  451. ################################################################################
  452. class PoolFile(ORMObject):
  453. def __init__(self, filename=None, filesize=-1,
  454. md5sum=None):
  455. self.filename = filename
  456. self.filesize = filesize
  457. self.md5sum = md5sum
  458. @property
  459. def fullpath(self) -> str:
  460. session = DBConn().session().object_session(self)
  461. af = session.query(ArchiveFile).join(Archive) \
  462. .filter(ArchiveFile.file == self) \
  463. .order_by(Archive.tainted.desc()).first()
  464. return af.path
  465. @property
  466. def component(self) -> Component:
  467. session = DBConn().session().object_session(self)
  468. component_id = session.query(ArchiveFile.component_id).filter(ArchiveFile.file == self) \
  469. .group_by(ArchiveFile.component_id).one()
  470. return session.query(Component).get(component_id)
  471. @property
  472. def basename(self) -> str:
  473. return os.path.basename(self.filename)
  474. def properties(self) -> list[str]:
  475. return ['filename', 'file_id', 'filesize', 'md5sum', 'sha1sum',
  476. 'sha256sum', 'source', 'binary', 'last_used']
  477. __all__.append('PoolFile')
  478. ################################################################################
  479. class Fingerprint(ORMObject):
  480. def __init__(self, fingerprint=None):
  481. self.fingerprint = fingerprint
  482. def properties(self) -> list[str]:
  483. return ['fingerprint', 'fingerprint_id', 'keyring', 'uid',
  484. 'binary_reject']
  485. __all__.append('Fingerprint')
  486. @session_wrapper
  487. def get_fingerprint(fpr: str, session=None) -> Optional[Fingerprint]:
  488. """
  489. Returns Fingerprint object for given fpr.
  490. :param fpr: The fpr to find / add
  491. :param session: Optional SQL session object (a temporary one will be
  492. generated if not supplied).
  493. :return: the Fingerprint object for the given fpr or None
  494. """
  495. q = session.query(Fingerprint).filter_by(fingerprint=fpr)
  496. return q.one_or_none()
  497. __all__.append('get_fingerprint')
  498. @session_wrapper
  499. def get_or_set_fingerprint(fpr: str, session=None) -> Fingerprint:
  500. """
  501. Returns Fingerprint object for given fpr.
  502. If no matching fpr is found, a row is inserted.
  503. :param fpr: The fpr to find / add
  504. :param session: Optional SQL session object (a temporary one will be
  505. generated if not supplied). If not passed, a commit will be performed at
  506. the end of the function, otherwise the caller is responsible for commiting.
  507. A flush will be performed either way.
  508. :return: the Fingerprint object for the given fpr
  509. """
  510. q = session.query(Fingerprint).filter_by(fingerprint=fpr)
  511. try:
  512. ret = q.one()
  513. except NoResultFound:
  514. fingerprint = Fingerprint()
  515. fingerprint.fingerprint = fpr
  516. session.add(fingerprint)
  517. session.commit_or_flush()
  518. ret = fingerprint
  519. return ret
  520. __all__.append('get_or_set_fingerprint')
  521. ################################################################################
  522. # Helper routine for Keyring class
  523. def get_ldap_name(entry) -> str:
  524. name = []
  525. for k in ["cn", "mn", "sn"]:
  526. ret = entry.get(k)
  527. if not ret:
  528. continue
  529. value = ret[0].decode()
  530. if value and value[0] != "-":
  531. name.append(value)
  532. return " ".join(name)
  533. ################################################################################
  534. class Keyring:
  535. keys = {}
  536. fpr_lookup: dict[str, str] = {}
  537. def __init__(self, *args, **kwargs):
  538. pass
  539. def __repr__(self):
  540. return '<Keyring %s>' % self.keyring_name
  541. def de_escape_gpg_str(self, txt: str) -> str:
  542. esclist = re.split(r'(\\x..)', txt)
  543. for x in range(1, len(esclist), 2):
  544. esclist[x] = "%c" % (int(esclist[x][2:], 16))
  545. return "".join(esclist)
  546. def parse_address(self, uid: str) -> tuple[str, str]:
  547. """parses uid and returns a tuple of real name and email address"""
  548. import email.utils
  549. (name, address) = email.utils.parseaddr(uid)
  550. name = re.sub(r"\s*[(].*[)]", "", name)
  551. name = self.de_escape_gpg_str(name)
  552. if name == "":
  553. name = uid
  554. return (name, address)
  555. def load_keys(self, keyring: str) -> None:
  556. if not self.keyring_id:
  557. raise Exception('Must be initialized with database information')
  558. cmd = ["gpg", "--no-default-keyring", "--keyring", keyring,
  559. "--with-colons", "--fingerprint", "--fingerprint"]
  560. p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  561. key = None
  562. need_fingerprint = False
  563. for line_raw in p.stdout:
  564. try:
  565. line = line_raw.decode()
  566. except UnicodeDecodeError:
  567. # Some old UIDs might not use UTF-8 encoding. We assume they
  568. # use latin1.
  569. line = line_raw.decode('latin1')
  570. field = line.split(":")
  571. if field[0] == "pub":
  572. key = field[4]
  573. self.keys[key] = {}
  574. (name, addr) = self.parse_address(field[9])
  575. if "@" in addr:
  576. self.keys[key]["email"] = addr
  577. self.keys[key]["name"] = name
  578. need_fingerprint = True
  579. elif key and field[0] == "uid":
  580. (name, addr) = self.parse_address(field[9])
  581. if "email" not in self.keys[key] and "@" in addr:
  582. self.keys[key]["email"] = addr
  583. self.keys[key]["name"] = name
  584. elif need_fingerprint and field[0] == "fpr":
  585. self.keys[key]["fingerprints"] = [field[9]]
  586. self.fpr_lookup[field[9]] = key
  587. need_fingerprint = False
  588. (out, err) = p.communicate()
  589. r = p.returncode
  590. if r != 0:
  591. raise daklib.gpg.GpgException("command failed: %s\nstdout: %s\nstderr: %s\n" % (cmd, out, err))
  592. def import_users_from_ldap(self, session) -> tuple[dict[str, tuple[int, str]], dict[int, tuple[str, str]]]:
  593. from .utils import open_ldap_connection
  594. import ldap # type: ignore
  595. l = open_ldap_connection()
  596. cnf = Config()
  597. LDAPDn = cnf["Import-LDAP-Fingerprints::LDAPDn"]
  598. Attrs = l.search_s(LDAPDn, ldap.SCOPE_ONELEVEL,
  599. "(&(keyfingerprint=*)(supplementaryGid=%s))" % (cnf["Import-Users-From-Passwd::ValidGID"]),
  600. ["uid", "keyfingerprint", "cn", "mn", "sn"])
  601. byuid: dict[int, tuple[str, str]] = {}
  602. byname: dict[str, tuple[int, str]] = {}
  603. for i in Attrs:
  604. entry = i[1]
  605. uid = entry["uid"][0].decode()
  606. name = get_ldap_name(entry)
  607. fingerprints = entry["keyFingerPrint"]
  608. keyid = None
  609. for f_raw in fingerprints:
  610. f = f_raw.decode()
  611. key = self.fpr_lookup.get(f, None)
  612. if key not in self.keys:
  613. continue
  614. self.keys[key]["uid"] = uid
  615. if keyid is not None:
  616. continue
  617. keyid = get_or_set_uid(uid, session).uid_id
  618. byuid[keyid] = (uid, name)
  619. byname[uid] = (keyid, name)
  620. return (byname, byuid)
  621. def generate_users_from_keyring(self, format: str, session) -> tuple[dict[str, tuple[int, str]], dict[int, tuple[str, str]]]:
  622. byuid: dict[int, tuple[str, str]] = {}
  623. byname: dict[str, tuple[int, str]] = {}
  624. any_invalid = False
  625. for x in list(self.keys.keys()):
  626. if "email" not in self.keys[x]:
  627. any_invalid = True
  628. self.keys[x]["uid"] = format % "invalid-uid"
  629. else:
  630. uid = format % self.keys[x]["email"]
  631. keyid = get_or_set_uid(uid, session).uid_id
  632. byuid[keyid] = (uid, self.keys[x]["name"])
  633. byname[uid] = (keyid, self.keys[x]["name"])
  634. self.keys[x]["uid"] = uid
  635. if any_invalid:
  636. uid = format % "invalid-uid"
  637. keyid = get_or_set_uid(uid, session).uid_id
  638. byuid[keyid] = (uid, "ungeneratable user id")
  639. byname[uid] = (keyid, "ungeneratable user id")
  640. return (byname, byuid)
  641. __all__.append('Keyring')
  642. @session_wrapper
  643. def get_keyring(keyring: str, session=None) -> Optional[Keyring]:
  644. """
  645. If `keyring` does not have an entry in the `keyrings` table yet, return None
  646. If `keyring` already has an entry, simply return the existing :class:`Keyring`
  647. :param keyring: the keyring name
  648. :return: the :class:`Keyring` object for this keyring
  649. """
  650. q = session.query(Keyring).filter_by(keyring_name=keyring)
  651. return q.one_or_none()
  652. __all__.append('get_keyring')
  653. @session_wrapper
  654. def get_active_keyring_paths(session=None) -> list[str]:
  655. """
  656. :return: list of active keyring paths
  657. """
  658. return [x.keyring_name for x in session.query(Keyring).filter(Keyring.active == True).order_by(desc(Keyring.priority)).all()] # noqa:E712
  659. __all__.append('get_active_keyring_paths')
  660. ################################################################################
  661. class DBChange:
  662. def __init__(self, *args, **kwargs):
  663. pass
  664. def __repr__(self):
  665. return '<DBChange %s>' % self.changesname
  666. __all__.append('DBChange')
  667. @session_wrapper
  668. def get_dbchange(filename: str, session=None) -> Optional[DBChange]:
  669. """
  670. returns DBChange object for given `filename`.
  671. :param filename: the name of the file
  672. :param session: Optional SQLA session object (a temporary one will be
  673. generated if not supplied)
  674. :return: DBChange object for the given filename (:const:`None` if not present)
  675. """
  676. q = session.query(DBChange).filter_by(changesname=filename)
  677. return q.one_or_none()
  678. __all__.append('get_dbchange')
  679. ################################################################################
  680. class Maintainer(ORMObject):
  681. def __init__(self, name=None):
  682. self.name = name
  683. def properties(self) -> list[str]:
  684. return ['name', 'maintainer_id']
  685. def get_split_maintainer(self) -> tuple[str, str, str, str]:
  686. if not hasattr(self, 'name') or self.name is None:
  687. return ('', '', '', '')
  688. return fix_maintainer(self.name.strip())
  689. __all__.append('Maintainer')
  690. @session_wrapper
  691. def get_or_set_maintainer(name: str, session=None) -> Maintainer:
  692. """
  693. Returns Maintainer object for given maintainer name.
  694. If no matching maintainer name is found, a row is inserted.
  695. :param name: The maintainer name to add
  696. :param session: Optional SQL session object (a temporary one will be
  697. generated if not supplied). If not passed, a commit will be performed at
  698. the end of the function, otherwise the caller is responsible for commiting.
  699. A flush will be performed either way.
  700. :return: the Maintainer object for the given maintainer
  701. """
  702. q = session.query(Maintainer).filter_by(name=name)
  703. try:
  704. ret = q.one()
  705. except NoResultFound:
  706. maintainer = Maintainer()
  707. maintainer.name = name
  708. session.add(maintainer)
  709. session.commit_or_flush()
  710. ret = maintainer
  711. return ret
  712. __all__.append('get_or_set_maintainer')
  713. @session_wrapper
  714. def get_maintainer(maintainer_id: int, session=None) -> Optional[Maintainer]:
  715. """
  716. Return the name of the maintainer behind `maintainer_id` or :const:`None`
  717. if that `maintainer_id` is invalid.
  718. :param maintainer_id: the id of the maintainer
  719. :return: the Maintainer with this `maintainer_id`
  720. """
  721. return session.query(Maintainer).get(maintainer_id)
  722. __all__.append('get_maintainer')
  723. ################################################################################
  724. class NewComment:
  725. def __init__(self, *args, **kwargs):
  726. pass
  727. def __repr__(self):
  728. return '''<NewComment for '%s %s' (%s)>''' % (self.package, self.version, self.comment_id)
  729. __all__.append('NewComment')
  730. @session_wrapper
  731. def has_new_comment(policy_queue: "PolicyQueue", package: str, version: str, session=None) -> bool:
  732. """
  733. Returns :const:`True` if the given combination of `package`, `version` has a comment.
  734. :param package: name of the package
  735. :param version: package version
  736. :param session: Optional SQLA session object (a temporary one will be
  737. generated if not supplied)
  738. """
  739. q = session.query(NewComment).filter_by(policy_queue=policy_queue)
  740. q = q.filter_by(package=package)
  741. q = q.filter_by(version=version)
  742. return bool(q.count() > 0)
  743. __all__.append('has_new_comment')
  744. @session_wrapper
  745. def get_new_comments(
  746. policy_queue: "PolicyQueue",
  747. package: Optional[str] = None,
  748. version: Optional[str] = None,
  749. comment_id: Optional[int] = None,
  750. session=None
  751. ) -> list[NewComment]:
  752. """
  753. Returns (possibly empty) list of NewComment objects for the given
  754. parameters
  755. :param package: name of the package
  756. :param version: package version
  757. :param comment_id: An id of a comment
  758. :param session: Optional SQLA session object (a temporary one will be
  759. generated if not supplied)
  760. :return: A (possibly empty) list of NewComment objects will be returned
  761. """
  762. q = session.query(NewComment).filter_by(policy_queue=policy_queue)
  763. if package is not None:
  764. q = q.filter_by(package=package)
  765. if version is not None:
  766. q = q.filter_by(version=version)
  767. if comment_id is not None:
  768. q = q.filter_by(comment_id=comment_id)
  769. return q.all()
  770. __all__.append('get_new_comments')
  771. ################################################################################
  772. class Override(ORMObject):
  773. def __init__(self, package=None, suite=None, component=None, overridetype=None,
  774. section=None, priority=None):
  775. self.package = package
  776. self.suite = suite
  777. self.component = component
  778. self.overridetype = overridetype
  779. self.section = section
  780. self.priority = priority
  781. def properties(self) -> list[str]:
  782. return ['package', 'suite', 'component', 'overridetype', 'section',
  783. 'priority']
  784. __all__.append('Override')
  785. @session_wrapper
  786. def get_override(
  787. package: str,
  788. suite: Union[str, list[str], None] = None,
  789. component: Union[str, list[str], None] = None,
  790. overridetype: Union[str, list[str], None] = None,
  791. session=None
  792. ) -> list[Override]:
  793. """
  794. Returns Override object for the given parameters
  795. :param package: The name of the package
  796. :param suite: The name of the suite (or suites if a list) to limit to. If
  797. None, don't limit. Defaults to None.
  798. :param component: The name of the component (or components if a list) to
  799. limit to. If None, don't limit. Defaults to None.
  800. :param overridetype: The name of the overridetype (or overridetypes if a list) to
  801. limit to. If None, don't limit. Defaults to None.
  802. :param session: Optional SQLA session object (a temporary one will be
  803. generated if not supplied)
  804. :return: A (possibly empty) list of Override objects will be returned
  805. """
  806. q = session.query(Override)
  807. q = q.filter_by(package=package)
  808. if suite is not None:
  809. if not isinstance(suite, list):
  810. suite = [suite]
  811. q = q.join(Suite).filter(Suite.suite_name.in_(suite))
  812. if component is not None:
  813. if not isinstance(component, list):
  814. component = [component]
  815. q = q.join(Component).filter(Component.component_name.in_(component))
  816. if overridetype is not None:
  817. if not isinstance(overridetype, list):
  818. overridetype = [overridetype]
  819. q = q.join(OverrideType).filter(OverrideType.overridetype.in_(overridetype))
  820. return q.all()
  821. __all__.append('get_override')
  822. ################################################################################
  823. class OverrideType(ORMObject):
  824. def __init__(self, overridetype=None):
  825. self.overridetype = overridetype
  826. def properties(self) -> list[str]:
  827. return ['overridetype', 'overridetype_id', 'overrides_count']
  828. __all__.append('OverrideType')
  829. @session_wrapper
  830. def get_override_type(override_type: str, session=None) -> Optional[OverrideType]:
  831. """
  832. Returns OverrideType object for given `override_type`.
  833. :param override_type: The name of the override type
  834. :param session: Optional SQLA session object (a temporary one will be
  835. generated if not supplied)
  836. :return: the database id for the given override type
  837. """
  838. q = session.query(OverrideType).filter_by(overridetype=override_type)
  839. return q.one_or_none()
  840. __all__.append('get_override_type')
  841. ################################################################################
  842. class PolicyQueue:
  843. def __init__(self, *args, **kwargs):
  844. pass
  845. def __repr__(self):
  846. return '<PolicyQueue %s>' % self.queue_name
  847. __all__.append('PolicyQueue')
  848. @session_wrapper
  849. def get_policy_queue(queuename: str, session=None) -> Optional[PolicyQueue]:
  850. """
  851. Returns PolicyQueue object for given `queuename`
  852. :param queuename: The name of the queue
  853. :param session: Optional SQLA session object (a temporary one will be
  854. generated if not supplied)
  855. :return: PolicyQueue object for the given queue
  856. """
  857. q = session.query(PolicyQueue).filter_by(queue_name=queuename)
  858. return q.one_or_none()
  859. __all__.append('get_policy_queue')
  860. ################################################################################
  861. @functools.total_ordering
  862. class PolicyQueueUpload:
  863. def _key(self):
  864. return (
  865. self.changes.source,
  866. AptVersion(self.changes.version),
  867. self.source is None,
  868. self.changes.changesname
  869. )
  870. def __eq__(self, other: object) -> bool:
  871. if not isinstance(other, PolicyQueueUpload):
  872. return NotImplemented
  873. return self._key() == other._key()
  874. def __lt__(self, other):
  875. return self._key() < other._key()
  876. __all__.append('PolicyQueueUpload')
  877. ################################################################################
  878. class PolicyQueueByhandFile:
  879. pass
  880. __all__.append('PolicyQueueByhandFile')
  881. ################################################################################
  882. class Priority(ORMObject):
  883. def __init__(self, priority=None, level=None):
  884. self.priority = priority
  885. self.level = level
  886. def properties(self) -> list[str]:
  887. return ['priority', 'priority_id', 'level', 'overrides_count']
  888. def __eq__(self, val):
  889. if isinstance(val, str):
  890. warnings.warn("comparison with a `str` is deprecated", DeprecationWarning, stacklevel=2)
  891. return (self.priority == val)
  892. # This signals to use the normal comparison operator
  893. return NotImplemented
  894. def __ne__(self, val):
  895. if isinstance(val, str):
  896. warnings.warn("comparison with a `str` is deprecated", DeprecationWarning, stacklevel=2)
  897. return (self.priority != val)
  898. # This signals to use the normal comparison operator
  899. return NotImplemented
  900. __hash__ = ORMObject.__hash__
  901. __all__.append('Priority')
  902. @session_wrapper
  903. def get_priority(priority: str, session=None) -> Optional[Priority]:
  904. """
  905. Returns Priority object for given `priority` name.
  906. :param priority: The name of the priority
  907. :param session: Optional SQLA session object (a temporary one will be
  908. generated if not supplied)
  909. :return: Priority object for the given priority
  910. """
  911. q = session.query(Priority).filter_by(priority=priority)
  912. return q.one_or_none()
  913. __all__.append('get_priority')
  914. @session_wrapper
  915. def get_priorities(session=None) -> dict[str, int]:
  916. """
  917. Returns dictionary of priority names -> id mappings
  918. :param session: Optional SQL session object (a temporary one will be
  919. generated if not supplied)
  920. :return: dictionary of priority names -> id mappings
  921. """
  922. ret = {}
  923. q = session.query(Priority)
  924. for x in q.all():
  925. ret[x.priority] = x.priority_id
  926. return ret
  927. __all__.append('get_priorities')
  928. ################################################################################
  929. from .database.section import Section
  930. __all__.append('Section')
  931. @session_wrapper
  932. def get_section(section: str, session=None) -> Optional[Section]:
  933. """
  934. Returns Section object for given `section` name.
  935. :param section: The name of the section
  936. :param session: Optional SQLA session object (a temporary one will be
  937. generated if not supplied)
  938. :return: Section object for the given section name
  939. """
  940. q = session.query(Section).filter_by(section=section)
  941. return q.one_or_none()
  942. __all__.append('get_section')
  943. @session_wrapper
  944. def get_sections(session=None) -> dict[str, int]:
  945. """
  946. Returns dictionary of section names -> id mappings
  947. :param session: Optional SQL session object (a temporary one will be
  948. generated if not supplied)
  949. :return: dictionary of section names -> id mappings
  950. """
  951. ret = {}
  952. q = session.query(Section)
  953. for x in q.all():
  954. ret[x.section] = x.section_id
  955. return ret
  956. __all__.append('get_sections')
  957. ################################################################################
  958. class SignatureHistory(ORMObject):
  959. @classmethod
  960. def from_signed_file(cls, signed_file: 'daklib.gpg.SignedFile') -> 'SignatureHistory':
  961. """signature history entry from signed file
  962. :param signed_file: signed file
  963. """
  964. self = cls()
  965. self.fingerprint = signed_file.primary_fingerprint
  966. self.signature_timestamp = signed_file.signature_timestamp
  967. self.contents_sha1 = signed_file.contents_sha1
  968. return self
  969. def query(self, session):
  970. return session.query(SignatureHistory).filter_by(fingerprint=self.fingerprint, signature_timestamp=self.signature_timestamp, contents_sha1=self.contents_sha1).first()
  971. __all__.append('SignatureHistory')
  972. ################################################################################
  973. class SrcContents(ORMObject):
  974. def __init__(self, file=None, source=None):
  975. self.file = file
  976. self.source = source
  977. def properties(self) -> list[str]:
  978. return ['file', 'source']
  979. __all__.append('SrcContents')
  980. ################################################################################
  981. class DBSource(ORMObject):
  982. def __init__(self, source=None, version=None, maintainer=None,
  983. changedby=None, poolfile=None, install_date=None, fingerprint=None):
  984. self.source = source
  985. self.version = version
  986. self.maintainer = maintainer
  987. self.changedby = changedby
  988. self.poolfile = poolfile
  989. self.install_date = install_date
  990. self.fingerprint = fingerprint
  991. @property
  992. def pkid(self) -> int:
  993. return self.source_id
  994. @property
  995. def name(self) -> str:
  996. return self.source
  997. @property
  998. def arch_string(self) -> str:
  999. return 'source'
  1000. def properties(self) -> list[str]:
  1001. return ['source', 'source_id', 'maintainer', 'changedby',
  1002. 'fingerprint', 'poolfile', 'version', 'suites_count',
  1003. 'install_date', 'binaries_count', 'uploaders_count']
  1004. def read_control_fields(self) -> Deb822:
  1005. '''
  1006. Reads the control information from a dsc
  1007. :return: fields is the dsc information in a dictionary form
  1008. '''
  1009. with open(self.poolfile.fullpath, 'r') as fd:
  1010. fields = Deb822(fd)
  1011. return fields
  1012. metadata = association_proxy('key', 'value')
  1013. def scan_contents(self) -> set[str]:
  1014. '''
  1015. Returns a set of names for non directories. The path names are
  1016. normalized after converting them from either utf-8 or iso8859-1
  1017. encoding.
  1018. '''
  1019. fullpath = self.poolfile.fullpath
  1020. from daklib.contents import UnpackedSource
  1021. unpacked = UnpackedSource(fullpath)
  1022. fileset = set()
  1023. for name in unpacked.get_all_filenames():
  1024. fileset.add(name)
  1025. return fileset
  1026. @property
  1027. def proxy(self) -> "MetadataProxy":
  1028. session = object_session(self)
  1029. query = session.query(SourceMetadata).filter_by(source=self)
  1030. return MetadataProxy(session, query)
  1031. __all__.append('DBSource')
  1032. @session_wrapper
  1033. def get_suites_source_in(source: str, session=None) -> 'list[Suite]':
  1034. """
  1035. Returns list of Suite objects which given `source` name is in
  1036. :param source: DBSource package name to search for
  1037. :return: list of Suite objects for the given source
  1038. """
  1039. return session.query(Suite).filter(Suite.sources.any(source=source)).all()
  1040. __all__.append('get_suites_source_in')
  1041. # FIXME: This function fails badly if it finds more than 1 source package and
  1042. # its implementation is trivial enough to be inlined.
  1043. @session_wrapper
  1044. def get_source_in_suite(source: str, suite_name: Optional[str], session=None) -> Optional[DBSource]:
  1045. """
  1046. Returns a DBSource object for a combination of `source` and `suite_name`.
  1047. :param source: source package name
  1048. :param suite_name: the suite name
  1049. :return: the version for `source` in `suite`
  1050. """
  1051. suite = get_suite(suite_name, session)
  1052. if suite is None:
  1053. return None
  1054. return suite.get_sources(source).one_or_none()
  1055. __all__.append('get_source_in_suite')
  1056. @session_wrapper
  1057. def import_metadata_into_db(obj: Union[DBBinary, DBSource], session=None) -> None:
  1058. """
  1059. This routine works on either DBBinary or DBSource objects and imports
  1060. their metadata into the database
  1061. """
  1062. fields = obj.read_control_fields()
  1063. for k in fields.keys():
  1064. try:
  1065. # Try raw ASCII
  1066. val = str(fields[k])
  1067. except UnicodeEncodeError:
  1068. # Fall back to UTF-8
  1069. try:
  1070. val = fields[k].encode('utf-8')
  1071. except UnicodeEncodeError:
  1072. # Finally try iso8859-1
  1073. val = fields[k].encode('iso8859-1')
  1074. # Otherwise we allow the exception to percolate up and we cause
  1075. # a reject as someone is playing silly buggers
  1076. obj.metadata[get_or_set_metadatakey(k, session)] = val
  1077. session.commit_or_flush()
  1078. __all__.append('import_metadata_into_db')
  1079. ################################################################################
  1080. class SrcFormat:
  1081. def __init__(self, *args, **kwargs):
  1082. pass
  1083. def __repr__(self):
  1084. return '<SrcFormat %s>' % (self.format_name)
  1085. __all__.append('SrcFormat')
  1086. ################################################################################
  1087. SUITE_FIELDS = [('SuiteName', 'suite_name'),
  1088. ('SuiteID', 'suite_id'),
  1089. ('Version', 'version'),
  1090. ('Origin', 'origin'),
  1091. ('Label', 'label'),
  1092. ('Description', 'description'),
  1093. ('Untouchable', 'untouchable'),
  1094. ('Announce', 'announce'),
  1095. ('Codename', 'codename'),
  1096. ('OverrideCodename', 'overridecodename'),
  1097. ('ValidTime', 'validtime'),
  1098. ('Priority', 'priority'),
  1099. ('NotAutomatic', 'notautomatic'),
  1100. ('CopyChanges', 'copychanges'),
  1101. ('OverrideSuite', 'overridesuite')]
  1102. # Why the heck don't we have any UNIQUE constraints in table suite?
  1103. # TODO: Add UNIQUE constraints for appropriate columns.
  1104. class Suite(ORMObject):
  1105. def __init__(self, suite_name=None, version=None):
  1106. self.suite_name = suite_name
  1107. self.version = version
  1108. def properties(self) -> list[str]:
  1109. return ['suite_name', 'version', 'sources_count', 'binaries_count',
  1110. 'overrides_count']
  1111. def __eq__(self, val):
  1112. if isinstance(val, str):
  1113. warnings.warn("comparison with a `str` is deprecated", DeprecationWarning, stacklevel=2)
  1114. return (self.suite_name == val)
  1115. # This signals to use the normal comparison operator
  1116. return NotImplemented
  1117. def __ne__(self, val):
  1118. if isinstance(val, str):
  1119. warnings.warn("comparison with a `str` is deprecated", DeprecationWarning, stacklevel=2)
  1120. return (self.suite_name != val)
  1121. # This signals to use the normal comparison operator
  1122. return NotImplemented
  1123. __hash__ = ORMObject.__hash__
  1124. def details(self) -> str:
  1125. ret = []
  1126. for disp, field in SUITE_FIELDS:
  1127. val = getattr(self, field, None)
  1128. if val is not None:
  1129. ret.append("%s: %s" % (disp, val))
  1130. return "\n".join(ret)
  1131. def get_architectures(self, skipsrc: bool = False, skipall: bool = False) -> list[Architecture]:
  1132. """
  1133. Returns list of Architecture objects
  1134. :param skipsrc: Whether to skip returning the 'source' architecture entry
  1135. :param skipall: Whether to skip returning the 'all' architecture entry
  1136. :return: list of Architecture objects for the given name (may be empty)
  1137. """
  1138. q = object_session(self).query(Architecture).with_parent(self)
  1139. if skipsrc:
  1140. q = q.filter(Architecture.arch_string != 'source')
  1141. if skipall:
  1142. q = q.filter(Architecture.arch_string != 'all')
  1143. return q.order_by(Architecture.arch_string).all()
  1144. def get_sources(self, source: str) -> sqlalchemy.orm.query.Query:
  1145. """
  1146. Returns a query object representing DBSource that is part of this suite.
  1147. :param source: source package name
  1148. :return: a query of DBSource
  1149. """
  1150. session = object_session(self)
  1151. return session.query(DBSource).filter_by(source=source). \
  1152. with_parent(self)
  1153. def get_overridesuite(self) -> "Suite":
  1154. if self.overridesuite is None:
  1155. return self
  1156. else:
  1157. return object_session(self).query(Suite).filter_by(suite_name=self.overridesuite).one()
  1158. def update_last_changed(self) -> None:
  1159. self.last_changed = sqlalchemy.func.now()
  1160. @property
  1161. def path(self) -> str:
  1162. return os.path.join(self.archive.path, 'dists', self.suite_name)
  1163. @property
  1164. def release_suite_output(self) -> str:
  1165. if self.release_suite is not None:
  1166. return self.release_suite
  1167. return self.suite_name
  1168. __all__.append('Suite')
  1169. @session_wrapper
  1170. def get_suite(suite: str, session=None) -> Optional[Suite]:
  1171. """
  1172. Returns Suite object for given `suite` name.
  1173. :param suite: The name of the suite
  1174. :param session: Optional SQLA session object (a temporary one will be
  1175. generated if not supplied)
  1176. :return: Suite object for the requested suite name (None if not present)
  1177. """
  1178. # Start by looking for the dak internal name
  1179. q = session.query(Suite).filter_by(suite_name=suite)
  1180. try:
  1181. return q.one()
  1182. except NoResultFound:
  1183. pass
  1184. # Now try codename
  1185. q = session.query(Suite).filter_by(codename=suite)
  1186. try:
  1187. return q.one()
  1188. except NoResultFound:
  1189. pass
  1190. # Finally give release_suite a try
  1191. q = session.query(Suite).filter_by(release_suite=suite)
  1192. return q.one_or_none()
  1193. __all__.append('get_suite')
  1194. ################################################################################
  1195. @session_wrapper
  1196. def get_suite_architectures(suite: str, skipsrc: bool = False, skipall: bool = False, session=None) -> list[Architecture]:
  1197. """
  1198. Returns list of Architecture objects for given `suite` name. The list is
  1199. empty if `suite` does not exist.
  1200. :param suite: Suite name to search for
  1201. :param skipsrc: Whether to skip returning the 'source' architecture entry
  1202. :param skipall: Whether to skip returning the 'all' architecture entry
  1203. :param session: Optional SQL session object (a temporary one will be
  1204. generated if not supplied)
  1205. :return: list of Architecture objects for the given name (may be empty)
  1206. """
  1207. try:
  1208. return get_suite(suite, session).get_architectures(skipsrc, skipall)
  1209. except AttributeError:
  1210. return []
  1211. __all__.append('get_suite_architectures')
  1212. ################################################################################
  1213. class Uid(ORMObject):
  1214. def __init__(self, uid=None, name=None):
  1215. self.uid = uid
  1216. self.name = name
  1217. def __eq__(self, val):
  1218. if isinstance(val, str):
  1219. warnings.warn("comparison with a `str` is deprecated", DeprecationWarning, stacklevel=2)
  1220. return (self.uid == val)
  1221. # This signals to use the normal comparison operator
  1222. return NotImplemented
  1223. def __ne__(self, val):
  1224. if isinstance(val, str):
  1225. warnings.warn("comparison with a `str` is deprecated", DeprecationWarning, stacklevel=2)
  1226. return (self.uid != val)
  1227. # This signals to use the normal comparison operator
  1228. return NotImplemented
  1229. __hash__ = ORMObject.__hash__
  1230. def properties(self) -> list[str]:
  1231. return ['uid', 'name', 'fingerprint']
  1232. __all__.append('Uid')
  1233. @session_wrapper
  1234. def get_or_set_uid(uidname: str, session=None) -> Uid:
  1235. """
  1236. Returns uid object for given uidname.
  1237. If no matching uidname is found, a row is inserted.
  1238. :param uidname: The uid to add
  1239. :param session: Optional SQL session object (a temporary one will be
  1240. generated if not supplied). If not passed, a commit will be performed at
  1241. the end of the function, otherwise the caller is responsible for commiting.
  1242. :return: the uid object for the given uidname
  1243. """
  1244. q = session.query(Uid).filter_by(uid=uidname)
  1245. try:
  1246. ret = q.one()
  1247. except NoResultFound:
  1248. uid = Uid()
  1249. uid.uid = uidname
  1250. session.add(uid)
  1251. session.commit_or_flush()
  1252. ret = uid
  1253. return ret
  1254. __all__.append('get_or_set_uid')
  1255. @session_wrapper
  1256. def get_uid_from_fingerprint(fpr: str, session=None) -> Optional[Uid]:
  1257. q = session.query(Uid)
  1258. q = q.join(Fingerprint).filter_by(fingerprint=fpr)
  1259. return q.one_or_none()
  1260. __all__.append('get_uid_from_fingerprint')
  1261. ################################################################################
  1262. class MetadataKey(ORMObject):
  1263. def __init__(self, key=None):
  1264. self.key = key
  1265. def properties(self) -> list[str]:
  1266. return ['key']
  1267. __all__.append('MetadataKey')
  1268. @session_wrapper
  1269. def get_or_set_metadatakey(keyname: str, session=None) -> MetadataKey:
  1270. """
  1271. Returns MetadataKey object for given uidname.
  1272. If no matching keyname is found, a row is inserted.
  1273. :param keyname: The keyname to add
  1274. :param session: Optional SQL session object (a temporary one will be
  1275. generated if not supplied). If not passed, a commit will be performed at
  1276. the end of the function, otherwise the caller is responsible for commiting.
  1277. :return: the metadatakey object for the given keyname
  1278. """
  1279. q = session.query(MetadataKey).filter_by(key=keyname)
  1280. try:
  1281. ret = q.one()
  1282. except NoResultFound:
  1283. ret = MetadataKey(keyname)
  1284. session.add(ret)
  1285. session.commit_or_flush()
  1286. return ret
  1287. __all__.append('get_or_set_metadatakey')
  1288. ################################################################################
  1289. class BinaryMetadata(ORMObject):
  1290. def __init__(self, key=None, value=None, binary=None):
  1291. self.key = key
  1292. self.value = value
  1293. if binary is not None:
  1294. self.binary = binary
  1295. def properties(self) -> list[str]:
  1296. return ['binary', 'key', 'value']
  1297. __all__.append('BinaryMetadata')
  1298. ################################################################################
  1299. class SourceMetadata(ORMObject):
  1300. def __init__(self, key=None, value=None, source=None):
  1301. self.key = key
  1302. self.value = value
  1303. if source is not None:
  1304. self.source = source
  1305. def properties(self) -> list[str]:
  1306. return ['source', 'key', 'value']
  1307. __all__.append('SourceMetadata')
  1308. ################################################################################
  1309. class MetadataProxy:
  1310. def __init__(self, session, query):
  1311. self.session = session
  1312. self.query = query
  1313. def _get(self, key):
  1314. metadata_key = self.session.query(MetadataKey).filter_by(key=key).first()
  1315. if metadata_key is None:
  1316. return None
  1317. metadata = self.query.filter_by(key=metadata_key).first()
  1318. return metadata
  1319. def __contains__(self, key: str) -> bool:
  1320. if self._get(key) is not None:
  1321. return True
  1322. return False
  1323. def __getitem__(self, key: str) -> str:
  1324. metadata = self._get(key)
  1325. if metadata is None:
  1326. raise KeyError
  1327. return metadata.value
  1328. def get(self, key: str, default: Optional[str] = None) -> Optional[str]:
  1329. try:
  1330. return self[key]
  1331. except KeyError:
  1332. return default
  1333. ################################################################################
  1334. class VersionCheck(ORMObject):
  1335. def __init__(self, *args, **kwargs):
  1336. pass
  1337. def properties(self) -> list[str]:
  1338. return ['check']
  1339. __all__.append('VersionCheck')
  1340. @session_wrapper
  1341. def get_version_checks(suite_name: str, check: Optional[str] = None, session=None) -> list[VersionCheck]:
  1342. suite = get_suite(suite_name, session)
  1343. if not suite:
  1344. # Make sure that what we return is iterable so that list comprehensions
  1345. # involving this don't cause a traceback
  1346. return []
  1347. q = session.query(VersionCheck).filter_by(suite=suite)
  1348. if check:
  1349. q = q.filter_by(check=check)
  1350. return q.all()
  1351. __all__.append('get_version_checks')
  1352. ################################################################################
  1353. class DBConn:
  1354. """
  1355. database module init.
  1356. """
  1357. __shared_state = {}
  1358. db_meta = None
  1359. tbl_architecture = Architecture.__table__
  1360. tables = (
  1361. 'acl',
  1362. 'acl_architecture_map',
  1363. 'acl_fingerprint_map',
  1364. 'acl_per_source',
  1365. 'acl_per_suite',
  1366. 'archive',
  1367. 'bin_associations',
  1368. 'bin_contents',
  1369. 'binaries',
  1370. 'binaries_metadata',
  1371. 'build_queue',
  1372. 'changelogs_text',
  1373. 'changes',
  1374. 'component',
  1375. 'component_suite',
  1376. 'config',
  1377. 'dsc_files',
  1378. 'external_files',
  1379. 'external_overrides',
  1380. 'external_signature_requests',
  1381. 'extra_src_references',
  1382. 'files',
  1383. 'files_archive_map',
  1384. 'fingerprint',
  1385. 'hashfile',
  1386. 'keyrings',
  1387. 'maintainer',
  1388. 'metadata_keys',
  1389. 'new_comments',
  1390. # TODO: the maintainer column in table override should be removed.
  1391. 'override',
  1392. 'override_type',
  1393. 'policy_queue',
  1394. 'policy_queue_upload',
  1395. 'policy_queue_upload_binaries_map',
  1396. 'policy_queue_byhand_file',
  1397. 'priority',
  1398. 'signature_history',
  1399. 'source',
  1400. 'source_metadata',
  1401. 'src_associations',
  1402. 'src_contents',
  1403. 'src_format',
  1404. 'src_uploaders',
  1405. 'suite',
  1406. 'suite_acl_map',
  1407. 'suite_architectures',
  1408. 'suite_build_queue_copy',
  1409. 'suite_permission',
  1410. 'suite_src_formats',
  1411. 'uid',
  1412. 'version_check',
  1413. )
  1414. views = (
  1415. 'bin_associations_binaries',
  1416. 'changelogs',
  1417. 'newest_source',
  1418. 'newest_src_association',
  1419. 'package_list',
  1420. 'source_suite',
  1421. 'src_associations_src',
  1422. )
  1423. def __init__(self, *args, **kwargs):
  1424. self.__dict__ = self.__shared_state
  1425. if not getattr(self, 'initialised', False):
  1426. self.initialised = True
  1427. self.debug = 'debug' in kwargs
  1428. self.__createconn()
  1429. def __setuptables(self):
  1430. for table_name in self.tables:
  1431. table = Table(table_name, self.db_meta,
  1432. autoload=True, extend_existing=True)
  1433. setattr(self, 'tbl_%s' % table_name, table)
  1434. for view_name in self.views:
  1435. view = Table(view_name, self.db_meta, autoload=True)
  1436. setattr(self, 'view_%s' % view_name, view)
  1437. def __setupmappers(self):
  1438. mapper(ACL, self.tbl_acl,
  1439. properties=dict(
  1440. architectures=relation(Architecture, secondary=self.tbl_acl_architecture_map, collection_class=set),
  1441. fingerprints=relation(Fingerprint, secondary=self.tbl_acl_fingerprint_map, collection_class=set),
  1442. match_keyring=relation(Keyring, primaryjoin=(self.tbl_acl.c.match_keyring_id == self.tbl_keyrings.c.id)),
  1443. per_source=relation(ACLPerSource, collection_class=set, back_populates="acl"),
  1444. per_suite=relation(ACLPerSuite, collection_class=set, back_populates="acl"),
  1445. ))
  1446. mapper(ACLPerSource, self.tbl_acl_per_source,
  1447. properties=dict(
  1448. acl=relation(ACL, back_populates="per_source"),
  1449. fingerprint=relation(Fingerprint, primaryjoin=(self.tbl_acl_per_source.c.fingerprint_id == self.tbl_fingerprint.c.id)),
  1450. created_by=relation(Fingerprint, primaryjoin=(self.tbl_acl_per_source.c.created_by_id == self.tbl_fingerprint.c.id)),
  1451. ))
  1452. mapper(ACLPerSuite, self.tbl_acl_per_suite,
  1453. properties=dict(
  1454. acl=relation(ACL, back_populates="per_suite"),
  1455. fingerprint=relation(Fingerprint, primaryjoin=(self.tbl_acl_per_suite.c.fingerprint_id == self.tbl_fingerprint.c.id)),
  1456. suite=relation(Suite, primaryjoin=(self.tbl_acl_per_suite.c.suite_id == self.tbl_suite.c.id)),
  1457. created_by=relation(Fingerprint, primaryjoin=(self.tbl_acl_per_suite.c.created_by_id == self.tbl_fingerprint.c.id)),
  1458. ))
  1459. mapper(Archive, self.tbl_archive,
  1460. properties=dict(archive_id=self.tbl_archive.c.id,
  1461. archive_name=self.tbl_archive.c.name))
  1462. mapper(ArchiveFile, self.tbl_files_archive_map,
  1463. properties=dict(archive=relation(Archive, backref='files'),
  1464. component=relation(Component),
  1465. file=relation(PoolFile, backref='archives')))
  1466. mapper(BuildQueue, self.tbl_build_queue,
  1467. properties=dict(queue_id=self.tbl_build_queue.c.id,
  1468. suite=relation(Suite, primaryjoin=(self.tbl_build_queue.c.suite_id == self.tbl_suite.c.id))))
  1469. mapper(DBBinary, self.tbl_binaries,
  1470. properties=dict(binary_id=self.tbl_binaries.c.id,
  1471. package=self.tbl_binaries.c.package,
  1472. version=self.tbl_binaries.c.version,
  1473. maintainer_id=self.tbl_binaries.c.maintainer,
  1474. maintainer=relation(Maintainer),
  1475. source_id=self.tbl_binaries.c.source,
  1476. source=relation(DBSource, backref='binaries'),
  1477. arch_id=self.tbl_binaries.c.architecture,
  1478. architecture=relation(Architecture),
  1479. poolfile_id=self.tbl_binaries.c.file,
  1480. poolfile=relation(PoolFile),
  1481. binarytype=self.tbl_binaries.c.type,
  1482. fingerprint_id=self.tbl_binaries.c.sig_fpr,
  1483. fingerprint=relation(Fingerprint),
  1484. install_date=self.tbl_binaries.c.install_date,
  1485. suites=relation(Suite, secondary=self.tbl_bin_associations,
  1486. backref=backref('binaries', lazy='dynamic')),
  1487. extra_sources=relation(DBSource, secondary=self.tbl_extra_src_references,
  1488. backref=backref('extra_binary_references', lazy='dynamic')),
  1489. key=relation(BinaryMetadata, cascade='all',
  1490. collection_class=attribute_mapped_collection('key'), back_populates="binary")),
  1491. )
  1492. mapper(Component, self.tbl_component,
  1493. properties=dict(component_id=self.tbl_component.c.id,
  1494. component_name=self.tbl_component.c.name),
  1495. )
  1496. mapper(DBConfig, self.tbl_config,
  1497. properties=dict(config_id=self.tbl_config.c.id))
  1498. mapper(DSCFile, self.tbl_dsc_files,
  1499. properties=dict(dscfile_id=self.tbl_dsc_files.c.id,
  1500. source_id=self.tbl_dsc_files.c.source,
  1501. source=relation(DBSource, back_populates="srcfiles"),
  1502. poolfile_id=self.tbl_dsc_files.c.file,
  1503. poolfile=relation(PoolFile)))
  1504. mapper(ExternalOverride, self.tbl_external_overrides,
  1505. properties=dict(
  1506. suite_id=self.tbl_external_overrides.c.suite,
  1507. suite=relation(Suite),
  1508. component_id=self.tbl_external_overrides.c.component,
  1509. component=relation(Component)))
  1510. mapper(PoolFile, self.tbl_files,
  1511. properties=dict(file_id=self.tbl_files.c.id,
  1512. filesize=self.tbl_files.c.size),
  1513. )
  1514. mapper(Fingerprint, self.tbl_fingerprint,
  1515. properties=dict(fingerprint_id=self.tbl_fingerprint.c.id,
  1516. uid_id=self.tbl_fingerprint.c.uid,
  1517. uid=relation(Uid, back_populates="fingerprint"),
  1518. keyring_id=self.tbl_fingerprint.c.keyring,
  1519. keyring=relation(Keyring),
  1520. acl=relation(ACL)),
  1521. )
  1522. mapper(Keyring, self.tbl_keyrings,
  1523. properties=dict(keyring_name=self.tbl_keyrings.c.name,
  1524. keyring_id=self.tbl_keyrings.c.id,
  1525. acl=relation(ACL, primaryjoin=(self.tbl_keyrings.c.acl_id == self.tbl_acl.c.id)))),
  1526. mapper(DBChange, self.tbl_changes,
  1527. properties=dict(change_id=self.tbl_changes.c.id,
  1528. seen=self.tbl_changes.c.seen,
  1529. source=self.tbl_changes.c.source,
  1530. binaries=self.tbl_changes.c.binaries,
  1531. architecture=self.tbl_changes.c.architecture,
  1532. distribution=self.tbl_changes.c.distribution,
  1533. urgency=self.tbl_changes.c.urgency,
  1534. maintainer=self.tbl_changes.c.maintainer,
  1535. changedby=self.tbl_changes.c.changedby,
  1536. date=self.tbl_changes.c.date,
  1537. version=self.tbl_changes.c.version))
  1538. mapper(Maintainer, self.tbl_maintainer,
  1539. properties=dict(maintainer_id=self.tbl_maintainer.c.id,
  1540. maintains_sources=relation(DBSource, backref='maintainer',
  1541. primaryjoin=(self.tbl_maintainer.c.id == self.tbl_source.c.maintainer)),
  1542. changed_sources=relation(DBSource, backref='changedby',
  1543. primaryjoin=(self.tbl_maintainer.c.id == self.tbl_source.c.changedby))),
  1544. )
  1545. mapper(NewComment, self.tbl_new_comments,
  1546. properties=dict(comment_id=self.tbl_new_comments.c.id,
  1547. policy_queue=relation(PolicyQueue)))
  1548. mapper(Override, self.tbl_override,
  1549. properties=dict(suite_id=self.tbl_override.c.suite,
  1550. suite=relation(Suite,
  1551. backref=backref('overrides', lazy='dynamic')),
  1552. package=self.tbl_override.c.package,
  1553. component_id=self.tbl_override.c.component,
  1554. component=relation(Component,
  1555. backref=backref('overrides', lazy='dynamic')),
  1556. priority_id=self.tbl_override.c.priority,
  1557. priority=relation(Priority,
  1558. backref=backref('overrides', lazy='dynamic')),
  1559. section_id=self.tbl_override.c.section,
  1560. section=relation(Section,
  1561. backref=backref('overrides', lazy='dynamic')),
  1562. overridetype_id=self.tbl_override.c.type,
  1563. overridetype=relation(OverrideType,
  1564. backref=backref('overrides', lazy='dynamic'))))
  1565. mapper(OverrideType, self.tbl_override_type,
  1566. properties=dict(overridetype=self.tbl_override_type.c.type,
  1567. overridetype_id=self.tbl_override_type.c.id))
  1568. mapper(PolicyQueue, self.tbl_policy_queue,
  1569. properties=dict(policy_queue_id=self.tbl_policy_queue.c.id,
  1570. suite=relation(Suite, primaryjoin=(self.tbl_policy_queue.c.suite_id == self.tbl_suite.c.id))))
  1571. mapper(PolicyQueueUpload, self.tbl_policy_queue_upload,
  1572. properties=dict(
  1573. changes=relation(DBChange),
  1574. policy_queue=relation(PolicyQueue, backref='uploads'),
  1575. target_suite=relation(Suite),
  1576. source=relation(DBSource),
  1577. binaries=relation(DBBinary, secondary=self.tbl_policy_queue_upload_binaries_map),
  1578. ))
  1579. mapper(PolicyQueueByhandFile, self.tbl_policy_queue_byhand_file,
  1580. properties=dict(
  1581. upload=relation(PolicyQueueUpload, backref='byhand'),
  1582. ))
  1583. mapper(Priority, self.tbl_priority,
  1584. properties=dict(priority_id=self.tbl_priority.c.id))
  1585. mapper(SignatureHistory, self.tbl_signature_history)
  1586. mapper(DBSource, self.tbl_source,
  1587. properties=dict(source_id=self.tbl_source.c.id,
  1588. version=self.tbl_source.c.version,
  1589. maintainer_id=self.tbl_source.c.maintainer,
  1590. poolfile_id=self.tbl_source.c.file,
  1591. poolfile=relation(PoolFile),
  1592. fingerprint_id=self.tbl_source.c.sig_fpr,
  1593. fingerprint=relation(Fingerprint),
  1594. changedby_id=self.tbl_source.c.changedby,
  1595. srcfiles=relation(DSCFile,
  1596. primaryjoin=(self.tbl_source.c.id == self.tbl_dsc_files.c.source),
  1597. back_populates="source"),
  1598. suites=relation(Suite, secondary=self.tbl_src_associations,
  1599. backref=backref('sources', lazy='dynamic')),
  1600. uploaders=relation(Maintainer,
  1601. secondary=self.tbl_src_uploaders),
  1602. key=relation(SourceMetadata, cascade='all',
  1603. collection_class=attribute_mapped_collection('key'), back_populates="source")),
  1604. )
  1605. mapper(SrcFormat, self.tbl_src_format,
  1606. properties=dict(src_format_id=self.tbl_src_format.c.id,
  1607. format_name=self.tbl_src_format.c.format_name))
  1608. mapper(Suite, self.tbl_suite,
  1609. properties=dict(suite_id=self.tbl_suite.c.id,
  1610. policy_queue=relation(PolicyQueue, primaryjoin=(self.tbl_suite.c.policy_queue_id == self.tbl_policy_queue.c.id)),
  1611. new_queue=relation(PolicyQueue, primaryjoin=(self.tbl_suite.c.new_queue_id == self.tbl_policy_queue.c.id)),
  1612. debug_suite=relation(Suite, remote_side=[self.tbl_suite.c.id]),
  1613. copy_queues=relation(BuildQueue,
  1614. secondary=self.tbl_suite_build_queue_copy),
  1615. srcformats=relation(SrcFormat, secondary=self.tbl_suite_src_formats,
  1616. backref=backref('suites', lazy='dynamic')),
  1617. archive=relation(Archive, backref='suites'),
  1618. acls=relation(ACL, secondary=self.tbl_suite_acl_map, collection_class=set),
  1619. components=relation(Component, secondary=self.tbl_component_suite,
  1620. order_by=self.tbl_component.c.ordering,
  1621. backref=backref('suites')),
  1622. architectures=relation(Architecture, secondary=self.tbl_suite_architectures,
  1623. backref=backref('suites'))),
  1624. )
  1625. mapper(Uid, self.tbl_uid,
  1626. properties=dict(uid_id=self.tbl_uid.c.id,
  1627. fingerprint=relation(Fingerprint, back_populates="uid")),
  1628. )
  1629. mapper(BinContents, self.tbl_bin_contents,
  1630. properties=dict(
  1631. binary=relation(DBBinary,
  1632. backref=backref('contents', lazy='dynamic', cascade='all')),
  1633. file=self.tbl_bin_contents.c.file))
  1634. mapper(SrcContents, self.tbl_src_contents,
  1635. properties=dict(
  1636. source=relation(DBSource,
  1637. backref=backref('contents', lazy='dynamic', cascade='all')),
  1638. file=self.tbl_src_contents.c.file))
  1639. mapper(MetadataKey, self.tbl_metadata_keys,
  1640. properties=dict(
  1641. key_id=self.tbl_metadata_keys.c.key_id,
  1642. key=self.tbl_metadata_keys.c.key))
  1643. mapper(BinaryMetadata, self.tbl_binaries_metadata,
  1644. properties=dict(
  1645. binary_id=self.tbl_binaries_metadata.c.bin_id,
  1646. binary=relation(DBBinary, back_populates="key"),
  1647. key_id=self.tbl_binaries_metadata.c.key_id,
  1648. key=relation(MetadataKey),
  1649. value=self.tbl_binaries_metadata.c.value))
  1650. mapper(SourceMetadata, self.tbl_source_metadata,
  1651. properties=dict(
  1652. source_id=self.tbl_source_metadata.c.src_id,
  1653. source=relation(DBSource, back_populates="key"),
  1654. key_id=self.tbl_source_metadata.c.key_id,
  1655. key=relation(MetadataKey),
  1656. value=self.tbl_source_metadata.c.value))
  1657. mapper(VersionCheck, self.tbl_version_check,
  1658. properties=dict(
  1659. suite_id=self.tbl_version_check.c.suite,
  1660. suite=relation(Suite, primaryjoin=self.tbl_version_check.c.suite == self.tbl_suite.c.id),
  1661. reference_id=self.tbl_version_check.c.reference,
  1662. reference=relation(Suite, primaryjoin=self.tbl_version_check.c.reference == self.tbl_suite.c.id, lazy='joined')))
  1663. ## Connection functions
  1664. def __createconn(self):
  1665. from .config import Config
  1666. cnf = Config()
  1667. if "DB::Service" in cnf:
  1668. connstr = "postgresql://service=%s" % cnf["DB::Service"]
  1669. elif "DB::Host" in cnf:
  1670. # TCP/IP
  1671. connstr = "postgresql://%s" % cnf["DB::Host"]
  1672. if "DB::Port" in cnf and cnf["DB::Port"] != "-1":
  1673. connstr += ":%s" % cnf["DB::Port"]
  1674. connstr += "/%s" % cnf["DB::Name"]
  1675. else:
  1676. # Unix Socket
  1677. connstr = "postgresql:///%s" % cnf["DB::Name"]
  1678. if "DB::Port" in cnf and cnf["DB::Port"] != "-1":
  1679. connstr += "?port=%s" % cnf["DB::Port"]
  1680. engine_args = {'echo': self.debug}
  1681. if 'DB::PoolSize' in cnf:
  1682. engine_args['pool_size'] = int(cnf['DB::PoolSize'])
  1683. if 'DB::MaxOverflow' in cnf:
  1684. engine_args['max_overflow'] = int(cnf['DB::MaxOverflow'])
  1685. # we don't support non-utf-8 connections
  1686. engine_args['client_encoding'] = 'utf-8'
  1687. # Monkey patch a new dialect in in order to support service= syntax
  1688. import sqlalchemy.dialects.postgresql
  1689. from sqlalchemy.dialects.postgresql.psycopg2 import PGDialect_psycopg2
  1690. class PGDialect_psycopg2_dak(PGDialect_psycopg2):
  1691. def create_connect_args(self, url):
  1692. if str(url).startswith('postgresql://service='):
  1693. # Eww
  1694. servicename = str(url)[21:]
  1695. return (['service=%s' % servicename], {})
  1696. else:
  1697. return PGDialect_psycopg2.create_connect_args(self, url)
  1698. sqlalchemy.dialects.postgresql.base.dialect = PGDialect_psycopg2_dak
  1699. try:
  1700. self.db_pg = create_engine(connstr, **engine_args)
  1701. self.db_smaker = sessionmaker(bind=self.db_pg,
  1702. autoflush=True,
  1703. autocommit=False)
  1704. if self.db_meta is None:
  1705. self.__class__.db_meta = Base.metadata
  1706. self.__class__.db_meta.bind = self.db_pg
  1707. self.__setuptables()
  1708. self.__setupmappers()
  1709. except OperationalError as e:
  1710. from . import utils
  1711. utils.fubar("Cannot connect to database (%s)" % str(e))
  1712. self.pid = os.getpid()
  1713. def session(self, work_mem=0):
  1714. '''
  1715. Returns a new session object. If a work_mem parameter is provided a new
  1716. transaction is started and the work_mem parameter is set for this
  1717. transaction. The work_mem parameter is measured in MB. A default value
  1718. will be used if the parameter is not set.
  1719. '''
  1720. # reinitialize DBConn in new processes
  1721. if self.pid != os.getpid():
  1722. self.__createconn()
  1723. session = self.db_smaker()
  1724. if work_mem > 0:
  1725. session.execute("SET LOCAL work_mem TO '%d MB'" % work_mem)
  1726. return session
  1727. __all__.append('DBConn')