purge deleted documents from couchdb in php - php

I am trying to write an automated script to run through a couchdb, find the deleted documents (About 100,000 doc deletetions a month) and purge them and their revisions.
I haven't found documentation explaining how to get all deleted documents, all their revisions, and construct them into the POST request shown here.
http://docs.couchdb.org/en/stable/api/database/misc.html
How do I construct the views, get the data, and create the POST to do this?
Thanks

So I ended up making a nodejs script for it that runs periodically.
Some things are hard coded since this was for testing, and not production (yet). Anyone referencing this should watch for hard coded references.
I used pouchdb to handle the replication, as it was able to run all 400,000 tombstones in a few minutes, whereas I never actually got couchdb to finish replicating after a full day of running.
This is my first node script ever, so I apologize if it's awful.
var PouchDB = require('pouchdb');
var fs = require('fs');
var child = require('child_process');
var originalDB = "dbName";
var tempDB = "dbName_clean";
var serviceName = "Apache CouchDB";
var couchDBDataPath = "C:\\bin\\couchdb\\couchdb.2.1.1\\data\\";
var db = new PouchDB('http://URL/' + originalDB);
var db2 = new PouchDB('http://URL/' + tempDB);
console.log("Compacting");
return db.compact().then(function (result) {
console.log("Compacting done, replicating");
var batch_size = 100;
return db2.destroy().then(function () {
db2 = new PouchDB('http://URL/' + tempDB);
return db.replicate.to(db2, {
batch_size: batch_size,
filter: function (doc, req) {
return !doc._deleted;
}
}).on('change', function (info) {
console.log("batch done");
}).on('complete', function () {
console.log('complete');
}).on('paused', function (err) {
// replication paused (e.g. replication up to date, user went offline)
console.log("paused", err);
}).on('active', function () {
// replicate resumed (e.g. new changes replicating, user went back online)
console.log("Active");
}).on('denied', function (err) {
// a document failed to replicate (e.g. due to permissions)
console.log("Denied", err);
}).on('error', function (err) {
// handle error
console.log("error", err);
// reject(err);
}).then(function () {
//replicate done, rename everything
var date = new Date();
console.log("Stopping service");
child.execSync('net stop "' + serviceName + '"');
console.log("Service Stopped");
var newName;
var counter = 0;
do {
newName = "_" + date.getFullYear() + date.getMonth() + date.getDay() + "_" + counter;
counter++;
} while (fs.existsSync(couchDBDataPath + originalDB + newName + ".couch") || fs.existsSync(couchDBDataPath + "." + originalDB + "_design" + newName));
console.log("Renaming original couch to backup labeled", originalDB + newName);
fs.renameSync(couchDBDataPath + originalDB + ".couch", couchDBDataPath + originalDB + newName + ".couch");
fs.renameSync(couchDBDataPath + "." + originalDB + "_design", couchDBDataPath + "." + originalDB + newName + "_design");
console.log("Renaming clean couch back to original", tempDB);
fs.renameSync(couchDBDataPath + tempDB + ".couch", couchDBDataPath + originalDB + ".couch");
fs.mkdirSync(couchDBDataPath + "." + originalDB + "_design");
console.log("Starting service");
child.execSync('net start "' + serviceName + '"');
console.log("Service started");
});
});
}).catch(function (err) {
console.log(err);
});

Related

TypeError: $ is undefined : $.widget("ui.combobox", {

I use jquery in comboboxes, and I'm not abele to get the comboboxes in the interface to be displayed. The error in firebug is the following :
TypeError: $ is undefined : $.widget("ui.combobox", {
I'm using the following file jquery.ui.combobox.js:
Code :
$.widget("ui.combobox", {
options: {
openDialogButtonText: "+",
dialogHeaderText: "Add option",
saveButtonImgUrl: null,
closeButtontext: "Ok"
},
_create: function() {
var selectBox = $(this.element),
id = selectBox.attr("id"),
self = this;
selectBox.addClass("ui-combobox");
// create HTML to inject in the DOM
this.addHtml(id, selectBox);
// turn dialog html into a JQuery UI dialog component
this.addDialog(id);
// #todo set proper button height (roughly equal to select height)
$("#" + id + "-button-opendialog").bind("click", function() {
$("#" + id + "-editor-dialog").dialog("open");
}).button();
$("#" + id + "-button-save").bind("click", function() {
self.addOption(id, selectBox);
}).button();
this._init();
return this;
},
addHtml: function(id, selectBox) {
var imgHtml = "";
if (this.options.saveButtonImgUrl != null) {
imgHtml = '<img src="' + this.options.saveButtonImgUrl + '" alt="opslaan" />';
}
$(' <button id="' + id + '-button-opendialog">' +
this.options.openDialogButtonText +
'</button>' +
'<div id="' + id + '-editor-dialog" class="ui-combobox-editor">' +
'<input id="' + id + '-newitem" type="text" /> ' +
' <button id="' + id + '-button-save">' +
imgHtml + ' Opslaan' +
' </button>' +
'</div>').insertAfter(selectBox);
},
addDialog: function(id) {
var options = this.options;
$("#" + id + "-editor-dialog").dialog( {
autoOpen: false,
modal: true,
overlay: {
opacity:0.5,
background:"black"
},
buttons: {
// #todo make button text configurable
"Ok": function() {
$("#" + id + "-editor-dialog").dialog("close");
return;
}
},
title: options.dialogHeaderText,
hide: 'fold'
});
},
addOption: function(id, selectBox) {
var newItem = $("#" + id + "-newitem");
// #todo do not allow duplicates
if (newItem !== null && $(newItem).val().length > 0) {
// #todo iterate over options and get the highest int value
//var newValue = selectBox.children("option").length + 1;
var highestInt = 0;
selectBox.children("option").each(function(i, n) {
var cInt = parseInt($(n).val());
if (cInt > highestInt) {
highestInt = cInt;
}
});
var newValue = highestInt + 1;
var newLabel = $(newItem).val();
selectBox.prepend("<option value='" + newValue + "' selected='selected'>" + newLabel + "</option>");
this._trigger("addoption", {}, newValue);
// cleanup and close dialog
$(newItem).val("");
$("#" + id + "-editor-dialog").dialog("close");
} else {
this._trigger("addoptionerror", {}, "You are required to supply a text");
}
},
_init: function() {
// called each time .statusbar(etc.) is called
},
destroy: function() {
$.Widget.prototype.destroy.apply(this, arguments); // default destroy
// $(".ui-combobox-button").remove();
// $(".ui-combobox-editor").remove();
}
});
Can you please help me?
The message "$ is undefined" means that the function called "$" is not defined anywhere on your page. Thus, when this code is executed, it does not know what to do when this line is encountered.
The $ function is defined by jQuery. Therefore, the message is indicating that it hasn't loaded the jQuery library by the time your code is executed. This could be for a number of things
You haven't included the full jQuery library on your page. This may be because you have forgotten to include it or you have only included some extension to jQuery such as jQuery.UI.
If you are unsure, try adding the following line to the top of your head element in your HTML. Make sure you haven't put any JS before this line:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
You have included jQuery but it is failing to load. This may be because the link you are using is incorrect. Double check by using the Net Panel in Firebug.
jQuery is included on your page, but you have included your own JS first. This won't work because the $ function won't get defined until jQuery is loaded, but your code will try and execute first. Check the order in which you are including your JS and make sure that jQuery is first.

Select boxes auto populated by JSON sometimes need a refresh before displaying

I have a JSON file that is being used to autopopulate some select boxes. Every now and then (I can't recreate the fault, it appears to be random) the items in the drop down do not display until I refresh the page.
I've checked the console and log etc, the file is loading fine, no errors are appearing and I'm a little at a loss.
Any ideas?
Example of JSON and the script that reads it below.
Thanks.
"radAbsorbed" : [
{
"value" : "rad",
"name" : "Rad(rd)"
},
{
"value" : "millirad",
"name" : "Millirad(mrd)"
}]
and the script:
<script>
// JSON:
// The key is the class identifier, temp, area etc etc
// Value is being used for both ID and Value when the list is being populated
$.getJSON('JSON/conversionJSON.json', function(data){
console.log(data);
//for testing output only
var list = $("<ul />");
$.each(data, function (key, conversions) {
console.log(key + ":" + conversions);
$.each(conversions, function (index, conversion) {
console.log("<li>Name: " + conversion.name + " :Value: " + conversion.value + "</li>");
if(key == "<?php echo $conversionType ?>"){
$("#from").append('<option class="'+key+'" id="'+conversion.value+'" value="'+conversion.value+'">'+conversion.name+'</option>');
//testing output
var elem = $("<li>Name: " + conversion.name + " :Value: " + conversion.value + "</li>").appendTo(list);
}
});
});
//$("#testJSON").html(list);
});
</script>
EDIT:
Updated script.
$(document).ready(function(){
$.getJSON('JSON/conversionJSON.json', function(data){
console.log(data);
//for testing output only
var list = $("<ul />");
$.each(data, function (key, conversions) {
console.log(key + ":" + conversions);
$.each(conversions, function (index, conversion) {
console.log("<li>Name: " + conversion.name + " :Value: " + conversion.value + "</li>");
if(key == "<?php echo $conversionType ?>"){
$("#from").append('<option class="'+key+'" id="'+conversion.value+'" value="'+conversion.value+'">'+conversion.name+'</option>');
$("#to").append('<option class="'+key+'" id="'+conversion.value+'" value="'+conversion.value+'">'+conversion.name+'</option>');
//testing output
var elem = $("<li>Name: " + conversion.name + " :Value: " + conversion.value + "</li>").appendTo(list);
}
});
});
//$("#testJSON").html(list);
});
});
EDIT: Thanks everyone for their help, it seems to be working fine and looked like an amateur mistake on my part.
I think the problem is that your script is sometimes running before the document is ready.
Try wrapping your code in a document ready function:
$(function() {
$.getJSON(...)
// ...
});
This will make it so that the code doesn't execute before the elements it's affecting are created. For instance, if your code executes before the element with the ID from gets created, then $('#from') will not match any elements, and it won't work.
Wrapping it in a document ready function will make sure that your code waits until the elements have been created before executing.
Alternatively, you could move your <script> tag out of the head and place it right after the #from element in your HTML. This might help it load slightly faster.

Countdown start on button press

Ive got an problem. I have an button that sends an command to an perl script. For 60 seconds the page will just load and load. So i need an countdown to tell the user how much time until the perl script is finished. So i got his javascript from the web that automaticly counts down when the page loads. Is it possible to reverse this?
http://goo.gl/cYdKg
You see what happens, when you don't state your requirements correctly? Two people doing the same wrong thing (bad for us, we did not clarified before, tho).
$.fn.timedDisable = function(time, callback) {
if (time == null) {
time = 5000;
}
var seconds = Math.ceil(time / 1000);
return $(this).each(function() {
$(this).attr('disabled', 'disabled');
var disabledElem = $(this);
var originalText = this.innerHTML;
disabledElem.text( originalText + ' (' + seconds + ')');
var interval = setInterval(function() {
disabledElem.text( originalText + ' (' + --seconds + ')');
if (seconds === 0) {
disabledElem.removeAttr('disabled')
.text(originalText);
clearInterval(interval);
if (typeof callback !== 'undefined')
callback();
}
}, 1000);
});
};
$(function() {
$('#btnContinue').click(function() {
$(this).timedDisable(5000, function() {
window.alert('done');
});
});
});

i am getting ajax response slow

i am using the following code for pass and get data through ajax.
function passdata(id)
{
var top = document.getElementById("tname").value;
var first = document.getElementById("fname").value;
var font_top = document.getElementById("font_top").value;
var font_first = document.getElementById("font_first").value;
var image_top = document.getElementById("image_top").value;
var image_first = document.getElementById("image_first").value;
var poststr = "id=" + id +
"&top=" + top +
"&first=" + first +
"&font_top=" + font_top +
"&font_first=" + font_first +
"&image_top=" + image_top +
"&image_first=" + image_first +
"&actype=getevent";
var reqAddCart = new Subsys_JsHttpRequest_Js();
reqAddCart.onreadystatechange = function() {
if (reqAddCart.readyState == 4) {
if (reqAddCart.responseJS) {
document.location.href = reqAddCart.responseJS.ajax_redirect;
return;
}
else {
//alert(reqAddCart.responseText);
//showModal('abc');
document.getElementById('data_content').innerHTML = reqAddCart.responseText;
result = (reqAddCart.responseText||'');
var brokenresult=result.split("#");
}
}
}
var senddata = new Object();
var url = 'product.php?'+poststr;
//alert(url);
reqAddCart.caching = false;
reqAddCart.open( 'GET', url, true);
reqAddCart.send( senddata );
return false;
}
i am using the passdata function to pass the data in product page.this function works but i am getting response very slow.
The time taken for an AJAX request to complete is affected by network latency and connection speed on both the server and client, as well as execution time of the script on the server.
I would expect AJAX requests made locally when testing to return a lot faster as it removes the need for transmitting data over the internet.

No results obtained with JQuery $.getJSON in the PhoneGap environment

Here is my funciton:
function getEmployeeList() {
alert("hello world3!");
$.getJSON(serviceURL + 'getemployees.php', function(data) {
alert("hello world4!");
$('#employeeList li').remove();
employees = data.items;
$.each(employees, function(index, employee) {
$('#employeeList').append('<li><a href="employeedetails.html?id=' + employee.id + '">' +
'<img src="pics/' + employee.picture + '"/>' +
'<h4>' + employee.firstName + ' ' + employee.lastName + '</h4>' +
'<p>' + employee.title + '</p>' +
'<span class="ui-li-count">' + employee.reportCount + '</span></a></li>');
});
$('#employeeList').listview('refresh');
});
}
When the page is ready, it will run this function, however, nothing is appended.
I have tested, all php can return correct format. What wrongs?? Please please help me...
You need to add the external host (in my case was mysite.localhost) in PhoneGap.plist under the "ExternalHosts" key.
I presume serviceURL is not on the same domain.
In that case you add callback=? in the end, and jQuery does some magic:
$.getJSON(serviceURL + 'getemployees.php?callback=?', function(data) {
...
If the URL includes the string "callback=?" (or similar, as defined by the server-side API), the request is treated as JSONP instead. See the discussion of the jsonp data type in $.ajax() for more details.
jQuery API

Categories