Generate a text dump compatible with SQLite.
        By yielding every table one by one as a byte string.
18020
def sqlite_dump_string(self, progress):
        """"""
        # First the schema #
        mdb_schema = sh.Command("mdb-schema")
        yield mdb_schema(self.path, "sqlite").encode('utf8')
        # Start a transaction, speeds things up when importing #
        yield "BEGIN TRANSACTION;\n"
        # Then export every table #
        mdb_export = sh.Command("mdb-export")
        for table in progress(self.tables):
            yield mdb_export('-I', 'sqlite', self.path, table).encode('utf8')
        # End the transaction
        yield "END TRANSACTION;\n"
1196589
def generate_one(tbl, args, table_name=None, file=None):
    
    table = Table(tbl, table_name=table_name, varying_length_text=args.text, uniques=args.uniques,
                  pk_name = args.key, force_pk=args.force_key, reorder=args.reorder, data_size_cushion=args.cushion,
                  save_metadata_to=args.save_metadata_to, metadata_source=args.use_metadata_from,
                  loglevel=args.log, limit=args.limit)
    if args.dialect.startswith('sqla'):
        if not args.no_creates:
            print(table.sqlalchemy(), file=file)
        if args.inserts:
            print("\n".join(table.inserts(dialect=args.dialect)), file=file)
    elif args.dialect.startswith('dj'):
        table.django_models()
    else:
        print(table.sql(dialect=args.dialect, inserts=args.inserts,
                        creates=(not args.no_creates), drops=args.drops,
                        metadata_source=args.use_metadata_from), file=file)
    return table
580679
def tables(db=None):
    '''
    
    '''
    cur = _connect(db)

    if not cur:
        return False

    cur.execute(
        "SELECT name FROM sqlite_master WHERE type='table' ORDER BY name;"
    )
    rows = cur.fetchall()
    return rows
133294
def to_db(self, table, dtypes=None):
        
        if self._check_db() is False:
            return
        if table not in self.db.tables:
            self.db.create_table(table)
            self.info("Created table ", table)
        self.start("Saving data to database table " + table + " ...")
        recs = self.to_records_()
        self.insert(table, recs, dtypes)
        self.end("Data inserted in table", table)
609398
def dumplist(args):
  """"""

  from .query import Database
  db = Database()

  r = db.objects(
      protocol=args.protocol,
      purposes=args.purpose,
      model_ids=(args.client,),
      groups=args.group,
      classes=args.sclass
  )

  output = sys.stdout
  if args.selftest:
    from bob.db.utils import null
    output = null()

  for f in r:
    output.write('%s\n' % (f.make_path(args.directory, args.extension),))

  return 0
691337
def generate(cache_fn):
    
    if not os.path.exists(cache_fn):
        print >> sys.stderr, "Can't access `%s`!" % cache_fn
        sys.exit(1)

    with SqliteDict(cache_fn) as db:
        for item in _pick_keywords(db):
            yield item
246614
public static void dumpCurrentRow(Cursor cursor, PrintStream stream) {
        String[] cols = cursor.getColumnNames();
        stream.println("" + cursor.getPosition() + " {");
        int length = cols.length;
        for (int i = 0; i< length; i++) {
            String value;
            try {
                value = cursor.getString(i);
            } catch (SQLiteException e) {
                // assume that if the getString threw this exception then the column is not
                // representable by a string, e.g. it is a BLOB.
                value = "<unprintable>";
            }
            stream.println("   " + cols[i] + '=' + value);
        }
        stream.println("}");
    }
301265
def format_output(data, fmt='table'):  # pylint: disable=R0911,R0912
    
    if isinstance(data, utils.string_types):
        if fmt in ('json', 'jsonraw'):
            return json.dumps(data)
        return data

    # responds to .prettytable()
    if hasattr(data, 'prettytable'):
        if fmt == 'table':
            return str(format_prettytable(data))
        elif fmt == 'raw':
            return str(format_no_tty(data))

    # responds to .to_python()
    if hasattr(data, 'to_python'):
        if fmt == 'json':
            return json.dumps(
                format_output(data, fmt='python'),
                indent=4,
                cls=CLIJSONEncoder)
        elif fmt == 'jsonraw':
            return json.dumps(format_output(data, fmt='python'),
                              cls=CLIJSONEncoder)
        elif fmt == 'python':
            return data.to_python()

    # responds to .formatted
    if hasattr(data, 'formatted'):
        if fmt == 'table':
            return data.formatted

    # responds to .separator
    if hasattr(data, 'separator'):
        output = [format_output(d, fmt=fmt) for d in data if d]
        return str(SequentialOutput(data.separator, output))

    # is iterable
    if isinstance(data, list) or isinstance(data, tuple):
        output = [format_output(d, fmt=fmt) for d in data]
        if fmt == 'python':
            return output
        return format_output(listing(output, separator=os.linesep))

    # fallback, convert this odd object to a string
    return data
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();
         }
      }
   }
1055194
def compile_insert(self, query, values):
        
        table = self.wrap_table(query.from__)

        if not isinstance(values, list):
            values = [values]

        # If there is only one row to insert, we just use the normal grammar
        if len(values) == 1:
            return super(SQLiteQueryGrammar, self).compile_insert(query, values)

        names = self.columnize(values[0].keys())

        columns = []

        # SQLite requires us to build the multi-row insert as a listing of select with
        # unions joining them together. So we'll build out this list of columns and
        # then join them all together with select unions to complete the queries.
        for column in values[0].keys():
            columns.append("%s AS %s" % (self.get_marker(), self.wrap(column)))

        columns = [", ".join(columns)] * len(values)

        return "INSERT INTO %s (%s) SELECT %s" % (
            table,
            names,
            " UNION ALL SELECT ".join(columns),
        )
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');
	}
264539
def table_output(data):
    ''''''
    if type(data) == DictType:
        data = data.items()
    headings = [ item[0] for item in data ]
    rows = [ item[1] for item in data ]
    columns = zip(*rows)
    if len(columns):
        widths = [ max([ len(str(y)) for y in row ]) for row in rows ]
    else:
        widths = [ 0 for c in headings ]
    for c, heading in enumerate(headings):
        widths[c] = max(widths[c], len(heading))
    column_count = range(len(rows))
    table = [ ' '.join([ headings[c].ljust(widths[c]) for c in column_count ]) ]
    table.append(' '.join([ '=' * widths[c] for c in column_count ]))
    for column in columns:
        table.append(' '.join([ str(column[c]).ljust(widths[c]) for c in column_count ]))
    return '\n'.join(table)
793494
public static void dump(Printer printer, String[] args) {
        boolean verbose = false;
        for (String arg : args) {
            if (arg.equals("-v")) {
                verbose = true;
            }
        }

        SQLiteDatabase.dumpAll(printer, verbose);
    }
391727
private String generatePageSQLStatement(boolean tableExists,
			Map<String, Set<Integer>> dataSourceToUse)
	{
		StringBuffer output = new StringBuffer();

		// Statement creates table for Template Id -> Page Id
		output.append("CREATE TABLE IF NOT EXISTS "
				+ GeneratorConstants.TABLE_TPLID_PAGEID
				+ " ("
				+ "templateId INTEGER UNSIGNED NOT NULL,"
				+ "pageId INTEGER UNSIGNED NOT NULL, UNIQUE(templateId, pageId));\r\n");

		// Statement for data into templateId -> pageId
		output.append(this.generateSQLStatementForDataInTable(dataSourceToUse,
				GeneratorConstants.TABLE_TPLID_PAGEID));

		if (!tableExists) {
			// Create index statement if table does not exists
			output.append("CREATE INDEX pageIdx ON "
					+ GeneratorConstants.TABLE_TPLID_PAGEID
					+ "(pageId);");
			output.append("\r\n");
		}

		return output.toString();

	}
164023
def instantiate_database(sqlite_file='ftwj.sqlite'):
    
    table_name = 'ftw'
    col1 = 'rule_id'
    col1_t = 'INTEGER'
    col2 = 'test_id'
    col2_t = 'STRING'
    col3 = 'time_start'
    col3_t = 'TEXT'
    col4 = 'time_end'
    col4_t = 'TEXT'
    col5 = 'response_blob'
    col5_t = 'TEXT'
    col6 = 'status_code'
    col6_t = 'INTEGER'
    col7 = 'stage'
    col7_t = 'INTEGER'
    conn = sqlite3.connect(sqlite_file)
    cur = conn.cursor()

    q = 'CREATE TABLE {tn}({col1} {col1_t},{col2} {col2_t},{col3} {col3_t},{col4} {col4_t},{col5} {col5_t},{col6} {col6_t},{col7} {col7_t})'.format(
        tn=table_name,
        col1=col1, col1_t=col1_t,
        col2=col2, col2_t=col2_t,
        col3=col3, col3_t=col3_t,
        col4=col4, col4_t=col4_t,
        col5=col5, col5_t=col5_t,
        col6=col6, col6_t=col6_t,
        col7=col7, col7_t=col7_t)
    cur.execute(q)
    conn.commit()
    conn.close()
480395
def dumps(self):
        """"""
        return {table_name: getattr(self, table_name).dumps() for table_name in self.TABLES}
483056
public static void dumpCurrentRow(Cursor cursor, StringBuilder sb) {
        String[] cols = cursor.getColumnNames();
        sb.append("" + cursor.getPosition() + " {\n");
        int length = cols.length;
        for (int i = 0; i < length; i++) {
            String value;
            try {
                value = cursor.getString(i);
            } catch (SQLiteException e) {
                // assume that if the getString threw this exception then the column is not
                // representable by a string, e.g. it is a BLOB.
                value = "<unprintable>";
            }
            sb.append("   " + cols[i] + '=' + value + "\n");
        }
        sb.append("}\n");
    }