Data dump from select query
550012
private function SetDebugDump($offset = null)
    {
        if (!$this->query_result or !$this->debug_on) {
            return;
        }

        $report = '<b>DATA:</b><br />
        <table border="0" cellpadding="5" cellspacing="1" style="background-color:#555555">
        <tr style="background-color:#eeeeee"><td nowrap valign="bottom"><font color="555599" size="2"><b>(row)</b></font></td>';

        if (is_numeric($offset)) {
            $z = 2;
            $report.= '<td nowrap align="left" valign="top"><font size="1" color="555599">'.$this->col_info[$offset]->type.' '.$this->col_info[$offset]->size.'</font><br><font size=2><b>'.$this->col_info[$offset]->name.'</b></font></td>';
        } else {
            $z = count($this->col_info);
            for ($i=0; $i < $z; $i++) {
                $report.= '<td nowrap align="left" valign="top"><font size="1" color="555599">'.$this->col_info[$i]->type.' '.$this->col_info[$i]->size.'</font><br><font size=2><b>'.$this->col_info[$i]->name.'</b></font></td>';
            }
        }

        $report .= "</tr>";

        if (is_array($this->result) and count($this->result) > 0) {
            $i=0;
            foreach ($this->result as $one_row) {
                $i++;
                $report.= '<tr bgcolor="ffffff"><td style="background-color:#eeeeee" nowrap align="middle"><font size="2" color="555599">'.$i.'</font></td>';

                if (is_array($one_row)) {
                    foreach ($one_row as $item) {
                        $report.= '<td nowrap style="background-color:#ffffff"><font size="2">'.htmlspecialchars($item).'</font></td>';
                    }
                } else {
                    $report.= '<td nowrap style="background-color:#ffffff"><font size="2">'.htmlspecialchars($one_row).'</font></td>';
                }


                $report.= "</tr>";
            }
        } else {
            $report.= '<tr bgcolor="ffffff"><td colspan="'.($z+1).'"><font size=2>No Results</font></td></tr>';
        }

        $report.= "</table>";
        $this->printOutStr .= $report;
    }
1006863
public function get_select_sql( $tables, $where = null, $fields = null, $limit = null, $offset = null, $order_by = null, $group_by = null, $for_update = false ) {
		$as = null;
		if ( is_array( $tables ) ) {
			if ( empty( $tables ) ) {
				return false;
			}
			$table = array_shift( $tables );
			$join  = $tables;
			if ( count( $table ) > 1 ) {
				$as = $table[1];
			}
			$table = $table[0];
		} else {
			$table = $tables;
			$join  = null;
		}
		if ( ! isset( $this->table_defines[ $table ] ) ) {
			return false;
		}

		$columns = $this->table_defines[ $table ]['columns'];

		! is_array( $where ) and $where = [];
		if ( $this->is_logical( $this->table_defines[ $table ] ) ) {
			$where['deleted_at'] = null;
		}

		list( $conditions, $values ) = $this->build_conditions( $where, $columns );
		$table  = $this->get_table( $table );
		$fields = $this->build_fields( $fields, $columns );
		$sql    = "SELECT {$fields} FROM $table";
		if ( isset( $as ) ) {
			$sql .= " AS $as";
		}
		$sql .= $this->build_join( $join );
		if ( ! empty( $conditions ) ) {
			$sql .= " WHERE $conditions";
		}
		$sql .= $this->build_group_by( $group_by, $columns );
		$sql .= $this->build_order_by( $order_by, $columns );
		$sql .= $this->build_limit( $limit, $offset );
		if ( $for_update ) {
			$sql .= ' FOR UPDATE';
		}

		return $this->prepare( $sql, $values );
	}
87475
def dump(self, fields=None, exclude=None):
        
        exclude = exclude or []
        d = {}
        if fields and self._primary_field not in fields:
            fields = list(fields)
            fields.append(self._primary_field)
        for k, v in self.properties.items():
            if ((not fields) or (k in fields)) and (not exclude or (k not in exclude)):
                if not isinstance(v, ManyToMany):
                    t = v.get_value_for_datastore(self)
                    if t is Lazy:
                        self.refresh()
                        t = v.get_value_for_datastore(self)
                    if isinstance(t, Model):
                        t = t._key
                    d[k] = v.to_str(t)
                else:
                    if fields:
                       d[k] = ','.join([str(x) for x in getattr(self, v._lazy_value(), [])])
        if self._primary_field and d and self._primary_field not in d:
            d[self._primary_field] = str(self._key)
        return d
641104
def doSQLInsert(sqlString)
   
      sql = sqlString.dup
      dbname = ""
      state = nil
      fieldName = ""
      fieldValue = ""
      fieldNames = []
      fieldValues = []
      index = 0
      
      clearFieldValuePairList
      
      sql.gsub!("("," ")
      sql.gsub!(")"," ")

      sql.split(' ').each{ |token|
         case token
            when "INSERT", "INTO" 
               state = "getTable"
               next
            when "VALUES" 
               state = "getFieldValue"
               next
         end
         if state == "getTable"
            dbname = token.strip
            state =   "getFieldName"
         elsif state  == "getFieldName" 
            fieldName = token.dup
            fieldName.gsub!("],","")
            fieldName.gsub!('[','')
            fieldName.gsub!(']','')
            fieldName.gsub!(',','')
            fieldNames << fieldName
         elsif state  == "getFieldValue" 
            test = token.dup
            if test[-1,1] == "'" or test[-2,2] == "',"
               fieldValue << token.dup
               if fieldValue[-2,2] == "',"
                  fieldValue.gsub!("',",'')
               end
               fieldValue.gsub!('\'','')
               if fieldValue.length > 0 and fieldNames[index] 
                  addFieldValuePair(fieldNames[index],nil,nil,fieldValue)
                  fieldName = ""
                  fieldValue = ""
               end
               index += 1
            elsif token == ","
               addFieldValuePair(fieldNames[index],nil,nil,"")
               fieldName = ""
               fieldValue = ""
               index += 1
            else
               fieldValue << "#{token.dup} "
            end
         end
      }
      
      if dbname and @dbid.nil?
         dbid = findDBByname( dbname )
      else
         dbid = lookupChdbid( dbname )
      end
      dbid ||= @dbid

      recordid = nil
      if dbid
         recordid,updateid = addRecord(dbid,@fvlist)
      end   
      recordid
      
   end
1085671
public static function dump($where = [], $columns = [])
    {
        $columns = (empty($columns))
            ? static::COLUMNS
            : array_values(self::getTypedColumns($columns));

        $database = self::getDatabase();
        return $database->select(static::TABLE, $columns, $where);
    }
813210
public function dump()
	{
		$tables   = App::get('db')->getTableList();
		$prefix   = App::get('db')->getPrefix();
		$excludes = [];
		$now      = new Date;
		$exclude  = '';
		$includes = (array)$this->arguments->getOpt('include-table', []);

		if (!$this->arguments->getOpt('all-tables'))
		{
			$this->output->addLine('Dumping database with all prefixed tables included');
			foreach ($tables as $table)
			{
				if (strpos($table, $prefix) !== 0 && !in_array(str_replace('#__', $prefix, $table), $includes))
				{
					$excludes[] = Config::get('db') . '.' . $table;
				}
				elseif (in_array(str_replace('#__', $prefix, $table), $includes))
				{
					$this->output->addLine('Also including `' . $table . '`');
				}
			}

			// Build exclude list string
			$exclude = '--ignore-table=' . implode(' --ignore-table=', $excludes);
		}
		else
		{
			$this->output->addLine('Dumping database with all tables included');
		}

		// Add save location option

		$home     = getenv('HOME');
		$hostname = gethostname();
		$filename = tempnam($home, "{$hostname}.mysql.dump." . $now->format('Y.m.d') . ".sql.");

		// Build command
		$cmd = "mysqldump -u " . Config::get('user') . " -p'" . Config::get('password') . "' " . Config::get('db') . " --routines {$exclude} > {$filename}";

		exec($cmd);

		// Print out location of file
		$this->output->addLine('File saved to: ' . $filename, 'success');
	}
438161
def select_from_table(fields, table, query):
    

    select_data = client.execute(f"SELECT {fields} FROM {table} {query}", with_column_types=True)

    keys = [i[0] for i in select_data[1]]

    result = []

    for i in range(len(select_data[0])):
        tmp = []

        for j in range(len(keys)):
            tmp.append(str(select_data[0][i][j]))

        result.append(dict(list(zip(keys, tmp))))

    # for i in range(len(select_data[0])):
    #     result.append(dict(list(zip(keys, select_data[0][i]))))

    return result
954516
def _get_sql(filename):
    """"""
    with open(os.path.join(SQL_DIR, filename), 'r') as f:
        return f.read()
428339
def dumps(self):
        """"""

        _s = super().dumps()

        # Tabu tables support a unusual syntax:
        # \begin{tabu} spread 0pt {<col format...>}
        #
        # Since this syntax isn't common, it doesn't make
        # sense to support it in the baseclass (e.g., Environment)
        # rather, here we fix the LaTeX string post-hoc
        if self._preamble:
            if _s.startswith(r"\begin{longtabu}"):
                _s = _s[:16] + self._preamble + _s[16:]
            elif _s.startswith(r"\begin{tabu}"):
                _s = _s[:12] + self._preamble + _s[12:]
            else:
                raise TableError("Can't apply preamble to Tabu table "
                                 "(unexpected initial command sequence)")

        return _s
877248
def dump_table(data: List[dict], fieldnames: Sequence[str]) -> str:
    

    def min3(num: int) -> int:
        return 3 if num < 4 else num

    width_by_col: Dict[str, int] = {
        f: min3(max([string_width(str(d.get(f))) for d in data] + [string_width(f)])) for f in fieldnames
    }

    def fill_spaces(word: str, width: int, center=False):
        """ aaa, 4 => ' aaa  ' """
        to_fills: int = width - string_width(word)
        return f" {' ' * floor(to_fills / 2)}{word}{' ' * ceil(to_fills / 2)} " if center \
            else f" {word}{' ' * to_fills} "

    def to_record(r: dict) -> str:
        return f"|{'|'.join([fill_spaces(str(r.get(f)), width_by_col.get(f)) for f in fieldnames])}|"

    return f"""
|{'|'.join([fill_spaces(x, width_by_col.get(x), center=True) for x in fieldnames])}|
|{'|'.join([fill_spaces(width_by_col.get(x) * "-", width_by_col.get(x)) for x in fieldnames])}|
{os.linesep.join([to_record(x) for x in data])}
""".lstrip()
29250
def dump(self):
        """"""
        data = dict(
            # Sessions
            sessions_active=self.sess_active,

            # Connections
            connections_active=self.conn_active,
            connections_ps=self.conn_ps.last_average,

            # Packets
            packets_sent_ps=self.pack_sent_ps.last_average,
            packets_recv_ps=self.pack_recv_ps.last_average
            )

        for k, v in self.sess_transports.items():
            data['transp_' + k] = v

        return data
615228
def full_datatype_to_mysql(d: str) -> str:
    """"""
    d = d.upper()
    (s, length) = split_long_sqltype(d)
    if d in ["VARCHAR(MAX)", "NVARCHAR(MAX)"]:
        # http://wiki.ispirer.com/sqlways/mysql/data-types/longtext
        return "LONGTEXT"
    elif d in ["VARBINARY(MAX)"] or s in ["IMAGE"]:
        # http://wiki.ispirer.com/sqlways/mysql/data-types/varbinary
        return "LONGBLOB"
    else:
        return d
361499
function Report_dump() {
  var maxKeyLen = this.maxKeyLen
  console.log("-------------------------------------------------------")
  this.lines.forEach(function(line){
    var val = line.val
    if (typeof val == "number") val = numberWithCommas(val)
    console.log(left(line.key + ":", maxKeyLen+1) + " " + val)
  })
}
1095111
function SQL(strs) {
  for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
    args[_key - 1] = arguments[_key];
  }

  var values = [];
  var text = strs.reduce(function (prev, curr, i) {
    var arg = args[i - 1];
    if (arg instanceof InsertValue) {
      return prev + arg.value + curr;
    } else {
      values.push(arg);
      return prev + '$' + values.length + curr;
    }
  });

  return {
    text: text,
    values: values
  };
}
44480
def get_dump(self):
  """"""
  res = []
  for section in self.sections():
   sec = []
   for option in self.options(section):
    sec.append([option, self.get(section, option)])
   res.append([section, sec])
  return res
320081
def data(self):
        """"""
        order_by_choices = []
        # self.column_names return sorted column_names
        for s in self.column_names:
            s = str(s or '')
            order_by_choices.append((json.dumps([s, True]), s + ' [asc]'))
            order_by_choices.append((json.dumps([s, False]), s + ' [desc]'))

        verbose_map = {'__timestamp': 'Time'}
        verbose_map.update({
            o.metric_name: o.verbose_name or o.metric_name
            for o in self.metrics
        })
        verbose_map.update({
            o.column_name: o.verbose_name or o.column_name
            for o in self.columns
        })
        return {
            # simple fields
            'id': self.id,
            'column_formats': self.column_formats,
            'description': self.description,
            'database': self.database.data,  # pylint: disable=no-member
            'default_endpoint': self.default_endpoint,
            'filter_select': self.filter_select_enabled,  # TODO deprecate
            'filter_select_enabled': self.filter_select_enabled,
            'name': self.name,
            'datasource_name': self.datasource_name,
            'type': self.type,
            'schema': self.schema,
            'offset': self.offset,
            'cache_timeout': self.cache_timeout,
            'params': self.params,
            'perm': self.perm,
            'edit_url': self.url,

            # sqla-specific
            'sql': self.sql,

            # one to many
            'columns': [o.data for o in self.columns],
            'metrics': [o.data for o in self.metrics],

            # TODO deprecate, move logic to JS
            'order_by_choices': order_by_choices,
            'owners': [owner.id for owner in self.owners],
            'verbose_map': verbose_map,
            'select_star': self.select_star,
        }
1051330
private static void dumpTable(Connection jdbcConn, String tableName, String script, File storageDir,
      ZipObjectWriter contentWriter, ZipObjectWriter contentLenWriter) throws IOException, SQLException
   {
      SecurityManager security = System.getSecurityManager();
      if (security != null)
      {
         security.checkPermission(JCRRuntimePermissions.MANAGE_REPOSITORY_PERMISSION);
      }

      Statement stmt = null;
      ResultSet rs = null;
      try
      {
         contentWriter.putNextEntry(new ZipEntry(tableName));
         contentLenWriter.putNextEntry(new ZipEntry(tableName));

         stmt = jdbcConn.createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY, java.sql.ResultSet.CONCUR_READ_ONLY);
         stmt.setFetchSize(FETCH_SIZE);
         rs = stmt.executeQuery(script);
         ResultSetMetaData metaData = rs.getMetaData();

         int columnCount = metaData.getColumnCount();
         int[] columnType = new int[columnCount];

         contentWriter.writeInt(columnCount);
         for (int i = 0; i < columnCount; i++)
         {
            columnType[i] = metaData.getColumnType(i + 1);
            contentWriter.writeInt(columnType[i]);
            contentWriter.writeString(metaData.getColumnName(i + 1));
         }

         byte[] tmpBuff = new byte[2048];

         // Now we can output the actual data
         while (rs.next())
         {
            for (int i = 0; i < columnCount; i++)
            {
               InputStream value;
               if (columnType[i] == Types.VARBINARY || columnType[i] == Types.LONGVARBINARY
                  || columnType[i] == Types.BLOB || columnType[i] == Types.BINARY || columnType[i] == Types.OTHER)
               {
                  value = rs.getBinaryStream(i + 1);
               }
               else
               {
                  String str = rs.getString(i + 1);
                  value = str == null ? null : new ByteArrayInputStream(str.getBytes(Constants.DEFAULT_ENCODING));
               }

               if (value == null)
               {
                  contentLenWriter.writeLong(-1);
               }
               else
               {
                  long len = 0;
                  int read = 0;

                  while ((read = value.read(tmpBuff)) >= 0)
                  {
                     contentWriter.write(tmpBuff, 0, read);
                     len += read;
                  }
                  contentLenWriter.writeLong(len);
               }
            }
         }

         contentWriter.closeEntry();
         contentLenWriter.closeEntry();
      }
      finally
      {
         if (rs != null)
         {
            rs.close();
         }

         if (stmt != null)
         {
            stmt.close();
         }
      }
   }