code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
pairs = [] for k, v in vars(obj).items(): pairs.append(u"{}={}".format(k, v)) return u", ".join(pairs)
def debug_object(obj: T) -> str
Prints key/value pairs for an object's dictionary.
3.707312
2.843536
1.303769
log.info(_LINE_EQUALS) log.info("DUMP OF: {}", obj) for f in fieldlist: log.info(u"{f}: {v}", f=f, v=getattr(obj, f)) log.info(_LINE_EQUALS)
def dump_database_object(obj: T, fieldlist: Iterable[str]) -> None
Prints key/value pairs for an object's dictionary.
5.361881
4.528036
1.184152
if len(fieldlist) != len(valuelist): raise AssertionError("assign_from_list: fieldlist and valuelist of " "different length") for i in range(len(valuelist)): setattr(obj, fieldlist[i], valuelist[i])
def assign_from_list(obj: T, fieldlist: Sequence[str], valuelist: Sequence[any]) -> None
Within "obj", assigns the values from the value list to the fields in the fieldlist.
2.418423
2.442433
0.990169
construct_with_pk = kwargs.pop('construct_with_pk', False) # print("construct_with_pk: {}".format(construct_with_pk)) # print("args: {}".format(args)) # print("kwargs: {}".format(kwargs)) if construct_with_pk: obj = cls(valuelist[0], *args, **kwargs) assign_from_list(obj, fieldl...
def create_object_from_list(cls: Type, fieldlist: Sequence[str], valuelist: Sequence[Any], *args, **kwargs) -> T
Create an object by instantiating ``cls(*args, **kwargs)`` and assigning the values in ``valuelist`` to the fields in ``fieldlist``. If ``construct_with_pk`` is ``True``, initialize with ``cls(valuelist[0], *args, **kwargs)`` and assign the values in ``valuelist[1:]`` to ``fieldlist[1:]``. Note: i...
2.220411
1.833994
1.210697
for f in fieldlist: setattr(obj, f, None)
def blank_object(obj: T, fieldlist: Sequence[str]) -> None
Within "obj", sets all fields in the fieldlist to None.
4.827184
2.999659
1.609244
log.info("Retrieved {} rows", len(rows)) for i in range(len(rows)): log.info("Row {}: {}", i, rows[i])
def debug_query_result(rows: Sequence[Any]) -> None
Writes a query result to the log.
4.202184
3.141177
1.337773
con = mysql.connect( host=server, port=port, user=user, passwd=password, charset=charset, use_unicode=use_unicode ) sql = ("CREATE DATABASE IF NOT EXISTS {} DEFAULT CHARACTER SET {} " "DEFAULT COLLATE {}").format( database, char...
def create_database_mysql(database: str, user: str, password: str, server: str = "localhost", port: int = 3306, charset: str = "utf8", collate: str = "utf8_general_...
Connects via PyMySQL/MySQLdb and creates a database.
2.661008
2.566703
1.036742
con = mysql.connect( host=server, port=port, user=root_user, passwd=root_password, charset=charset, use_unicode=use_unicode ) wherefrom = "localhost" if localhost_only else "%" sql = ("GRANT ALL PRIVILEGES ON {}.* TO '{}'@'{}' " "IDENTIFIED...
def add_master_user_mysql(database: str, root_user: str, root_password: str, new_user: str, new_password: str, server: str = "localhost", port: int = 3306, ...
Connects via PyMySQL/MySQLdb and creates a database superuser.
2.591691
2.489385
1.041097
raise RuntimeError(_MSG_NO_FLAVOUR)
def describe_table(cls, db: DATABASE_SUPPORTER_FWD_REF, table: str) -> List[List[Any]]
Returns details on a specific table.
62.620014
59.447666
1.053364
raise RuntimeError(_MSG_NO_FLAVOUR)
def fetch_column_names(cls, db: DATABASE_SUPPORTER_FWD_REF, table: str) -> List[str]
Returns all column names for a table.
59.870453
54.741684
1.09369
raise RuntimeError(_MSG_NO_FLAVOUR)
def get_datatype(cls, db: DATABASE_SUPPORTER_FWD_REF, table: str, column: str) -> str
Returns database SQL datatype for a column: e.g. VARCHAR.
97.148804
51.306923
1.893483
def convert_enums(row_): # All these columns are of type enum('N', 'Y'); # https://dev.mysql.com/doc/refman/5.0/en/enum.html return [True if x == 'Y' else (False if x == 'N' else None) for x in row_] # 1. Check per-database privileges. ...
def is_read_only(cls, db: DATABASE_SUPPORTER_FWD_REF, logger: logging.Logger = None) -> bool
Do we have read-only access?
4.267018
4.151641
1.027791
# Catch all exceptions, so the error-catcher never shows a password. # Note also that higher-level things may catch exceptions, so use the # logger as well. try: return self._connect( engine=engine, interface=interface, host=host, por...
def connect(self, engine: str = None, interface: str = None, host: str = None, port: int = None, database: str = None, driver: str = None, dsn: str = None, odbc_connection_string: str = None, ...
engine: access, mysql, sqlserver interface: mysql, odbc, jdbc
3.565773
3.514941
1.014462
if self.db is None or self.db_pythonlib not in [PYTHONLIB_MYSQLDB, PYTHONLIB_PYMYSQL]: return try: self.db.ping(True) # test connection; reconnect upon failure # ... should auto-reconnect; however, it s...
def ping(self) -> None
Pings a database connection, reconnecting if necessary.
5.905184
5.440543
1.085403
self.connect(engine=ENGINE_MYSQL, interface=INTERFACE_ODBC, database=database, user=user, password=password, host=server, port=port, driver=driver, autocommit=autocommit)
def connect_to_database_odbc_mysql(self, database: str, user: str, password: str, server: str = "localhost", port: int = 3306...
Connects to a MySQL database via ODBC.
3.396729
2.683875
1.265606
self.connect(engine=ENGINE_SQLSERVER, interface=INTERFACE_ODBC, odbc_connection_string=odbc_connection_string, dsn=dsn, database=database, user=user, password=password, host=server, driver=driver, a...
def connect_to_database_odbc_sqlserver(self, odbc_connection_string: str = None, dsn: str = None, database: str = None, user: str = None, ...
Connects to an SQL Server database via ODBC.
2.83524
2.421862
1.170686
self.connect(engine=ENGINE_ACCESS, interface=INTERFACE_ODBC, dsn=dsn, autocommit=autocommit)
def connect_to_database_odbc_access(self, dsn: str, autocommit: bool = True) -> None
Connects to an Access database via ODBC, with the DSN prespecified.
7.407277
5.277688
1.403508
# pyodbc seems happy with ? now (pyodbc.paramstyle is 'qmark'); # using ? is much simpler, because we may want to use % with LIKE # fields or (in my case) with date formatting strings for # STR_TO_DATE(). # If you get this wrong, you may see "not all arguments converted ...
def localize_sql(self, sql: str) -> str
Translates ?-placeholder SQL to appropriate dialect. For example, MySQLdb uses %s rather than ?.
14.510689
13.286784
1.092114
self.ensure_db_open() if len(fields) != len(values): raise AssertionError("Field/value mismatch") if update_on_duplicate_key: sql = get_sql_insert_or_update(table, fields, self.get_delims()) else: sql = get_sql_insert(table, fields, self.get_d...
def insert_record(self, table: str, fields: Sequence[str], values: Sequence[Any], update_on_duplicate_key: bool = False) -> int
Inserts a record into database, table "table", using the list of fieldnames and the list of values. Returns the new PK (or None).
4.364212
4.015252
1.086908
fields = [] values = [] for fs in fieldspeclist: fields.append(fs["name"]) values.append(fs["value"]) return self.insert_record(table, fields, values)
def insert_record_by_fieldspecs_with_values( self, table: str, fieldspeclist: FIELDSPECLIST_TYPE) -> int
Inserts a record into the database using a list of fieldspecs having their value stored under the 'value' key.
2.834042
2.154512
1.315399
if not valuedict: return None n = len(valuedict) fields = [] args = [] for f, v in valuedict.items(): fields.append(self.delimit(f)) args.append(v) query = .format( table=table, fields=",".join(fields), ...
def insert_record_by_dict(self, table: str, valuedict: Dict[str, Any]) -> Optional[int]
Inserts a record into database, table "table", using a dictionary containing field/value mappings. Returns the new PK (or None).
3.395381
3.233502
1.050063
self.ensure_db_open() sql = self.localize_sql(get_sql_insert(table, fields, self.get_delims())) log.debug("About to insert multiple records with SQL template: " + sql) try: cursor = self.db.cursor() debug_sql...
def insert_multiple_records(self, table: str, fields: Sequence[str], records: Sequence[Sequence[Any]]) -> int
Inserts a record into database, table "table", using the list of fieldnames and the list of records (each a list of values). Returns number of rows affected.
5.313095
5.111829
1.039372
sql = self.localize_sql(sql) try: debug_sql(sql, args) cursor.execute(sql, args) return cursor.rowcount except: # nopep8 log.exception("db_exec_with_cursor: SQL was: " + sql) raise
def db_exec_with_cursor(self, cursor, sql: str, *args) -> int
Executes SQL on a supplied cursor, with "?" placeholders, substituting in the arguments. Returns number of rows affected.
4.236582
3.482175
1.216648
self.ensure_db_open() cursor = self.db.cursor() return self.db_exec_with_cursor(cursor, sql, *args)
def db_exec(self, sql: str, *args) -> int
Executes SQL (with "?" placeholders for arguments).
4.249253
3.257946
1.304274
rowcount = self.db_exec(sql, *args) self.commit() return rowcount
def db_exec_and_commit(self, sql: str, *args) -> int
Execute SQL and commit.
4.383492
3.1022
1.413027
self.ensure_db_open() cursor = self.db.cursor() debug_sql(sql) try: cursor.execute(sql) return cursor.rowcount except: # nopep8 log.exception("db_exec_literal: SQL was: " + sql) raise
def db_exec_literal(self, sql: str) -> int
Executes SQL without modification. Returns rowcount.
4.456766
3.78343
1.17797
row = self.fetchone(sql, *args) if row is None: return None return row[0]
def fetchvalue(self, sql: str, *args) -> Optional[Any]
Executes SQL; returns the first value of the first row, or None.
2.680931
2.370514
1.130949
self.ensure_db_open() cursor = self.db.cursor() self.db_exec_with_cursor(cursor, sql, *args) try: return cursor.fetchone() except: # nopep8 log.exception("fetchone: SQL was: " + sql) raise
def fetchone(self, sql: str, *args) -> Optional[Sequence[Any]]
Executes SQL; returns the first row, or None.
4.432959
4.046785
1.095427
self.ensure_db_open() cursor = self.db.cursor() self.db_exec_with_cursor(cursor, sql, *args) try: rows = cursor.fetchall() return rows except: # nopep8 log.exception("fetchall: SQL was: " + sql) raise
def fetchall(self, sql: str, *args) -> Sequence[Sequence[Any]]
Executes SQL; returns all rows, or [].
4.537564
4.135504
1.097222
self.ensure_db_open() cursor = self.db.cursor() self.db_exec_with_cursor(cursor, sql, *args) try: row = cursor.fetchone() while row is not None: yield row row = cursor.fetchone() except: # nopep8 log.ex...
def gen_fetchall(self, sql: str, *args) -> Iterator[Sequence[Any]]
fetchall() as a generator.
3.225083
3.096422
1.041551
self.ensure_db_open() cursor = self.db.cursor() self.db_exec_with_cursor(cursor, sql, *args) try: rows = cursor.fetchall() fieldnames = [i[0] for i in cursor.description] return rows, fieldnames except: # nopep8 log.except...
def fetchall_with_fieldnames(self, sql: str, *args) \ -> Tuple[Sequence[Sequence[Any]], Sequence[str]]
Executes SQL; returns (rows, fieldnames).
3.109718
2.913132
1.067483
self.ensure_db_open() cursor = self.db.cursor() self.db_exec_with_cursor(cursor, sql, *args) try: rows = cursor.fetchall() fieldnames = [i[0] for i in cursor.description] dictlist = [] for r in rows: dictlist.append...
def fetchall_as_dictlist(self, sql: str, *args) -> List[Dict[str, Any]]
Executes SQL; returns list of dictionaries, where each dict contains fieldname/value pairs.
2.800671
2.657928
1.053705
rows = self.fetchall(sql, *args) return [row[0] for row in rows]
def fetchallfirstvalues(self, sql: str, *args) -> List[Any]
Executes SQL; returns list of first values of each row.
3.03855
2.628334
1.156075
self.ensure_db_open() cursor = self.db.cursor() self.db_exec_with_cursor(cursor, sql, *args) try: return [i[0] for i in cursor.description] except: # nopep8 log.exception("fetch_fieldnames: SQL was: " + sql) raise
def fetch_fieldnames(self, sql: str, *args) -> List[str]
Executes SQL; returns just the output fieldnames.
3.876315
3.668303
1.056705
sql = "SELECT COUNT(*) FROM " + self.delimit(table) if wheredict is not None: sql += " WHERE " + " AND ".join([ self.delimit(k) + "=?" for k in wheredict.keys() ]) whereargs = wheredict.values() count = self.fetchon...
def count_where(self, table: str, wheredict: Dict[str, Any] = None) -> int
Counts rows in a table, given a set of WHERE criteria (ANDed), returning a count.
2.382808
2.170717
1.097706
sql = ("SELECT COUNT(*) FROM " + self.delimit(table) + " WHERE " + self.delimit(field) + "=?") row = self.fetchone(sql, value) return True if row[0] >= 1 else False
def does_row_exist(self, table: str, field: str, value: Any) -> bool
Checks for the existence of a record by a single field (typically a PK).
3.558688
2.943583
1.208965
sql = ("DELETE FROM " + self.delimit(table) + " WHERE " + self.delimit(field) + "=?") return self.db_exec(sql, value)
def delete_by_field(self, table: str, field: str, value: Any) -> int
Deletes all records where "field" is "value".
4.059479
3.2255
1.258558
if pkvalue is None: blank_object(obj, fieldlist) return False row = self.fetchone( get_sql_select_all_non_pk_fields_by_pk(table, fieldlist, self.get_delims()), pkvalue ) if row is ...
def fetch_object_from_db_by_pk(self, obj: Any, table: str, fieldlist: Sequence[str], pkvalue: Any) -> bool
Fetches object from database table by PK value. Writes back to object. Returns True/False for success/failure.
3.953071
3.841837
1.028953
row = self.fetchone( get_sql_select_all_fields_by_key(table, fieldlist, keyname, self.get_delims()), keyvalue ) if row is None: blank_object(obj, fieldlist) return False assign_from_list...
def fetch_object_from_db_by_other_field(self, obj: Any, table: str, fieldlist: Sequence[str], keyname: str, ...
Fetches object from database table by a field specified by keyname/keyvalue. Writes back to object. Returns True/False for success/failure.
5.677911
5.452189
1.0414
return self.fetch_all_objects_from_db_where( cls, table, fieldlist, construct_with_pk, None, *args)
def fetch_all_objects_from_db(self, cls: Type[T], table: str, fieldlist: Sequence[str], construct_with_pk: bool, *args) -> List[T]
Fetches all objects from a table, returning an array of objects of class cls.
2.759422
2.742229
1.00627
objarray = [] for pk in pklist: if construct_with_pk: obj = cls(pk, *args) # should do its own fetching else: obj = cls(*args) self.fetch_object_from_db_by_pk(obj, table, fieldlist, pk) objarray.append(obj) ...
def fetch_all_objects_from_db_by_pklist(self, cls: Type, table: str, fieldlist: Sequence[str], pklist: Sequence[Any], ...
Fetches all objects from a table, given a list of PKs.
2.984634
2.971893
1.004287
sql = ( "SELECT " + ",".join([self.delimit(x) for x in fieldlist]) + " FROM " + self.delimit(table) ) whereargs = [] if wheredict is not None: sql += " WHERE " + " AND ".join([ self.delimit(k) + "=?" for k in wh...
def fetch_all_objects_from_db_where(self, cls: Type[T], table: str, fieldlist: Sequence[str], construct_with_pk: bool, w...
Fetches all objects from a table, given a set of WHERE criteria (ANDed), returning an array of objects of class cls. As usual here, the first field in the fieldlist must be the PK.
2.219634
2.230125
0.995296
pkvalue = getattr(obj, fieldlist[0]) if pkvalue is None: raise AssertionError("insert_object_intoto_db_pk_known called " "without PK") valuelist = [] for f in fieldlist: valuelist.append(getattr(obj, f)) self.db_ex...
def insert_object_into_db_pk_known(self, obj: Any, table: str, fieldlist: Sequence[str]) -> None
Inserts object into database table, with PK (first field) already known.
4.520443
4.39511
1.028517
self.ensure_db_open() valuelist = [] for f in fieldlist[1:]: valuelist.append(getattr(obj, f)) cursor = self.db.cursor() self.db_exec_with_cursor( cursor, get_sql_insert_without_first_field(table, fieldlist, ...
def insert_object_into_db_pk_unknown(self, obj: Any, table: str, fieldlist: Sequence[str]) -> None
Inserts object into database table, with PK (first field) initially unknown (and subsequently set in the object from the database).
4.339437
3.854404
1.125839
self.ensure_db_open() pkvalue = getattr(obj, fieldlist[0]) valuelist = [] # Non-PK fields first for f in fieldlist[1:]: valuelist.append(getattr(obj, f)) # Then PK valuelist.append(pkvalue) cursor = self.db.cursor() self.db_exe...
def update_object_in_db(self, obj: Any, table: str, fieldlist: Sequence[str]) -> None
Updates an object in the database (saves it to the database, where it exists there already).
4.123711
3.91954
1.05209
if is_new_record: pkvalue = getattr(obj, fieldlist[0]) if pkvalue is None: self.insert_object_into_db_pk_unknown(obj, table, fieldlist) else: self.insert_object_into_db_pk_known(obj, table, fieldlist) else: self.upd...
def save_object_to_db(self, obj: Any, table: str, fieldlist: Sequence[str], is_new_record: bool) -> None
Saves a object to the database, inserting or updating as necessary.
2.351027
2.132476
1.102487
# MySQL: sql = ("SELECT COUNT(*) FROM information_schema.statistics" " WHERE table_name=? AND index_name=?") row = self.fetchone(sql, table, indexname) return True if row[0] >= 1 else False
def index_exists(self, table: str, indexname: str) -> bool
Does an index exist? (Specific to MySQL.)
4.146623
3.079061
1.346717
limit = "" if nchars is not None: limit = "({})".format(nchars) if indexname is None: indexname = "_idx_{}".format(field) if self.index_exists(table, indexname): return None uniquestr = "UNIQUE" if unique else "" sql = ( ...
def create_index(self, table: str, field: str, nchars: int = None, indexname: str = None, unique: bool = False) -> Optional[int]
Creates an index (default name _idx_FIELDNAME), unless it exists already.
2.132474
2.142138
0.995489
if "indexed" in fieldspec and fieldspec["indexed"]: if "index_nchar" in fieldspec: nchar = fieldspec["index_nchar"] else: nchar = None self.create_index(table, fieldspec["name"], nchar, indexname=indexname...
def create_index_from_fieldspec(self, table: str, fieldspec: FIELDSPEC_TYPE, indexname: str = None) -> None
Calls create_index based on a fieldspec, if the fieldspec has indexed = True.
3.304361
2.652168
1.245909
if indexname is None: indexname = "_idxft_{}".format(field) if self.index_exists(table, indexname): return None sql = "CREATE FULLTEXT INDEX {} ON {} ({})".format(indexname, table, field) return s...
def create_fulltext_index(self, table: str, field: str, indexname: str = None) -> Optional[int]
Creates a FULLTEXT index (default name _idxft_FIELDNAME), unless it exists already. See: http://dev.mysql.com/doc/refman/5.6/en/innodb-fulltext-index.html http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html
3.064315
2.391262
1.281463
sql = fieldspec["name"] + " " + fieldspec["sqltype"] if "notnull" in fieldspec and fieldspec["notnull"]: sql += " NOT NULL" if "autoincrement" in fieldspec and fieldspec["autoincrement"]: sql += " AUTO_INCREMENT" if "pk" in fieldspec and fieldspec["pk"]: ...
def fielddefsql_from_fieldspec(fieldspec: FIELDSPEC_TYPE) -> str
Returns SQL fragment to define a field.
1.853043
1.730336
1.070915
return ",".join([ self.fielddefsql_from_fieldspec(x) for x in fieldspeclist ])
def fielddefsql_from_fieldspeclist( self, fieldspeclist: FIELDSPECLIST_TYPE) -> str
Returns list of field-defining SQL fragments.
3.93547
3.201548
1.22924
result = [] for x in fieldspeclist: if x["name"] in fieldnames: result.append(x) return result
def fieldspec_subset_by_name( fieldspeclist: FIELDSPECLIST_TYPE, fieldnames: Container[str]) -> FIELDSPECLIST_TYPE
Returns a subset of the fieldspecs matching the fieldnames list.
3.509598
2.634959
1.331937
# information_schema is ANSI standard sql = .format(self.get_current_schema_expr()) row = self.fetchone(sql, tablename) return True if row[0] >= 1 else False
def table_exists(self, tablename: str) -> bool
Does the table exist?
11.521729
9.090417
1.267459
sql = .format(self.get_current_schema_expr()) row = self.fetchone(sql, tablename, column) return True if row[0] >= 1 else False
def column_exists(self, tablename: str, column: str) -> bool
Does the column exist?
7.945471
6.173121
1.287108
sql = "DROP TABLE IF EXISTS {}".format(tablename) log.info("Dropping table " + tablename + " (ignore any warning here)") return self.db_exec_literal(sql)
def drop_table(self, tablename: str) -> int
Drops a table. Use caution!
8.207344
6.4009
1.282217
sql = "DROP VIEW IF EXISTS {}".format(viewname) log.info("Dropping view " + viewname + " (ignore any warning here)") return self.db_exec_literal(sql)
def drop_view(self, viewname: str) -> int
Drops a view.
7.823507
6.635864
1.178973
if self.table_exists(tablename): log.info("Skipping creation of table " + tablename + " (already exists)") return None if not self.is_mysql(): dynamic = False compressed = False # http://dev.mysql.com/doc/refman/5.5/en...
def make_table(self, tablename: str, fieldspeclist: FIELDSPECLIST_TYPE, dynamic: bool = False, compressed: bool = False) -> Optional[int]
Makes a table, if it doesn't already exist.
3.34304
3.307496
1.010747
if not self.table_exists(from_table): log.info("Skipping renaming of table " + from_table + " (doesn't exist)") return None if self.table_exists(to_table): raise RuntimeError("Can't rename table {} to {}: destination " ...
def rename_table(self, from_table: str, to_table: str) -> Optional[int]
Renames a table. MySQL-specific.
2.603097
2.565099
1.014813
sql = "ALTER TABLE {} ADD COLUMN {}".format( tablename, self.fielddefsql_from_fieldspec(fieldspec)) log.info(sql) return self.db_exec_literal(sql)
def add_column(self, tablename: str, fieldspec: FIELDSPEC_TYPE) -> int
Adds a column to an existing table.
6.093739
5.060163
1.204257
sql = "ALTER TABLE {} DROP COLUMN {}".format(tablename, fieldname) log.info(sql) return self.db_exec_literal(sql)
def drop_column(self, tablename: str, fieldname: str) -> int
Drops (deletes) a column from an existing table.
5.454942
4.149183
1.314703
if not self.table_exists(tablename): return None sql = "ALTER TABLE {t} MODIFY COLUMN {field} {newdef}".format( t=tablename, field=fieldname, newdef=newdef ) log.info(sql) return self.db_exec_literal(sql)
def modify_column_if_table_exists(self, tablename: str, fieldname: str, newdef: str) -> Optional[int]
Alters a column's definition without renaming it.
2.816797
2.756225
1.021976
if not self.table_exists(tablename): return None if not self.column_exists(tablename, oldfieldname): return None sql = "ALTER TABLE {t} CHANGE COLUMN {old} {new} {newdef}".format( t=tablename, old=oldfieldname, new=newfieldname...
def change_column_if_table_exists(self, tablename: str, oldfieldname: str, newfieldname: str, newdef: str) -> Optional[int]
Renames a column and alters its definition.
2.336257
2.300446
1.015567
# 1. Make table, if it doesn't exist self.make_table(tablename, fieldspeclist, dynamic=dynamic, compressed=compressed) # 2. Are all the fields there? # ... copes fine with fieldnames coming back in Unicode and being # compared to str ...
def create_or_update_table(self, tablename: str, fieldspeclist: FIELDSPECLIST_TYPE, drop_superfluous_columns: bool = False, dynamic: bool = False, compressed: bool =...
- Make table, if it doesn't exist. - Add fields that aren't there. - Warn about superfluous fields, but don't delete them, unless ``drop_superfluous_columns == True``. - Make indexes, if requested.
3.255905
2.998147
1.085972
return self.flavour.describe_table(self, table)
def describe_table(self, table: str) -> List[List[Any]]
Returns details on a specific table.
10.585894
9.100833
1.163179
return self.flavour.fetch_column_names(self, table)
def fetch_column_names(self, table: str) -> List[str]
Returns all column names for a table.
9.589164
7.480264
1.281928
return self.flavour.get_datatype(self, table, column).upper()
def get_datatype(self, table: str, column: str) -> str
Returns database SQL datatype for a column: e.g. VARCHAR.
15.148774
7.767332
1.950319
return self.flavour.get_column_type(self, table, column).upper()
def get_column_type(self, table: str, column: str) -> str
Returns database SQL datatype for a column, e.g. VARCHAR(50).
11.510213
6.908825
1.666016
return self.flavour.get_comment(self, table, column)
def get_comment(self, table: str, column: str) -> str
Returns database SQL comment for a column.
12.329081
6.484635
1.901276
rows = self.fetchall(sql, *args) debug_query_result(rows)
def debug_query(self, sql: str, *args) -> None
Executes SQL and writes the result to the log.
9.683419
6.413217
1.509916
sql = "DELETE FROM " + self.delimit(table) return self.db_exec(sql)
def wipe_table(self, table: str) -> int
Delete all records from a table. Use caution!
8.345985
5.446234
1.532432
# *** create_or_replace_primary_key: Uses code specific to MySQL sql = .format(self.get_current_schema_expr()) # http://forums.mysql.com/read.php?10,114742,114748#msg-114748 row = self.fetchone(sql, table) has_pk_already = True if row[0] >= 1 else False drop_pk_i...
def create_or_replace_primary_key(self, table: str, fieldnames: Sequence[str]) -> int
Make a primary key, or replace it if it exists.
4.871586
4.612372
1.0562
ev = fit.eigenvalues measurement_noise = ev[-1]/(fit.n-dof) return 4*ev*measurement_noise
def noise_covariance(fit, dof=2, **kw)
Covariance taking into account the 'noise covariance' of the data. This is technically more realistic for continuously sampled data. From Faber, 1993
15.86552
15.268766
1.039083
# Not quite sure why this is sqrt but it is empirically correct ax = N.sqrt(hyp_axes) return tuple(N.arctan2(ax[-1],ax[:-1]))
def angular_errors(hyp_axes)
Minimum and maximum angular errors corresponding to 1st and 2nd axes of PCA distribution. Ordered as [minimum, maximum] angular error.
12.418313
14.723052
0.843461
method = kw.pop('method', 'noise') confidence_level = kw.pop('confidence_level', 0.95) dof = kw.pop('dof',2) nominal = fit.eigenvalues if method == 'sampling': cov = sampling_covariance(fit,**kw) elif method == 'noise': cov = noise_covariance(fit,**kw) if kw.pop('chis...
def statistical_axes(fit, **kw)
Hyperbolic error using a statistical process (either sampling or noise errors) Integrates covariance with error level and degrees of freedom for plotting confidence intervals. Degrees of freedom is set to 2, which is the relevant number of independent dimensions to planar fitting of *a pri...
7.726809
7.515819
1.028073
operations.execute("CREATE VIEW %s AS %s" % ( operation.target.name, operation.target.sqltext ))
def create_view(operations, operation)
Implements ``CREATE VIEW``. Args: operations: instance of ``alembic.operations.base.Operations`` operation: instance of :class:`.ReversibleOp` Returns: ``None``
6.226337
6.459537
0.963898
operations.execute( "CREATE FUNCTION %s %s" % ( operation.target.name, operation.target.sqltext ) )
def create_sp(operations, operation)
Implements ``CREATE FUNCTION``. Args: operations: instance of ``alembic.operations.base.Operations`` operation: instance of :class:`.ReversibleOp` Returns: ``None``
9.199746
7.242677
1.270214
version, objname = ident.split(".") module_ = operations.get_context().script.get_revision(version).module obj = getattr(module_, objname) return obj
def _get_object_from_version(cls, operations, ident)
Returns a Python object from an Alembic migration module (script). Args: operations: instance of ``alembic.operations.base.Operations`` ident: string of the format ``version.objname`` Returns: the object whose name is ``objname`` within the Alembic migration ...
9.565816
5.09095
1.878984
if not isostring: return None # if you parse() an empty string, you get today's date return dateutil.parser.parse(isostring)
def iso_string_to_python_datetime( isostring: str) -> Optional[datetime.datetime]
Takes an ISO-8601 string and returns a ``datetime``.
6.950845
6.489131
1.071152
millisec_str = str(round(value.microsecond / 1000)).zfill(3) return value.strftime("%Y-%m-%d %H:%M:%S") + "." + millisec_str
def python_utc_datetime_to_sqlite_strftime_string( value: datetime.datetime) -> str
Converts a Python datetime to a string literal compatible with SQLite, including the millisecond field.
3.16645
2.728316
1.160587
s = value.strftime("%Y-%m-%dT%H:%M:%S.%f%z") return s[:29] + ":" + s[29:]
def python_localized_datetime_to_human_iso(value: datetime.datetime) -> str
Converts a Python ``datetime`` that has a timezone to an ISO-8601 string with ``:`` between the hours and minutes of the timezone. Example: >>> import datetime >>> import pytz >>> x = datetime.datetime.now(pytz.utc) >>> python_localized_datetime_to_human_iso(x) '2017-08-...
3.999744
3.673956
1.088675
lhs, lhs_params = compiler.compile(lookup.lhs) rhs, rhs_params = lookup.process_rhs(compiler, connection) params = lhs_params + rhs_params return '{lhs} {op} {rhs}'.format( lhs=iso_string_to_sql_utcdatetime_mysql(lhs), op=operator, rhs=rhs, ), params
def isodt_lookup_mysql(lookup, compiler, connection, operator) -> Tuple[str, Any]
For a comparison "LHS *op* RHS", transforms the LHS from a column containing an ISO-8601 date/time into an SQL ``DATETIME``, for MySQL.
3.904661
3.763265
1.037573
name, path, args, kwargs = super().deconstruct() del kwargs['max_length'] return name, path, args, kwargs
def deconstruct(self) -> Tuple[str, str, List[Any], Dict[str, Any]]
Takes an instance and calculates the arguments to pass to ``__init__`` to reconstruct it.
3.287806
3.850272
0.853915
# log.debug("from_db_value: {}, {}", value, type(value)) if value is None: return value if value == '': return None return iso_string_to_python_datetime(value)
def from_db_value(self, value, expression, connection, context)
Convert database value to Python value. Called when data is loaded from the database.
4.4971
4.378282
1.027138
# https://docs.djangoproject.com/en/1.8/howto/custom-model-fields/ # log.debug("to_python: {}, {}", value, type(value)) if isinstance(value, datetime.datetime): return value if value is None: return value if value == '': return None ...
def to_python(self, value: Optional[str]) -> Optional[Any]
Called during deserialization and during form ``clean()`` calls. Must deal with an instance of the correct type; a string; or ``None`` (if the field allows ``null=True``). Should raise ``ValidationError`` if problems.
3.177385
3.142021
1.011255
log.debug("get_prep_value: {}, {}", value, type(value)) if not value: return '' # For underlying (database) string types, e.g. VARCHAR, this # function must always return a string type. # https://docs.djangoproject.com/en/1.8/howto/custom-model-fi...
def get_prep_value(self, value)
Convert Python value to database value for QUERYING. We query with UTC, so this function converts datetime values to UTC. Calls to this function are followed by calls to ``get_db_prep_value()``, which is for backend-specific conversions.
5.795462
5.437196
1.065892
log.debug("get_db_prep_value: {}, {}", value, type(value)) value = super().get_db_prep_value(value, connection, prepared) if value is None: return value # log.debug("connection.settings_dict['ENGINE']: {}", # connection.settings_dict['ENGINE']) ...
def get_db_prep_value(self, value, connection, prepared=False)
Further conversion of Python value to database value for QUERYING. This follows ``get_prep_value()``, and is for backend-specific stuff. See notes above.
3.024949
3.028564
0.998807
log.debug("get_db_prep_save: {}, {}", value, type(value)) if not value: return '' # For underlying (database) string types, e.g. VARCHAR, this # function must always return a string type. # https://docs.djangoproject.com/en/1.8/howto/custom-model-...
def get_db_prep_save(self, value, connection, prepared=False)
Convert Python value to database value for SAVING. We save with full timezone information.
6.907531
6.579238
1.049898
extensions = set() count = 0 for root, dirs, files in os.walk(path): count += 1 if count % reportevery == 0: log.debug("Walking directory {}: {!r}", count, root) for file in files: filename, ext = os.path.splitext(file) extensions.add(ext) ...
def list_file_extensions(path: str, reportevery: int = 1) -> List[str]
Returns a sorted list of every file extension found in a directory and its subdirectories. Args: path: path to scan reportevery: report directory progress after every *n* steps Returns: sorted list of every file extension found
2.429758
2.842783
0.854711
main_only_quicksetup_rootlogger(level=logging.DEBUG) parser = argparse.ArgumentParser() parser.add_argument("directory", nargs="?", default=os.getcwd()) parser.add_argument("--reportevery", default=10000) args = parser.parse_args() log.info("Extensions in directory {!r}:", args.directory) ...
def main() -> None
Command-line processor. See ``--help`` for details.
4.936552
4.871557
1.013342
assert len(packages) >= 1 require_executable(DPKG_QUERY) args = [ DPKG_QUERY, "-W", # --show # "-f='${Package} ${Status} ${Version}\n'", "-f=${Package} ${Status}\n", # --showformat ] + packages completed_process = subprocess.run(args, ...
def are_debian_packages_installed(packages: List[str]) -> Dict[str, bool]
Check which of a list of Debian packages are installed, via ``dpkg-query``. Args: packages: list of Debian package names Returns: dict: mapping from package name to boolean ("present?")
3.163974
3.03221
1.043455
present = are_debian_packages_installed(packages) missing_packages = [k for k, v in present.items() if not v] if missing_packages: missing_packages.sort() msg = ( "Debian packages are missing, as follows. Suggest:\n\n" "sudo apt install {}".format(" ".join(missin...
def require_debian_packages(packages: List[str]) -> None
Ensure specific packages are installed under Debian. Args: packages: list of packages Raises: ValueError: if any are missing
4.19559
4.33736
0.967314
try: if len(ob) != 2: log.warning("Unexpected result: {!r}", ob) raise ValueError() except ValueError: return False return True
def validate_pair(ob: Any) -> bool
Does the object have length 2?
6.264911
4.702639
1.332212
# noqa if not isinstance(env_cmd, (list, tuple)): env_cmd = [env_cmd] # construct the command that will alter the environment env_cmd = subprocess.list2cmdline(env_cmd) # create a tag so we can tell in the output when the proc is done tag = '+/!+/!+/! Finished command to set/print env ...
def windows_get_environment_from_batch_command( env_cmd: Union[str, List[str]], initial_env: Dict[str, str] = None) -> Dict[str, str]
Take a command (either a single command or list of arguments) and return the environment created after running that command. Note that the command must be a batch (``.bat``) file or ``.cmd`` file, or the changes to the environment will not be captured. If ``initial_env`` is supplied, it is used as the ...
4.665766
4.648161
1.003787
in_quote = False for c in x: if c == quote: in_quote = not in_quote elif c == target: if not in_quote: return True return False
def contains_unquoted_target(x: str, quote: str = '"', target: str = '&') -> bool
Checks if ``target`` exists in ``x`` outside quotes (as defined by ``quote``). Principal use: from :func:`contains_unquoted_ampersand_dangerous_to_windows`.
2.580317
2.574816
1.002137
wrapper = Message() wrapper.add_header('Content-Type', 'message/external-body', access_type='x-spam-deleted', expiration=time.strftime("%a, %d %b %Y %H:%M:%S %z"), size=str(len(message.get_payload()))) message.set_payload('') wra...
def gut_message(message: Message) -> Message
Remove body from a message, and wrap in a message/external-body.
5.780333
4.715597
1.22579
if message.is_multipart(): # Don't recurse in already-deleted attachments if message.get_content_type() != 'message/external-body': parts = message.get_payload() parts[:] = map(clean_message, parts) elif message_is_binary(message): # Don't gut if this is the ...
def clean_message(message: Message, topmost: bool = False) -> Message
Clean a message of all its binary parts. This guts all binary attachments, and returns the message itself for convenience.
5.847119
4.939589
1.183726
salt = bcrypt.gensalt(log_rounds) # optional parameter governs complexity hashedpw = bcrypt.hashpw(plaintextpw, salt) return hashedpw
def hash_password(plaintextpw: str, log_rounds: int = BCRYPT_DEFAULT_LOG_ROUNDS) -> str
Makes a hashed password (using a new salt) using ``bcrypt``. The hashed password includes the salt at its start, so no need to store a separate salt.
6.350303
6.017248
1.05535
# Upon CamCOPS from MySQL 5.5.34 (Ubuntu) to 5.1.71 (CentOS 6.5), the # VARCHAR was retrieved as Unicode. We needed to convert that to a str. # For Python 3 compatibility, we just str-convert everything, avoiding the # unicode keyword, which no longer exists. if storedhash is None: stor...
def is_password_valid(plaintextpw: str, storedhash: str) -> bool
Checks if a plaintext password matches a stored hash. Uses ``bcrypt``. The stored hash includes its own incorporated salt.
7.448984
7.293966
1.021253
attributes = [] # type: List[str] for attr in kw.keys(): attributes.append("%s=%s" % (attr, kw[attr])) return bool( ctypes.windll.ODBCCP32.SQLConfigDataSource(0, ODBC_ADD_SYS_DSN, driver, ...
def create_sys_dsn(driver: str, **kw) -> bool
(Windows only.) Create a system ODBC data source name (DSN). Args: driver: ODBC driver name kw: Driver attributes Returns: bool: was the DSN created?
7.256251
6.85068
1.059201