I wanted to back up my Flutter SQFlite database to mobile.
And i need to restore the database in existing app.
I am searching on internet but did not get any proper tutorial or document.
Anyone please help!!!
Thanks in advance.
For complete details, go to link
ElevatedButton(
onPressed: () async {
final dbFolder = await getDatabasesPath();
File source1 = File('$dbFolder/doggie_database.db');
Directory copyTo =
Directory("storage/emulated/0/Sqlite Backup");
if ((await copyTo.exists())) {
// print("Path exist");
var status = await Permission.storage.status;
if (!status.isGranted) {
await Permission.storage.request();
}
} else {
print("not exist");
if (await Permission.storage.request().isGranted) {
// Either the permission was already granted before or the user just granted it.
await copyTo.create();
} else {
print('Please give permission');
}
}
String newPath = "${copyTo.path}/doggie_database.db";
await source1.copy(newPath);
setState(() {
message = 'Successfully Copied DB';
});
},
child: const Text('Copy DB'),
),
ElevatedButton(
onPressed: () async {
var databasesPath = await getDatabasesPath();
var dbPath = join(databasesPath, 'doggie_database.db');
FilePickerResult? result =
await FilePicker.platform.pickFiles();
if (result != null) {
File source = File(result.files.single.path!);
await source.copy(dbPath);
setState(() {
message = 'Successfully Restored DB';
});
} else {
// User canceled the picker
}
},
child: const Text('Restore DB'),
),
Related
const { Client, Intents } = require('discord.js');
const { GoogleSpreadsheet } = require('google-spreadsheet');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MEMBERS, Intents.FLAGS.GUILD_MESSAGES] });
const PREFIX = '!';
// Specify your credentials here
const creds = {
client_email: 'myclient',
private_key: 'myprivatekey',
};
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on('message', async (message) => {
if (!message.content.startsWith(PREFIX) || message.author.bot) return;
const args = message.content.slice(PREFIX.length).trim().split(/ +/);
const command = args.shift().toLowerCase();
if (command === 'assignrole') {
if (!message.member.permissions.has('MANAGE_ROLES')) {
console.error('Error: User does not have the ManageRole permission');
message.reply('You do not have permission to use this command');
return;
}
const sheetId = args[0];
if (!sheetId) {
console.error('Error: Missing spreadsheet ID in command');
message.reply('Please provide a valid spreadsheet ID');
return;
}
const doc = new GoogleSpreadsheet(sheetId);
try {
await doc.useServiceAccountAuth(creds);
await doc.loadInfo(); // loads document properties and worksheets
const sheet = doc.sheetsByIndex[0]; // assumes sheet is first in document
const rows = await sheet.getRows();
const role = message.mentions.roles.first();
if (!role) {
console.error('Error: Missing role in command');
message.reply('Please provide a valid role');
return;
}
const roleName = role.name;
const successfulUsers = [];
for (let i = 0; i < rows.length; i++) {
const row = rows[i];
const user = message.guild.members.cache.find(
(member) => member.user.username === row._rawData[0]
);
if (user) {
try {
await user.roles.add(role);
row._rawData[1] = 'OK';
await row.save();
successfulUsers.push(user.user.username);
} catch (err) {
console.error(`Error: ${err.message}`);
}
}
}
message.channel.send(
`The role ${roleName} was added to the following users: ${successfulUsers.join(', ')}`
);
} catch (err) {
console.error(`Error: ${err.message}`);
message.reply('An error occurred while trying to access the spreadsheet');
}
}
});
client.login('mykey');
This is code was made to access a google sheet, reads column A and adds specified role to Users in column A, then adds 'OK' to column B to users who actually got the roleThis runs without errors, but cannot add anyone to any roles.
How can I change this so that it reads usernames on column A, and adds the role specified in the command?
I tried with a test code that exports whats in column A, and it seems to be reading column A.
I have checked permisions on discord side and the role I was trying to assign was under the bot role.
I have a general question about DB transactions and specifically mongo DB.
Is the following code safe in terms of read and write operations?
import { MongoClient, ObjectId } from "mongodb";
const CONNECTION = "mongodb+srv://...";
const client = new MongoClient(CONNECTION);
const con = await client.connect();
const session = con.startSession();
try {
await session.withTransaction(
async () => {
const _id = new ObjectId("...");
const col = con.db("purchases").collection("collection");
// READ
const purchase = await col.findOne({ _id }) as any;
if (purchase.test) {
// WRITE
await col.updateOne({ _id }, { $set: { test: false } });
}
},
{ readConcern: "majority", writeConcern: { w: "majority" } }
);
} finally {
await session.endSession();
await client.close();
}
I know that I can also achieve this functionality using findOneAndUpdate but I'm interested in the transactions specifically.
I tried to get Data of the Document but I only get Null.
Documentpicker is working, except: The Selected Data is NULL.
async openDocumentReader() {
try {
const res = await DocumentPicker.pick({
type: [DocumentPicker.types.csv],
});
console.log(
res.uri,
res.type,
res.name,
res.size,
);
if (res.name == null) {
Alert.alert('Document is Null');
}
} catch (err) {
if (DocumentPicker.isCancel(err)) {
//User canceld
} else {
throw err;
}
}
Any recommendations?
I found a solution:
I had to choose pickSingle for it.
try {
const res = await DocumentPicker.pickSingle({
type: [DocumentPicker.types.csv], mode : 'import', copyTo: 'documentDirectory',
});
var uri = res.uri;
var name = res.name;
var fileCopyUri = res.fileCopyUri;
console.log(JSON.stringify(res));
console.log(res.uri);
}
Or something like that.
First of all sorry for the bad English
I'm trying to do a "tweet" system. I check if the link is true and has an image but if you put something like https://askhdkjahs.png the program thinks is an image and put in the embed giving an error
I need handle the error and put a default image or reply saying 'the image give a error'
thats my code
if (comando === `${prefix}atwt`) {
msg.delete({ timeout: 100 });
if (!argumento[0]) {
msg.reply('pon algo').then(msg => {
msg.delete({ timeout: 10000 });
}).catch(console.error);
}
else if(argumento !== null && argumento !== '') {
const TweetAnon = new Discord.MessageEmbed()
.setAuthor('Anonimo!', 'https://i.imgur.com/wSTFkRM.png')
.setColor('BLUE')
.setTimestamp();
const url = argumento[0].toString();
if (url.match(/^https.*\.(png|jpeg|jpg|gif|bmp)$/i)) {
TweetAnon.setImage(argumento[0]);
TweetAnon.setDescription(`**${argumento.slice(1).join(' ')}**`);
}
else{
TweetAnon.setDescription(`**${argumento.join(' ')}**`);
}
const msgEmbed = await msg.channel.send(TweetAnon).catch(TweetAnon.setImage('https://i.imgur.com/wSTFkRM.png'));
await msgEmbed.react('👍');
await msgEmbed.react('👎');
await msgEmbed.react('🔄');
}
}
I see something like that and I tried but doesn't work
if (comando === `${prefix}atwt`) {
const url = argumento[0].toString();
const TweetAnon = new Discord.MessageEmbed()
.setAuthor('Anonimo!', 'https://cdn.discordapp.com/attachments/769965806850670634/854834517709422602/anon.png')
.setColor('BLUE')
.setTimestamp();
msg.delete({ timeout: 100 });
try {
if (!url.match(/^https.*\.(png|jpeg|jpg|gif|bmp)$/i)) {
throw new Error('Invalid URL');
}
TweetAnon.setImage(argumento[0]);
TweetAnon.setDescription(`**${argumento.slice(1).join(' ')}**`);
}
catch (error) {
TweetAnon.setImage('https://i.imgur.com/wSTFkRM.png');
}
// else
// TweetAnon.setDescription(`**${argumento.join(' ')}**`);
// }
const msgEmbed = await msg.channel.send(TweetAnon).catch(err => console.log(err));
await msgEmbed.react('👍');
await msgEmbed.react('👎');
await msgEmbed.react('🔄');
}
You could check if the image exists like this:
function imageExists(image_url){
var http = new XMLHttpRequest();
http.open('HEAD', image_url, false);
http.send();
return http.status != 404;
}
Usage:
if(imageExists(argumento[0])){
TweetAnon.setImage(argumento[0]);
}
I have to upload images in the directory and save that name into a database using graphql resolver. When I upload an image and pass that image in resolver but I am getting an undefined value of image name. So how can I get the image name?
In the Below code, I saved information with file upload but a problem to get a file name after uploading an image. So how can I get the file uploaded file name?
const fs = require("fs");
function ProfileImage(argsprofilephoto) {
try {
argsprofilephoto.then(profilephoto => {
const {
createReadStream,
filename,
mimetype
} = profilephoto;
const fileStream = createReadStream();
fileStream.pipe(fs.createWriteStream(`./uploadedFiles/${filename}`));
console.log("filename=", filename);
return filename;
});
} catch (err) {
console.log(err);
}
}
export default {
Mutation: {
signUp: async (parent, args, {
models,
secret
}) => {
try {
let profimgnm = "";
let docimgnm = "";
// Prfile Photo Upload
if (args.profilephoto != "") {
profimgnm = ProfileImage(args.profilephoto);
console.log("profimgnm=", profimgnm);
}
if (args.documents != "") {
docimgnm = ProfileImage(args.documents);
console.log("docimgnm=", docimgnm);
}
let name = args.name;
let email = args.email;
let phone = args.phone;
let address = args.address;
let zipcode = args.zipcode;
let profilephoto = profimgnm;
let documents = docimgnm;
const user = await models.User.create({
name,
email,
phone,
address,
zipcode,
profilephoto,
documents
});
return user;
} catch (err) {}
}
}
};
I am getting this output.
profimgnm= undefined
docimgnm= undefined
filename= download.jpg
filename= dimg.jpg
Anyone, please give me a solution.
There are a few issues here. You are not returning the promise from ProfileImage async method. You should be doing something like:
function ProfileImage(argsprofilephoto) {
return argsprofilephoto.then(profilephoto => {
const {
createReadStream,
filename,
mimetype
} = profilephoto;
const fileStream = createReadStream();
fileStream.pipe(fs.createWriteStream(`./uploadedFiles/${filename}`));
console.log("filename=", filename);
return filename;
}).catch(e => {
// you might want to return some sensible default depending on your usecase, or let the error bubble up by not catching
console.log(e)
});
}
and in your resolver you need to wait for the promise to resolve:
if (args.profilephoto != "") {
// could still be undefined if the promise above failed on catch block returned nothing, but you get the idea
profimgnm = await ProfileImage(args.profilephoto);
console.log("profimgnm=", profimgnm);
}
if (args.documents != "") {
docimgnm = await ProfileImage(args.documents);
console.log("docimgnm=", docimgnm);
}