Thursday, March 23, 2017

oracle inserted row OUT SYS_REFCURSOR by execution procedure

CREATE TABLE "BOROO"."CMS_TEMP"
   (    "ID" VARCHAR2(36 BYTE) DEFAULT SYS_GUID() NOT NULL ENABLE,
    "NAME" NVARCHAR2(150),
    "RCDATE" TIMESTAMP (6) DEFAULT SYS_EXTRACT_UTC(SYSTIMESTAMP) NOT NULL ENABLE
   )
 
procedure

create or replace PROCEDURE INSEL_TEMP (p_name NVARCHAR2, v_cur OUT SYS_REFCURSOR)
AS
v_id NVARCHAR2(36);
BEGIN
INSERT INTO CMS_TEMP (NAME) VALUES (p_name) RETURNING ID INTO v_id;
COMMIT;
OPEN v_cur FOR SELECT ID,NAME,RCDATE FROM CMS_TEMP WHERE ID=v_id;
END;



call






DECLARE
  l_cursor  SYS_REFCURSOR;
  l_id   cms_temp.ID%TYPE;
  l_name   cms_temp.NAME%TYPE;
  l_rcdate  cms_temp.RCDATE%TYPE;
BEGIN
  INSEL_TEMP('name 1', l_cursor);
 
  LOOP FETCH l_cursor
    INTO l_id, l_name, l_rcdate;
    EXIT WHEN l_cursor%NOTFOUND;
    DBMS_OUTPUT.PUT_LINE(l_id || ' | ' || l_name || ' | ' || l_rcdate);
  END LOOP;
  CLOSE l_cursor;
END;

Tuesday, March 21, 2017

oracle SYS_EXTRACT_UTC(SYSTIMESTAMP), mssql GETUTCDATE(), mysql CURRENT_TIMESTAMP

inORACLE

DROP TABLE "CMS_TEMP";

CREATE TABLE "CMS_TEMP" (  
"ID" VARCHAR2(36) DEFAULT SYS_GUID() NOT NULL,
"NAME" NVARCHAR2(150),
"RCDATE" TIMESTAMP DEFAULT SYS_EXTRACT_UTC(SYSTIMESTAMP) NOT NULL
);

insert into "BOROO"."CMS_TEMP" (NAME)
values ('new name 1');

select TO_CHAR(RCDATE, 'YYYY-MM-DD HH24:MI:SS.FF') from CMS_TEMP;


inMSSQL


DROP TABLE [dbo].[table1]
GO
/****** Object:  Table [dbo].[table1]    Script Date: 3/21/2017 5:50:45 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[table1](
    [ID] [uniqueidentifier] ROWGUIDCOL NOT NULL CONSTRAINT [DF_table1_ID]  DEFAULT (newid()),
    [Name] [nvarchar](50) NOT NULL,
    [rcdate] datetime NOT NULL DEFAULT GETUTCDATE()
) ON [PRIMARY]
GO
insert into table1(name)
values ('name 1');
GO
select rcdate from table1;


inMySQL

CREATE TABLE `table1` (
  `id` char(36) DEFAULT NULL,
  `name` varchar(250) NOT NULL,
  `rcdate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE OR REPLACE PROCEDURE test for REF CURSOR

CREATE OR REPLACE PROCEDURE test
IS
  TYPE ref_cursor_type IS REF CURSOR;
  c_ref_cursor ref_cursor_type;
  v_sql VARCHAR2(1000) := 'SELECT 1 FROM some_object';
  v_dummy NUMBER;
BEGIN
  OPEN c_ref_cursor FOR v_sql;
  FETCH c_ref_cursor INTO v_dummy;
  CLOSE c_ref_cursor;
END;

oracle sys_guid(), mssql newid(), mysql trigger all for default uniqueidentifier ID

inORACLE


DROP TABLE "CMS_TEMP";

CREATE TABLE "CMS_TEMP" (   
"ID" VARCHAR2(36) NOT NULL,
"NAME" NVARCHAR2(150),
"RCTIME" TIMESTAMP (6) DEFAULT SYS_EXTRACT_UTC(SYSTIMESTAMP) NOT NULL
);

create or replace FUNCTION NEWID RETURN VARCHAR2 IS guid VARCHAR2(36);
BEGIN
    SELECT SYS_GUID() INTO guid FROM DUAL;
guid := regexp_replace(rawtohex(sys_guid())
       , '([A-F0-9]{8})([A-F0-9]{4})([A-F0-9]{4})([A-F0-9]{4})([A-F0-9]{12})'
       , '\1-\2-\3-\4-\5');
--OR
guid := SUBSTR(guid,  1, 8) ||
        '-' || SUBSTR(guid,  9, 4) ||
        '-' || SUBSTR(guid, 13, 4) ||
        '-' || SUBSTR(guid, 17, 4) ||
        '-' || SUBSTR(guid, 21);
    RETURN guid;
END NEWID;

create or replace TRIGGER SetGUIDforCMS_TEMP BEFORE INSERT ON CMS_TEMP
FOR EACH ROW
BEGIN
    :new.ID := NEWID();
END;

insert into "CMS_TEMP" (NAME)
values ('new name 1');

select * from cms_temp;

DECLARE
  v_Return VARCHAR2(36);
BEGIN
  v_Return := NEWID;
  DBMS_OUTPUT.PUT_LINE(v_Return);
END;

select NEWID from dual;

inMSSQL


Data Type: uniqueidentifier
Default Value or Binding: (newid())

CREATE TABLE [dbo].[table1](
    [ID] [uniqueidentifier] ROWGUIDCOL NOT NULL CONSTRAINT [DF_table1_ID]  DEFAULT (newid()),
    [Name] [nvarchar](50) NOT NULL,
    [rcdate] datetime NOT NULL DEFAULT GETUTCDATE()
) ON [PRIMARY]
GO

inMYSQL

CREATE TRIGGER `before_insert_table1` BEFORE INSERT ON `table1`
FOR EACH ROW BEGIN
    SET new.id = UPPER(uuid());
END

Monday, March 20, 2017

php session start with save_path

<?php
$dr = $_SERVER['DOCUMENT_ROOT'];
echo '$dr is '.$dr.'<br>';
$dn = dirname($dr);
echo '$dn is '.$dn.'<br>';
$sp = $dn . '/../sessions';
echo '$sp is '.$sp.'<br>';
$rp = realpath($sp);/*C:/sessions on windows*/
echo '$rp is '.$rp.'<br>';
ini_set('session.save_path', $rp);
echo 'ini_get is '.ini_get('session.save_path').'<br>';
session_start();
echo 'session is '.$_SESSION['hello'];
$_SESSION['hello'] = 'boroo';

Friday, March 17, 2017

oracle CREATE OR REPLACE Function with cursor, if clause

CREATE OR REPLACE Function IncomeLevel
   ( name_in IN varchar2 )
   RETURN varchar2
IS
   monthly_value number(6);
   ILevel varchar2(20);

   cursor c1 is
     SELECT monthly_income
     FROM employees
     WHERE name = name_in;

BEGIN

   open c1;
   fetch c1 into monthly_value;
   close c1;

   IF monthly_value <= 4000 THEN
      ILevel := 'Low Income';

   ELSIF monthly_value > 4000 and monthly_value <= 7000 THEN
      ILevel := 'Avg Income';

   ELSIF monthly_value > 7000 and monthly_value <= 15000 THEN
      ILevel := 'Moderate Income';

   ELSE
      ILevel := 'High Income';

   END IF;

   RETURN ILevel;

END;

node.js dateFormat library with test by jsfiddle

http://jsfiddle.net/phZr7/1/

/*
     * Date Format 1.2.3
     * (c) 2007-2009 Steven Levithan <stevenlevithan.com>
     * MIT license
     *
     * Includes enhancements by Scott Trenda <scott.trenda.net>
     * and Kris Kowal <cixar.com/~kris.kowal/>
     *
     * Accepts a date, a mask, or a date and a mask.
     * Returns a formatted version of the given date.
     * The date defaults to the current date/time.
     * The mask defaults to dateFormat.masks.default.
     */

    var dateFormat = function () {
        var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
            timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
            timezoneClip = /[^-+\dA-Z]/g,
            pad = function (val, len) {
                val = String(val);
                len = len || 2;
                while (val.length < len) val = "0" + val;
                return val;
            };
  
        // Regexes and supporting functions are cached through closure
        return function (date, mask, utc) {
            var dF = dateFormat;
  
            // You can't provide utc if you skip other args (use the "UTC:" mask prefix)
            if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
                mask = date;
                date = undefined;
            }
  
            // Passing date through Date applies Date.parse, if necessary
            date = date ? new Date(date) : new Date;
            if (isNaN(date)) throw SyntaxError("invalid date");
  
            mask = String(dF.masks[mask] || mask || dF.masks["default"]);
  
            // Allow setting the utc argument via the mask
            if (mask.slice(0, 4) == "UTC:") {
                mask = mask.slice(4);
                utc = true;
            }
  
            var    _ = utc ? "getUTC" : "get",
                d = date[_ + "Date"](),
                D = date[_ + "Day"](),
                m = date[_ + "Month"](),
                y = date[_ + "FullYear"](),
                H = date[_ + "Hours"](),
                M = date[_ + "Minutes"](),
                s = date[_ + "Seconds"](),
                L = date[_ + "Milliseconds"](),
                o = utc ? 0 : date.getTimezoneOffset(),
                flags = {
                    d:    d,
                    dd:   pad(d),
                    ddd:  dF.i18n.dayNames[D],
                    dddd: dF.i18n.dayNames[D + 7],
                    m:    m + 1,
                    mm:   pad(m + 1),
                    mmm:  dF.i18n.monthNames[m],
                    mmmm: dF.i18n.monthNames[m + 12],
                    yy:   String(y).slice(2),
                    yyyy: y,
                    h:    H % 12 || 12,
                    hh:   pad(H % 12 || 12),
                    H:    H,
                    HH:   pad(H),
                    M:    M,
                    MM:   pad(M),
                    s:    s,
                    ss:   pad(s),
                    l:    pad(L, 3),
                    L:    pad(L > 99 ? Math.round(L / 10) : L),
                    t:    H < 12 ? "a"  : "p",
                    tt:   H < 12 ? "am" : "pm",
                    T:    H < 12 ? "A"  : "P",
                    TT:   H < 12 ? "AM" : "PM",
                    Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
                    o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
                    S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
                };
  
            return mask.replace(token, function ($0) {
                return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
            });
        };
    }();
  
    // Some common format strings
    dateFormat.masks = {
        "default":      "ddd mmm dd yyyy HH:MM:ss",
        shortDate:      "m/d/yy",
        mediumDate:     "mmm d, yyyy",
        longDate:       "mmmm d, yyyy",
        fullDate:       "dddd, mmmm d, yyyy",
        shortTime:      "h:MM TT",
        mediumTime:     "h:MM:ss TT",
        longTime:       "h:MM:ss TT Z",
        isoDate:        "yyyy-mm-dd",
        isoTime:        "HH:MM:ss",
        isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
        isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
    };
  
    // Internationalization strings
    dateFormat.i18n = {
        dayNames: [
            "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
            "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
        ],
        monthNames: [
            "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
            "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
        ]
    };
  
    // For convenience...
    Date.prototype.format = function (mask, utc) {
        return dateFormat(this, mask, utc);
    };

today = new Date();
alert(dateFormat.isoUtcDateTime);
var dateString = today.format(dateFormat.isoUtcDateTime);
alert(dateString);

Tuesday, March 14, 2017

npm install oracledb using python27,node-gyp,bcrypt,build-tools,oracle-instantclient in windows

1.
install python 2.7
>npm config set python python2.7

2.
download and extract Oracle Instant Client to C:\oracle\instantclient
C:\oracle\instantclient; add to PATH of system variables

3. may be, not use that
>npm install --global --production windows-build-tools
>npm config set msvs_version 2013 --global
>npm install bcrypt
>npm install -g node-gyp
>node-gyp rebuild

4.
http://landinghub.visualstudio.com/visual-cpp-build-tools
or
visual studio 2015 install
>npm config set msvs_version 2015

5.
>set OCI_LIB_DIR=C:\oracle\instantclient\sdk\lib\msvc
>set OCI_INC_DIR=C:\oracle\instantclient\sdk\include
or
>set OCI_LIB_DIR=C:\oracle\BOR\product\11.2.0\dbhome_1\OCI\lib\msvc
>set OCI_INC_DIR=C:\oracle\BOR\product\11.2.0\dbhome_1\OCI\include

6.
>npm install oracledb --save

Friday, March 10, 2017

VSCode task, Gulp-sass concat many js to one minify js, sass to compressed css

'use strict';
const gulp = require('gulp');
const autoprefixer = require('gulp-autoprefixer');
const sourcemaps = require('gulp-sourcemaps');
const concat = require('gulp-concat');
const uglify = require('gulp-uglify');
const sass = require('gulp-sass');
const path = require('path');

var _adminSassInc = path.resolve(__dirname'private/themes/admin/scss');
var _adminSass = './private/themes/admin/scss/*.scss';
var _adminSassMain = './private/themes/admin/scss/*.scss';
var _adminCssDest = './public/themes/admin/css/';
var _adminJsPrivate = [
    './private/themes/admin/jss/*.js'
];
var _adminJsPublic = './public/themes/admin/js/';
var _admin_js_name = 'ajs.js';

var _siteSassInc = path.resolve(__dirname'private/themes/default/scss');
var _siteSass = './private/themes/default/scss/*.scss';
var _siteSassMain = './private/themes/default/scss/*.scss';
var _siteCssDest = './public/themes/default/css/';
var _siteJsPrivate = [
    './private/themes/default/jss/jishee.js',
    './private/themes/default/jss/scripts.js'
];
var _siteJsPublic = './public/themes/default/js/';
var _site_js_name = 'sjs.js';


var _outputStyle = 'compressed';
var config = {
    sass: {
        style: 'expanded',
        outputStyle: _outputStyle,
        errLogToConsole: true,
        sourceMap: true
    },
    autoprefixer: {
        browsers: ['last 2 versions'],
        cascade: false
    }
};

/**
 * for admin themes
 */
var admin_css_task = function () {
    config.sass.includePaths = _adminSassInc;
    gulp.src(_adminSassMain)
        .pipe(sass(config.sass))
        .pipe(gulp.dest(_adminCssDest));
};
gulp.task('admin-css'admin_css_task);
var admin_js_task = function () {
    gulp.src(_adminJsPrivate)
        .pipe(concat(_admin_js_name))
        .pipe(uglify())
        .pipe(gulp.dest(_adminJsPublic))
};
gulp.task('admin-js'admin_js_task);

/**
 * for site themes
 */
var site_css_task = function () {
    config.sass.includePaths = _siteSassInc;
    gulp.src(_siteSassMain)
        .pipe(sass(config.sass))
        .pipe(gulp.dest(_siteCssDest));
};
gulp.task('site-css'site_css_task);
var site_js_task = function () {
    gulp.src(_siteJsPrivate)
        .pipe(concat(_site_js_name))
        .pipe(uglify())
        .pipe(gulp.dest(_siteJsPublic))
};
gulp.task('site-js'site_js_task);

/**
 * .pipe(sourcemaps.init())
        .pipe(sass(config.sass))
        .pipe(sourcemaps.write({ includeContent: false }))
        .pipe(sourcemaps.init({ loadMaps: true }))
        .pipe(autoprefixer(config.autoprefixer))
        .pipe(sourcemaps.write('.'))
 */

gulp.task('watch'function () {
    var changeHandler = function (evt) {
        console.log(
            '[watcher] File ' + evt.path.replace(/.*(?=sass)/'') + ' was ' + evt.type + ', compiling...'
        );
    };
    
    gulp.watch(_adminSassfunction () {
        setTimeout(function () {
            admin_css_task();
        }, 500);
    }).on('change'changeHandler);
    gulp.watch(_adminJsPrivateadmin_js_task);

    gulp.watch(_siteSassfunction () {
        setTimeout(function () {
            site_css_task();
        }, 500);
    }).on('change'changeHandler);
    gulp.watch(_siteJsPrivatesite_js_task);
});

gulp.task('run', ['admin-css''site-css''admin-js''site-js''watch']);

Dynamically injects @import statements into the main app.less file

// gulpfile.js
var gulp = require('gulp'),
    less = require('gulp-less'),
    inject = require('gulp-inject');

gulp.task('less', function() {
    return gulp.src('src/styles/main.less')
    /**
     * Dynamically injects @import statements into the main app.less file, allowing
     * .less files to be placed around the app structure with the component
     * or page they apply to.
     */
        .pipe(inject(gulp.src(['../**/*.less'], {read: false, cwd: 'src/styles/'}), {
            starttag: '/* inject:imports */',
            endtag: '/* endinject */',
            transform: function (filepath) {
                return '@import ".' + filepath + '";';
            }
        }))
        .pipe(less())
        .pipe(gulp.dest('build/styles'));
});

How to Automate Tasks in Visual Studio Code

var gulp = require('gulp');
var uglify = require('gulp-uglify');
var sass = require('gulp-sass');

var jsSrc = './js/src/**/*.js';
var sassSrc = './css/sass/**/*.scss';

gulp.task( 'scripts', function() {
  return  gulp.src( jsSrc )
                .pipe( uglify() )
                .pipe( gulp.dest( './js' ) )
});

gulp.task( 'styles', function() {
  return  gulp.src( sassSrc )
                .pipe( sass( { outputStyle: 'compressed' } ) )
                .pipe( gulp.dest( './css' ) );
});

gulp.task( 'automate', function() {
  gulp.watch( [ sassSrc, jsSrc ], [ 'scripts', 'styles' ] );
});

gulp.task( 'default', ['scripts', 'styles', 'automate'] );

Tuesday, March 7, 2017

oracle database date, timestamp, utc (SYS_EXTRACT_UTC(SYSTIMESTAMP)) field convert to local time example


  CREATE TABLE "BOROO"."CMS_TEMP"
   (    "ID" VARCHAR2(32 BYTE) DEFAULT SYS_GUID() NOT NULL ENABLE,
    "NAME" NVARCHAR2(150) NOT NULL ENABLE,
    "DESCR" NVARCHAR2(500),
    "ISDELETED" NUMBER(1,0) DEFAULT 0 NOT NULL ENABLE,
    "RCDATE" DATE NOT NULL ENABLE,
    "RCTIME" TIMESTAMP (6) DEFAULT SYS_EXTRACT_UTC(SYSTIMESTAMP) NOT NULL ENABLE
   ) SEGMENT CREATION IMMEDIATE
  PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS LOGGING
  STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "USERS" ;


  CREATE UNIQUE INDEX "BOROO"."CMS_TEMP_INDEX1" ON "BOROO"."CMS_TEMP" ("ID")
  PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS
  STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "USERS" ;


  CREATE INDEX "BOROO"."CMS_TEMP_INDEX2" ON "BOROO"."CMS_TEMP" ("NAME")
  PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS
  STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "USERS" ;


  CREATE INDEX "BOROO"."CMS_TEMP_INDEX3" ON "BOROO"."CMS_TEMP" ("RCDATE" DESC)
  PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS
  STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "USERS" ;


INSERT INTO CMS_TEMP (NAME,DESCR,ISDELETED,RCDATE)
VALUES ('my name', 'миний тайлбар', 0, TO_DATE('2017-03-07 15:17:19', 'YYYY-MM-DD HH24:MI:SS'));

/*UTC timestamp field view as local date*/
SELECT ID,NAME,TO_CHAR(RCDATE, 'YYYY-MM-DD HH24:MI:SS') as DATETIME,RCTIME as UTC
,TO_CHAR(FROM_TZ(RCTIME, 'UTC') at LOCAL, 'YYYY-MM-DD HH24:MI:SSxFF6') as local
FROM CMS_TEMP;

/*UTC without TZH:TZM*/
SELECT SYSTIMESTAMP as local, SYS_EXTRACT_UTC(SYSTIMESTAMP) as utc, TO_CHAR(SYS_EXTRACT_UTC(SYSTIMESTAMP), 'YYYY-MM-DD HH24:MI:SSxFF6') as str from dual;