Example #1
0
    def update(self, gid, sid, did, scid, tid, clid):
        """
        This function will updates existing the schema object

         Args:
           gid: Server Group ID
           sid: Server ID
           did: Database ID
           scid: Schema ID
           tid: Table ID
           clid: Column ID
        """
        data = request.form if request.form else json.loads(request.data,
                                                            encoding='utf-8')

        # Adding parent into data dict, will be using it while creating sql
        data['schema'] = self.schema
        data['table'] = self.table

        # check type for '[]' in it
        if 'cltype' in data:
            data['cltype'], data['hasSqrBracket'] = \
                column_utils.type_formatter(data['cltype'])

        SQL, name = self.get_sql(scid, tid, clid, data)
        if not isinstance(SQL, str):
            return SQL
        SQL = SQL.strip('\n').strip(' ')
        status, res = self.conn.execute_scalar(SQL)
        if not status:
            return internal_server_error(errormsg=res)

        return jsonify(node=self.blueprint.generate_browser_node(
            clid, tid, name, icon="icon-%s" % self.node_type))
Example #2
0
    def _check_type(self, data, old_data):
        """
        Check cltype and get required data form it.
        :param data: Data.
        :param old_data: old data for check and get default values.
        """
        # check type for '[]' in it
        if 'cltype' in old_data:
            old_data['cltype'], old_data['hasSqrBracket'] = \
                column_utils.type_formatter(old_data['cltype'])

            if 'cltype' in data and data['cltype'] != old_data['cltype']:
                length, precision, typeval = \
                    self.get_length_precision(data['cltype'])

                # if new datatype does not have length or precision
                # then we cannot apply length or precision of old
                # datatype to new one.
                if not length:
                    old_data['attlen'] = -1
                if not precision:
                    old_data['attprecision'] = None
Example #3
0
    def msql(self, gid, sid, did, scid, tid, clid=None):
        """
        This function will generates modified sql for schema object

         Args:
           gid: Server Group ID
           sid: Server ID
           did: Database ID
           scid: Schema ID
           tid: Table ID
           clid: Column ID (When working with existing column)
        """
        data = dict()
        for k, v in request.args.items():
            data[k] = json.loads(v, encoding='utf-8', cls=ColParamsJSONDecoder)

        # Adding parent into data dict, will be using it while creating sql
        data['schema'] = self.schema
        data['table'] = self.table

        # check type for '[]' in it
        if 'cltype' in data:
            data['cltype'], data['hasSqrBracket'] = \
                column_utils.type_formatter(data['cltype'])

        try:
            SQL, name = self.get_sql(scid, tid, clid, data)
            if not isinstance(SQL, str):
                return SQL

            SQL = SQL.strip('\n').strip(' ')
            if SQL == '':
                SQL = "--modified SQL"
            return make_json_response(
                data=SQL,
                status=200
            )
        except Exception as e:
            return internal_server_error(errormsg=str(e))
Example #4
0
    def sql(self, gid, sid, did, scid, tid, clid):
        """
        This function will generates reverse engineered sql for schema object

         Args:
           gid: Server Group ID
           sid: Server ID
           did: Database ID
           scid: Schema ID
           tid: Table ID
           clid: Column ID
        """
        try:
            SQL = render_template(
                "/".join([self.template_path, 'properties.sql']),
                tid=tid,
                clid=clid,
                show_sys_objects=self.blueprint.show_system_objects)

            status, res = self.conn.execute_dict(SQL)
            if not status:
                return internal_server_error(errormsg=res)
            if len(res['rows']) == 0:
                return gone(
                    gettext("Could not find the column on the server."))

            data = dict(res['rows'][0])
            # We do not want to display length as -1 in create query
            if 'attlen' in data and data['attlen'] == -1:
                data['attlen'] = ''
            # Adding parent into data dict, will be using it while creating sql
            data['schema'] = self.schema
            data['table'] = self.table
            # check type for '[]' in it
            if 'cltype' in data:
                data['cltype'], data['hasSqrBracket'] = \
                    column_utils.type_formatter(data['cltype'])

            # We will add table & schema as well
            # Passing edit_types_list param so that it does not fetch
            # edit types. It is not required here.
            data = column_utils.column_formatter(self.conn, tid, clid, data,
                                                 [])

            SQL, name = self.get_sql(scid, tid, None, data, is_sql=True)
            if not isinstance(SQL, str):
                return SQL

            sql_header = u"-- Column: {0}\n\n-- ".format(
                self.qtIdent(self.conn, data['schema'], data['table'],
                             data['name']))

            sql_header += render_template("/".join(
                [self.template_path, 'delete.sql']),
                                          data=data,
                                          conn=self.conn)
            SQL = sql_header + '\n\n' + SQL

            return ajax_response(response=SQL.strip('\n'))

        except Exception as e:
            return internal_server_error(errormsg=str(e))
Example #5
0
    def get_sql(self, scid, tid, clid, data, is_sql=False):
        """
        This function will genrate sql from model data
        """
        data = column_utils.convert_length_precision_to_string(data)

        if clid is not None:
            SQL = render_template(
                "/".join([self.template_path, 'properties.sql']),
                tid=tid,
                clid=clid,
                show_sys_objects=self.blueprint.show_system_objects)

            status, res = self.conn.execute_dict(SQL)
            if not status:
                return internal_server_error(errormsg=res)
            if len(res['rows']) == 0:
                return gone(
                    gettext("Could not find the column on the server."))
            old_data = dict(res['rows'][0])
            # We will add table & schema as well
            old_data = column_utils.column_formatter(self.conn, tid, clid,
                                                     old_data)

            # check type for '[]' in it
            if 'cltype' in old_data:
                old_data['cltype'], old_data['hasSqrBracket'] = \
                    column_utils.type_formatter(old_data['cltype'])

                if 'cltype' in data and data['cltype'] != old_data['cltype']:
                    length, precision, typeval = \
                        self.get_length_precision(data['cltype'])

                    # if new datatype does not have length or precision
                    # then we cannot apply length or precision of old
                    # datatype to new one.
                    if not length:
                        old_data['attlen'] = -1
                    if not precision:
                        old_data['attprecision'] = None

            # If name is not present in data then
            # we will fetch it from old data, we also need schema & table name
            if 'name' not in data:
                data['name'] = old_data['name']

            # Convert acl coming from client in db parsing format
            key = 'attacl'
            if key in data and data[key] is not None:
                if 'added' in data[key]:
                    data[key]['added'] = parse_priv_to_db(
                        data[key]['added'], self.acl)
                if 'changed' in data[key]:
                    data[key]['changed'] = parse_priv_to_db(
                        data[key]['changed'], self.acl)
                if 'deleted' in data[key]:
                    data[key]['deleted'] = parse_priv_to_db(
                        data[key]['deleted'], self.acl)

            SQL = render_template("/".join([self.template_path, 'update.sql']),
                                  data=data,
                                  o_data=old_data,
                                  conn=self.conn)
        else:
            required_args = ['name', 'cltype']

            for arg in required_args:
                if arg not in data:
                    return gettext('-- definition incomplete')

            # We will convert privileges coming from client required
            # in server side format
            if 'attacl' in data:
                data['attacl'] = parse_priv_to_db(data['attacl'], self.acl)
            # If the request for new object which do not have did
            SQL = render_template("/".join([self.template_path, 'create.sql']),
                                  data=data,
                                  conn=self.conn,
                                  is_sql=is_sql)
        return SQL, data['name'] if 'name' in data else old_data['name']
Example #6
0
    def create(self, gid, sid, did, scid, tid):
        """
        This function will creates new the schema object

         Args:
           gid: Server Group ID
           sid: Server ID
           did: Database ID
           scid: Schema ID
           tid: Table ID
        """
        data = request.form if request.form else json.loads(request.data,
                                                            encoding='utf-8')

        for k, v in data.items():
            # comments should be taken as is because if user enters a
            # json comment it is parsed by loads which should not happen
            if k in ('description', ):
                data[k] = v
            else:
                data[k] = json.loads(v,
                                     encoding='utf-8',
                                     cls=ColParamsJSONDecoder)

        required_args = {'name': 'Name', 'cltype': 'Type'}

        for arg in required_args:
            if arg not in data:
                return make_json_response(
                    status=410,
                    success=0,
                    errormsg=gettext(
                        "Could not find the required parameter ({}).").format(
                            required_args[arg]))

        # Parse privilege data coming from client according to database format
        if 'attacl' in data:
            data['attacl'] = parse_priv_to_db(data['attacl'], self.acl)

        # Adding parent into data dict, will be using it while creating sql
        data['schema'] = self.schema
        data['table'] = self.table
        if len(data['table']) == 0:
            return gone(gettext("The specified table could not be found."))

        # check type for '[]' in it
        data['cltype'], data['hasSqrBracket'] = \
            column_utils.type_formatter(data['cltype'])
        data = column_utils.convert_length_precision_to_string(data)

        SQL = render_template("/".join([self.template_path, 'create.sql']),
                              data=data,
                              conn=self.conn)
        status, res = self.conn.execute_scalar(SQL)
        if not status:
            return internal_server_error(errormsg=res)

        # we need oid to to add object in tree at browser
        SQL = render_template("/".join(
            [self.template_path, 'get_position.sql']),
                              tid=tid,
                              data=data)
        status, clid = self.conn.execute_scalar(SQL)
        if not status:
            return internal_server_error(errormsg=tid)

        return jsonify(node=self.blueprint.generate_browser_node(
            clid, tid, data['name'], icon="icon-column"))