Database migration notnull()? - database-migration

I use migration to add nullable() to column.
class ChangeUgIdCanNull extends Migration
{
public function up()
{
Schema::table('service_request_step', function (Blueprint $table) {
$table->dropForeign(['ug_id']);
});
Schema::table('service_request_step', function (Blueprint $table) {
$table->dropIndex(['ug_id']);
});
Schema::table('service_request_step', function (Blueprint $table) {
$table->integer('ug_id')->unsigned()->index()->nullable()->change();
$table->foreign('ug_id')->references('ug_id')
->on('user_group')->onDelete('cascade');
});
}
public function down()
{
Schema::table('service_request_step', function (Blueprint $table) {
$table->dropForeign(['ug_id']);
});
Schema::table('service_request_step', function (Blueprint $table) {
$table->dropIndex(['ug_id']);
});
Schema::table('service_request_step', function (Blueprint $table) {
$table->integer('ug_id')->unsigned()->index()->change();
$table->foreign('ug_id')->references('ug_id')
->on('user_group')->onDelete('cascade');
});
}
}
When i use php artisan migrate is fine.
But, When I want to php artisan migrate:rollback. In my database in 'ug_id' column is still nullable.
Did I have some function like $table->integer('ug_id')->unsigned()->index()->notnull()->change();
Laravel Version: 5.4.19
PHP Version: 7.1.3
Database Driver & Version: 10.2.4-MariaDB

You can use nullable(false).
Your code should be
$table->integer('ug_id')->unsigned()->index()->nullable(false)->change();

Related

Can't get a directive using a controller test to pass Jasmine : Error: [$injector:unpr] Unknown provider: utilsProvider <- utils

I've been searching a long time for an answer to the question I'm about to ask without success.
Let's say I have the following directive :
(function () {
'use strict';
angular
.module('com.acme.mymod')
.directive('myDirective', myDirective);
function myDirective() {
var directive = {
restrict: 'EA',
scope: {},
replace: true,
templateUrl: 'folder/myDirective/myDirective.tpl.html',
controller: "myDirectiveController",
controllerAs: 'vm',
bindToController: {
somedata: "#?",
endpoint: "#?"
},
link: link
};
return directive;
function link(scope, element) {
activate();
function activate() {
scope.$on('$destroy', destroy);
element.on('$destroy', destroy);
}
}
function destroy() {
}
}
})();
myDirectiveController is as follow:
(function () {
'use strict';
angular
.module('com.acme.mymod')
.controller('myDirectiveController', myDirectiveController);
myDirectiveController.$inject = ['utils', '$log'];
// utils is an external library factory in another module
function myDirectiveController(utils, $log) {
var vm = this;
vm.menuIsOpen = false;
function activate() {
vm.dataPromise = utils.getValuePromise(null, vm.somedata, vm.endpoint);
vm.dataPromise.then(function (result) {
vm.data = result.data;
}, function () {
$log.debug("data is not Valid");
});
}
activate();
}
})();
The spec file is as follow:
describe('myDirective Spec', function () {
'use strict';
angular.module('com.acme.mymod', []);
var compile, scope, directiveElem, utils;
beforeEach(function(){
module('com.acme.mymod');
inject(function($compile, $rootScope, $injector,utils){
compile = $compile;
scope = $rootScope.$new();
scope.$digest();
directiveElem = getCompiledElement();
//utils=utils;
console.log(utils.test());
});
});
function getCompiledElement(){
var element = angular.element('<div my-directive="" data-some-data=\' lorem\'></div>');
var compiledElement = compile(element)(scope);
scope.$digest();
return compiledElement;
}
it('should have a nav element of class', function () {
var navElement = directiveElem.find('nav');
expect(navElement.attr('class')).toBeDefined();
});
it('should have a valid json data-model' ,function () {
var data=directiveElem.attr('data-somedata');
var validJSON=false;
try{
validJSON=JSON.parse(dataNav);
}
catch(e){
}
expect(validJSON).toBeTruthy();
});
});
What I can't quite figure out is that every test I try to run, the directive is not compiled or created correctly I'm not sure.
I get :
Error: [$injector:unpr] Unknown provider: utilsProvider <- utils
I tried:
Injecting the controller or utils with $injector.get()
Looked at this post $injector:unpr Unknown provider error when testing with Jasmine
Any tips, pointers or clues as to what I'm doing wrong would be more than welcome
I found the solution after feeling a hitch in my brain :)
In the beforeEach function, all I needed to do is to reference my utils module name this way:
module('com.acme.myutilsmod');
This line "expose" modules components so consumers can use it.

Angular 2: BehaviorSubject/Subject does not work outside constructor

Hi I need pass the data from one component to another, for this I am using the class BehavorSubject(I tried too with Subject class, but doesnt works for me). This is my code:
Home page has a filter, and when is selected a filter, it called the service and it service should change a variable of homePage
HomePage.ts
#Component({
providers: [PatientService],
})
export class HomePage {
subscription: Subscription;
constructor( public auth: AuthService,
public patientService: PatientService) {
this.subscription = this.patientService.nameGiven.subscribe(
nameGiven => {
this.patientsByElement = nameGiven.toString();
});
------ more code---
}
Filtro.ts
export class FiltroPage {
showFilter(filter : FiltroT): void{
... code ...
clearTimeout(this.timeout);
this.timeout = setTimeout(() => {
this.PatientService.getPatientsByTags(this.token,this.filterSelected);
} , 1000);
}
}
patient-service.ts
import { Subject } from 'rxjs/Subject';
import { Observable ,BehaviorSubject } from 'rxjs/Rx';
#Injectable()
export class PatientService {
nameSource = new BehaviorSubject("asd");
nameGiven = this.nameSource.asObservable();
this.nameSource.next('hi!!!'); //**it works but only in the constructor**
this.nameGiven.subscribe(()=>{
console.log("it changed");
});
getPatientsByTags(token: String, tags: Array<string>){
return new Promise(resolve => {
this.http.get(ConnectionParams.DevEnv + ProceduresNames.TagsByPatient + ProceduresNames.TagIdEtiqueta + tags, options)
.map(res => res.json())
.subscribe(data => {
if(data.data.poAnicuRegistros){
console.log("here")
this.nameSource.next('hi TON :/'); // <-- ***here is the problem. It doesnt work***
}
else
console.log("XX");
resolve( this.data);
});
});
}
}
Finally i didn't use the BehaviorSubject/Subject, i pass the data from the filter to Homepage of this way :
HomePage.ts
public popoverCtrl: PopoverController
//code ...
showFilter(myEvent) {
let popover = this.popoverCtrl.create(FiltroPage, {
showConfirm: (x) => {
//do something with the data received from the filter
}
});
popover.present({
ev: myEvent
});
}
Filter.ts
//code...
params: NavParams;
showConfirm() {// function that return the data to homePage
this.params.get('showConfirm')(this.patientsBytag);
}

Ionic 2: How to call Provider function in Controller class

I have created new Cordova Plugin only on my machine. Then I added it to my project. It is working fine when I call that plugin. Now, I tried to make a structured caller for my plugin. I created a Provider for it, but the problem is I don't know how to call my plugin function from my Controller class. Below is my sample code.
Provider: my-service.ts
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import 'rxjs/add/operator/map';
declare let myPlugin: any;
#Injectable()
export class MyService {
constructor(public http: Http) {
console.log('Hello MyService Provider');
}
public myFunction() {
myPlugin.myPluginFunction(
(data) => {
return data;
},
(err) => {
return err;
});
}
}
Pages: my-page.ts
import { Component } from '#angular/core';
import { NavController, ViewController } from 'ionic-angular';
import { MyService } from '../../providers/my-service';
#Component({
selector: 'page-my-page-ionic',
templateUrl: 'hello-ionic.html'
})
export class MyPage {
constructor(private viewCtrl: ViewController, private myService: MyService) {}
ionViewWillEnter() {
//I tried to call like this
this.myService.myFunction().subscribe(
data => {
alert("success");
},
error => {
alert("error");
});
}
}
It returns me this error - Property 'subscribe' does not exist on type 'void'. I don't know how to call that function, since my provider returns me success or error.
I think since your myFunction() does not return any observable you cannot subscribe to it. It just returns data directly.
You can use it like this in this case:
var data = this.myService.myFunction();
console.log("Data from plugin is :", data);
If you want to use it as an Observable, return a new observable like this:
public myFunction() {
return Observable.create(observer => {
myPlugin.myPluginFunction(
(data) => {
observer.next(data);
},
(err) => {
observer.next(data);
});
},
(err) => {
observer.error(err);
});
}

deleteRecord not getting called in ember-data

I'm making an adapter for the Web SQL storage for use in a Cordova application. So far it's going pretty well except for some reason the deleteRecord method isn't getting called at all. Here's an excerpt of my code:
DS.CordovaStorageAdapter = DS.Adapter.extend({
// Other methods...
deleteRecord: function(store, type, record) {
console.info('Deleting!');
var adapter = this;
var qr = new QueryRapper({id: record.get('id')}).tableName(this.tableName(type));
var query = qr.deleteQuery();
console.info(query);
function deleteSuccess(tx, results) {
adapter.didDeleteRecord(store,type,record);
}
return this.db.transaction(
function(tx) { tx.executeSql(query, [], deleteSuccess); },
function(err) { this.dbError(query, err, type, record); }
);
},
// Support methods...
});
Here's my Jasmine test:
describe('EmberCordovaStorageAdapter', function() {
var m;
beforeEach(function() {
waitForDbInit();
runs(function() {
m = App.TestModel.createRecord({
string: 'String!',
number: 1234,
date: new Date(),
boolean: true
});
m.save();
waitForReady();
});
});
// Other tests...
it('deletes a record', function() {
waitForReady();
runs(function() { console.info('Deleting in test!'); m.deleteRecord(); waitForDeleted(); });
runs(function() { expect(m.get('isDeleted')).toBe(true); });
});
function waitForDeleted(model) {
model = model || m;
waitForMessage(model, 'rootState.deleted.committed');
}
function waitForReady(model) {
model = model || m;
waitForMessage(model, 'rootState.loaded.saved');
}
function waitForMessage(model, msg) {
waitsFor(function() {
console.info(msg, model.get('stateManager.currentPath'));
return model.get('stateManager.currentPath') == msg;
}, 'model message: ' + msg, 1500);
}
});
I'm seeing in my JS console the message "Deleting in test!" but not the message "Deleting!". The github repo can be found here: https://github.com/eltiare/ember-cordova-storage
I don't have experience writing custom adapters, but a quick glance at your test I see your calling deleteRecord but I don't see a call to commit
In order for ember-data to actually attempt to delete the record you need to call commit. To commit the defaultTransaction you can do something like this:
m.get('store').commit();

unit testing custom knockoutjs binding

How can I unit test this knockoutjs binding where I call a certain function 'myValueAccessor' when the element is swiped on my touchpad?
I am also unsure what the unit should or is able to test at all here.
It would be ok for the first time to assert wether myValueAccessor is called.
But how can I trigger/imitate or should I say mock... the swiperight event?
ko.bindingHandlers.tap = {
'init': function (element, valueAccessor) {
var value = valueAccessor();
var hammertime1 = Hammer(element).on("swiperight", function (event) {
$(element).fadeOut('fast', function () {
value();
});
});
}
};
self.myValueAccessor = function () {
location.href = 'set a new url'
};
UPDATE
I have put here my unit test with mocha.js
I can outcomment the 'value()' in the binding but still the test succeeded thats odd.
Is it not correct to put this (as a test):
function (element,args) {
alert('assertion here');
}
as a 3rd parameter into the ko.test function?
ko.bindingHandlers.tap = {
'init': function (element, valueAccessor) {
var value = valueAccessor();
var hammertime1 = $(element).on("swiperight", function (event) {
$(element).fadeOut('fast', function () {
//value();
});
});
}
};
// Subscribe the swiperight event to the jquery on function
$.fn.on = function (event, callback) {
if (event === "swiperight") {
callback();
}
};
// Subscribe the fadeOut event to the jquery fadeOut function
$.fn.fadeOut = function (speed, callback) {
callback();
};
ko.test("div", {
tap: function () {
assert.ok(true, "It should call the accessor");
}
}, function () {
});
UPDATE:
custom.bindings.js:
define(['knockout','hammer'], function (ko,Hammer) {
return function Bindings() {
ko.bindingHandlers.tap = {
'init': function (element, valueAccessor) {
var value = valueAccessor();
var hammertime1 = Hammer(element).on("swiperight", function (event) {
$(element).fadeOut('fast', function () {
value();
});
});
}
};
};
});
unittest.js:
how can I connect this code to knockout in my test?
UPDATE
The Bindings is injected via require.js from my bindings.js file:
describe("When swiping left or right", function () {
it("then the accessor function should be called", function () {
ko.bindingHandlers.tap = new Bindings();
Hammer.Instance.prototype.on = function (event, callback) {
if (event === "swiperight") {
callback();
}
};
$.fn.fadeOut = function (speed, callback) {
callback();
};
var accessorCalled = false;
ko.test("div", {
tap: function () {
accessorCalled = true;
}
}, function () {
assert.ok(accessorCalled, "It should call the accessor");
});
});
});
bindings.js
define(['knockout','hammer'], function (ko,Hammer) {
return function () {
return {
'init': function (element, valueAccessor) {
var value = valueAccessor();
var hammertime1 = Hammer(element).on("swiperight", function (event) {
$(element).fadeOut('fast', function () {
value();
});
});
}
};
};
});
myviewmodel.js
...
ko.bindingHandlers.tap = new Bindings();
...
You can check my binding collection for how to test
https://github.com/AndersMalmgren/Knockout.Bindings/tree/master/test
This is my function that all my tests using
ko.test = function (tag, binding, test) {
var element = $("<" + tag + "/>");
element.appendTo("body");
ko.applyBindingsToNode(element[0], binding);
var args = {
clean: function () {
element.remove();
}
};
test(element, args);
if (!args.async) {
args.clean();
}
};
edit: Sorry forgot mocking, you just do
$.fn.on = function() {
}
I do not know what exact logic you want to test in that code since there hardly is any, but something like this
http://jsfiddle.net/Akqur/
edit:
May you get confused where i hook up your binding? Its done here
{
tap: function() {
ok(true, "It should call the accessor");
}
}
I tell ko to hook up a "tap" binding and instead of hooking in up to a observable I use a mocking function, when your custom bindnig calls value() from the fadeout function the test assert will fire
edit:
Maybe this approuch makes more sense to you?
http://jsfiddle.net/Akqur/5/
Note that it only works if your code is executed synchronous
edit:
Here i use the third argument of ko.test
http://jsfiddle.net/Akqur/8/