This command includes Django DB Session
197723
def shell_django(session: DjangoSession, backend: ShellBackend):
    
    namespace = {
        'session': session
    }
    namespace.update(backend.get_namespace())
    embed(user_ns=namespace, header=backend.header)
102907
def runSql(self, migrationName, version):
        
        sys.stdout.write("Running migration %s to version %s: ..."%(migrationName, version))
        sqlPath = os.path.join(self.migrationDirectory, migrationName)
        sql = open(sqlPath, "r").read()
        try:
            if self.session.is_active:
                print "session is active"
                self.session.commit()
            self.session.begin()
            executeBatch(self.session, sql)
            self.session.add(models.Migration(version, migrationName))
        except:
            print "\n"
            self.session.rollback()
            raise
        else:
            self.session.commit()
        sys.stdout.write("\r")
        sys.stdout.flush()
        sys.stdout.write("Running migration %s to version %s: SUCCESS!\n"%(migrationName, version))
139159
def query(self, command):
        
        if self.closed:
            Log.error("database is closed")

        signal = _allocate_lock()
        signal.acquire()
        result = Data()
        trace = extract_stack(1) if self.get_trace else None

        if self.get_trace:
            current_thread = Thread.current()
            with self.locker:
                for t in self.available_transactions:
                    if t.thread is current_thread:
                        Log.error(DOUBLE_TRANSACTION_ERROR)

        self.queue.add(CommandItem(command, result, signal, trace, None))
        signal.acquire()

        if result.exception:
            Log.error("Problem with Sqlite call", cause=result.exception)
        return result
995413
def action_rm(self):
        

        name = self.args['<name>']

        if self.args['all']:
            # delete all

            if ask_yes_no('Really delete ALL shortcuts?', default='no'):
                self.db_exec(''' DELETE FROM shortcuts ''')
                print_msg("All shortcuts deleted.")
            else:
                print_err("Aborted.")
                return

        else:
            # delete one

            # find by name
            self.db_exec('''
                SELECT id FROM shortcuts WHERE name=?
                ''', (name,))

            q = self.db_fetch_one()
            id = q[0]

            # delete if exists
            if q is None:
                print_err('Shortcut "%s" does not exist!' % name)

            else:
                self.db_exec('''
                    DELETE FROM shortcuts WHERE id=?
                    ''', (id,))

                # show OK message
                print_msg('Shortcut "%s" deleted.' % name)
1240798
def handle(self, *args, **options):
        

        def get_user(username):
            try:
                return User.objects.get(username=username)
            except ObjectDoesNotExist as e:
                raise CommandError("This user doesn't exist in the database")

        def get_fields_permissions(user):
            try:
                return UserFieldPermissions.objects.get(user=user)
            except ObjectDoesNotExist as e:
                raise CommandError("This user doesn't have fields permissions")



        if len(args) !=1:
            raise CommandError("Specifies a user")
        else:
            try:
                self.stdout.ending = None
                user = get_user(args[0])
                fields_permissions  = get_fields_permissions(user)
                permissions = fields_permissions.permissions.all()

                jsoneatthat = {'username': user.username, 
                    'fields_permissions' : [ {'app_label': permission.content_type.app_label, 'model' : permission.content_type.model, 'name': permission.name } for permission in permissions]}

                self.stdout.write(json.dumps(jsoneatthat))

            except:
                raise
701263
def data_from_query(self, cmd):
        
        res  = None
        ckey = "%s /%s" % (self.command, cmd)

        if not isinstance(self._query_params, dict):
            self._query_params = {}

        if ckey in _NCMD:
            self._cmd = _NCMD[ckey]
        else:
            for key in sorted(_RCMD, key=len, reverse=True):
                if not key.startswith("%s " % self.command):
                    continue

                m = _RCMD[key].name.match(cmd)
                if m:
                    self._cmd = _RCMD[key]
                    self._query_params.update(m.groupdict())
                    break

        try:
            if not self._cmd:
                raise self.req_error(404)

            if not self._cmd.to_log:
                self._to_log = False

            if self._cmd.to_auth:
                self.authenticate(self._cmd.auth_users)

            if self._cmd.static:
                if self._cmd.handler:
                    res = self._cmd.handler(self)

                return self.static_file(cmd, res)

            res = self._cmd.handler(self)

            if not isinstance(res, HttpResponse):
                return self.response_dumps(res)

            return res
        finally:
            self._query_params = {}
707279
def main(arguments=None):
    
    # setup the command-line util settings
    su = tools(
        arguments=arguments,
        docString=__doc__,
        logLevel="DEBUG",
        options_first=False,
        projectName="HMpTy"
    )
    arguments, settings, log, dbConn = su.setup()

    # unpack remaining cl arguments using `exec` to setup the variable names
    # automatically
    for arg, val in arguments.iteritems():
        if arg[0] == "-":
            varname = arg.replace("-", "") + "Flag"
        else:
            varname = arg.replace("<", "").replace(">", "")
        if isinstance(val, str) or isinstance(val, unicode):
            exec(varname + " = '%s'" % (val,))
        else:
            exec(varname + " = %s" % (val,))
        if arg == "--dbConn":
            dbConn = val
        log.debug('%s = %s' % (varname, val,))

    ## START LOGGING ##
    startTime = times.get_now_sql_datetime()
    log.info(
        '--- STARTING TO RUN THE cl_utils.py AT %s' %
        (startTime,))

    if hostFlag:
        dbSettings = {
            'host': hostFlag,
            'user': userFlag,
            'password': passwdFlag,
            'db': dbNameFlag
        }
    elif settings:
        dbSettings = settings["database settings"]

    # CALL FUNCTIONS/OBJECTS
    if index:
        add_htm_ids_to_mysql_database_table(
            raColName=raCol,
            declColName=decCol,
            tableName=tableName,
            dbConn=dbConn,
            log=log,
            primaryIdColumnName=primaryIdCol,
            reindex=forceFlag,
            dbSettings=dbSettings
        )

    if search:
        cs = conesearch(
            log=log,
            dbConn=dbConn,
            tableName=tableName,
            columns=False,
            ra=ra,
            dec=dec,
            radiusArcsec=float(radius),
            separations=True,
            distinct=False,
            sqlWhere=False
        )
        matchIndies, matches = cs.search()
        if not renderFlag:
            print matches.table()
        elif renderFlag == "json":
            print matches.json()
        elif renderFlag == "csv":
            print matches.csv()
        elif renderFlag == "yaml":
            print matches.yaml()
        elif renderFlag == "md":
            print matches.markdown()
        elif renderFlag == "table":
            print matches.markdown()
        elif renderFlag == "mysql":
            print matches.mysql(tableName=resultsTable)

    if level:
        from HMpTy import HTM
        mesh = HTM(
            depth=int(level),
            log=log
        )

        htmids = mesh.lookup_id(ra, dec)
        print htmids[0]

    if "dbConn" in locals() and dbConn:
        dbConn.commit()
        dbConn.close()
    ## FINISH LOGGING ##
    endTime = times.get_now_sql_datetime()
    runningTime = times.calculate_time_difference(startTime, endTime)
    log.info('-- FINISHED ATTEMPT TO RUN THE cl_utils.py AT %s (RUNTIME: %s) --' %
             (endTime, runningTime, ))

    return
126023
def mock_django_connection(disabled_features=None):
    
    db = connections.databases['default']
    db['PASSWORD'] = '****'
    db['USER'] = '**Database disabled for unit tests**'
    ConnectionHandler.__getitem__ = MagicMock(name='mock_connection')
    # noinspection PyUnresolvedReferences
    mock_connection = ConnectionHandler.__getitem__.return_value
    if disabled_features:
        for feature in disabled_features:
            setattr(mock_connection.features, feature, False)
    mock_ops = mock_connection.ops

    # noinspection PyUnusedLocal
    def compiler(queryset, connection, using, **kwargs):
        result = MagicMock(name='mock_connection.ops.compiler()')
        # noinspection PyProtectedMember
        result.execute_sql.side_effect = NotSupportedError(
            "Mock database tried to execute SQL for {} model.".format(
                queryset.model._meta.object_name))
        result.has_results.side_effect = result.execute_sql.side_effect
        return result

    mock_ops.compiler.return_value.side_effect = compiler
    mock_ops.integer_field_range.return_value = (-sys.maxsize - 1, sys.maxsize)
    mock_ops.max_name_length.return_value = sys.maxsize

    Model.refresh_from_db = Mock()
556094
private static function run_sql( $sql_cmd, $assoc_args = array(), $add_database = false ) {
		$default_assoc_args = array(
			'host' => self::$db_settings['dbhost'],
			'user' => self::$db_settings['dbuser'],
			'pass' => self::$db_settings['dbpass'],
		);
		if ( $add_database ) {
			$sql_cmd .= ' ' . escapeshellarg( self::$db_settings['dbname'] );
		}
		$start_time = microtime( true );
		Utils\run_mysql_command( $sql_cmd, array_merge( $assoc_args, $default_assoc_args ) );
		if ( self::$log_run_times ) {
			self::log_proc_method_run_time( 'run_sql ' . $sql_cmd, $start_time );
		}
	}
768410
def cleardb(force=False):
    """"""

    # Drop database, if it exists
    if db_exists():
        try:
            dropdb(force)
        except subprocess.CalledProcessError as error:
            output = error.output.decode("utf-8")
            if "is being accessed by other users" in output:
                raise ValueError(
                    "{}\n"
                    "To forcibly terminate other sessions, run "
                    "this command again with --force".format(output)
                )
            else:
                raise
    else:
        logger.info(
            "Database %s does not currently exist; no need to drop", repr(DB["NAME"])
        )
    createdb()
1022107
def db_exec(self, query, args=None):
        
        if args is None:
            self.db_query(query)
        else:
            self.db_query(query, args)

        self.db.commit()
833406
def purge_objects(self, request):
        

        def truncate_table(model):
            if settings.TRUNCATE_TABLE_SQL_STATEMENT:
                from django.db import connection
                sql = settings.TRUNCATE_TABLE_SQL_STATEMENT.format(db_table=model._meta.db_table)
                cursor = connection.cursor()
                cursor.execute(sql)
            else:
                model.objects.all().delete()

        modeladmin = self
        opts = modeladmin.model._meta

        # Check that the user has delete permission for the actual model
        if not request.user.is_superuser:
           raise PermissionDenied
        if not modeladmin.has_delete_permission(request):
            raise PermissionDenied

        # If the user has already confirmed or cancelled the deletion,
        # (eventually) do the deletion and return to the change list view again.
        if request.method == 'POST':
            if 'btn-confirm' in request.POST:
                try:
                    n = modeladmin.model.objects.count()
                    truncate_table(modeladmin.model)
                    modeladmin.message_user(request, _("Successfully removed %d rows" % n), messages.SUCCESS);
                except Exception as e:
                    modeladmin.message_user(request, _(u'ERROR') + ': %r' % e, messages.ERROR)
            else:
                modeladmin.message_user(request, _("Action cancelled by user"), messages.SUCCESS);
            return HttpResponseRedirect(reverse('admin:%s_%s_changelist' % (opts.app_label, opts.model_name)))

        context = {
            "title": _("Purge all %s ... are you sure?") % opts.verbose_name_plural,
            "opts": opts,
            "app_label": opts.app_label,
        }

        # Display the confirmation page
        return render(
            request,
            'admin/easyaudit/purge_confirmation.html',
            context
        )
1350948
def shell_sqlalchemy(session: SqlalchemySession, backend: ShellBackend):
    
    namespace = {
        'session': session
    }
    namespace.update(backend.get_namespace())
    embed(user_ns=namespace, header=backend.header)
235401
def delete(self, db_session=None):
        
        db_session = get_db_session(db_session, self)
        db_session.delete(self)
903288
def do_session(self, args):
        """"""
        filename = 'Not specified' if self.__session.filename is None \
            else self.__session.filename

        print('{0: <30}: {1}'.format('Filename', filename))
1009597
def main() -> None:
    
    main_only_quicksetup_rootlogger()
    wdcd_suffix = "_with_drop_create_database"
    timeformat = "%Y%m%dT%H%M%S"
    parser = argparse.ArgumentParser(
        description="""
        Back up a specific MySQL database. The resulting filename has the
        format '<DATABASENAME>_<DATETIME><SUFFIX>.sql', where <DATETIME> is of
        the ISO-8601 format {timeformat!r} and <SUFFIX> is either blank or
        {suffix!r}. A typical filename is therefore 'mydb_20190415T205524.sql'.
        """.format(timeformat=timeformat, suffix=wdcd_suffix),
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument(
        "databases", nargs="+",
        help="Database(s) to back up")
    parser.add_argument(
        "--max_allowed_packet", default="1GB",
        help="Maximum size of buffer")
    parser.add_argument(
        "--mysqldump", default="mysqldump",
        help="mysqldump executable")
    parser.add_argument(
        "--username", default="root",
        help="MySQL user")
    parser.add_argument(
        "--password",
        help="MySQL password (AVOID THIS OPTION IF POSSIBLE; VERY INSECURE; "
             "VISIBLE TO OTHER PROCESSES; if you don't use it, you'll be "
             "prompted for the password)")
    parser.add_argument(
        "--with_drop_create_database", action="store_true",
        help="Include DROP DATABASE and CREATE DATABASE commands, and append "
             "a suffix to the output filename as above")
    parser.add_argument(
        "--output_dir", type=str,
        help="Output directory (if not specified, current directory will be "
             "used)")
    parser.add_argument(
        "--verbose", action="store_true",
        help="Verbose output")
    args = parser.parse_args()

    output_dir = args.output_dir or os.getcwd()
    os.chdir(output_dir)

    password = args.password or getpass.getpass(
        prompt="MySQL password for user {}: ".format(args.username))

    output_files = []  # type: List[str]
    if args.with_drop_create_database:
        log.info("Note that the DROP DATABASE commands will look like they're "
                 "commented out, but they're not: "
                 "https://dba.stackexchange.com/questions/59294/")
        suffix = wdcd_suffix
    else:
        suffix = ""
    for db in args.databases:
        now = datetime.datetime.now().strftime(timeformat)
        outfilename = "{db}_{now}{suffix}.sql".format(db=db, now=now,
                                                      suffix=suffix)
        display_args = cmdargs(
            mysqldump=args.mysqldump,
            username=args.username,
            password=password,
            database=db,
            verbose=args.verbose,
            with_drop_create_database=args.with_drop_create_database,
            max_allowed_packet=args.max_allowed_packet,
            hide_password=True
        )
        actual_args = cmdargs(
            mysqldump=args.mysqldump,
            username=args.username,
            password=password,
            database=db,
            verbose=args.verbose,
            with_drop_create_database=args.with_drop_create_database,
            max_allowed_packet=args.max_allowed_packet,
            hide_password=False
        )
        log.info("Executing: " + repr(display_args))
        log.info("Output file: " + repr(outfilename))
        try:
            with open(outfilename, "w") as f:
                subprocess.check_call(actual_args, stdout=f)
        except subprocess.CalledProcessError:
            os.remove(outfilename)
            log.critical("Failed!")
            sys.exit(1)
        output_files.append(outfilename)
    log.info("Done. See:\n" + "\n".join("    " + x for x in output_files))
    if args.with_drop_create_database:
        log.info("To restore: mysql -u USER -p < BACKUP.sql")
    else:
        log.info("To restore: mysql -u USER -p DATABASE < BACKUP.sql")
889378
def create_database_session(engine):
    """"""

    try:
        Session = sessionmaker(bind=engine)
        return Session()
    except OperationalError as e:
        raise DatabaseError(error=e.orig.args[1], code=e.orig.args[0])