Best Python code snippet using locust
cockroachdbddlmanager.py
Source:cockroachdbddlmanager.py
1# --*-- coding: utf-8 --*--2import logging3from managers.manager import Manager4from tools.translations import trlocal as _5_logger = logging.getLogger('listener.' + __name__)6class pgdbddl_exception(Exception): pass7class pgdbddlManager(Manager):8 """9 ÐÑполнÑÐµÑ DDL манипÑлÑÑии Ñ ÑелÑÑионной базой даннÑÑ
POSTGRESQL 10 """11 _name = 'pgdbddlManager'12 _alias = 'ddl'13 _inherit = 'db.cockroachdb'14 def __init__(self):15 super(pgdbddlManager,self).__init__()16 def _checkExistRole(self,rolname):17 self._dispatcher.db.pgdb._execute("SELECT count(*) FROM pg_roles WHERE rolname = %s", (rolname,))18 return self._dispatcher.db.pgdb.cr.fetchone()[0] > 019 def listRoles(self):20 self._dispatcher.db.pgdb._execute("SELECT rolname FROM pg_roles order by rolname")21 return list(map(lambda x: x[0], self._dispatcher.db.pgdb.cr.fetchall()))22 def listsRole(self):23 self._dispatcher.db.pgdb._execute("SELECT rolname, rolsuper, rolinherit, rolcreaterole, rolcreatedb, rolcatupdate, rolreplication, rolconnlimit, to_char(rolvaliduntil,'YYYY-MM-DD HH24:MI:SS TZ') as rolvaliduntil, d.description AS comment FROM ((pg_authid AS a LEFT OUTER JOIN pg_shdescription AS d ON (d.objoid = a.oid)) LEFT OUTER JOIN pg_class AS c ON (d.classoid = c.oid AND c.relname = 'pg_authid'))")24 return self._dispatcher.db.pgdb.cr.dictfetchone()25 def getRoleAttrs(self,rolname):26 self._dispatcher.db.pgdb._execute("SELECT rolname, rolsuper, rolinherit, rolcreaterole, rolcreatedb, rolcatupdate, rolreplication, rolconnlimit, to_char(rolvaliduntil,'YYYY-MM-DD HH24:MI:SS TZ') as rolvaliduntil, d.description AS comment FROM ((pg_authid AS a LEFT OUTER JOIN pg_shdescription AS d ON (d.objoid = a.oid)) LEFT OUTER JOIN pg_class AS c ON (d.classoid = c.oid AND c.relname = 'pg_authid')) WHERE a.rolname = %s", (rolname,))27 return self._dispatcher.db.pgdb.cr.dictfetchone()28 def alterRole(self, rolname, password = None, confirm_password = None,rolsuper = False, rolinherit = False, rolcreaterole = False, rolcreatedb = False, rolcatupdate = False, rolreplication = False, rolconnlimit = -1, rolvaliduntil = 'infinity', comment = None):29 _locals = locals()30 self._dispatcher.db.pgdb.cr._setAutocommit()31 if not self._checkExistRole(rolname):32 self._dispatcher.db.pgdb.cr._restoreAutocommit()33 return [1,_(u'Role %s is not exist') % (rolname,)]34 _attrs = {'rolsuper': {True:' SUPERUSER',False:' NOSUPERUSER'},'password':" ENCRYPTED PASSWORD %s",'rolinherit':{True:' INHERIT',False:' NOINHERIT'},'rolcreatedb':{True:' CREATEDB',False:' NOCREATEDB'},'rolcreaterole':{True:' CREATEROLE',False:' NOCREATEROLE'},'rolreplication':{True:' REPLICATION',False:' NOREPLICATION'},'rolconnlimit':" CONNECTION LIMIT %s",'rolvaliduntil':" VALID UNTIL '%s'"}35 _rolAttrs = self.getRoleAttrs(rolname)36 _sqls = []37 _sql = "ALTER ROLE "+rolname38 _rolchange = False39 for key in _locals.keys():40 if key in ('self', 'rolname','rolcatupdate' ,'comment','confirm_password'):41 continue42 if key == 'password':43 if _locals[key]:44 _sql += _attrs[key] % (_locals[key],)45 continue46 if _locals[key] != _rolAttrs[key]:47 if key in ('rolconnlimit', 'rolvaliduntil'):48 _sql += _attrs[key] % (_locals[key],)49 else:50 _sql += _attrs[key][_locals[key]]51 _rolchange = True52 if _rolchange:53 _sqls.append([_sql,None])54 if _locals['rolsuper']:55 if _locals['rolcatupdate']:56 if _locals['rolcatupdate'] != _rolAttrs['rolcatupdate']:57 _sqls.append(["UPDATE pg_authid SET rolcatupdate=true WHERE rolname=%s", (_locals['rolname'],)])58 _sqls.append(_sql)59 else:60 if _locals['rolcatupdate'] != _rolAttrs['rolcatupdate']:61 _sqls.append(["UPDATE pg_authid SET rolcatupdate=false WHERE rolname=%s", (_locals['rolname'],)])62 if comment:63 if _rolAttrs['comment']:64 if _rolAttrs['comment'] != comment:65 _sqls.append(["COMMENT ON ROLE "+rolname+" IS %s", (comment,)])66 else:67 _sqls.append(["COMMENT ON ROLE "+rolname+" IS %s", (comment,)])68 else:69 if _rolAttrs['comment']:70 _sqls.append(["COMMENT ON ROLE "+rolname+" IS %s", ('',)])71 if _sqls.__len__() > 0:72 self._dispatcher.db.pgdb.cr._executeList(_sqls)73 _logger.info("ALTER ROLE %s" % (_locals['rolname'],))74 self._dispatcher.db.pgdb.cr._restoreAutocommit()75 return [True, _("Role %s was altered") % (_locals['rolname'],)]76 else:77 self._dispatcher.db.pgdb.cr._restoreAutocommit()78 return [True, _("Role %s not changed") % (_locals['rolname'],)]79 def createRole(self, rolname, password = None, confirm_password = None,rolsuper = False, rolinherit = False, rolcreaterole = False, rolcreatedb = False, rolcatupdate = False, rolreplication = False, rolconnlimit = -1, rolvaliduntil = 'infinity', comment = None):80 self._dispatcher.db.pgdb.cr._setAutocommit()81 if self._checkExistRole(rolname):82 self._dispatcher.db.pgdb.cr._restoreAutocommit()83 return [1,_('Role %s is exist') % (rolname,)]84 _sqls = []85 _sql = "CREATE ROLE %s LOGIN ENCRYPTED PASSWORD '%s' " % (rolname, password)86 if rolsuper:87 _sql += ' SUPERUSER'88 if rolinherit:89 _sql += ' INHERIT'90 else:91 _sql += ' NOINHERIT'92 if rolcreatedb:93 _sql += ' CREATEDB'94 if rolcreaterole:95 _sql += ' CREATEROLE'96 if rolreplication:97 _sql += ' REPLICATION'98 if rolvaliduntil.__len__() == 0:99 rolvaliduntil = 'infinity'100 _sql += " VALID UNTIL '%s'" % (rolvaliduntil,)101 _sql += ' CONNECTION LIMIT %s' % (rolconnlimit,)102 _sqls.append(_sql)103 print('SQL', _sql)104 if comment and comment.__len__() > 0:105 _sql = "COMMENT ON ROLE %s IS '%s'" % (rolname,comment)106 _sqls.append(_sql)107 if rolsuper:108 if rolcatupdate:109 _val = 'true'110 else:111 _val = 'false'112 _sql = "UPDATE pg_authid SET rolcatupdate=%s WHERE rolname='%s'" % (_val,rolname)113 _sqls.append(_sql)114 self._dispatcher.db.pgdb.cr._executeList(_sqls)115 _logger.info("CREATE ROLE %s" % (rolname,))116 self._dispatcher.db.pgdb.cr._restoreAutocommit()117 return [True, _("Role %s was creared") % (rolname,)]118 def dropRole(self, rolname):119 self._dispatcher.db.pgdb.cr._setAutocommit()120 if not self._checkExistRole(rolname):121 self._dispatcher.db.pgdb.cr._restoreAutocommit()122 return [2,_('Role %s is not exist') % (rolname,)]123 self._dispatcher.db.pgdb.cr._execute('DROP ROLE %s' % (rolname,))124 _logger.info("DROP ROLE %s" % (rolname,))125 self._dispatcher.db.pgdb.cr._restoreAutocommit()126 return [True, _("Role %s was droped") % (rolname,)]127# Tablespace128 def _checkExistTablespace(self,spcname):129 self._dispatcher.db.pgdb.cr._execute("SELECT count(*) FROM pg_tablespace WHERE spcname = %s", (spcname,))130 return self._dispatcher.db.pgdb.cr.fetchone()[0] > 0131 def listTablespaces(self):132 self._dispatcher.db.pgdb.cr._execute("SELECT spcname FROM pg_tablespace order by spcname")133 return list(map(lambda x: x[0], self._dispatcher.db.pgdb.cr.fetchall()))134 def getTablespaceAttrs(self,spcname):135 self._dispatcher.db.pgdb.cr._execute("SELECT spcname, auth.rolname as owner, pg_tablespace_location(t.oid) as location, d.description AS comment FROM (((pg_tablespace as t INNER JOIN pg_authid as auth on (t.spcowner = auth.oid)) LEFT OUTER JOIN pg_shdescription AS d ON (d.objoid = t.oid)) LEFT OUTER JOIN pg_class AS c ON (d.classoid = c.oid AND c.relname = 'pg_tablespace')) WHERE t.spcname = %s", (spcname,))136 return self._dispatcher.db.pgdb.cr.dictfetchone()137 def alterTablespace(self, spcname, location, owner, comment = None):138 self._dispatcher.db.pgdb.cr._setAutocommit()139 if not self._checkExistTablespace(spcname):140 self._dispatcher.db.pgdb.cr._restoreAutocommit()141 return [1,'Tablespace %s is not exist' % (spcname,)]142 _sqls = []143 _tablespacechange = False144 _sql = "ALTER TABLESPACE %s" % (spcname,)145 _tablespaceAttrs = self.getTablespaceAttrs(spcname)146 if owner != _tablespaceAttrs['owner']:147 _sql += " OWNER TO %s" % (owner,)148 _tablespacechange = True149 if _tablespacechange:150 _sqls.append([_sql, None])151 if comment != _tablespaceAttrs['comment']:152 _sql = "COMMENT ON TABLESPACE %s IS '%s'" % (spcname,comment)153 _sqls.append([_sql, None])154 if _sqls.__len__() > 0:155 self._dispatcher.db.pgdb.cr._executeList(_sqls)156 _logger.info("ALTER TABLESPACE %s" % (spcname,))157 self._dispatcher.db.pgdb.cr._restoreAutocommit()158 return [True, _("Tablespace %s was altered") % (spcname,)]159 else:160 return [True, _("Tablespace %s not changed") % (spcname,)]161 def createTablespace(self, spcname, owner = None, location = None, comment = None):162 self._dispatcher.db.pgdb.cr._setAutocommit()163 if self._checkExistTablespace(spcname):164 self._dispatcher.db.pgdb.cr._restoreAutocommit()165 return [1, _('Tablespace %s is exist') % (spcname,)]166 _sqls = []167 _sql = "CREATE TABLESPACE %s" % (spcname, )168 if owner:169 _sql += " OWNER %s" % (owner,)170 if location:171 _sql += " LOCATION '%s'" % (location,)172 _sqls.append([_sql, None])173 if comment:174 _sql = "COMMENT ON TABLESPACE %s IS '%s'" % (spcname,comment)175 _sqls.append([_sql, None])176 self._dispatcher.db.pgdb.cr._executeList(_sqls)177 _logger.info("CREATE TABLESPACE %s" % (spcname,))178 self._dispatcher.db.pgdb.cr._restoreAutocommit()179 return [True, _("Tablespace %s was created") % (spcname,)]180 def dropTablespace(self, spcname):181 self._dispatcher.db.pgdb.cr._setAutocommit()182 if not self._checkExistTablespace(spcname):183 self._dispatcher.db.pgdb.cr._restoreAutocommit()184 return [2, _('Tablespace %s is not exist') % (spcname,)]185 self._dispatcher.db.pgdb.cr._execute('DROP TABLESPACE %s' % (spcname,))186 self._dispatcher.db.pgdb.cr._restoreAutocommit()187 _logger.info("DROP TABLESPACE %s" % (spcname,))188 return [True, _("Tablespace %s was droped") % (spcname,)]189# Database190 def _checkExistDatabase(self,datname):191 self._dispatcher.db.pgdb.cr._execute("SELECT count(*) FROM pg_database WHERE datname = %s", (datname,))192 return self._dispatcher.db.pgdb.cr.fetchone()[0] > 0193 def listDatabases(self):194 self._dispatcher.db.pgdb.cr._execute("SELECT datname FROM pg_database order by datname")195 return list(map(lambda x: x[0], self._dispatcher.db.pgdb.cr.fetchall()))196 def getDatabaseAttrs(self,datname):197 self._dispatcher.db.pgdb.cr._execute("SELECT datname, pg_encoding_to_char(encoding) as encoding, auth.rolname as owner,datcollate as lc_collate, datctype as lc_ctype, datconnlimit as datconnlimit, t.spcname as spcname,d.description AS comment FROM (((pg_database AS p INNER JOIN pg_tablespace as t on (p.dattablespace = t.oid) INNER JOIN pg_authid as auth on (p.datdba = auth.oid)) LEFT OUTER JOIN pg_shdescription AS d ON (d.objoid = p.oid)) LEFT OUTER JOIN pg_class AS c ON (d.classoid = c.oid AND c.relname = 'pg_database')) WHERE p.datname = %s", (datname,))198 return self._dispatcher.db.pgdb.cr.dictfetchone()199 def alterDatabase(self,datname, owner, datconnlimit, spcname, comment=None, encoding=None,newdatname = None,):200 """201 ALTER DATABASE q2202 RENAME TO q21;203 ALTER DATABASE q21204 OWNER TO q1234567;205 COMMENT ON DATABASE q21206 IS 'qwerty23';207 ALTER DATABASE q21208 SET TABLESPACE pg_default;209 ALTER DATABASE q21210 WITH CONNECTION LIMIT = 5;211 """212 self._dispatcher.db.pgdb.cr._setAutocommit()213 if not self._checkExistDatabase(datname):214 self._dispatcher.db.pgdb.cr._restoreAutocommit()215 return [2, _('Database %s is not exist') % (datname,)]216 _dbchange = False217 _sqls = []218 _dbAttrs = self.getDatabaseAttrs(datname)219 if newdatname and datname != newdatname:220 _sql = "ALTER DATABASE %s RENAME to %s" % (datname, newdatname)221 _sqls.append([_sql, None])222 datname = newdatname 223 if owner != _dbAttrs['owner']:224 _sql = "ALTER DATABASE %s OWNER TO %s" % (datname, owner)225 _sqls.append([_sql, None])226 if datconnlimit != _dbAttrs['datconnlimit']:227 _sql = "ALTER DATABASE %s WITH CONNECTION LIMIT %s" % (datname, datconnlimit)228 _sqls.append([_sql, None])229 if spcname != _dbAttrs['spcname']:230 _sql = "ALTER DATABASE %s SET TABLESPACE %s" % (datname, spcname)231 _sqls.append([_sql, None])232 if comment != _dbAttrs['comment']:233 _sql = "COMMENT ON DATABASE %s IS '%s'" % (datname, comment)234 _sqls.append([_sql, None])235 if len(_sqls) > 0:236 self._dispatcher.db.pgdb.cr._executeList(_sqls)237 self._dispatcher.db.pgdb.cr._restoreAutocommit()238 _logger.info(_("ALTER DATABASE %s") % (datname,))239 return [True, _("Database %s was atered") % (datname,)]240 else:241 self._dispatcher.db.pgdb.cr._restoreAutocommit()242 return [True, _("Database %s not changed") % (datname,)]243 def createDatabase(self, datname, encoding = None, owner = None, template = None, lc_collate = None, lc_ctype = None, datconnlimit = -1, spcname = None, comment = None):244 self._dispatcher.db.pgdb.cr._setAutocommit()245 if self._checkExistDatabase(datname):246 self._dispatcher.db.pgdb.cr._restoreAutocommit()247 return [1, _('Database %s is exist') % (datname,)]248 _sqls = []249 _sql = "CREATE DATABASE %s" %(datname,)250 if encoding:251 _sql += " WITH ENCODING '%s'" % (encoding,)252 if owner:253 _sql += " OWNER %s" % (owner,)254 if template:255 _sql += " TEMPLATE %s" % (template,)256 if lc_collate:257 _sql += " LC_COLLATE '%s'" % (lc_collate,)258 if lc_ctype:259 _sql += " LC_CTYPE '%s'" % (lc_ctype,)260 if datconnlimit != -1:261 _sql += " CONNECTION LIMIT %s" % (datconnlimit,)262 if spcname:263 _sql += " TABLESPACE %s" % (spcname,)264 _sqls.append([_sql, None])265 if comment:266 _sql = "COMMENT ON DATABASE %s IS '%s'" % (datname,comment)267 _sqls.append([_sql, None])268 rc = self._dispatcher.db.pgdb.cr._executeList(_sqls)269 self._dispatcher.db.pgdb.cr._restoreAutocommit()270 _logger.info("CREATE DATABASE %s" % (datname,))271 return [True, _("Database %s was created") % (datname,)]272 def dropDatabase(self,datname):273 self._dispatcher.db.pgdb.cr._setAutocommit()274 if not self._checkExistDatabase(datname):275 self._dispatcher.db.pgdb.cr._restoreAutocommit()276 return [2, _('Database %s is not exist') % (datname,)]277 self._dispatcher.db.pgdb.cr._execute('DROP DATABASE %s' % (datname,))278 self._dispatcher.db.pgdb.cr._restoreAutocommit()279 _logger.info("DROP DATABASE %s" % (datname,)) 280 return [True, _("Database %s was droped") % (datname,)]281# Schema282 def _checkExistSchema(self,nspname):283 self._dispatcher.db.pgdb.cr._execute("SELECT count(*) FROM pg_namespace WHERE nspname = %s", (nspname,))284 return self._dispatcher.db.pgdb.cr.fetchone()[0] > 0285 def getSchemaAttrs(self,nspname):286 self._dispatcher.db.pgdb._execute("select a.nspname,b.rolname as owner,d.description as comment from (pg_namespace as a inner join pg_authid as b on(a.nspowner=b.oid) left outer join pg_description as d on(a.oid=d.objoid)) LEFT OUTER JOIN pg_class AS c ON (d.classoid = c.oid AND c.relname = 'pg_namespace') WHERE a.nspname = %s", (nspname,))287 return self._dispatcher.db.pgdb.cr.dictfetchone()288 def listSchemas(self):289 self._dispatcher.db.pgdb.cr._execute("SELECT nspname FROM pg_namespace where nspname not in ('pg_catalog','pg_toast','public','pg_temp_1','pg_toast_temp_1','information_schema') order by nspname")290 return list(map(lambda x: x[0], self._dispatcher.db.pgdb.cr.fetchall()))291 def alterSchema(self, nspname, owner, newnspname = None, comment = None):292 """ALTER SCHEMA <nspname> OWNER TO <owner>;293 COMMENT ON SCHEMA <nspname> IS '<comment>';"""294 self._dispatcher.db.pgdb.cr._setAutocommit()295 if not self._checkExistSchema(nspname):296 self._dispatcher.db.pgdb.cr._restoreAutocommit()297 return [2, _('Schema %s is not exist') % (nspname,)]298 _schchange = False299 _sqls = []300 _dbAttrs = self.getSchemaAttrs(nspname)301 if newnspname and nspname != newnspname:302 _sql = "ALTER SCHEMA %s RENAME to %s" % (nspname, newnspname)303 _sqls.append([_sql, None])304 nspname = newnspname 305 if owner != _dbAttrs['owner']:306 _sql = "ALTER SCHEMA %s OWNER TO %s" % (nspname, owner)307 _sqls.append([_sql, None])308 if comment and comment != _dbAttrs['comment']:309 _sql = "COMMENT ON SCHEMA %s IS '%s'" % (nspname, comment)310 _sqls.append([_sql, None])311 if len(_sqls) > 0:312 self._dispatcher.db.pgdb.cr._executeList(_sqls)313 self._dispatcher.db.pgdb.cr._restoreAutocommit()314 _logger.info(_("ALTER SCHEMA %s") % (nspname,))315 return [True, _("Schema %s was atered") % (nspname,)]316 else:317 self._dispatcher.db.pgdb.cr._restoreAutocommit()318 return [True, _("Schema %s not changed") % (nspname,)]319 def createSchema(self, nspname, owner= None, comment = None):320 """CREATE SCHEMA <nspname> AUTHORIZATION <owner>;321 COMMENT ON SCHEMA <nspname> IS '<comment>';"""322 self._dispatcher.db.pgdb.cr._setAutocommit()323 if self._checkExistSchema(nspname):324 self._dispatcher.db.pgdb.cr._restoreAutocommit()325 return [1, _('Schema %s is exist') % (nspname)]326 _sqls = []327 _sql = "CREATE SCHEMA %s" %(nspname,)328 if owner:329 _sql += " AUTHORIZATION %s" % (owner,)330 _sqls.append(_sql)331 if comment:332 _sql = "COMMENT ON SCHEMA %s IS '%s'" % (nspname,comment)333 _sqls.append([_sql, None])334 rc = self._dispatcher.db.pgdb.cr._executeList(_sqls)335 self._dispatcher.db.pgdb.cr._restoreAutocommit()336 _logger.info("CREATE SCHEMA %s" % (nspname,))337 return [True, _("Schema %s was created") % (nspname,)]338 pass339 def dropSchema(self,nspname):340 """DROP SCHEMA <nspname>"""341 self._dispatcher.db.pgdb.cr._setAutocommit()342 if not self._checkExistSchema(nspname):343 self._dispatcher.db.pgdb.cr._restoreAutocommit()344 return [2, _('Schema %s is not exist') % (nspname)]345 self._dispatcher.db.pgdb.cr._execute('DROP SCHEMA %s' % (nspname,))346 self._dispatcher.db.pgdb.cr._restoreAutocommit()347 _logger.info("DROP SCHEMA %s" % (nspname,))348 return [True, _("Schema %s was droped") % (nspname,)]...
pgdbddlmanager.py
Source:pgdbddlmanager.py
1# --*-- coding: utf-8 --*--2import logging3from managers.manager import Manager4from tools.translations import trlocal as _5_logger = logging.getLogger('listener.' + __name__)6class pgdbddl_exception(Exception): pass7class pgdbddlManager(Manager):8 """9 ÐÑполнÑÐµÑ DDL манипÑлÑÑии Ñ ÑелÑÑионной базой даннÑÑ
POSTGRESQL 10 """11 _name = 'pgdbddlManager'12 _alias = 'ddl'13 _inherit = 'db.pgdb'14 def __init__(self):15 super(pgdbddlManager,self).__init__()16 def _checkExistRole(self,rolname):17 self._dispatcher.db.pgdb._execute("SELECT count(*) FROM pg_roles WHERE rolname = %s", (rolname,))18 return self._dispatcher.db.pgdb.cr.fetchone()[0] > 019 def listRoles(self):20 self._dispatcher.db.pgdb._execute("SELECT rolname FROM pg_roles order by rolname")21 return list(map(lambda x: x[0], self._dispatcher.db.pgdb.cr.fetchall()))22 def listsRole(self):23 self._dispatcher.db.pgdb._execute("SELECT rolname, rolsuper, rolinherit, rolcreaterole, rolcreatedb, rolcatupdate, rolreplication, rolconnlimit, to_char(rolvaliduntil,'YYYY-MM-DD HH24:MI:SS TZ') as rolvaliduntil, d.description AS comment FROM ((pg_authid AS a LEFT OUTER JOIN pg_shdescription AS d ON (d.objoid = a.oid)) LEFT OUTER JOIN pg_class AS c ON (d.classoid = c.oid AND c.relname = 'pg_authid'))")24 return self._dispatcher.db.pgdb.cr.dictfetchone()25 def getRoleAttrs(self,rolname):26 self._dispatcher.db.pgdb._execute("SELECT rolname, rolsuper, rolinherit, rolcreaterole, rolcreatedb, rolcatupdate, rolreplication, rolconnlimit, to_char(rolvaliduntil,'YYYY-MM-DD HH24:MI:SS TZ') as rolvaliduntil, d.description AS comment FROM ((pg_authid AS a LEFT OUTER JOIN pg_shdescription AS d ON (d.objoid = a.oid)) LEFT OUTER JOIN pg_class AS c ON (d.classoid = c.oid AND c.relname = 'pg_authid')) WHERE a.rolname = %s", (rolname,))27 return self._dispatcher.db.pgdb.cr.dictfetchone()28 def alterRole(self, rolname, password = None, confirm_password = None,rolsuper = False, rolinherit = False, rolcreaterole = False, rolcreatedb = False, rolcatupdate = False, rolreplication = False, rolconnlimit = -1, rolvaliduntil = 'infinity', comment = None):29 _locals = locals()30 self._dispatcher.db.pgdb.cr._setAutocommit()31 if not self._checkExistRole(rolname):32 self._dispatcher.db.pgdb.cr._restoreAutocommit()33 return [1,_(u'Role %s is not exist') % (rolname,)]34 _attrs = {'rolsuper': {True:' SUPERUSER',False:' NOSUPERUSER'},'password':" ENCRYPTED PASSWORD %s",'rolinherit':{True:' INHERIT',False:' NOINHERIT'},'rolcreatedb':{True:' CREATEDB',False:' NOCREATEDB'},'rolcreaterole':{True:' CREATEROLE',False:' NOCREATEROLE'},'rolreplication':{True:' REPLICATION',False:' NOREPLICATION'},'rolconnlimit':" CONNECTION LIMIT %s",'rolvaliduntil':" VALID UNTIL '%s'"}35 _rolAttrs = self.getRoleAttrs(rolname)36 _sqls = []37 _sql = "ALTER ROLE "+rolname38 _rolchange = False39 for key in _locals.keys():40 if key in ('self', 'rolname','rolcatupdate' ,'comment','confirm_password'):41 continue42 if key == 'password':43 if _locals[key]:44 _sql += _attrs[key] % (_locals[key],)45 continue46 if _locals[key] != _rolAttrs[key]:47 if key in ('rolconnlimit', 'rolvaliduntil'):48 _sql += _attrs[key] % (_locals[key],)49 else:50 _sql += _attrs[key][_locals[key]]51 _rolchange = True52 if _rolchange:53 _sqls.append([_sql,None])54 if _locals['rolsuper']:55 if _locals['rolcatupdate']:56 if _locals['rolcatupdate'] != _rolAttrs['rolcatupdate']:57 _sqls.append(["UPDATE pg_authid SET rolcatupdate=true WHERE rolname=%s", (_locals['rolname'],)])58 _sqls.append(_sql)59 else:60 if _locals['rolcatupdate'] != _rolAttrs['rolcatupdate']:61 _sqls.append(["UPDATE pg_authid SET rolcatupdate=false WHERE rolname=%s", (_locals['rolname'],)])62 if comment:63 if _rolAttrs['comment']:64 if _rolAttrs['comment'] != comment:65 _sqls.append(["COMMENT ON ROLE "+rolname+" IS %s", (comment,)])66 else:67 _sqls.append(["COMMENT ON ROLE "+rolname+" IS %s", (comment,)])68 else:69 if _rolAttrs['comment']:70 _sqls.append(["COMMENT ON ROLE "+rolname+" IS %s", ('',)])71 if _sqls.__len__() > 0:72 self._dispatcher.db.pgdb.cr._executeList(_sqls)73 _logger.info("ALTER ROLE %s" % (_locals['rolname'],))74 self._dispatcher.db.pgdb.cr._restoreAutocommit()75 return [True, _("Role %s was altered") % (_locals['rolname'],)]76 else:77 self._dispatcher.db.pgdb.cr._restoreAutocommit()78 return [True, _("Role %s not changed") % (_locals['rolname'],)]79 def createRole(self, rolname, password = None, confirm_password = None,rolsuper = False, rolinherit = False, rolcreaterole = False, rolcreatedb = False, rolcatupdate = False, rolreplication = False, rolconnlimit = -1, rolvaliduntil = 'infinity', comment = None):80 self._dispatcher.db.pgdb.cr._setAutocommit()81 if self._checkExistRole(rolname):82 self._dispatcher.db.pgdb.cr._restoreAutocommit()83 return [1,_('Role %s is exist') % (rolname,)]84 _sqls = []85 _sql = "CREATE ROLE %s LOGIN ENCRYPTED PASSWORD '%s' " % (rolname, password)86 if rolsuper:87 _sql += ' SUPERUSER'88 if rolinherit:89 _sql += ' INHERIT'90 else:91 _sql += ' NOINHERIT'92 if rolcreatedb:93 _sql += ' CREATEDB'94 if rolcreaterole:95 _sql += ' CREATEROLE'96 if rolreplication:97 _sql += ' REPLICATION'98 if rolvaliduntil.__len__() == 0:99 rolvaliduntil = 'infinity'100 _sql += " VALID UNTIL '%s'" % (rolvaliduntil,)101 _sql += ' CONNECTION LIMIT %s' % (rolconnlimit,)102 _sqls.append(_sql)103 print('SQL', _sql)104 if comment and comment.__len__() > 0:105 _sql = "COMMENT ON ROLE %s IS '%s'" % (rolname,comment)106 _sqls.append(_sql)107 if rolsuper:108 if rolcatupdate:109 _val = 'true'110 else:111 _val = 'false'112 _sql = "UPDATE pg_authid SET rolcatupdate=%s WHERE rolname='%s'" % (_val,rolname)113 _sqls.append(_sql)114 self._dispatcher.db.pgdb.cr._executeList(_sqls)115 _logger.info("CREATE ROLE %s" % (rolname,))116 self._dispatcher.db.pgdb.cr._restoreAutocommit()117 return [True, _("Role %s was creared") % (rolname,)]118 def dropRole(self, rolname):119 self._dispatcher.db.pgdb.cr._setAutocommit()120 if not self._checkExistRole(rolname):121 self._dispatcher.db.pgdb.cr._restoreAutocommit()122 return [2,_('Role %s is not exist') % (rolname,)]123 self._dispatcher.db.pgdb.cr._execute('DROP ROLE %s' % (rolname,))124 _logger.info("DROP ROLE %s" % (rolname,))125 self._dispatcher.db.pgdb.cr._restoreAutocommit()126 return [True, _("Role %s was droped") % (rolname,)]127# Tablespace128 def _checkExistTablespace(self,spcname):129 self._dispatcher.db.pgdb.cr._execute("SELECT count(*) FROM pg_tablespace WHERE spcname = %s", (spcname,))130 return self._dispatcher.db.pgdb.cr.fetchone()[0] > 0131 def listTablespaces(self):132 self._dispatcher.db.pgdb.cr._execute("SELECT spcname FROM pg_tablespace order by spcname")133 return list(map(lambda x: x[0], self._dispatcher.db.pgdb.cr.fetchall()))134 def getTablespaceAttrs(self,spcname):135 self._dispatcher.db.pgdb.cr._execute("SELECT spcname, auth.rolname as owner, pg_tablespace_location(t.oid) as location, d.description AS comment FROM (((pg_tablespace as t INNER JOIN pg_authid as auth on (t.spcowner = auth.oid)) LEFT OUTER JOIN pg_shdescription AS d ON (d.objoid = t.oid)) LEFT OUTER JOIN pg_class AS c ON (d.classoid = c.oid AND c.relname = 'pg_tablespace')) WHERE t.spcname = %s", (spcname,))136 return self._dispatcher.db.pgdb.cr.dictfetchone()137 def alterTablespace(self, spcname, location, owner, comment = None):138 self._dispatcher.db.pgdb.cr._setAutocommit()139 if not self._checkExistTablespace(spcname):140 self._dispatcher.db.pgdb.cr._restoreAutocommit()141 return [1,'Tablespace %s is not exist' % (spcname,)]142 _sqls = []143 _tablespacechange = False144 _sql = "ALTER TABLESPACE %s" % (spcname,)145 _tablespaceAttrs = self.getTablespaceAttrs(spcname)146 if owner != _tablespaceAttrs['owner']:147 _sql += " OWNER TO %s" % (owner,)148 _tablespacechange = True149 if _tablespacechange:150 _sqls.append([_sql, None])151 if comment != _tablespaceAttrs['comment']:152 _sql = "COMMENT ON TABLESPACE %s IS '%s'" % (spcname,comment)153 _sqls.append([_sql, None])154 if _sqls.__len__() > 0:155 self._dispatcher.db.pgdb.cr._executeList(_sqls)156 _logger.info("ALTER TABLESPACE %s" % (spcname,))157 self._dispatcher.db.pgdb.cr._restoreAutocommit()158 return [True, _("Tablespace %s was altered") % (spcname,)]159 else:160 return [True, _("Tablespace %s not changed") % (spcname,)]161 def createTablespace(self, spcname, owner = None, location = None, comment = None):162 self._dispatcher.db.pgdb.cr._setAutocommit()163 if self._checkExistTablespace(spcname):164 self._dispatcher.db.pgdb.cr._restoreAutocommit()165 return [1, _('Tablespace %s is exist') % (spcname,)]166 _sqls = []167 _sql = "CREATE TABLESPACE %s" % (spcname, )168 if owner:169 _sql += " OWNER %s" % (owner,)170 if location:171 _sql += " LOCATION '%s'" % (location,)172 _sqls.append([_sql, None])173 if comment:174 _sql = "COMMENT ON TABLESPACE %s IS '%s'" % (spcname,comment)175 _sqls.append([_sql, None])176 self._dispatcher.db.pgdb.cr._executeList(_sqls)177 _logger.info("CREATE TABLESPACE %s" % (spcname,))178 self._dispatcher.db.pgdb.cr._restoreAutocommit()179 return [True, _("Tablespace %s was created") % (spcname,)]180 def dropTablespace(self, spcname):181 self._dispatcher.db.pgdb.cr._setAutocommit()182 if not self._checkExistTablespace(spcname):183 self._dispatcher.db.pgdb.cr._restoreAutocommit()184 return [2, _('Tablespace %s is not exist') % (spcname,)]185 self._dispatcher.db.pgdb.cr._execute('DROP TABLESPACE %s' % (spcname,))186 self._dispatcher.db.pgdb.cr._restoreAutocommit()187 _logger.info("DROP TABLESPACE %s" % (spcname,))188 return [True, _("Tablespace %s was droped") % (spcname,)]189# Database190 def _checkExistDatabase(self,datname):191 self._dispatcher.db.pgdb.cr._execute("SELECT count(*) FROM pg_database WHERE datname = %s", (datname,))192 return self._dispatcher.db.pgdb.cr.fetchone()[0] > 0193 def listDatabases(self):194 self._dispatcher.db.pgdb.cr._execute("SELECT datname FROM pg_database order by datname")195 return list(map(lambda x: x[0], self._dispatcher.db.pgdb.cr.fetchall()))196 def getDatabaseAttrs(self,datname):197 self._dispatcher.db.pgdb.cr._execute("SELECT datname, pg_encoding_to_char(encoding) as encoding, auth.rolname as owner,datcollate as lc_collate, datctype as lc_ctype, datconnlimit as datconnlimit, t.spcname as spcname,d.description AS comment FROM (((pg_database AS p INNER JOIN pg_tablespace as t on (p.dattablespace = t.oid) INNER JOIN pg_authid as auth on (p.datdba = auth.oid)) LEFT OUTER JOIN pg_shdescription AS d ON (d.objoid = p.oid)) LEFT OUTER JOIN pg_class AS c ON (d.classoid = c.oid AND c.relname = 'pg_database')) WHERE p.datname = %s", (datname,))198 return self._dispatcher.db.pgdb.cr.dictfetchone()199 def alterDatabase(self,datname, owner, datconnlimit, spcname, comment=None, encoding=None,newdatname = None,):200 """201 ALTER DATABASE q2202 RENAME TO q21;203 ALTER DATABASE q21204 OWNER TO q1234567;205 COMMENT ON DATABASE q21206 IS 'qwerty23';207 ALTER DATABASE q21208 SET TABLESPACE pg_default;209 ALTER DATABASE q21210 WITH CONNECTION LIMIT = 5;211 """212 self._dispatcher.db.pgdb.cr._setAutocommit()213 if not self._checkExistDatabase(datname):214 self._dispatcher.db.pgdb.cr._restoreAutocommit()215 return [2, _('Database %s is not exist') % (datname,)]216 _dbchange = False217 _sqls = []218 _dbAttrs = self.getDatabaseAttrs(datname)219 if newdatname and datname != newdatname:220 _sql = "ALTER DATABASE %s RENAME to %s" % (datname, newdatname)221 _sqls.append([_sql, None])222 datname = newdatname 223 if owner != _dbAttrs['owner']:224 _sql = "ALTER DATABASE %s OWNER TO %s" % (datname, owner)225 _sqls.append([_sql, None])226 if datconnlimit != _dbAttrs['datconnlimit']:227 _sql = "ALTER DATABASE %s WITH CONNECTION LIMIT %s" % (datname, datconnlimit)228 _sqls.append([_sql, None])229 if spcname != _dbAttrs['spcname']:230 _sql = "ALTER DATABASE %s SET TABLESPACE %s" % (datname, spcname)231 _sqls.append([_sql, None])232 if comment != _dbAttrs['comment']:233 _sql = "COMMENT ON DATABASE %s IS '%s'" % (datname, comment)234 _sqls.append([_sql, None])235 if len(_sqls) > 0:236 self._dispatcher.db.pgdb.cr._executeList(_sqls)237 self._dispatcher.db.pgdb.cr._restoreAutocommit()238 _logger.info(_("ALTER DATABASE %s") % (datname,))239 return [True, _("Database %s was atered") % (datname,)]240 else:241 self._dispatcher.db.pgdb.cr._restoreAutocommit()242 return [True, _("Database %s not changed") % (datname,)]243 def createDatabase(self, datname, encoding = None, owner = None, template = None, lc_collate = None, lc_ctype = None, datconnlimit = -1, spcname = None, comment = None):244 self._dispatcher.db.pgdb.cr._setAutocommit()245 if self._checkExistDatabase(datname):246 self._dispatcher.db.pgdb.cr._restoreAutocommit()247 return [1, _('Database %s is exist') % (datname,)]248 _sqls = []249 _sql = "CREATE DATABASE %s" %(datname,)250 if encoding:251 _sql += " WITH ENCODING '%s'" % (encoding,)252 if owner:253 _sql += " OWNER %s" % (owner,)254 if template:255 _sql += " TEMPLATE %s" % (template,)256 if lc_collate:257 _sql += " LC_COLLATE '%s'" % (lc_collate,)258 if lc_ctype:259 _sql += " LC_CTYPE '%s'" % (lc_ctype,)260 if datconnlimit != -1:261 _sql += " CONNECTION LIMIT %s" % (datconnlimit,)262 if spcname:263 _sql += " TABLESPACE %s" % (spcname,)264 _sqls.append([_sql, None])265 if comment:266 _sql = "COMMENT ON DATABASE %s IS '%s'" % (datname,comment)267 _sqls.append([_sql, None])268 rc = self._dispatcher.db.pgdb.cr._executeList(_sqls)269 self._dispatcher.db.pgdb.cr._restoreAutocommit()270 _logger.info("CREATE DATABASE %s" % (datname,))271 return [True, _("Database %s was created") % (datname,)]272 def dropDatabase(self,datname):273 self._dispatcher.db.pgdb.cr._setAutocommit()274 if not self._checkExistDatabase(datname):275 self._dispatcher.db.pgdb.cr._restoreAutocommit()276 return [2, _('Database %s is not exist') % (datname,)]277 self._dispatcher.db.pgdb.cr._execute('DROP DATABASE %s' % (datname,))278 self._dispatcher.db.pgdb.cr._restoreAutocommit()279 _logger.info("DROP DATABASE %s" % (datname,)) 280 return [True, _("Database %s was droped") % (datname,)]281# Schema282 def _checkExistSchema(self,nspname):283 self._dispatcher.db.pgdb.cr._execute("SELECT count(*) FROM pg_namespace WHERE nspname = %s", (nspname,))284 return self._dispatcher.db.pgdb.cr.fetchone()[0] > 0285 def getSchemaAttrs(self,nspname):286 self._dispatcher.db.pgdb._execute("select a.nspname,b.rolname as owner,d.description as comment from (pg_namespace as a inner join pg_authid as b on(a.nspowner=b.oid) left outer join pg_description as d on(a.oid=d.objoid)) LEFT OUTER JOIN pg_class AS c ON (d.classoid = c.oid AND c.relname = 'pg_namespace') WHERE a.nspname = %s", (nspname,))287 return self._dispatcher.db.pgdb.cr.dictfetchone()288 def listSchemas(self):289 self._dispatcher.db.pgdb.cr._execute("SELECT nspname FROM pg_namespace where nspname not in ('pg_catalog','pg_toast','public','pg_temp_1','pg_toast_temp_1','information_schema') order by nspname")290 return list(map(lambda x: x[0], self._dispatcher.db.pgdb.cr.fetchall()))291 def alterSchema(self, nspname, owner, newnspname = None, comment = None):292 """ALTER SCHEMA <nspname> OWNER TO <owner>;293 COMMENT ON SCHEMA <nspname> IS '<comment>';"""294 self._dispatcher.db.pgdb.cr._setAutocommit()295 if not self._checkExistSchema(nspname):296 self._dispatcher.db.pgdb.cr._restoreAutocommit()297 return [2, _('Schema %s is not exist') % (nspname,)]298 _schchange = False299 _sqls = []300 _dbAttrs = self.getSchemaAttrs(nspname)301 if newnspname and nspname != newnspname:302 _sql = "ALTER SCHEMA %s RENAME to %s" % (nspname, newnspname)303 _sqls.append([_sql, None])304 nspname = newnspname 305 if owner != _dbAttrs['owner']:306 _sql = "ALTER SCHEMA %s OWNER TO %s" % (nspname, owner)307 _sqls.append([_sql, None])308 if comment and comment != _dbAttrs['comment']:309 _sql = "COMMENT ON SCHEMA %s IS '%s'" % (nspname, comment)310 _sqls.append([_sql, None])311 if len(_sqls) > 0:312 self._dispatcher.db.pgdb.cr._executeList(_sqls)313 self._dispatcher.db.pgdb.cr._restoreAutocommit()314 _logger.info(_("ALTER SCHEMA %s") % (nspname,))315 return [True, _("Schema %s was atered") % (nspname,)]316 else:317 self._dispatcher.db.pgdb.cr._restoreAutocommit()318 return [True, _("Schema %s not changed") % (nspname,)]319 def createSchema(self, nspname, owner= None, comment = None):320 """CREATE SCHEMA <nspname> AUTHORIZATION <owner>;321 COMMENT ON SCHEMA <nspname> IS '<comment>';"""322 self._dispatcher.db.pgdb.cr._setAutocommit()323 if self._checkExistSchema(nspname):324 self._dispatcher.db.pgdb.cr._restoreAutocommit()325 return [1, _('Schema %s is exist') % (nspname)]326 _sqls = []327 _sql = "CREATE SCHEMA %s" %(nspname,)328 if owner:329 _sql += " AUTHORIZATION %s" % (owner,)330 _sqls.append(_sql)331 if comment:332 _sql = "COMMENT ON SCHEMA %s IS '%s'" % (nspname,comment)333 _sqls.append([_sql, None])334 rc = self._dispatcher.db.pgdb.cr._executeList(_sqls)335 self._dispatcher.db.pgdb.cr._restoreAutocommit()336 _logger.info("CREATE SCHEMA %s" % (nspname,))337 return [True, _("Schema %s was created") % (nspname,)]338 pass339 def dropSchema(self,nspname):340 """DROP SCHEMA <nspname>"""341 self._dispatcher.db.pgdb.cr._setAutocommit()342 if not self._checkExistSchema(nspname):343 self._dispatcher.db.pgdb.cr._restoreAutocommit()344 return [2, _('Schema %s is not exist') % (nspname)]345 self._dispatcher.db.pgdb.cr._execute('DROP SCHEMA %s' % (nspname,))346 self._dispatcher.db.pgdb.cr._restoreAutocommit()347 _logger.info("DROP SCHEMA %s" % (nspname,))348 return [True, _("Schema %s was droped") % (nspname,)]...
bootstrap.py
Source:bootstrap.py
...9logger = logging.getLogger(__name__)10logger.setLevel(level=settings.BASE_LOG_LEVEL)11logging.basicConfig(level=settings.BASE_LOG_LEVEL)12__DISPATCHER__: Optional[Dispatcher] = None13def get_dispatcher() -> Dispatcher:14 global __DISPATCHER__15 if not __DISPATCHER__:16 dispatcher = Dispatcher(17 bot=Bot(settings.TELEGRAM_BOT_TOKEN),18 storage=MemoryStorage()19 )20 __DISPATCHER__ = dispatcher21 __setup_dispatcher__(_dispatcher=dispatcher)22 return __DISPATCHER__23async def startup(_dispatcher: Dispatcher):24 if is_running_as_webhook(_dispatcher=_dispatcher):25 await _dispatcher.bot.set_webhook(26 url=settings.WEBHOOK_URL27 )...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!